(math-restore-underscores, math-string-restore-underscores):
[emacs.git] / src / fileio.c
blob2d6f74a88409b514604723199c8acec0bfccfd94
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 3, 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 "charset.h"
78 #include "coding.h"
79 #include "window.h"
80 #include "blockinput.h"
81 #include "frame.h"
82 #include "dispextern.h"
84 #ifdef WINDOWSNT
85 #define NOMINMAX 1
86 #include <windows.h>
87 #include <stdlib.h>
88 #include <fcntl.h>
89 #endif /* not WINDOWSNT */
91 #ifdef MSDOS
92 #include "msdos.h"
93 #include <sys/param.h>
94 #if __DJGPP__ >= 2
95 #include <fcntl.h>
96 #include <string.h>
97 #endif
98 #endif
100 #ifdef DOS_NT
101 #define CORRECT_DIR_SEPS(s) \
102 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
103 else unixtodos_filename (s); \
104 } while (0)
105 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
106 redirector allows the six letters between 'Z' and 'a' as well. */
107 #ifdef MSDOS
108 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
109 #endif
110 #ifdef WINDOWSNT
111 #define IS_DRIVE(x) isalpha (x)
112 #endif
113 /* Need to lower-case the drive letter, or else expanded
114 filenames will sometimes compare inequal, because
115 `expand-file-name' doesn't always down-case the drive letter. */
116 #define DRIVE_LETTER(x) (tolower (x))
117 #endif
119 #ifdef VMS
120 #include <file.h>
121 #include <rmsdef.h>
122 #include <fab.h>
123 #include <nam.h>
124 #endif
126 #include "systime.h"
128 #ifdef HPUX
129 #include <netio.h>
130 #ifndef HPUX8
131 #ifndef HPUX9
132 #include <errnet.h>
133 #endif
134 #endif
135 #endif
137 #include "commands.h"
138 extern int use_dialog_box;
139 extern int use_file_dialog;
141 #ifndef O_WRONLY
142 #define O_WRONLY 1
143 #endif
145 #ifndef O_RDONLY
146 #define O_RDONLY 0
147 #endif
149 #ifndef S_ISLNK
150 # define lstat stat
151 #endif
153 #ifndef FILE_SYSTEM_CASE
154 #define FILE_SYSTEM_CASE(filename) (filename)
155 #endif
157 /* Nonzero during writing of auto-save files */
158 int auto_saving;
160 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
161 a new file with the same mode as the original */
162 int auto_save_mode_bits;
164 /* The symbol bound to coding-system-for-read when
165 insert-file-contents is called for recovering a file. This is not
166 an actual coding system name, but just an indicator to tell
167 insert-file-contents to use `emacs-mule' with a special flag for
168 auto saving and recovering a file. */
169 Lisp_Object Qauto_save_coding;
171 /* Coding system for file names, or nil if none. */
172 Lisp_Object Vfile_name_coding_system;
174 /* Coding system for file names used only when
175 Vfile_name_coding_system is nil. */
176 Lisp_Object Vdefault_file_name_coding_system;
178 /* Alist of elements (REGEXP . HANDLER) for file names
179 whose I/O is done with a special handler. */
180 Lisp_Object Vfile_name_handler_alist;
182 /* Property name of a file name handler,
183 which gives a list of operations it handles.. */
184 Lisp_Object Qoperations;
186 /* Lisp functions for translating file formats */
187 Lisp_Object Qformat_decode, Qformat_annotate_function;
189 /* Function to be called to decide a coding system of a reading file. */
190 Lisp_Object Vset_auto_coding_function;
192 /* Functions to be called to process text properties in inserted file. */
193 Lisp_Object Vafter_insert_file_functions;
195 /* Lisp function for setting buffer-file-coding-system and the
196 multibyteness of the current buffer after inserting a file. */
197 Lisp_Object Qafter_insert_file_set_coding;
199 /* Functions to be called to create text property annotations for file. */
200 Lisp_Object Vwrite_region_annotate_functions;
201 Lisp_Object Qwrite_region_annotate_functions;
203 /* During build_annotations, each time an annotation function is called,
204 this holds the annotations made by the previous functions. */
205 Lisp_Object Vwrite_region_annotations_so_far;
207 /* File name in which we write a list of all our auto save files. */
208 Lisp_Object Vauto_save_list_file_name;
210 /* Function to call to read a file name. */
211 Lisp_Object Vread_file_name_function;
213 /* Current predicate used by read_file_name_internal. */
214 Lisp_Object Vread_file_name_predicate;
216 /* Nonzero means completion ignores case when reading file name. */
217 int read_file_name_completion_ignore_case;
219 /* Nonzero means, when reading a filename in the minibuffer,
220 start out by inserting the default directory into the minibuffer. */
221 int insert_default_directory;
223 /* On VMS, nonzero means write new files with record format stmlf.
224 Zero means use var format. */
225 int vms_stmlf_recfm;
227 /* On NT, specifies the directory separator character, used (eg.) when
228 expanding file names. This can be bound to / or \. */
229 Lisp_Object Vdirectory_sep_char;
231 #ifdef HAVE_FSYNC
232 /* Nonzero means skip the call to fsync in Fwrite-region. */
233 int write_region_inhibit_fsync;
234 #endif
236 extern Lisp_Object Vuser_login_name;
238 #ifdef WINDOWSNT
239 extern Lisp_Object Vw32_get_true_file_attributes;
240 #endif
242 extern int minibuf_level;
244 extern int minibuffer_auto_raise;
246 extern int history_delete_duplicates;
248 /* These variables describe handlers that have "already" had a chance
249 to handle the current operation.
251 Vinhibit_file_name_handlers is a list of file name handlers.
252 Vinhibit_file_name_operation is the operation being handled.
253 If we try to handle that operation, we ignore those handlers. */
255 static Lisp_Object Vinhibit_file_name_handlers;
256 static Lisp_Object Vinhibit_file_name_operation;
258 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
259 Lisp_Object Qexcl;
260 Lisp_Object Qfile_name_history;
262 Lisp_Object Qcar_less_than_car;
264 static int a_write P_ ((int, Lisp_Object, int, int,
265 Lisp_Object *, struct coding_system *));
266 static int e_write P_ ((int, Lisp_Object, int, int, struct coding_system *));
269 void
270 report_file_error (string, data)
271 const char *string;
272 Lisp_Object data;
274 Lisp_Object errstring;
275 int errorno = errno;
277 synchronize_system_messages_locale ();
278 errstring = code_convert_string_norecord (build_string (strerror (errorno)),
279 Vlocale_coding_system, 0);
281 while (1)
282 switch (errorno)
284 case EEXIST:
285 xsignal (Qfile_already_exists, Fcons (errstring, data));
286 break;
287 default:
288 /* System error messages are capitalized. Downcase the initial
289 unless it is followed by a slash. */
290 if (SREF (errstring, 1) != '/')
291 SSET (errstring, 0, DOWNCASE (SREF (errstring, 0)));
293 xsignal (Qfile_error,
294 Fcons (build_string (string), Fcons (errstring, data)));
298 Lisp_Object
299 close_file_unwind (fd)
300 Lisp_Object fd;
302 emacs_close (XFASTINT (fd));
303 return Qnil;
306 /* Restore point, having saved it as a marker. */
308 static Lisp_Object
309 restore_point_unwind (location)
310 Lisp_Object location;
312 Fgoto_char (location);
313 Fset_marker (location, Qnil, Qnil);
314 return Qnil;
317 Lisp_Object Qexpand_file_name;
318 Lisp_Object Qsubstitute_in_file_name;
319 Lisp_Object Qdirectory_file_name;
320 Lisp_Object Qfile_name_directory;
321 Lisp_Object Qfile_name_nondirectory;
322 Lisp_Object Qunhandled_file_name_directory;
323 Lisp_Object Qfile_name_as_directory;
324 Lisp_Object Qcopy_file;
325 Lisp_Object Qmake_directory_internal;
326 Lisp_Object Qmake_directory;
327 Lisp_Object Qdelete_directory;
328 Lisp_Object Qdelete_file;
329 Lisp_Object Qrename_file;
330 Lisp_Object Qadd_name_to_file;
331 Lisp_Object Qmake_symbolic_link;
332 Lisp_Object Qfile_exists_p;
333 Lisp_Object Qfile_executable_p;
334 Lisp_Object Qfile_readable_p;
335 Lisp_Object Qfile_writable_p;
336 Lisp_Object Qfile_symlink_p;
337 Lisp_Object Qaccess_file;
338 Lisp_Object Qfile_directory_p;
339 Lisp_Object Qfile_regular_p;
340 Lisp_Object Qfile_accessible_directory_p;
341 Lisp_Object Qfile_modes;
342 Lisp_Object Qset_file_modes;
343 Lisp_Object Qset_file_times;
344 Lisp_Object Qfile_newer_than_file_p;
345 Lisp_Object Qinsert_file_contents;
346 Lisp_Object Qwrite_region;
347 Lisp_Object Qverify_visited_file_modtime;
348 Lisp_Object Qset_visited_file_modtime;
350 DEFUN ("find-file-name-handler", Ffind_file_name_handler, Sfind_file_name_handler, 2, 2, 0,
351 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
352 Otherwise, return nil.
353 A file name is handled if one of the regular expressions in
354 `file-name-handler-alist' matches it.
356 If OPERATION equals `inhibit-file-name-operation', then we ignore
357 any handlers that are members of `inhibit-file-name-handlers',
358 but we still do run any other handlers. This lets handlers
359 use the standard functions without calling themselves recursively. */)
360 (filename, operation)
361 Lisp_Object filename, operation;
363 /* This function must not munge the match data. */
364 Lisp_Object chain, inhibited_handlers, result;
365 int pos = -1;
367 result = Qnil;
368 CHECK_STRING (filename);
370 if (EQ (operation, Vinhibit_file_name_operation))
371 inhibited_handlers = Vinhibit_file_name_handlers;
372 else
373 inhibited_handlers = Qnil;
375 for (chain = Vfile_name_handler_alist; CONSP (chain);
376 chain = XCDR (chain))
378 Lisp_Object elt;
379 elt = XCAR (chain);
380 if (CONSP (elt))
382 Lisp_Object string = XCAR (elt);
383 int match_pos;
384 Lisp_Object handler = XCDR (elt);
385 Lisp_Object operations = Qnil;
387 if (SYMBOLP (handler))
388 operations = Fget (handler, Qoperations);
390 if (STRINGP (string)
391 && (match_pos = fast_string_match (string, filename)) > pos
392 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
394 Lisp_Object tem;
396 handler = XCDR (elt);
397 tem = Fmemq (handler, inhibited_handlers);
398 if (NILP (tem))
400 result = handler;
401 pos = match_pos;
406 QUIT;
408 return result;
411 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
412 1, 1, 0,
413 doc: /* Return the directory component in file name FILENAME.
414 Return nil if FILENAME does not include a directory.
415 Otherwise return a directory spec.
416 Given a Unix syntax file name, returns a string ending in slash;
417 on VMS, perhaps instead a string ending in `:', `]' or `>'. */)
418 (filename)
419 Lisp_Object filename;
421 #ifndef DOS_NT
422 register const unsigned char *beg;
423 #else
424 register unsigned char *beg;
425 #endif
426 register const unsigned char *p;
427 Lisp_Object handler;
429 CHECK_STRING (filename);
431 /* If the file name has special constructs in it,
432 call the corresponding file handler. */
433 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
434 if (!NILP (handler))
435 return call2 (handler, Qfile_name_directory, filename);
437 filename = FILE_SYSTEM_CASE (filename);
438 beg = SDATA (filename);
439 #ifdef DOS_NT
440 beg = strcpy (alloca (strlen (beg) + 1), beg);
441 #endif
442 p = beg + SBYTES (filename);
444 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
445 #ifdef VMS
446 && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
447 #endif /* VMS */
448 #ifdef DOS_NT
449 /* only recognise drive specifier at the beginning */
450 && !(p[-1] == ':'
451 /* handle the "/:d:foo" and "/:foo" cases correctly */
452 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
453 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
454 #endif
455 ) p--;
457 if (p == beg)
458 return Qnil;
459 #ifdef DOS_NT
460 /* Expansion of "c:" to drive and default directory. */
461 if (p[-1] == ':')
463 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
464 unsigned char *res = alloca (MAXPATHLEN + 1);
465 unsigned char *r = res;
467 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
469 strncpy (res, beg, 2);
470 beg += 2;
471 r += 2;
474 if (getdefdir (toupper (*beg) - 'A' + 1, r))
476 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
477 strcat (res, "/");
478 beg = res;
479 p = beg + strlen (beg);
482 CORRECT_DIR_SEPS (beg);
483 #endif /* DOS_NT */
485 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
488 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
489 Sfile_name_nondirectory, 1, 1, 0,
490 doc: /* Return file name FILENAME sans its directory.
491 For example, in a Unix-syntax file name,
492 this is everything after the last slash,
493 or the entire name if it contains no slash. */)
494 (filename)
495 Lisp_Object filename;
497 register const unsigned char *beg, *p, *end;
498 Lisp_Object handler;
500 CHECK_STRING (filename);
502 /* If the file name has special constructs in it,
503 call the corresponding file handler. */
504 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
505 if (!NILP (handler))
506 return call2 (handler, Qfile_name_nondirectory, filename);
508 beg = SDATA (filename);
509 end = p = beg + SBYTES (filename);
511 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
512 #ifdef VMS
513 && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
514 #endif /* VMS */
515 #ifdef DOS_NT
516 /* only recognise drive specifier at beginning */
517 && !(p[-1] == ':'
518 /* handle the "/:d:foo" case correctly */
519 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
520 #endif
522 p--;
524 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
527 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
528 Sunhandled_file_name_directory, 1, 1, 0,
529 doc: /* Return a directly usable directory name somehow associated with FILENAME.
530 A `directly usable' directory name is one that may be used without the
531 intervention of any file handler.
532 If FILENAME is a directly usable file itself, return
533 \(file-name-directory FILENAME).
534 The `call-process' and `start-process' functions use this function to
535 get a current directory to run processes in. */)
536 (filename)
537 Lisp_Object filename;
539 Lisp_Object handler;
541 /* If the file name has special constructs in it,
542 call the corresponding file handler. */
543 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
544 if (!NILP (handler))
545 return call2 (handler, Qunhandled_file_name_directory, filename);
547 return Ffile_name_directory (filename);
551 char *
552 file_name_as_directory (out, in)
553 char *out, *in;
555 int size = strlen (in) - 1;
557 strcpy (out, in);
559 if (size < 0)
561 out[0] = '.';
562 out[1] = '/';
563 out[2] = 0;
564 return out;
567 #ifdef VMS
568 /* Is it already a directory string? */
569 if (in[size] == ':' || in[size] == ']' || in[size] == '>')
570 return out;
571 /* Is it a VMS directory file name? If so, hack VMS syntax. */
572 else if (! index (in, '/')
573 && ((size > 3 && ! strcmp (&in[size - 3], ".DIR"))
574 || (size > 3 && ! strcmp (&in[size - 3], ".dir"))
575 || (size > 5 && (! strncmp (&in[size - 5], ".DIR", 4)
576 || ! strncmp (&in[size - 5], ".dir", 4))
577 && (in[size - 1] == '.' || in[size - 1] == ';')
578 && in[size] == '1')))
580 register char *p, *dot;
581 char brack;
583 /* x.dir -> [.x]
584 dir:x.dir --> dir:[x]
585 dir:[x]y.dir --> dir:[x.y] */
586 p = in + size;
587 while (p != in && *p != ':' && *p != '>' && *p != ']') p--;
588 if (p != in)
590 strncpy (out, in, p - in);
591 out[p - in] = '\0';
592 if (*p == ':')
594 brack = ']';
595 strcat (out, ":[");
597 else
599 brack = *p;
600 strcat (out, ".");
602 p++;
604 else
606 brack = ']';
607 strcpy (out, "[.");
609 dot = index (p, '.');
610 if (dot)
612 /* blindly remove any extension */
613 size = strlen (out) + (dot - p);
614 strncat (out, p, dot - p);
616 else
618 strcat (out, p);
619 size = strlen (out);
621 out[size++] = brack;
622 out[size] = '\0';
624 #else /* not VMS */
625 /* For Unix syntax, Append a slash if necessary */
626 if (!IS_DIRECTORY_SEP (out[size]))
628 /* Cannot use DIRECTORY_SEP, which could have any value */
629 out[size + 1] = '/';
630 out[size + 2] = '\0';
632 #ifdef DOS_NT
633 CORRECT_DIR_SEPS (out);
634 #endif
635 #endif /* not VMS */
636 return out;
639 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
640 Sfile_name_as_directory, 1, 1, 0,
641 doc: /* Return a string representing the file name FILE interpreted as a directory.
642 This operation exists because a directory is also a file, but its name as
643 a directory is different from its name as a file.
644 The result can be used as the value of `default-directory'
645 or passed as second argument to `expand-file-name'.
646 For a Unix-syntax file name, just appends a slash.
647 On VMS, converts \"[X]FOO.DIR\" to \"[X.FOO]\", etc. */)
648 (file)
649 Lisp_Object file;
651 char *buf;
652 Lisp_Object handler;
654 CHECK_STRING (file);
655 if (NILP (file))
656 return Qnil;
658 /* If the file name has special constructs in it,
659 call the corresponding file handler. */
660 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
661 if (!NILP (handler))
662 return call2 (handler, Qfile_name_as_directory, file);
664 buf = (char *) alloca (SBYTES (file) + 10);
665 file_name_as_directory (buf, SDATA (file));
666 return make_specified_string (buf, -1, strlen (buf),
667 STRING_MULTIBYTE (file));
671 * Convert from directory name to filename.
672 * On VMS:
673 * xyzzy:[mukesh.emacs] => xyzzy:[mukesh]emacs.dir.1
674 * xyzzy:[mukesh] => xyzzy:[000000]mukesh.dir.1
675 * On UNIX, it's simple: just make sure there isn't a terminating /
677 * Value is nonzero if the string output is different from the input.
681 directory_file_name (src, dst)
682 char *src, *dst;
684 long slen;
685 #ifdef VMS
686 long rlen;
687 char * ptr, * rptr;
688 char bracket;
689 struct FAB fab = cc$rms_fab;
690 struct NAM nam = cc$rms_nam;
691 char esa[NAM$C_MAXRSS];
692 #endif /* VMS */
694 slen = strlen (src);
695 #ifdef VMS
696 if (! index (src, '/')
697 && (src[slen - 1] == ']'
698 || src[slen - 1] == ':'
699 || src[slen - 1] == '>'))
701 /* VMS style - convert [x.y.z] to [x.y]z, [x] to [000000]x */
702 fab.fab$l_fna = src;
703 fab.fab$b_fns = slen;
704 fab.fab$l_nam = &nam;
705 fab.fab$l_fop = FAB$M_NAM;
707 nam.nam$l_esa = esa;
708 nam.nam$b_ess = sizeof esa;
709 nam.nam$b_nop |= NAM$M_SYNCHK;
711 /* We call SYS$PARSE to handle such things as [--] for us. */
712 if (SYS$PARSE (&fab, 0, 0) == RMS$_NORMAL)
714 slen = nam.nam$b_esl;
715 if (esa[slen - 1] == ';' && esa[slen - 2] == '.')
716 slen -= 2;
717 esa[slen] = '\0';
718 src = esa;
720 if (src[slen - 1] != ']' && src[slen - 1] != '>')
722 /* what about when we have logical_name:???? */
723 if (src[slen - 1] == ':')
724 { /* Xlate logical name and see what we get */
725 ptr = strcpy (dst, src); /* upper case for getenv */
726 while (*ptr)
728 if ('a' <= *ptr && *ptr <= 'z')
729 *ptr -= 040;
730 ptr++;
732 dst[slen - 1] = 0; /* remove colon */
733 if (!(src = egetenv (dst)))
734 return 0;
735 /* should we jump to the beginning of this procedure?
736 Good points: allows us to use logical names that xlate
737 to Unix names,
738 Bad points: can be a problem if we just translated to a device
739 name...
740 For now, I'll punt and always expect VMS names, and hope for
741 the best! */
742 slen = strlen (src);
743 if (src[slen - 1] != ']' && src[slen - 1] != '>')
744 { /* no recursion here! */
745 strcpy (dst, src);
746 return 0;
749 else
750 { /* not a directory spec */
751 strcpy (dst, src);
752 return 0;
755 bracket = src[slen - 1];
757 /* If bracket is ']' or '>', bracket - 2 is the corresponding
758 opening bracket. */
759 ptr = index (src, bracket - 2);
760 if (ptr == 0)
761 { /* no opening bracket */
762 strcpy (dst, src);
763 return 0;
765 if (!(rptr = rindex (src, '.')))
766 rptr = ptr;
767 slen = rptr - src;
768 strncpy (dst, src, slen);
769 dst[slen] = '\0';
770 if (*rptr == '.')
772 dst[slen++] = bracket;
773 dst[slen] = '\0';
775 else
777 /* If we have the top-level of a rooted directory (i.e. xx:[000000]),
778 then translate the device and recurse. */
779 if (dst[slen - 1] == ':'
780 && dst[slen - 2] != ':' /* skip decnet nodes */
781 && strcmp (src + slen, "[000000]") == 0)
783 dst[slen - 1] = '\0';
784 if ((ptr = egetenv (dst))
785 && (rlen = strlen (ptr) - 1) > 0
786 && (ptr[rlen] == ']' || ptr[rlen] == '>')
787 && ptr[rlen - 1] == '.')
789 char * buf = (char *) alloca (strlen (ptr) + 1);
790 strcpy (buf, ptr);
791 buf[rlen - 1] = ']';
792 buf[rlen] = '\0';
793 return directory_file_name (buf, dst);
795 else
796 dst[slen - 1] = ':';
798 strcat (dst, "[000000]");
799 slen += 8;
801 rptr++;
802 rlen = strlen (rptr) - 1;
803 strncat (dst, rptr, rlen);
804 dst[slen + rlen] = '\0';
805 strcat (dst, ".DIR.1");
806 return 1;
808 #endif /* VMS */
809 /* Process as Unix format: just remove any final slash.
810 But leave "/" unchanged; do not change it to "". */
811 strcpy (dst, src);
812 #ifdef APOLLO
813 /* Handle // as root for apollo's. */
814 if ((slen > 2 && dst[slen - 1] == '/')
815 || (slen > 1 && dst[0] != '/' && dst[slen - 1] == '/'))
816 dst[slen - 1] = 0;
817 #else
818 if (slen > 1
819 && IS_DIRECTORY_SEP (dst[slen - 1])
820 #ifdef DOS_NT
821 && !IS_ANY_SEP (dst[slen - 2])
822 #endif
824 dst[slen - 1] = 0;
825 #endif
826 #ifdef DOS_NT
827 CORRECT_DIR_SEPS (dst);
828 #endif
829 return 1;
832 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
833 1, 1, 0,
834 doc: /* Returns the file name of the directory named DIRECTORY.
835 This is the name of the file that holds the data for the directory DIRECTORY.
836 This operation exists because a directory is also a file, but its name as
837 a directory is different from its name as a file.
838 In Unix-syntax, this function just removes the final slash.
839 On VMS, given a VMS-syntax directory name such as \"[X.Y]\",
840 it returns a file name such as \"[X]Y.DIR.1\". */)
841 (directory)
842 Lisp_Object directory;
844 char *buf;
845 Lisp_Object handler;
847 CHECK_STRING (directory);
849 if (NILP (directory))
850 return Qnil;
852 /* If the file name has special constructs in it,
853 call the corresponding file handler. */
854 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
855 if (!NILP (handler))
856 return call2 (handler, Qdirectory_file_name, directory);
858 #ifdef VMS
859 /* 20 extra chars is insufficient for VMS, since we might perform a
860 logical name translation. an equivalence string can be up to 255
861 chars long, so grab that much extra space... - sss */
862 buf = (char *) alloca (SBYTES (directory) + 20 + 255);
863 #else
864 buf = (char *) alloca (SBYTES (directory) + 20);
865 #endif
866 directory_file_name (SDATA (directory), buf);
867 return make_specified_string (buf, -1, strlen (buf),
868 STRING_MULTIBYTE (directory));
871 static char make_temp_name_tbl[64] =
873 'A','B','C','D','E','F','G','H',
874 'I','J','K','L','M','N','O','P',
875 'Q','R','S','T','U','V','W','X',
876 'Y','Z','a','b','c','d','e','f',
877 'g','h','i','j','k','l','m','n',
878 'o','p','q','r','s','t','u','v',
879 'w','x','y','z','0','1','2','3',
880 '4','5','6','7','8','9','-','_'
883 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
885 /* Value is a temporary file name starting with PREFIX, a string.
887 The Emacs process number forms part of the result, so there is
888 no danger of generating a name being used by another process.
889 In addition, this function makes an attempt to choose a name
890 which has no existing file. To make this work, PREFIX should be
891 an absolute file name.
893 BASE64_P non-zero means add the pid as 3 characters in base64
894 encoding. In this case, 6 characters will be added to PREFIX to
895 form the file name. Otherwise, if Emacs is running on a system
896 with long file names, add the pid as a decimal number.
898 This function signals an error if no unique file name could be
899 generated. */
901 Lisp_Object
902 make_temp_name (prefix, base64_p)
903 Lisp_Object prefix;
904 int base64_p;
906 Lisp_Object val;
907 int len, clen;
908 int pid;
909 unsigned char *p, *data;
910 char pidbuf[20];
911 int pidlen;
913 CHECK_STRING (prefix);
915 /* VAL is created by adding 6 characters to PREFIX. The first
916 three are the PID of this process, in base 64, and the second
917 three are incremented if the file already exists. This ensures
918 262144 unique file names per PID per PREFIX. */
920 pid = (int) getpid ();
922 if (base64_p)
924 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
925 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
926 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
927 pidlen = 3;
929 else
931 #ifdef HAVE_LONG_FILE_NAMES
932 sprintf (pidbuf, "%d", pid);
933 pidlen = strlen (pidbuf);
934 #else
935 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
936 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
937 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
938 pidlen = 3;
939 #endif
942 len = SBYTES (prefix); clen = SCHARS (prefix);
943 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
944 if (!STRING_MULTIBYTE (prefix))
945 STRING_SET_UNIBYTE (val);
946 data = SDATA (val);
947 bcopy(SDATA (prefix), data, len);
948 p = data + len;
950 bcopy (pidbuf, p, pidlen);
951 p += pidlen;
953 /* Here we try to minimize useless stat'ing when this function is
954 invoked many times successively with the same PREFIX. We achieve
955 this by initializing count to a random value, and incrementing it
956 afterwards.
958 We don't want make-temp-name to be called while dumping,
959 because then make_temp_name_count_initialized_p would get set
960 and then make_temp_name_count would not be set when Emacs starts. */
962 if (!make_temp_name_count_initialized_p)
964 make_temp_name_count = (unsigned) time (NULL);
965 make_temp_name_count_initialized_p = 1;
968 while (1)
970 struct stat ignored;
971 unsigned num = make_temp_name_count;
973 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
974 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
975 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
977 /* Poor man's congruential RN generator. Replace with
978 ++make_temp_name_count for debugging. */
979 make_temp_name_count += 25229;
980 make_temp_name_count %= 225307;
982 if (stat (data, &ignored) < 0)
984 /* We want to return only if errno is ENOENT. */
985 if (errno == ENOENT)
986 return val;
987 else
988 /* The error here is dubious, but there is little else we
989 can do. The alternatives are to return nil, which is
990 as bad as (and in many cases worse than) throwing the
991 error, or to ignore the error, which will likely result
992 in looping through 225307 stat's, which is not only
993 dog-slow, but also useless since it will fallback to
994 the errow below, anyway. */
995 report_file_error ("Cannot create temporary name for prefix",
996 Fcons (prefix, Qnil));
997 /* not reached */
1001 error ("Cannot create temporary name for prefix `%s'",
1002 SDATA (prefix));
1003 return Qnil;
1007 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
1008 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
1009 The Emacs process number forms part of the result,
1010 so there is no danger of generating a name being used by another process.
1012 In addition, this function makes an attempt to choose a name
1013 which has no existing file. To make this work,
1014 PREFIX should be an absolute file name.
1016 There is a race condition between calling `make-temp-name' and creating the
1017 file which opens all kinds of security holes. For that reason, you should
1018 probably use `make-temp-file' instead, except in three circumstances:
1020 * If you are creating the file in the user's home directory.
1021 * If you are creating a directory rather than an ordinary file.
1022 * If you are taking special precautions as `make-temp-file' does. */)
1023 (prefix)
1024 Lisp_Object prefix;
1026 return make_temp_name (prefix, 0);
1031 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1032 doc: /* Convert filename NAME to absolute, and canonicalize it.
1033 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
1034 \(does not start with slash); if DEFAULT-DIRECTORY is nil or missing,
1035 the current buffer's value of `default-directory' is used.
1036 File name components that are `.' are removed, and
1037 so are file name components followed by `..', along with the `..' itself;
1038 note that these simplifications are done without checking the resulting
1039 file names in the file system.
1040 An initial `~/' expands to your home directory.
1041 An initial `~USER/' expands to USER's home directory.
1042 See also the function `substitute-in-file-name'. */)
1043 (name, default_directory)
1044 Lisp_Object name, default_directory;
1046 unsigned char *nm;
1048 register unsigned char *newdir, *p, *o;
1049 int tlen;
1050 unsigned char *target;
1051 struct passwd *pw;
1052 #ifdef VMS
1053 unsigned char * colon = 0;
1054 unsigned char * close = 0;
1055 unsigned char * slash = 0;
1056 unsigned char * brack = 0;
1057 int lbrack = 0, rbrack = 0;
1058 int dots = 0;
1059 #endif /* VMS */
1060 #ifdef DOS_NT
1061 int drive = 0;
1062 int collapse_newdir = 1;
1063 int is_escaped = 0;
1064 #endif /* DOS_NT */
1065 int length;
1066 Lisp_Object handler, result;
1067 int multibyte;
1069 CHECK_STRING (name);
1071 /* If the file name has special constructs in it,
1072 call the corresponding file handler. */
1073 handler = Ffind_file_name_handler (name, Qexpand_file_name);
1074 if (!NILP (handler))
1075 return call3 (handler, Qexpand_file_name, name, default_directory);
1077 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
1078 if (NILP (default_directory))
1079 default_directory = current_buffer->directory;
1080 if (! STRINGP (default_directory))
1082 #ifdef DOS_NT
1083 /* "/" is not considered a root directory on DOS_NT, so using "/"
1084 here causes an infinite recursion in, e.g., the following:
1086 (let (default-directory)
1087 (expand-file-name "a"))
1089 To avoid this, we set default_directory to the root of the
1090 current drive. */
1091 extern char *emacs_root_dir (void);
1093 default_directory = build_string (emacs_root_dir ());
1094 #else
1095 default_directory = build_string ("/");
1096 #endif
1099 if (!NILP (default_directory))
1101 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
1102 if (!NILP (handler))
1103 return call3 (handler, Qexpand_file_name, name, default_directory);
1106 o = SDATA (default_directory);
1108 /* Make sure DEFAULT_DIRECTORY is properly expanded.
1109 It would be better to do this down below where we actually use
1110 default_directory. Unfortunately, calling Fexpand_file_name recursively
1111 could invoke GC, and the strings might be relocated. This would
1112 be annoying because we have pointers into strings lying around
1113 that would need adjusting, and people would add new pointers to
1114 the code and forget to adjust them, resulting in intermittent bugs.
1115 Putting this call here avoids all that crud.
1117 The EQ test avoids infinite recursion. */
1118 if (! NILP (default_directory) && !EQ (default_directory, name)
1119 /* Save time in some common cases - as long as default_directory
1120 is not relative, it can be canonicalized with name below (if it
1121 is needed at all) without requiring it to be expanded now. */
1122 #ifdef DOS_NT
1123 /* Detect MSDOS file names with drive specifiers. */
1124 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1]) && IS_DIRECTORY_SEP (o[2]))
1125 #ifdef WINDOWSNT
1126 /* Detect Windows file names in UNC format. */
1127 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
1128 #endif
1129 #else /* not DOS_NT */
1130 /* Detect Unix absolute file names (/... alone is not absolute on
1131 DOS or Windows). */
1132 && ! (IS_DIRECTORY_SEP (o[0]))
1133 #endif /* not DOS_NT */
1136 struct gcpro gcpro1;
1138 GCPRO1 (name);
1139 default_directory = Fexpand_file_name (default_directory, Qnil);
1140 UNGCPRO;
1143 name = FILE_SYSTEM_CASE (name);
1144 nm = SDATA (name);
1145 multibyte = STRING_MULTIBYTE (name);
1147 #ifdef DOS_NT
1148 /* We will force directory separators to be either all \ or /, so make
1149 a local copy to modify, even if there ends up being no change. */
1150 nm = strcpy (alloca (strlen (nm) + 1), nm);
1152 /* Note if special escape prefix is present, but remove for now. */
1153 if (nm[0] == '/' && nm[1] == ':')
1155 is_escaped = 1;
1156 nm += 2;
1159 /* Find and remove drive specifier if present; this makes nm absolute
1160 even if the rest of the name appears to be relative. Only look for
1161 drive specifier at the beginning. */
1162 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
1164 drive = nm[0];
1165 nm += 2;
1168 #ifdef WINDOWSNT
1169 /* If we see "c://somedir", we want to strip the first slash after the
1170 colon when stripping the drive letter. Otherwise, this expands to
1171 "//somedir". */
1172 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1173 nm++;
1174 #endif /* WINDOWSNT */
1175 #endif /* DOS_NT */
1177 #ifdef WINDOWSNT
1178 /* Discard any previous drive specifier if nm is now in UNC format. */
1179 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1181 drive = 0;
1183 #endif
1185 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
1186 none are found, we can probably return right away. We will avoid
1187 allocating a new string if name is already fully expanded. */
1188 if (
1189 IS_DIRECTORY_SEP (nm[0])
1190 #ifdef MSDOS
1191 && drive && !is_escaped
1192 #endif
1193 #ifdef WINDOWSNT
1194 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
1195 #endif
1196 #ifdef VMS
1197 || index (nm, ':')
1198 #endif /* VMS */
1201 /* If it turns out that the filename we want to return is just a
1202 suffix of FILENAME, we don't need to go through and edit
1203 things; we just need to construct a new string using data
1204 starting at the middle of FILENAME. If we set lose to a
1205 non-zero value, that means we've discovered that we can't do
1206 that cool trick. */
1207 int lose = 0;
1209 p = nm;
1210 while (*p)
1212 /* Since we know the name is absolute, we can assume that each
1213 element starts with a "/". */
1215 /* "." and ".." are hairy. */
1216 if (IS_DIRECTORY_SEP (p[0])
1217 && p[1] == '.'
1218 && (IS_DIRECTORY_SEP (p[2])
1219 || p[2] == 0
1220 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1221 || p[3] == 0))))
1222 lose = 1;
1223 /* We want to replace multiple `/' in a row with a single
1224 slash. */
1225 else if (p > nm
1226 && IS_DIRECTORY_SEP (p[0])
1227 && IS_DIRECTORY_SEP (p[1]))
1228 lose = 1;
1230 #ifdef VMS
1231 if (p[0] == '\\')
1232 lose = 1;
1233 if (p[0] == '/') {
1234 /* if dev:[dir]/, move nm to / */
1235 if (!slash && p > nm && (brack || colon)) {
1236 nm = (brack ? brack + 1 : colon + 1);
1237 lbrack = rbrack = 0;
1238 brack = 0;
1239 colon = 0;
1241 slash = p;
1243 if (p[0] == '-')
1244 #ifdef NO_HYPHENS_IN_FILENAMES
1245 if (lbrack == rbrack)
1247 /* Avoid clobbering negative version numbers. */
1248 if (dots < 2)
1249 p[0] = '_';
1251 else
1252 #endif /* NO_HYPHENS_IN_FILENAMES */
1253 if (lbrack > rbrack
1254 && ((p[-1] == '.' || p[-1] == '[' || p[-1] == '<')
1255 && (p[1] == '.' || p[1] == ']' || p[1] == '>')))
1256 lose = 1;
1257 #ifdef NO_HYPHENS_IN_FILENAMES
1258 else
1259 p[0] = '_';
1260 #endif /* NO_HYPHENS_IN_FILENAMES */
1261 /* count open brackets, reset close bracket pointer */
1262 if (p[0] == '[' || p[0] == '<')
1263 lbrack++, brack = 0;
1264 /* count close brackets, set close bracket pointer */
1265 if (p[0] == ']' || p[0] == '>')
1266 rbrack++, brack = p;
1267 /* detect ][ or >< */
1268 if ((p[0] == ']' || p[0] == '>') && (p[1] == '[' || p[1] == '<'))
1269 lose = 1;
1270 if ((p[0] == ':' || p[0] == ']' || p[0] == '>') && p[1] == '~')
1271 nm = p + 1, lose = 1;
1272 if (p[0] == ':' && (colon || slash))
1273 /* if dev1:[dir]dev2:, move nm to dev2: */
1274 if (brack)
1276 nm = brack + 1;
1277 brack = 0;
1279 /* if /name/dev:, move nm to dev: */
1280 else if (slash)
1281 nm = slash + 1;
1282 /* if node::dev:, move colon following dev */
1283 else if (colon && colon[-1] == ':')
1284 colon = p;
1285 /* if dev1:dev2:, move nm to dev2: */
1286 else if (colon && colon[-1] != ':')
1288 nm = colon + 1;
1289 colon = 0;
1291 if (p[0] == ':' && !colon)
1293 if (p[1] == ':')
1294 p++;
1295 colon = p;
1297 if (lbrack == rbrack)
1298 if (p[0] == ';')
1299 dots = 2;
1300 else if (p[0] == '.')
1301 dots++;
1302 #endif /* VMS */
1303 p++;
1305 if (!lose)
1307 #ifdef VMS
1308 if (index (nm, '/'))
1310 nm = sys_translate_unix (nm);
1311 return make_specified_string (nm, -1, strlen (nm), multibyte);
1313 #endif /* VMS */
1314 #ifdef DOS_NT
1315 /* Make sure directories are all separated with / or \ as
1316 desired, but avoid allocation of a new string when not
1317 required. */
1318 CORRECT_DIR_SEPS (nm);
1319 #ifdef WINDOWSNT
1320 if (IS_DIRECTORY_SEP (nm[1]))
1322 if (strcmp (nm, SDATA (name)) != 0)
1323 name = make_specified_string (nm, -1, strlen (nm), multibyte);
1325 else
1326 #endif
1327 /* drive must be set, so this is okay */
1328 if (strcmp (nm - 2, SDATA (name)) != 0)
1330 char temp[] = " :";
1332 name = make_specified_string (nm, -1, p - nm, multibyte);
1333 temp[0] = DRIVE_LETTER (drive);
1334 name = concat2 (build_string (temp), name);
1336 return name;
1337 #else /* not DOS_NT */
1338 if (nm == SDATA (name))
1339 return name;
1340 return make_specified_string (nm, -1, strlen (nm), multibyte);
1341 #endif /* not DOS_NT */
1345 /* At this point, nm might or might not be an absolute file name. We
1346 need to expand ~ or ~user if present, otherwise prefix nm with
1347 default_directory if nm is not absolute, and finally collapse /./
1348 and /foo/../ sequences.
1350 We set newdir to be the appropriate prefix if one is needed:
1351 - the relevant user directory if nm starts with ~ or ~user
1352 - the specified drive's working dir (DOS/NT only) if nm does not
1353 start with /
1354 - the value of default_directory.
1356 Note that these prefixes are not guaranteed to be absolute (except
1357 for the working dir of a drive). Therefore, to ensure we always
1358 return an absolute name, if the final prefix is not absolute we
1359 append it to the current working directory. */
1361 newdir = 0;
1363 if (nm[0] == '~') /* prefix ~ */
1365 if (IS_DIRECTORY_SEP (nm[1])
1366 #ifdef VMS
1367 || nm[1] == ':'
1368 #endif /* VMS */
1369 || nm[1] == 0) /* ~ by itself */
1371 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1372 newdir = (unsigned char *) "";
1373 nm++;
1374 #ifdef DOS_NT
1375 collapse_newdir = 0;
1376 #endif
1377 #ifdef VMS
1378 nm++; /* Don't leave the slash in nm. */
1379 #endif /* VMS */
1381 else /* ~user/filename */
1383 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)
1384 #ifdef VMS
1385 && *p != ':'
1386 #endif /* VMS */
1387 ); p++);
1388 o = (unsigned char *) alloca (p - nm + 1);
1389 bcopy ((char *) nm, o, p - nm);
1390 o [p - nm] = 0;
1392 BLOCK_INPUT;
1393 pw = (struct passwd *) getpwnam (o + 1);
1394 UNBLOCK_INPUT;
1395 if (pw)
1397 newdir = (unsigned char *) pw -> pw_dir;
1398 #ifdef VMS
1399 nm = p + 1; /* skip the terminator */
1400 #else
1401 nm = p;
1402 #ifdef DOS_NT
1403 collapse_newdir = 0;
1404 #endif
1405 #endif /* VMS */
1408 /* If we don't find a user of that name, leave the name
1409 unchanged; don't move nm forward to p. */
1413 #ifdef DOS_NT
1414 /* On DOS and Windows, nm is absolute if a drive name was specified;
1415 use the drive's current directory as the prefix if needed. */
1416 if (!newdir && drive)
1418 /* Get default directory if needed to make nm absolute. */
1419 if (!IS_DIRECTORY_SEP (nm[0]))
1421 newdir = alloca (MAXPATHLEN + 1);
1422 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1423 newdir = NULL;
1425 if (!newdir)
1427 /* Either nm starts with /, or drive isn't mounted. */
1428 newdir = alloca (4);
1429 newdir[0] = DRIVE_LETTER (drive);
1430 newdir[1] = ':';
1431 newdir[2] = '/';
1432 newdir[3] = 0;
1435 #endif /* DOS_NT */
1437 /* Finally, if no prefix has been specified and nm is not absolute,
1438 then it must be expanded relative to default_directory. */
1440 if (1
1441 #ifndef DOS_NT
1442 /* /... alone is not absolute on DOS and Windows. */
1443 && !IS_DIRECTORY_SEP (nm[0])
1444 #endif
1445 #ifdef WINDOWSNT
1446 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1447 #endif
1448 #ifdef VMS
1449 && !index (nm, ':')
1450 #endif
1451 && !newdir)
1453 newdir = SDATA (default_directory);
1454 multibyte |= STRING_MULTIBYTE (default_directory);
1455 #ifdef DOS_NT
1456 /* Note if special escape prefix is present, but remove for now. */
1457 if (newdir[0] == '/' && newdir[1] == ':')
1459 is_escaped = 1;
1460 newdir += 2;
1462 #endif
1465 #ifdef DOS_NT
1466 if (newdir)
1468 /* First ensure newdir is an absolute name. */
1469 if (
1470 /* Detect MSDOS file names with drive specifiers. */
1471 ! (IS_DRIVE (newdir[0])
1472 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1473 #ifdef WINDOWSNT
1474 /* Detect Windows file names in UNC format. */
1475 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1476 #endif
1479 /* Effectively, let newdir be (expand-file-name newdir cwd).
1480 Because of the admonition against calling expand-file-name
1481 when we have pointers into lisp strings, we accomplish this
1482 indirectly by prepending newdir to nm if necessary, and using
1483 cwd (or the wd of newdir's drive) as the new newdir. */
1485 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1487 drive = newdir[0];
1488 newdir += 2;
1490 if (!IS_DIRECTORY_SEP (nm[0]))
1492 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1493 file_name_as_directory (tmp, newdir);
1494 strcat (tmp, nm);
1495 nm = tmp;
1497 newdir = alloca (MAXPATHLEN + 1);
1498 if (drive)
1500 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1501 newdir = "/";
1503 else
1504 getwd (newdir);
1507 /* Strip off drive name from prefix, if present. */
1508 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1510 drive = newdir[0];
1511 newdir += 2;
1514 /* Keep only a prefix from newdir if nm starts with slash
1515 (//server/share for UNC, nothing otherwise). */
1516 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1518 #ifdef WINDOWSNT
1519 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1521 newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
1522 p = newdir + 2;
1523 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1524 p++;
1525 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1526 *p = 0;
1528 else
1529 #endif
1530 newdir = "";
1533 #endif /* DOS_NT */
1535 if (newdir)
1537 /* Get rid of any slash at the end of newdir, unless newdir is
1538 just / or // (an incomplete UNC name). */
1539 length = strlen (newdir);
1540 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1541 #ifdef WINDOWSNT
1542 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1543 #endif
1546 unsigned char *temp = (unsigned char *) alloca (length);
1547 bcopy (newdir, temp, length - 1);
1548 temp[length - 1] = 0;
1549 newdir = temp;
1551 tlen = length + 1;
1553 else
1554 tlen = 0;
1556 /* Now concatenate the directory and name to new space in the stack frame */
1557 tlen += strlen (nm) + 1;
1558 #ifdef DOS_NT
1559 /* Reserve space for drive specifier and escape prefix, since either
1560 or both may need to be inserted. (The Microsoft x86 compiler
1561 produces incorrect code if the following two lines are combined.) */
1562 target = (unsigned char *) alloca (tlen + 4);
1563 target += 4;
1564 #else /* not DOS_NT */
1565 target = (unsigned char *) alloca (tlen);
1566 #endif /* not DOS_NT */
1567 *target = 0;
1569 if (newdir)
1571 #ifndef VMS
1572 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1574 #ifdef DOS_NT
1575 /* If newdir is effectively "C:/", then the drive letter will have
1576 been stripped and newdir will be "/". Concatenating with an
1577 absolute directory in nm produces "//", which will then be
1578 incorrectly treated as a network share. Ignore newdir in
1579 this case (keeping the drive letter). */
1580 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1581 && newdir[1] == '\0'))
1582 #endif
1583 strcpy (target, newdir);
1585 else
1586 #endif
1587 file_name_as_directory (target, newdir);
1590 strcat (target, nm);
1591 #ifdef VMS
1592 if (index (target, '/'))
1593 strcpy (target, sys_translate_unix (target));
1594 #endif /* VMS */
1596 /* ASSERT (IS_DIRECTORY_SEP (target[0])) if not VMS */
1598 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1599 appear. */
1601 p = target;
1602 o = target;
1604 while (*p)
1606 #ifdef VMS
1607 if (*p != ']' && *p != '>' && *p != '-')
1609 if (*p == '\\')
1610 p++;
1611 *o++ = *p++;
1613 else if ((p[0] == ']' || p[0] == '>') && p[0] == p[1] + 2)
1614 /* brackets are offset from each other by 2 */
1616 p += 2;
1617 if (*p != '.' && *p != '-' && o[-1] != '.')
1618 /* convert [foo][bar] to [bar] */
1619 while (o[-1] != '[' && o[-1] != '<')
1620 o--;
1621 else if (*p == '-' && *o != '.')
1622 *--p = '.';
1624 else if (p[0] == '-' && o[-1] == '.'
1625 && (p[1] == '.' || p[1] == ']' || p[1] == '>'))
1626 /* flush .foo.- ; leave - if stopped by '[' or '<' */
1629 o--;
1630 while (o[-1] != '.' && o[-1] != '[' && o[-1] != '<');
1631 if (p[1] == '.') /* foo.-.bar ==> bar. */
1632 p += 2;
1633 else if (o[-1] == '.') /* '.foo.-]' ==> ']' */
1634 p++, o--;
1635 /* else [foo.-] ==> [-] */
1637 else
1639 #ifdef NO_HYPHENS_IN_FILENAMES
1640 if (*p == '-'
1641 && o[-1] != '[' && o[-1] != '<' && o[-1] != '.'
1642 && p[1] != ']' && p[1] != '>' && p[1] != '.')
1643 *p = '_';
1644 #endif /* NO_HYPHENS_IN_FILENAMES */
1645 *o++ = *p++;
1647 #else /* not VMS */
1648 if (!IS_DIRECTORY_SEP (*p))
1650 *o++ = *p++;
1652 else if (p[1] == '.'
1653 && (IS_DIRECTORY_SEP (p[2])
1654 || p[2] == 0))
1656 /* If "/." is the entire filename, keep the "/". Otherwise,
1657 just delete the whole "/.". */
1658 if (o == target && p[2] == '\0')
1659 *o++ = *p;
1660 p += 2;
1662 else if (p[1] == '.' && p[2] == '.'
1663 /* `/../' is the "superroot" on certain file systems.
1664 Turned off on DOS_NT systems because they have no
1665 "superroot" and because this causes us to produce
1666 file names like "d:/../foo" which fail file-related
1667 functions of the underlying OS. (To reproduce, try a
1668 long series of "../../" in default_directory, longer
1669 than the number of levels from the root.) */
1670 #ifndef DOS_NT
1671 && o != target
1672 #endif
1673 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1675 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1677 /* Keep initial / only if this is the whole name. */
1678 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1679 ++o;
1680 p += 3;
1682 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1683 /* Collapse multiple `/' in a row. */
1684 p++;
1685 else
1687 *o++ = *p++;
1689 #endif /* not VMS */
1692 #ifdef DOS_NT
1693 /* At last, set drive name. */
1694 #ifdef WINDOWSNT
1695 /* Except for network file name. */
1696 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1697 #endif /* WINDOWSNT */
1699 if (!drive) abort ();
1700 target -= 2;
1701 target[0] = DRIVE_LETTER (drive);
1702 target[1] = ':';
1704 /* Reinsert the escape prefix if required. */
1705 if (is_escaped)
1707 target -= 2;
1708 target[0] = '/';
1709 target[1] = ':';
1711 CORRECT_DIR_SEPS (target);
1712 #endif /* DOS_NT */
1714 result = make_specified_string (target, -1, o - target, multibyte);
1716 /* Again look to see if the file name has special constructs in it
1717 and perhaps call the corresponding file handler. This is needed
1718 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1719 the ".." component gives us "/user@host:/bar/../baz" which needs
1720 to be expanded again. */
1721 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1722 if (!NILP (handler))
1723 return call3 (handler, Qexpand_file_name, result, default_directory);
1725 return result;
1728 #if 0
1729 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1730 This is the old version of expand-file-name, before it was thoroughly
1731 rewritten for Emacs 10.31. We leave this version here commented-out,
1732 because the code is very complex and likely to have subtle bugs. If
1733 bugs _are_ found, it might be of interest to look at the old code and
1734 see what did it do in the relevant situation.
1736 Don't remove this code: it's true that it will be accessible via CVS,
1737 but a few years from deletion, people will forget it is there. */
1739 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1740 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1741 "Convert FILENAME to absolute, and canonicalize it.\n\
1742 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1743 \(does not start with slash); if DEFAULT is nil or missing,\n\
1744 the current buffer's value of default-directory is used.\n\
1745 Filenames containing `.' or `..' as components are simplified;\n\
1746 initial `~/' expands to your home directory.\n\
1747 See also the function `substitute-in-file-name'.")
1748 (name, defalt)
1749 Lisp_Object name, defalt;
1751 unsigned char *nm;
1753 register unsigned char *newdir, *p, *o;
1754 int tlen;
1755 unsigned char *target;
1756 struct passwd *pw;
1757 int lose;
1758 #ifdef VMS
1759 unsigned char * colon = 0;
1760 unsigned char * close = 0;
1761 unsigned char * slash = 0;
1762 unsigned char * brack = 0;
1763 int lbrack = 0, rbrack = 0;
1764 int dots = 0;
1765 #endif /* VMS */
1767 CHECK_STRING (name);
1769 #ifdef VMS
1770 /* Filenames on VMS are always upper case. */
1771 name = Fupcase (name);
1772 #endif
1774 nm = SDATA (name);
1776 /* If nm is absolute, flush ...// and detect /./ and /../.
1777 If no /./ or /../ we can return right away. */
1778 if (
1779 nm[0] == '/'
1780 #ifdef VMS
1781 || index (nm, ':')
1782 #endif /* VMS */
1785 p = nm;
1786 lose = 0;
1787 while (*p)
1789 if (p[0] == '/' && p[1] == '/'
1790 #ifdef APOLLO
1791 /* // at start of filename is meaningful on Apollo system. */
1792 && nm != p
1793 #endif /* APOLLO */
1795 nm = p + 1;
1796 if (p[0] == '/' && p[1] == '~')
1797 nm = p + 1, lose = 1;
1798 if (p[0] == '/' && p[1] == '.'
1799 && (p[2] == '/' || p[2] == 0
1800 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1801 lose = 1;
1802 #ifdef VMS
1803 if (p[0] == '\\')
1804 lose = 1;
1805 if (p[0] == '/') {
1806 /* if dev:[dir]/, move nm to / */
1807 if (!slash && p > nm && (brack || colon)) {
1808 nm = (brack ? brack + 1 : colon + 1);
1809 lbrack = rbrack = 0;
1810 brack = 0;
1811 colon = 0;
1813 slash = p;
1815 if (p[0] == '-')
1816 #ifndef VMS4_4
1817 /* VMS pre V4.4,convert '-'s in filenames. */
1818 if (lbrack == rbrack)
1820 if (dots < 2) /* this is to allow negative version numbers */
1821 p[0] = '_';
1823 else
1824 #endif /* VMS4_4 */
1825 if (lbrack > rbrack
1826 && ((p[-1] == '.' || p[-1] == '[' || p[-1] == '<')
1827 && (p[1] == '.' || p[1] == ']' || p[1] == '>')))
1828 lose = 1;
1829 #ifndef VMS4_4
1830 else
1831 p[0] = '_';
1832 #endif /* VMS4_4 */
1833 /* count open brackets, reset close bracket pointer */
1834 if (p[0] == '[' || p[0] == '<')
1835 lbrack++, brack = 0;
1836 /* count close brackets, set close bracket pointer */
1837 if (p[0] == ']' || p[0] == '>')
1838 rbrack++, brack = p;
1839 /* detect ][ or >< */
1840 if ((p[0] == ']' || p[0] == '>') && (p[1] == '[' || p[1] == '<'))
1841 lose = 1;
1842 if ((p[0] == ':' || p[0] == ']' || p[0] == '>') && p[1] == '~')
1843 nm = p + 1, lose = 1;
1844 if (p[0] == ':' && (colon || slash))
1845 /* if dev1:[dir]dev2:, move nm to dev2: */
1846 if (brack)
1848 nm = brack + 1;
1849 brack = 0;
1851 /* If /name/dev:, move nm to dev: */
1852 else if (slash)
1853 nm = slash + 1;
1854 /* If node::dev:, move colon following dev */
1855 else if (colon && colon[-1] == ':')
1856 colon = p;
1857 /* If dev1:dev2:, move nm to dev2: */
1858 else if (colon && colon[-1] != ':')
1860 nm = colon + 1;
1861 colon = 0;
1863 if (p[0] == ':' && !colon)
1865 if (p[1] == ':')
1866 p++;
1867 colon = p;
1869 if (lbrack == rbrack)
1870 if (p[0] == ';')
1871 dots = 2;
1872 else if (p[0] == '.')
1873 dots++;
1874 #endif /* VMS */
1875 p++;
1877 if (!lose)
1879 #ifdef VMS
1880 if (index (nm, '/'))
1881 return build_string (sys_translate_unix (nm));
1882 #endif /* VMS */
1883 if (nm == SDATA (name))
1884 return name;
1885 return build_string (nm);
1889 /* Now determine directory to start with and put it in NEWDIR */
1891 newdir = 0;
1893 if (nm[0] == '~') /* prefix ~ */
1894 if (nm[1] == '/'
1895 #ifdef VMS
1896 || nm[1] == ':'
1897 #endif /* VMS */
1898 || nm[1] == 0)/* ~/filename */
1900 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1901 newdir = (unsigned char *) "";
1902 nm++;
1903 #ifdef VMS
1904 nm++; /* Don't leave the slash in nm. */
1905 #endif /* VMS */
1907 else /* ~user/filename */
1909 /* Get past ~ to user */
1910 unsigned char *user = nm + 1;
1911 /* Find end of name. */
1912 unsigned char *ptr = (unsigned char *) index (user, '/');
1913 int len = ptr ? ptr - user : strlen (user);
1914 #ifdef VMS
1915 unsigned char *ptr1 = index (user, ':');
1916 if (ptr1 != 0 && ptr1 - user < len)
1917 len = ptr1 - user;
1918 #endif /* VMS */
1919 /* Copy the user name into temp storage. */
1920 o = (unsigned char *) alloca (len + 1);
1921 bcopy ((char *) user, o, len);
1922 o[len] = 0;
1924 /* Look up the user name. */
1925 BLOCK_INPUT;
1926 pw = (struct passwd *) getpwnam (o + 1);
1927 UNBLOCK_INPUT;
1928 if (!pw)
1929 error ("\"%s\" isn't a registered user", o + 1);
1931 newdir = (unsigned char *) pw->pw_dir;
1933 /* Discard the user name from NM. */
1934 nm += len;
1937 if (nm[0] != '/'
1938 #ifdef VMS
1939 && !index (nm, ':')
1940 #endif /* not VMS */
1941 && !newdir)
1943 if (NILP (defalt))
1944 defalt = current_buffer->directory;
1945 CHECK_STRING (defalt);
1946 newdir = SDATA (defalt);
1949 /* Now concatenate the directory and name to new space in the stack frame */
1951 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1952 target = (unsigned char *) alloca (tlen);
1953 *target = 0;
1955 if (newdir)
1957 #ifndef VMS
1958 if (nm[0] == 0 || nm[0] == '/')
1959 strcpy (target, newdir);
1960 else
1961 #endif
1962 file_name_as_directory (target, newdir);
1965 strcat (target, nm);
1966 #ifdef VMS
1967 if (index (target, '/'))
1968 strcpy (target, sys_translate_unix (target));
1969 #endif /* VMS */
1971 /* Now canonicalize by removing /. and /foo/.. if they appear */
1973 p = target;
1974 o = target;
1976 while (*p)
1978 #ifdef VMS
1979 if (*p != ']' && *p != '>' && *p != '-')
1981 if (*p == '\\')
1982 p++;
1983 *o++ = *p++;
1985 else if ((p[0] == ']' || p[0] == '>') && p[0] == p[1] + 2)
1986 /* brackets are offset from each other by 2 */
1988 p += 2;
1989 if (*p != '.' && *p != '-' && o[-1] != '.')
1990 /* convert [foo][bar] to [bar] */
1991 while (o[-1] != '[' && o[-1] != '<')
1992 o--;
1993 else if (*p == '-' && *o != '.')
1994 *--p = '.';
1996 else if (p[0] == '-' && o[-1] == '.'
1997 && (p[1] == '.' || p[1] == ']' || p[1] == '>'))
1998 /* flush .foo.- ; leave - if stopped by '[' or '<' */
2001 o--;
2002 while (o[-1] != '.' && o[-1] != '[' && o[-1] != '<');
2003 if (p[1] == '.') /* foo.-.bar ==> bar. */
2004 p += 2;
2005 else if (o[-1] == '.') /* '.foo.-]' ==> ']' */
2006 p++, o--;
2007 /* else [foo.-] ==> [-] */
2009 else
2011 #ifndef VMS4_4
2012 if (*p == '-'
2013 && o[-1] != '[' && o[-1] != '<' && o[-1] != '.'
2014 && p[1] != ']' && p[1] != '>' && p[1] != '.')
2015 *p = '_';
2016 #endif /* VMS4_4 */
2017 *o++ = *p++;
2019 #else /* not VMS */
2020 if (*p != '/')
2022 *o++ = *p++;
2024 else if (!strncmp (p, "//", 2)
2025 #ifdef APOLLO
2026 /* // at start of filename is meaningful in Apollo system. */
2027 && o != target
2028 #endif /* APOLLO */
2031 o = target;
2032 p++;
2034 else if (p[0] == '/' && p[1] == '.'
2035 && (p[2] == '/' || p[2] == 0))
2036 p += 2;
2037 else if (!strncmp (p, "/..", 3)
2038 /* `/../' is the "superroot" on certain file systems. */
2039 && o != target
2040 && (p[3] == '/' || p[3] == 0))
2042 while (o != target && *--o != '/')
2044 #ifdef APOLLO
2045 if (o == target + 1 && o[-1] == '/' && o[0] == '/')
2046 ++o;
2047 else
2048 #endif /* APOLLO */
2049 if (o == target && *o == '/')
2050 ++o;
2051 p += 3;
2053 else
2055 *o++ = *p++;
2057 #endif /* not VMS */
2060 return make_string (target, o - target);
2062 #endif
2064 /* If /~ or // appears, discard everything through first slash. */
2065 static int
2066 file_name_absolute_p (filename)
2067 const unsigned char *filename;
2069 return
2070 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
2071 #ifdef VMS
2072 /* ??? This criterion is probably wrong for '<'. */
2073 || index (filename, ':') || index (filename, '<')
2074 || (*filename == '[' && (filename[1] != '-'
2075 || (filename[2] != '.' && filename[2] != ']'))
2076 && filename[1] != '.')
2077 #endif /* VMS */
2078 #ifdef DOS_NT
2079 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
2080 && IS_DIRECTORY_SEP (filename[2]))
2081 #endif
2085 static unsigned char *
2086 search_embedded_absfilename (nm, endp)
2087 unsigned char *nm, *endp;
2089 unsigned char *p, *s;
2091 for (p = nm + 1; p < endp; p++)
2093 if ((0
2094 #ifdef VMS
2095 || p[-1] == ':' || p[-1] == ']' || p[-1] == '>'
2096 #endif /* VMS */
2097 || IS_DIRECTORY_SEP (p[-1]))
2098 && file_name_absolute_p (p)
2099 #if defined (APOLLO) || defined (WINDOWSNT) || defined(CYGWIN)
2100 /* // at start of file name is meaningful in Apollo,
2101 WindowsNT and Cygwin systems. */
2102 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
2103 #endif /* not (APOLLO || WINDOWSNT || CYGWIN) */
2106 for (s = p; *s && (!IS_DIRECTORY_SEP (*s)
2107 #ifdef VMS
2108 && *s != ':'
2109 #endif /* VMS */
2110 ); s++);
2111 if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
2113 unsigned char *o = alloca (s - p + 1);
2114 struct passwd *pw;
2115 bcopy (p, o, s - p);
2116 o [s - p] = 0;
2118 /* If we have ~user and `user' exists, discard
2119 everything up to ~. But if `user' does not exist, leave
2120 ~user alone, it might be a literal file name. */
2121 BLOCK_INPUT;
2122 pw = getpwnam (o + 1);
2123 UNBLOCK_INPUT;
2124 if (pw)
2125 return p;
2127 else
2128 return p;
2131 return NULL;
2134 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
2135 Ssubstitute_in_file_name, 1, 1, 0,
2136 doc: /* Substitute environment variables referred to in FILENAME.
2137 `$FOO' where FOO is an environment variable name means to substitute
2138 the value of that variable. The variable name should be terminated
2139 with a character not a letter, digit or underscore; otherwise, enclose
2140 the entire variable name in braces.
2141 If `/~' appears, all of FILENAME through that `/' is discarded.
2143 On VMS, `$' substitution is not done; this function does little and only
2144 duplicates what `expand-file-name' does. */)
2145 (filename)
2146 Lisp_Object filename;
2148 unsigned char *nm;
2150 register unsigned char *s, *p, *o, *x, *endp;
2151 unsigned char *target = NULL;
2152 int total = 0;
2153 int substituted = 0;
2154 unsigned char *xnm;
2155 Lisp_Object handler;
2157 CHECK_STRING (filename);
2159 /* If the file name has special constructs in it,
2160 call the corresponding file handler. */
2161 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
2162 if (!NILP (handler))
2163 return call2 (handler, Qsubstitute_in_file_name, filename);
2165 nm = SDATA (filename);
2166 #ifdef DOS_NT
2167 nm = strcpy (alloca (strlen (nm) + 1), nm);
2168 CORRECT_DIR_SEPS (nm);
2169 substituted = (strcmp (nm, SDATA (filename)) != 0);
2170 #endif
2171 endp = nm + SBYTES (filename);
2173 /* If /~ or // appears, discard everything through first slash. */
2174 p = search_embedded_absfilename (nm, endp);
2175 if (p)
2176 /* Start over with the new string, so we check the file-name-handler
2177 again. Important with filenames like "/home/foo//:/hello///there"
2178 which whould substitute to "/:/hello///there" rather than "/there". */
2179 return Fsubstitute_in_file_name
2180 (make_specified_string (p, -1, endp - p,
2181 STRING_MULTIBYTE (filename)));
2183 #ifdef VMS
2184 return filename;
2185 #else
2187 /* See if any variables are substituted into the string
2188 and find the total length of their values in `total' */
2190 for (p = nm; p != endp;)
2191 if (*p != '$')
2192 p++;
2193 else
2195 p++;
2196 if (p == endp)
2197 goto badsubst;
2198 else if (*p == '$')
2200 /* "$$" means a single "$" */
2201 p++;
2202 total -= 1;
2203 substituted = 1;
2204 continue;
2206 else if (*p == '{')
2208 o = ++p;
2209 while (p != endp && *p != '}') p++;
2210 if (*p != '}') goto missingclose;
2211 s = p;
2213 else
2215 o = p;
2216 while (p != endp && (isalnum (*p) || *p == '_')) p++;
2217 s = p;
2220 /* Copy out the variable name */
2221 target = (unsigned char *) alloca (s - o + 1);
2222 strncpy (target, o, s - o);
2223 target[s - o] = 0;
2224 #ifdef DOS_NT
2225 strupr (target); /* $home == $HOME etc. */
2226 #endif /* DOS_NT */
2228 /* Get variable value */
2229 o = (unsigned char *) egetenv (target);
2230 if (o)
2232 total += strlen (o);
2233 substituted = 1;
2235 else if (*p == '}')
2236 goto badvar;
2239 if (!substituted)
2240 return filename;
2242 /* If substitution required, recopy the string and do it */
2243 /* Make space in stack frame for the new copy */
2244 xnm = (unsigned char *) alloca (SBYTES (filename) + total + 1);
2245 x = xnm;
2247 /* Copy the rest of the name through, replacing $ constructs with values */
2248 for (p = nm; *p;)
2249 if (*p != '$')
2250 *x++ = *p++;
2251 else
2253 p++;
2254 if (p == endp)
2255 goto badsubst;
2256 else if (*p == '$')
2258 *x++ = *p++;
2259 continue;
2261 else if (*p == '{')
2263 o = ++p;
2264 while (p != endp && *p != '}') p++;
2265 if (*p != '}') goto missingclose;
2266 s = p++;
2268 else
2270 o = p;
2271 while (p != endp && (isalnum (*p) || *p == '_')) p++;
2272 s = p;
2275 /* Copy out the variable name */
2276 target = (unsigned char *) alloca (s - o + 1);
2277 strncpy (target, o, s - o);
2278 target[s - o] = 0;
2279 #ifdef DOS_NT
2280 strupr (target); /* $home == $HOME etc. */
2281 #endif /* DOS_NT */
2283 /* Get variable value */
2284 o = (unsigned char *) egetenv (target);
2285 if (!o)
2287 *x++ = '$';
2288 strcpy (x, target); x+= strlen (target);
2290 else if (STRING_MULTIBYTE (filename))
2292 /* If the original string is multibyte,
2293 convert what we substitute into multibyte. */
2294 while (*o)
2296 int c = unibyte_char_to_multibyte (*o++);
2297 x += CHAR_STRING (c, x);
2300 else
2302 strcpy (x, o);
2303 x += strlen (o);
2307 *x = 0;
2309 /* If /~ or // appears, discard everything through first slash. */
2310 while ((p = search_embedded_absfilename (xnm, x)))
2311 /* This time we do not start over because we've already expanded envvars
2312 and replaced $$ with $. Maybe we should start over as well, but we'd
2313 need to quote some $ to $$ first. */
2314 xnm = p;
2316 return make_specified_string (xnm, -1, x - xnm, STRING_MULTIBYTE (filename));
2318 badsubst:
2319 error ("Bad format environment-variable substitution");
2320 missingclose:
2321 error ("Missing \"}\" in environment-variable substitution");
2322 badvar:
2323 error ("Substituting nonexistent environment variable \"%s\"", target);
2325 /* NOTREACHED */
2326 #endif /* not VMS */
2327 return Qnil;
2330 /* A slightly faster and more convenient way to get
2331 (directory-file-name (expand-file-name FOO)). */
2333 Lisp_Object
2334 expand_and_dir_to_file (filename, defdir)
2335 Lisp_Object filename, defdir;
2337 register Lisp_Object absname;
2339 absname = Fexpand_file_name (filename, defdir);
2340 #ifdef VMS
2342 register int c = SREF (absname, SBYTES (absname) - 1);
2343 if (c == ':' || c == ']' || c == '>')
2344 absname = Fdirectory_file_name (absname);
2346 #else
2347 /* Remove final slash, if any (unless this is the root dir).
2348 stat behaves differently depending! */
2349 if (SCHARS (absname) > 1
2350 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
2351 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
2352 /* We cannot take shortcuts; they might be wrong for magic file names. */
2353 absname = Fdirectory_file_name (absname);
2354 #endif
2355 return absname;
2358 /* Signal an error if the file ABSNAME already exists.
2359 If INTERACTIVE is nonzero, ask the user whether to proceed,
2360 and bypass the error if the user says to go ahead.
2361 QUERYSTRING is a name for the action that is being considered
2362 to alter the file.
2364 *STATPTR is used to store the stat information if the file exists.
2365 If the file does not exist, STATPTR->st_mode is set to 0.
2366 If STATPTR is null, we don't store into it.
2368 If QUICK is nonzero, we ask for y or n, not yes or no. */
2370 void
2371 barf_or_query_if_file_exists (absname, querystring, interactive, statptr, quick)
2372 Lisp_Object absname;
2373 unsigned char *querystring;
2374 int interactive;
2375 struct stat *statptr;
2376 int quick;
2378 register Lisp_Object tem, encoded_filename;
2379 struct stat statbuf;
2380 struct gcpro gcpro1;
2382 encoded_filename = ENCODE_FILE (absname);
2384 /* stat is a good way to tell whether the file exists,
2385 regardless of what access permissions it has. */
2386 if (lstat (SDATA (encoded_filename), &statbuf) >= 0)
2388 if (! interactive)
2389 xsignal2 (Qfile_already_exists,
2390 build_string ("File already exists"), absname);
2391 GCPRO1 (absname);
2392 tem = format2 ("File %s already exists; %s anyway? ",
2393 absname, build_string (querystring));
2394 if (quick)
2395 tem = Fy_or_n_p (tem);
2396 else
2397 tem = do_yes_or_no_p (tem);
2398 UNGCPRO;
2399 if (NILP (tem))
2400 xsignal2 (Qfile_already_exists,
2401 build_string ("File already exists"), absname);
2402 if (statptr)
2403 *statptr = statbuf;
2405 else
2407 if (statptr)
2408 statptr->st_mode = 0;
2410 return;
2413 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 5,
2414 "fCopy file: \nGCopy %s to file: \np\nP",
2415 doc: /* Copy FILE to NEWNAME. Both args must be strings.
2416 If NEWNAME names a directory, copy FILE there.
2418 This function always sets the file modes of the output file to match
2419 the input file.
2421 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
2422 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
2423 signal a `file-already-exists' error without overwriting. If
2424 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
2425 about overwriting; this is what happens in interactive use with M-x.
2426 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
2427 existing file.
2429 Fourth arg KEEP-TIME non-nil means give the output file the same
2430 last-modified time as the old one. (This works on only some systems.)
2432 A prefix arg makes KEEP-TIME non-nil.
2434 If PRESERVE-UID-GID is non-nil, we try to transfer the
2435 uid and gid of FILE to NEWNAME. */)
2436 (file, newname, ok_if_already_exists, keep_time, preserve_uid_gid)
2437 Lisp_Object file, newname, ok_if_already_exists, keep_time;
2438 Lisp_Object preserve_uid_gid;
2440 int ifd, ofd, n;
2441 char buf[16 * 1024];
2442 struct stat st, out_st;
2443 Lisp_Object handler;
2444 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2445 int count = SPECPDL_INDEX ();
2446 int input_file_statable_p;
2447 Lisp_Object encoded_file, encoded_newname;
2449 encoded_file = encoded_newname = Qnil;
2450 GCPRO4 (file, newname, encoded_file, encoded_newname);
2451 CHECK_STRING (file);
2452 CHECK_STRING (newname);
2454 if (!NILP (Ffile_directory_p (newname)))
2455 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2456 else
2457 newname = Fexpand_file_name (newname, Qnil);
2459 file = Fexpand_file_name (file, Qnil);
2461 /* If the input file name has special constructs in it,
2462 call the corresponding file handler. */
2463 handler = Ffind_file_name_handler (file, Qcopy_file);
2464 /* Likewise for output file name. */
2465 if (NILP (handler))
2466 handler = Ffind_file_name_handler (newname, Qcopy_file);
2467 if (!NILP (handler))
2468 RETURN_UNGCPRO (call6 (handler, Qcopy_file, file, newname,
2469 ok_if_already_exists, keep_time, preserve_uid_gid));
2471 encoded_file = ENCODE_FILE (file);
2472 encoded_newname = ENCODE_FILE (newname);
2474 if (NILP (ok_if_already_exists)
2475 || INTEGERP (ok_if_already_exists))
2476 barf_or_query_if_file_exists (newname, "copy to it",
2477 INTEGERP (ok_if_already_exists), &out_st, 0);
2478 else if (stat (SDATA (encoded_newname), &out_st) < 0)
2479 out_st.st_mode = 0;
2481 #ifdef WINDOWSNT
2482 if (!CopyFile (SDATA (encoded_file),
2483 SDATA (encoded_newname),
2484 FALSE))
2485 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
2486 /* CopyFile retains the timestamp by default. */
2487 else if (NILP (keep_time))
2489 EMACS_TIME now;
2490 DWORD attributes;
2491 char * filename;
2493 EMACS_GET_TIME (now);
2494 filename = SDATA (encoded_newname);
2496 /* Ensure file is writable while its modified time is set. */
2497 attributes = GetFileAttributes (filename);
2498 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
2499 if (set_file_times (filename, now, now))
2501 /* Restore original attributes. */
2502 SetFileAttributes (filename, attributes);
2503 xsignal2 (Qfile_date_error,
2504 build_string ("Cannot set file date"), newname);
2506 /* Restore original attributes. */
2507 SetFileAttributes (filename, attributes);
2509 #else /* not WINDOWSNT */
2510 immediate_quit = 1;
2511 ifd = emacs_open (SDATA (encoded_file), O_RDONLY, 0);
2512 immediate_quit = 0;
2514 if (ifd < 0)
2515 report_file_error ("Opening input file", Fcons (file, Qnil));
2517 record_unwind_protect (close_file_unwind, make_number (ifd));
2519 /* We can only copy regular files and symbolic links. Other files are not
2520 copyable by us. */
2521 input_file_statable_p = (fstat (ifd, &st) >= 0);
2523 #if !defined (MSDOS) || __DJGPP__ > 1
2524 if (out_st.st_mode != 0
2525 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2527 errno = 0;
2528 report_file_error ("Input and output files are the same",
2529 Fcons (file, Fcons (newname, Qnil)));
2531 #endif
2533 #if defined (S_ISREG) && defined (S_ISLNK)
2534 if (input_file_statable_p)
2536 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
2538 #if defined (EISDIR)
2539 /* Get a better looking error message. */
2540 errno = EISDIR;
2541 #endif /* EISDIR */
2542 report_file_error ("Non-regular file", Fcons (file, Qnil));
2545 #endif /* S_ISREG && S_ISLNK */
2547 #ifdef VMS
2548 /* Create the copy file with the same record format as the input file */
2549 ofd = sys_creat (SDATA (encoded_newname), 0666, ifd);
2550 #else
2551 #ifdef MSDOS
2552 /* System's default file type was set to binary by _fmode in emacs.c. */
2553 ofd = emacs_open (SDATA (encoded_newname),
2554 O_WRONLY | O_TRUNC | O_CREAT
2555 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2556 S_IREAD | S_IWRITE);
2557 #else /* not MSDOS */
2558 ofd = emacs_open (SDATA (encoded_newname),
2559 O_WRONLY | O_TRUNC | O_CREAT
2560 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2561 0666);
2562 #endif /* not MSDOS */
2563 #endif /* VMS */
2564 if (ofd < 0)
2565 report_file_error ("Opening output file", Fcons (newname, Qnil));
2567 record_unwind_protect (close_file_unwind, make_number (ofd));
2569 immediate_quit = 1;
2570 QUIT;
2571 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2572 if (emacs_write (ofd, buf, n) != n)
2573 report_file_error ("I/O error", Fcons (newname, Qnil));
2574 immediate_quit = 0;
2576 #ifndef MSDOS
2577 /* Preserve the original file modes, and if requested, also its
2578 owner and group. */
2579 if (input_file_statable_p)
2581 if (! NILP (preserve_uid_gid))
2582 fchown (ofd, st.st_uid, st.st_gid);
2583 fchmod (ofd, st.st_mode & 07777);
2585 #endif /* not MSDOS */
2587 /* Closing the output clobbers the file times on some systems. */
2588 if (emacs_close (ofd) < 0)
2589 report_file_error ("I/O error", Fcons (newname, Qnil));
2591 if (input_file_statable_p)
2593 if (!NILP (keep_time))
2595 EMACS_TIME atime, mtime;
2596 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2597 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2598 if (set_file_times (SDATA (encoded_newname),
2599 atime, mtime))
2600 xsignal2 (Qfile_date_error,
2601 build_string ("Cannot set file date"), newname);
2605 emacs_close (ifd);
2607 #if defined (__DJGPP__) && __DJGPP__ > 1
2608 if (input_file_statable_p)
2610 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2611 and if it can't, it tells so. Otherwise, under MSDOS we usually
2612 get only the READ bit, which will make the copied file read-only,
2613 so it's better not to chmod at all. */
2614 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2615 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2617 #endif /* DJGPP version 2 or newer */
2618 #endif /* not WINDOWSNT */
2620 /* Discard the unwind protects. */
2621 specpdl_ptr = specpdl + count;
2623 UNGCPRO;
2624 return Qnil;
2627 DEFUN ("make-directory-internal", Fmake_directory_internal,
2628 Smake_directory_internal, 1, 1, 0,
2629 doc: /* Create a new directory named DIRECTORY. */)
2630 (directory)
2631 Lisp_Object directory;
2633 const unsigned char *dir;
2634 Lisp_Object handler;
2635 Lisp_Object encoded_dir;
2637 CHECK_STRING (directory);
2638 directory = Fexpand_file_name (directory, Qnil);
2640 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2641 if (!NILP (handler))
2642 return call2 (handler, Qmake_directory_internal, directory);
2644 encoded_dir = ENCODE_FILE (directory);
2646 dir = SDATA (encoded_dir);
2648 #ifdef WINDOWSNT
2649 if (mkdir (dir) != 0)
2650 #else
2651 if (mkdir (dir, 0777) != 0)
2652 #endif
2653 report_file_error ("Creating directory", list1 (directory));
2655 return Qnil;
2658 DEFUN ("delete-directory", Fdelete_directory, Sdelete_directory, 1, 1, "FDelete directory: ",
2659 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2660 (directory)
2661 Lisp_Object directory;
2663 const unsigned char *dir;
2664 Lisp_Object handler;
2665 Lisp_Object encoded_dir;
2667 CHECK_STRING (directory);
2668 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2670 handler = Ffind_file_name_handler (directory, Qdelete_directory);
2671 if (!NILP (handler))
2672 return call2 (handler, Qdelete_directory, directory);
2674 encoded_dir = ENCODE_FILE (directory);
2676 dir = SDATA (encoded_dir);
2678 if (rmdir (dir) != 0)
2679 report_file_error ("Removing directory", list1 (directory));
2681 return Qnil;
2684 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 1, "fDelete file: ",
2685 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2686 If file has multiple names, it continues to exist with the other names. */)
2687 (filename)
2688 Lisp_Object filename;
2690 Lisp_Object handler;
2691 Lisp_Object encoded_file;
2692 struct gcpro gcpro1;
2694 GCPRO1 (filename);
2695 if (!NILP (Ffile_directory_p (filename))
2696 && NILP (Ffile_symlink_p (filename)))
2697 xsignal2 (Qfile_error,
2698 build_string ("Removing old name: is a directory"),
2699 filename);
2700 UNGCPRO;
2701 filename = Fexpand_file_name (filename, Qnil);
2703 handler = Ffind_file_name_handler (filename, Qdelete_file);
2704 if (!NILP (handler))
2705 return call2 (handler, Qdelete_file, filename);
2707 encoded_file = ENCODE_FILE (filename);
2709 if (0 > unlink (SDATA (encoded_file)))
2710 report_file_error ("Removing old name", list1 (filename));
2711 return Qnil;
2714 static Lisp_Object
2715 internal_delete_file_1 (ignore)
2716 Lisp_Object ignore;
2718 return Qt;
2721 /* Delete file FILENAME, returning 1 if successful and 0 if failed. */
2724 internal_delete_file (filename)
2725 Lisp_Object filename;
2727 Lisp_Object tem;
2728 tem = internal_condition_case_1 (Fdelete_file, filename,
2729 Qt, internal_delete_file_1);
2730 return NILP (tem);
2733 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2734 "fRename file: \nGRename %s to file: \np",
2735 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2736 If file has names other than FILE, it continues to have those names.
2737 Signals a `file-already-exists' error if a file NEWNAME already exists
2738 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2739 A number as third arg means request confirmation if NEWNAME already exists.
2740 This is what happens in interactive use with M-x. */)
2741 (file, newname, ok_if_already_exists)
2742 Lisp_Object file, newname, ok_if_already_exists;
2744 Lisp_Object handler;
2745 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2746 Lisp_Object encoded_file, encoded_newname, symlink_target;
2748 symlink_target = encoded_file = encoded_newname = Qnil;
2749 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2750 CHECK_STRING (file);
2751 CHECK_STRING (newname);
2752 file = Fexpand_file_name (file, Qnil);
2754 if ((!NILP (Ffile_directory_p (newname)))
2755 #ifdef DOS_NT
2756 /* If the file names are identical but for the case,
2757 don't attempt to move directory to itself. */
2758 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2759 #endif
2761 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2762 else
2763 newname = Fexpand_file_name (newname, Qnil);
2765 /* If the file name has special constructs in it,
2766 call the corresponding file handler. */
2767 handler = Ffind_file_name_handler (file, Qrename_file);
2768 if (NILP (handler))
2769 handler = Ffind_file_name_handler (newname, Qrename_file);
2770 if (!NILP (handler))
2771 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2772 file, newname, ok_if_already_exists));
2774 encoded_file = ENCODE_FILE (file);
2775 encoded_newname = ENCODE_FILE (newname);
2777 #ifdef DOS_NT
2778 /* If the file names are identical but for the case, don't ask for
2779 confirmation: they simply want to change the letter-case of the
2780 file name. */
2781 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2782 #endif
2783 if (NILP (ok_if_already_exists)
2784 || INTEGERP (ok_if_already_exists))
2785 barf_or_query_if_file_exists (newname, "rename to it",
2786 INTEGERP (ok_if_already_exists), 0, 0);
2787 #ifndef BSD4_1
2788 if (0 > rename (SDATA (encoded_file), SDATA (encoded_newname)))
2789 #else
2790 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname))
2791 || 0 > unlink (SDATA (encoded_file)))
2792 #endif
2794 if (errno == EXDEV)
2796 #ifdef S_IFLNK
2797 symlink_target = Ffile_symlink_p (file);
2798 if (! NILP (symlink_target))
2799 Fmake_symbolic_link (symlink_target, newname,
2800 NILP (ok_if_already_exists) ? Qnil : Qt);
2801 else
2802 #endif
2803 Fcopy_file (file, newname,
2804 /* We have already prompted if it was an integer,
2805 so don't have copy-file prompt again. */
2806 NILP (ok_if_already_exists) ? Qnil : Qt,
2807 Qt, Qt);
2809 Fdelete_file (file);
2811 else
2812 report_file_error ("Renaming", list2 (file, newname));
2814 UNGCPRO;
2815 return Qnil;
2818 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2819 "fAdd name to file: \nGName to add to %s: \np",
2820 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2821 Signals a `file-already-exists' error if a file NEWNAME already exists
2822 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2823 A number as third arg means request confirmation if NEWNAME already exists.
2824 This is what happens in interactive use with M-x. */)
2825 (file, newname, ok_if_already_exists)
2826 Lisp_Object file, newname, ok_if_already_exists;
2828 Lisp_Object handler;
2829 Lisp_Object encoded_file, encoded_newname;
2830 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2832 GCPRO4 (file, newname, encoded_file, encoded_newname);
2833 encoded_file = encoded_newname = Qnil;
2834 CHECK_STRING (file);
2835 CHECK_STRING (newname);
2836 file = Fexpand_file_name (file, Qnil);
2838 if (!NILP (Ffile_directory_p (newname)))
2839 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2840 else
2841 newname = Fexpand_file_name (newname, Qnil);
2843 /* If the file name has special constructs in it,
2844 call the corresponding file handler. */
2845 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2846 if (!NILP (handler))
2847 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2848 newname, ok_if_already_exists));
2850 /* If the new name has special constructs in it,
2851 call the corresponding file handler. */
2852 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2853 if (!NILP (handler))
2854 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2855 newname, ok_if_already_exists));
2857 encoded_file = ENCODE_FILE (file);
2858 encoded_newname = ENCODE_FILE (newname);
2860 if (NILP (ok_if_already_exists)
2861 || INTEGERP (ok_if_already_exists))
2862 barf_or_query_if_file_exists (newname, "make it a new name",
2863 INTEGERP (ok_if_already_exists), 0, 0);
2865 unlink (SDATA (newname));
2866 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname)))
2867 report_file_error ("Adding new name", list2 (file, newname));
2869 UNGCPRO;
2870 return Qnil;
2873 #ifdef S_IFLNK
2874 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2875 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2876 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2877 Both args must be strings.
2878 Signals a `file-already-exists' error if a file LINKNAME already exists
2879 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2880 A number as third arg means request confirmation if LINKNAME already exists.
2881 This happens for interactive use with M-x. */)
2882 (filename, linkname, ok_if_already_exists)
2883 Lisp_Object filename, linkname, ok_if_already_exists;
2885 Lisp_Object handler;
2886 Lisp_Object encoded_filename, encoded_linkname;
2887 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2889 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2890 encoded_filename = encoded_linkname = Qnil;
2891 CHECK_STRING (filename);
2892 CHECK_STRING (linkname);
2893 /* If the link target has a ~, we must expand it to get
2894 a truly valid file name. Otherwise, do not expand;
2895 we want to permit links to relative file names. */
2896 if (SREF (filename, 0) == '~')
2897 filename = Fexpand_file_name (filename, Qnil);
2899 if (!NILP (Ffile_directory_p (linkname)))
2900 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2901 else
2902 linkname = Fexpand_file_name (linkname, Qnil);
2904 /* If the file name has special constructs in it,
2905 call the corresponding file handler. */
2906 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2907 if (!NILP (handler))
2908 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2909 linkname, ok_if_already_exists));
2911 /* If the new link name has special constructs in it,
2912 call the corresponding file handler. */
2913 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2914 if (!NILP (handler))
2915 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2916 linkname, ok_if_already_exists));
2918 encoded_filename = ENCODE_FILE (filename);
2919 encoded_linkname = ENCODE_FILE (linkname);
2921 if (NILP (ok_if_already_exists)
2922 || INTEGERP (ok_if_already_exists))
2923 barf_or_query_if_file_exists (linkname, "make it a link",
2924 INTEGERP (ok_if_already_exists), 0, 0);
2925 if (0 > symlink (SDATA (encoded_filename),
2926 SDATA (encoded_linkname)))
2928 /* If we didn't complain already, silently delete existing file. */
2929 if (errno == EEXIST)
2931 unlink (SDATA (encoded_linkname));
2932 if (0 <= symlink (SDATA (encoded_filename),
2933 SDATA (encoded_linkname)))
2935 UNGCPRO;
2936 return Qnil;
2940 report_file_error ("Making symbolic link", list2 (filename, linkname));
2942 UNGCPRO;
2943 return Qnil;
2945 #endif /* S_IFLNK */
2947 #ifdef VMS
2949 DEFUN ("define-logical-name", Fdefine_logical_name, Sdefine_logical_name,
2950 2, 2, "sDefine logical name: \nsDefine logical name %s as: ",
2951 doc: /* Define the job-wide logical name NAME to have the value STRING.
2952 If STRING is nil or a null string, the logical name NAME is deleted. */)
2953 (name, string)
2954 Lisp_Object name;
2955 Lisp_Object string;
2957 CHECK_STRING (name);
2958 if (NILP (string))
2959 delete_logical_name (SDATA (name));
2960 else
2962 CHECK_STRING (string);
2964 if (SCHARS (string) == 0)
2965 delete_logical_name (SDATA (name));
2966 else
2967 define_logical_name (SDATA (name), SDATA (string));
2970 return string;
2972 #endif /* VMS */
2974 #ifdef HPUX_NET
2976 DEFUN ("sysnetunam", Fsysnetunam, Ssysnetunam, 2, 2, 0,
2977 doc: /* Open a network connection to PATH using LOGIN as the login string. */)
2978 (path, login)
2979 Lisp_Object path, login;
2981 int netresult;
2983 CHECK_STRING (path);
2984 CHECK_STRING (login);
2986 netresult = netunam (SDATA (path), SDATA (login));
2988 if (netresult == -1)
2989 return Qnil;
2990 else
2991 return Qt;
2993 #endif /* HPUX_NET */
2995 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2996 1, 1, 0,
2997 doc: /* Return t if file FILENAME specifies an absolute file name.
2998 On Unix, this is a name starting with a `/' or a `~'. */)
2999 (filename)
3000 Lisp_Object filename;
3002 CHECK_STRING (filename);
3003 return file_name_absolute_p (SDATA (filename)) ? Qt : Qnil;
3006 /* Return nonzero if file FILENAME exists and can be executed. */
3008 static int
3009 check_executable (filename)
3010 char *filename;
3012 #ifdef DOS_NT
3013 int len = strlen (filename);
3014 char *suffix;
3015 struct stat st;
3016 if (stat (filename, &st) < 0)
3017 return 0;
3018 #if defined (WINDOWSNT) || (defined (MSDOS) && __DJGPP__ > 1)
3019 return ((st.st_mode & S_IEXEC) != 0);
3020 #else
3021 return (S_ISREG (st.st_mode)
3022 && len >= 5
3023 && (stricmp ((suffix = filename + len-4), ".com") == 0
3024 || stricmp (suffix, ".exe") == 0
3025 || stricmp (suffix, ".bat") == 0)
3026 || (st.st_mode & S_IFMT) == S_IFDIR);
3027 #endif /* not WINDOWSNT */
3028 #else /* not DOS_NT */
3029 #ifdef HAVE_EUIDACCESS
3030 return (euidaccess (filename, 1) >= 0);
3031 #else
3032 /* Access isn't quite right because it uses the real uid
3033 and we really want to test with the effective uid.
3034 But Unix doesn't give us a right way to do it. */
3035 return (access (filename, 1) >= 0);
3036 #endif
3037 #endif /* not DOS_NT */
3040 /* Return nonzero if file FILENAME exists and can be written. */
3042 static int
3043 check_writable (filename)
3044 char *filename;
3046 #ifdef MSDOS
3047 struct stat st;
3048 if (stat (filename, &st) < 0)
3049 return 0;
3050 return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
3051 #else /* not MSDOS */
3052 #ifdef HAVE_EUIDACCESS
3053 return (euidaccess (filename, 2) >= 0);
3054 #else
3055 /* Access isn't quite right because it uses the real uid
3056 and we really want to test with the effective uid.
3057 But Unix doesn't give us a right way to do it.
3058 Opening with O_WRONLY could work for an ordinary file,
3059 but would lose for directories. */
3060 return (access (filename, 2) >= 0);
3061 #endif
3062 #endif /* not MSDOS */
3065 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
3066 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
3067 See also `file-readable-p' and `file-attributes'.
3068 This returns nil for a symlink to a nonexistent file.
3069 Use `file-symlink-p' to test for such links. */)
3070 (filename)
3071 Lisp_Object filename;
3073 Lisp_Object absname;
3074 Lisp_Object handler;
3075 struct stat statbuf;
3077 CHECK_STRING (filename);
3078 absname = Fexpand_file_name (filename, Qnil);
3080 /* If the file name has special constructs in it,
3081 call the corresponding file handler. */
3082 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
3083 if (!NILP (handler))
3084 return call2 (handler, Qfile_exists_p, absname);
3086 absname = ENCODE_FILE (absname);
3088 return (stat (SDATA (absname), &statbuf) >= 0) ? Qt : Qnil;
3091 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
3092 doc: /* Return t if FILENAME can be executed by you.
3093 For a directory, this means you can access files in that directory. */)
3094 (filename)
3095 Lisp_Object filename;
3097 Lisp_Object absname;
3098 Lisp_Object handler;
3100 CHECK_STRING (filename);
3101 absname = Fexpand_file_name (filename, Qnil);
3103 /* If the file name has special constructs in it,
3104 call the corresponding file handler. */
3105 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
3106 if (!NILP (handler))
3107 return call2 (handler, Qfile_executable_p, absname);
3109 absname = ENCODE_FILE (absname);
3111 return (check_executable (SDATA (absname)) ? Qt : Qnil);
3114 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
3115 doc: /* Return t if file FILENAME exists and you can read it.
3116 See also `file-exists-p' and `file-attributes'. */)
3117 (filename)
3118 Lisp_Object filename;
3120 Lisp_Object absname;
3121 Lisp_Object handler;
3122 int desc;
3123 int flags;
3124 struct stat statbuf;
3126 CHECK_STRING (filename);
3127 absname = Fexpand_file_name (filename, Qnil);
3129 /* If the file name has special constructs in it,
3130 call the corresponding file handler. */
3131 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
3132 if (!NILP (handler))
3133 return call2 (handler, Qfile_readable_p, absname);
3135 absname = ENCODE_FILE (absname);
3137 #if defined(DOS_NT) || defined(macintosh)
3138 /* Under MS-DOS, Windows, and Macintosh, open does not work for
3139 directories. */
3140 if (access (SDATA (absname), 0) == 0)
3141 return Qt;
3142 return Qnil;
3143 #else /* not DOS_NT and not macintosh */
3144 flags = O_RDONLY;
3145 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
3146 /* Opening a fifo without O_NONBLOCK can wait.
3147 We don't want to wait. But we don't want to mess wth O_NONBLOCK
3148 except in the case of a fifo, on a system which handles it. */
3149 desc = stat (SDATA (absname), &statbuf);
3150 if (desc < 0)
3151 return Qnil;
3152 if (S_ISFIFO (statbuf.st_mode))
3153 flags |= O_NONBLOCK;
3154 #endif
3155 desc = emacs_open (SDATA (absname), flags, 0);
3156 if (desc < 0)
3157 return Qnil;
3158 emacs_close (desc);
3159 return Qt;
3160 #endif /* not DOS_NT and not macintosh */
3163 /* Having this before file-symlink-p mysteriously caused it to be forgotten
3164 on the RT/PC. */
3165 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
3166 doc: /* Return t if file FILENAME can be written or created by you. */)
3167 (filename)
3168 Lisp_Object filename;
3170 Lisp_Object absname, dir, encoded;
3171 Lisp_Object handler;
3172 struct stat statbuf;
3174 CHECK_STRING (filename);
3175 absname = Fexpand_file_name (filename, Qnil);
3177 /* If the file name has special constructs in it,
3178 call the corresponding file handler. */
3179 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
3180 if (!NILP (handler))
3181 return call2 (handler, Qfile_writable_p, absname);
3183 encoded = ENCODE_FILE (absname);
3184 if (stat (SDATA (encoded), &statbuf) >= 0)
3185 return (check_writable (SDATA (encoded))
3186 ? Qt : Qnil);
3188 dir = Ffile_name_directory (absname);
3189 #ifdef VMS
3190 if (!NILP (dir))
3191 dir = Fdirectory_file_name (dir);
3192 #endif /* VMS */
3193 #ifdef MSDOS
3194 if (!NILP (dir))
3195 dir = Fdirectory_file_name (dir);
3196 #endif /* MSDOS */
3198 dir = ENCODE_FILE (dir);
3199 #ifdef WINDOWSNT
3200 /* The read-only attribute of the parent directory doesn't affect
3201 whether a file or directory can be created within it. Some day we
3202 should check ACLs though, which do affect this. */
3203 if (stat (SDATA (dir), &statbuf) < 0)
3204 return Qnil;
3205 return (statbuf.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
3206 #else
3207 return (check_writable (!NILP (dir) ? (char *) SDATA (dir) : "")
3208 ? Qt : Qnil);
3209 #endif
3212 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
3213 doc: /* Access file FILENAME, and get an error if that does not work.
3214 The second argument STRING is used in the error message.
3215 If there is no error, returns nil. */)
3216 (filename, string)
3217 Lisp_Object filename, string;
3219 Lisp_Object handler, encoded_filename, absname;
3220 int fd;
3222 CHECK_STRING (filename);
3223 absname = Fexpand_file_name (filename, Qnil);
3225 CHECK_STRING (string);
3227 /* If the file name has special constructs in it,
3228 call the corresponding file handler. */
3229 handler = Ffind_file_name_handler (absname, Qaccess_file);
3230 if (!NILP (handler))
3231 return call3 (handler, Qaccess_file, absname, string);
3233 encoded_filename = ENCODE_FILE (absname);
3235 fd = emacs_open (SDATA (encoded_filename), O_RDONLY, 0);
3236 if (fd < 0)
3237 report_file_error (SDATA (string), Fcons (filename, Qnil));
3238 emacs_close (fd);
3240 return Qnil;
3243 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
3244 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
3245 The value is the link target, as a string.
3246 Otherwise it returns nil.
3248 This function returns t when given the name of a symlink that
3249 points to a nonexistent file. */)
3250 (filename)
3251 Lisp_Object filename;
3253 Lisp_Object handler;
3255 CHECK_STRING (filename);
3256 filename = Fexpand_file_name (filename, Qnil);
3258 /* If the file name has special constructs in it,
3259 call the corresponding file handler. */
3260 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
3261 if (!NILP (handler))
3262 return call2 (handler, Qfile_symlink_p, filename);
3264 #ifdef S_IFLNK
3266 char *buf;
3267 int bufsize;
3268 int valsize;
3269 Lisp_Object val;
3271 filename = ENCODE_FILE (filename);
3273 bufsize = 50;
3274 buf = NULL;
3277 bufsize *= 2;
3278 buf = (char *) xrealloc (buf, bufsize);
3279 bzero (buf, bufsize);
3281 errno = 0;
3282 valsize = readlink (SDATA (filename), buf, bufsize);
3283 if (valsize == -1)
3285 #ifdef ERANGE
3286 /* HP-UX reports ERANGE if buffer is too small. */
3287 if (errno == ERANGE)
3288 valsize = bufsize;
3289 else
3290 #endif
3292 xfree (buf);
3293 return Qnil;
3297 while (valsize >= bufsize);
3299 val = make_string (buf, valsize);
3300 if (buf[0] == '/' && index (buf, ':'))
3301 val = concat2 (build_string ("/:"), val);
3302 xfree (buf);
3303 val = DECODE_FILE (val);
3304 return val;
3306 #else /* not S_IFLNK */
3307 return Qnil;
3308 #endif /* not S_IFLNK */
3311 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
3312 doc: /* Return t if FILENAME names an existing directory.
3313 Symbolic links to directories count as directories.
3314 See `file-symlink-p' to distinguish symlinks. */)
3315 (filename)
3316 Lisp_Object filename;
3318 register Lisp_Object absname;
3319 struct stat st;
3320 Lisp_Object handler;
3322 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3324 /* If the file name has special constructs in it,
3325 call the corresponding file handler. */
3326 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
3327 if (!NILP (handler))
3328 return call2 (handler, Qfile_directory_p, absname);
3330 absname = ENCODE_FILE (absname);
3332 if (stat (SDATA (absname), &st) < 0)
3333 return Qnil;
3334 return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
3337 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
3338 doc: /* Return t if file FILENAME names a directory you can open.
3339 For the value to be t, FILENAME must specify the name of a directory as a file,
3340 and the directory must allow you to open files in it. In order to use a
3341 directory as a buffer's current directory, this predicate must return true.
3342 A directory name spec may be given instead; then the value is t
3343 if the directory so specified exists and really is a readable and
3344 searchable directory. */)
3345 (filename)
3346 Lisp_Object filename;
3348 Lisp_Object handler;
3349 int tem;
3350 struct gcpro gcpro1;
3352 /* If the file name has special constructs in it,
3353 call the corresponding file handler. */
3354 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
3355 if (!NILP (handler))
3356 return call2 (handler, Qfile_accessible_directory_p, filename);
3358 GCPRO1 (filename);
3359 tem = (NILP (Ffile_directory_p (filename))
3360 || NILP (Ffile_executable_p (filename)));
3361 UNGCPRO;
3362 return tem ? Qnil : Qt;
3365 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
3366 doc: /* Return t if FILENAME names a regular file.
3367 This is the sort of file that holds an ordinary stream of data bytes.
3368 Symbolic links to regular files count as regular files.
3369 See `file-symlink-p' to distinguish symlinks. */)
3370 (filename)
3371 Lisp_Object filename;
3373 register Lisp_Object absname;
3374 struct stat st;
3375 Lisp_Object handler;
3377 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3379 /* If the file name has special constructs in it,
3380 call the corresponding file handler. */
3381 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
3382 if (!NILP (handler))
3383 return call2 (handler, Qfile_regular_p, absname);
3385 absname = ENCODE_FILE (absname);
3387 #ifdef WINDOWSNT
3389 int result;
3390 Lisp_Object tem = Vw32_get_true_file_attributes;
3392 /* Tell stat to use expensive method to get accurate info. */
3393 Vw32_get_true_file_attributes = Qt;
3394 result = stat (SDATA (absname), &st);
3395 Vw32_get_true_file_attributes = tem;
3397 if (result < 0)
3398 return Qnil;
3399 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
3401 #else
3402 if (stat (SDATA (absname), &st) < 0)
3403 return Qnil;
3404 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
3405 #endif
3408 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3409 doc: /* Return mode bits of file named FILENAME, as an integer.
3410 Return nil, if file does not exist or is not accessible. */)
3411 (filename)
3412 Lisp_Object filename;
3414 Lisp_Object absname;
3415 struct stat st;
3416 Lisp_Object handler;
3418 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3420 /* If the file name has special constructs in it,
3421 call the corresponding file handler. */
3422 handler = Ffind_file_name_handler (absname, Qfile_modes);
3423 if (!NILP (handler))
3424 return call2 (handler, Qfile_modes, absname);
3426 absname = ENCODE_FILE (absname);
3428 if (stat (SDATA (absname), &st) < 0)
3429 return Qnil;
3430 #if defined (MSDOS) && __DJGPP__ < 2
3431 if (check_executable (SDATA (absname)))
3432 st.st_mode |= S_IEXEC;
3433 #endif /* MSDOS && __DJGPP__ < 2 */
3435 return make_number (st.st_mode & 07777);
3438 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3439 "(let ((file (read-file-name \"File: \"))) \
3440 (list file (read-file-modes nil file)))",
3441 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3442 Only the 12 low bits of MODE are used. */)
3443 (filename, mode)
3444 Lisp_Object filename, mode;
3446 Lisp_Object absname, encoded_absname;
3447 Lisp_Object handler;
3449 absname = Fexpand_file_name (filename, current_buffer->directory);
3450 CHECK_NUMBER (mode);
3452 /* If the file name has special constructs in it,
3453 call the corresponding file handler. */
3454 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3455 if (!NILP (handler))
3456 return call3 (handler, Qset_file_modes, absname, mode);
3458 encoded_absname = ENCODE_FILE (absname);
3460 if (chmod (SDATA (encoded_absname), XINT (mode)) < 0)
3461 report_file_error ("Doing chmod", Fcons (absname, Qnil));
3463 return Qnil;
3466 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3467 doc: /* Set the file permission bits for newly created files.
3468 The argument MODE should be an integer; only the low 9 bits are used.
3469 This setting is inherited by subprocesses. */)
3470 (mode)
3471 Lisp_Object mode;
3473 CHECK_NUMBER (mode);
3475 umask ((~ XINT (mode)) & 0777);
3477 return Qnil;
3480 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3481 doc: /* Return the default file protection for created files.
3482 The value is an integer. */)
3485 int realmask;
3486 Lisp_Object value;
3488 realmask = umask (0);
3489 umask (realmask);
3491 XSETINT (value, (~ realmask) & 0777);
3492 return value;
3495 extern int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
3497 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3498 doc: /* Set times of file FILENAME to TIME.
3499 Set both access and modification times.
3500 Return t on success, else nil.
3501 Use the current time if TIME is nil. TIME is in the format of
3502 `current-time'. */)
3503 (filename, time)
3504 Lisp_Object filename, time;
3506 Lisp_Object absname, encoded_absname;
3507 Lisp_Object handler;
3508 time_t sec;
3509 int usec;
3511 if (! lisp_time_argument (time, &sec, &usec))
3512 error ("Invalid time specification");
3514 absname = Fexpand_file_name (filename, current_buffer->directory);
3516 /* If the file name has special constructs in it,
3517 call the corresponding file handler. */
3518 handler = Ffind_file_name_handler (absname, Qset_file_times);
3519 if (!NILP (handler))
3520 return call3 (handler, Qset_file_times, absname, time);
3522 encoded_absname = ENCODE_FILE (absname);
3525 EMACS_TIME t;
3527 EMACS_SET_SECS (t, sec);
3528 EMACS_SET_USECS (t, usec);
3530 if (set_file_times (SDATA (encoded_absname), t, t))
3532 #ifdef DOS_NT
3533 struct stat st;
3535 /* Setting times on a directory always fails. */
3536 if (stat (SDATA (encoded_absname), &st) == 0
3537 && (st.st_mode & S_IFMT) == S_IFDIR)
3538 return Qnil;
3539 #endif
3540 report_file_error ("Setting file times", Fcons (absname, Qnil));
3541 return Qnil;
3545 return Qt;
3548 #ifdef HAVE_SYNC
3549 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3550 doc: /* Tell Unix to finish all pending disk updates. */)
3553 sync ();
3554 return Qnil;
3557 #endif /* HAVE_SYNC */
3559 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3560 doc: /* Return t if file FILE1 is newer than file FILE2.
3561 If FILE1 does not exist, the answer is nil;
3562 otherwise, if FILE2 does not exist, the answer is t. */)
3563 (file1, file2)
3564 Lisp_Object file1, file2;
3566 Lisp_Object absname1, absname2;
3567 struct stat st;
3568 int mtime1;
3569 Lisp_Object handler;
3570 struct gcpro gcpro1, gcpro2;
3572 CHECK_STRING (file1);
3573 CHECK_STRING (file2);
3575 absname1 = Qnil;
3576 GCPRO2 (absname1, file2);
3577 absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
3578 absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
3579 UNGCPRO;
3581 /* If the file name has special constructs in it,
3582 call the corresponding file handler. */
3583 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3584 if (NILP (handler))
3585 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3586 if (!NILP (handler))
3587 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3589 GCPRO2 (absname1, absname2);
3590 absname1 = ENCODE_FILE (absname1);
3591 absname2 = ENCODE_FILE (absname2);
3592 UNGCPRO;
3594 if (stat (SDATA (absname1), &st) < 0)
3595 return Qnil;
3597 mtime1 = st.st_mtime;
3599 if (stat (SDATA (absname2), &st) < 0)
3600 return Qt;
3602 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3605 #ifdef DOS_NT
3606 Lisp_Object Qfind_buffer_file_type;
3607 #endif /* DOS_NT */
3609 #ifndef READ_BUF_SIZE
3610 #define READ_BUF_SIZE (64 << 10)
3611 #endif
3613 extern void adjust_markers_for_delete P_ ((int, int, int, int));
3615 /* This function is called after Lisp functions to decide a coding
3616 system are called, or when they cause an error. Before they are
3617 called, the current buffer is set unibyte and it contains only a
3618 newly inserted text (thus the buffer was empty before the
3619 insertion).
3621 The functions may set markers, overlays, text properties, or even
3622 alter the buffer contents, change the current buffer.
3624 Here, we reset all those changes by:
3625 o set back the current buffer.
3626 o move all markers and overlays to BEG.
3627 o remove all text properties.
3628 o set back the buffer multibyteness. */
3630 static Lisp_Object
3631 decide_coding_unwind (unwind_data)
3632 Lisp_Object unwind_data;
3634 Lisp_Object multibyte, undo_list, buffer;
3636 multibyte = XCAR (unwind_data);
3637 unwind_data = XCDR (unwind_data);
3638 undo_list = XCAR (unwind_data);
3639 buffer = XCDR (unwind_data);
3641 if (current_buffer != XBUFFER (buffer))
3642 set_buffer_internal (XBUFFER (buffer));
3643 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3644 adjust_overlays_for_delete (BEG, Z - BEG);
3645 BUF_INTERVALS (current_buffer) = 0;
3646 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3648 /* Now we are safe to change the buffer's multibyteness directly. */
3649 current_buffer->enable_multibyte_characters = multibyte;
3650 current_buffer->undo_list = undo_list;
3652 return Qnil;
3656 /* Used to pass values from insert-file-contents to read_non_regular. */
3658 static int non_regular_fd;
3659 static int non_regular_inserted;
3660 static int non_regular_nbytes;
3663 /* Read from a non-regular file.
3664 Read non_regular_trytry bytes max from non_regular_fd.
3665 Non_regular_inserted specifies where to put the read bytes.
3666 Value is the number of bytes read. */
3668 static Lisp_Object
3669 read_non_regular ()
3671 int nbytes;
3673 immediate_quit = 1;
3674 QUIT;
3675 nbytes = emacs_read (non_regular_fd,
3676 BEG_ADDR + PT_BYTE - BEG_BYTE + non_regular_inserted,
3677 non_regular_nbytes);
3678 immediate_quit = 0;
3679 return make_number (nbytes);
3683 /* Condition-case handler used when reading from non-regular files
3684 in insert-file-contents. */
3686 static Lisp_Object
3687 read_non_regular_quit ()
3689 return Qnil;
3693 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3694 1, 5, 0,
3695 doc: /* Insert contents of file FILENAME after point.
3696 Returns list of absolute file name and number of characters inserted.
3697 If second argument VISIT is non-nil, the buffer's visited filename and
3698 last save file modtime are set, and it is marked unmodified. If
3699 visiting and the file does not exist, visiting is completed before the
3700 error is signaled.
3702 The optional third and fourth arguments BEG and END specify what portion
3703 of the file to insert. These arguments count bytes in the file, not
3704 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3706 If optional fifth argument REPLACE is non-nil, replace the current
3707 buffer contents (in the accessible portion) with the file contents.
3708 This is better than simply deleting and inserting the whole thing
3709 because (1) it preserves some marker positions and (2) it puts less data
3710 in the undo list. When REPLACE is non-nil, the second return value is
3711 the number of characters that replace previous buffer contents.
3713 This function does code conversion according to the value of
3714 `coding-system-for-read' or `file-coding-system-alist', and sets the
3715 variable `last-coding-system-used' to the coding system actually used. */)
3716 (filename, visit, beg, end, replace)
3717 Lisp_Object filename, visit, beg, end, replace;
3719 struct stat st;
3720 register int fd;
3721 int inserted = 0;
3722 register int how_much;
3723 register int unprocessed;
3724 int count = SPECPDL_INDEX ();
3725 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3726 Lisp_Object handler, val, insval, orig_filename, old_undo;
3727 Lisp_Object p;
3728 int total = 0;
3729 int not_regular = 0;
3730 unsigned char read_buf[READ_BUF_SIZE];
3731 struct coding_system coding;
3732 unsigned char buffer[1 << 14];
3733 int replace_handled = 0;
3734 int set_coding_system = 0;
3735 int coding_system_decided = 0;
3736 int read_quit = 0;
3737 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3738 int we_locked_file = 0;
3740 if (current_buffer->base_buffer && ! NILP (visit))
3741 error ("Cannot do file visiting in an indirect buffer");
3743 if (!NILP (current_buffer->read_only))
3744 Fbarf_if_buffer_read_only ();
3746 val = Qnil;
3747 p = Qnil;
3748 orig_filename = Qnil;
3749 old_undo = Qnil;
3751 GCPRO5 (filename, val, p, orig_filename, old_undo);
3753 CHECK_STRING (filename);
3754 filename = Fexpand_file_name (filename, Qnil);
3756 /* If the file name has special constructs in it,
3757 call the corresponding file handler. */
3758 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3759 if (!NILP (handler))
3761 val = call6 (handler, Qinsert_file_contents, filename,
3762 visit, beg, end, replace);
3763 if (CONSP (val) && CONSP (XCDR (val)))
3764 inserted = XINT (XCAR (XCDR (val)));
3765 goto handled;
3768 orig_filename = filename;
3769 filename = ENCODE_FILE (filename);
3771 fd = -1;
3773 #ifdef WINDOWSNT
3775 Lisp_Object tem = Vw32_get_true_file_attributes;
3777 /* Tell stat to use expensive method to get accurate info. */
3778 Vw32_get_true_file_attributes = Qt;
3779 total = stat (SDATA (filename), &st);
3780 Vw32_get_true_file_attributes = tem;
3782 if (total < 0)
3783 #else
3784 #ifndef APOLLO
3785 if (stat (SDATA (filename), &st) < 0)
3786 #else
3787 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0
3788 || fstat (fd, &st) < 0)
3789 #endif /* not APOLLO */
3790 #endif /* WINDOWSNT */
3792 if (fd >= 0) emacs_close (fd);
3793 badopen:
3794 if (NILP (visit))
3795 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3796 st.st_mtime = -1;
3797 how_much = 0;
3798 if (!NILP (Vcoding_system_for_read))
3799 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3800 goto notfound;
3803 #ifdef S_IFREG
3804 /* This code will need to be changed in order to work on named
3805 pipes, and it's probably just not worth it. So we should at
3806 least signal an error. */
3807 if (!S_ISREG (st.st_mode))
3809 not_regular = 1;
3811 if (! NILP (visit))
3812 goto notfound;
3814 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3815 xsignal2 (Qfile_error,
3816 build_string ("not a regular file"), orig_filename);
3818 #endif
3820 if (fd < 0)
3821 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0)
3822 goto badopen;
3824 /* Replacement should preserve point as it preserves markers. */
3825 if (!NILP (replace))
3826 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3828 record_unwind_protect (close_file_unwind, make_number (fd));
3830 /* Supposedly happens on VMS. */
3831 /* Can happen on any platform that uses long as type of off_t, but allows
3832 file sizes to exceed 2Gb. VMS is no longer officially supported, so
3833 give a message suitable for the latter case. */
3834 if (! not_regular && st.st_size < 0)
3835 error ("Maximum buffer size exceeded");
3837 /* Prevent redisplay optimizations. */
3838 current_buffer->clip_changed = 1;
3840 if (!NILP (visit))
3842 if (!NILP (beg) || !NILP (end))
3843 error ("Attempt to visit less than an entire file");
3844 if (BEG < Z && NILP (replace))
3845 error ("Cannot do file visiting in a non-empty buffer");
3848 if (!NILP (beg))
3849 CHECK_NUMBER (beg);
3850 else
3851 XSETFASTINT (beg, 0);
3853 if (!NILP (end))
3854 CHECK_NUMBER (end);
3855 else
3857 if (! not_regular)
3859 XSETINT (end, st.st_size);
3861 /* Arithmetic overflow can occur if an Emacs integer cannot
3862 represent the file size, or if the calculations below
3863 overflow. The calculations below double the file size
3864 twice, so check that it can be multiplied by 4 safely. */
3865 if (XINT (end) != st.st_size
3866 || ((int) st.st_size * 4) / 4 != st.st_size)
3867 error ("Maximum buffer size exceeded");
3869 /* The file size returned from stat may be zero, but data
3870 may be readable nonetheless, for example when this is a
3871 file in the /proc filesystem. */
3872 if (st.st_size == 0)
3873 XSETINT (end, READ_BUF_SIZE);
3877 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3879 /* We use emacs-mule for auto saving... */
3880 setup_coding_system (Qemacs_mule, &coding);
3881 /* ... but with the special flag to indicate to read in a
3882 multibyte sequence for eight-bit-control char as is. */
3883 coding.flags = 1;
3884 coding.src_multibyte = 0;
3885 coding.dst_multibyte
3886 = !NILP (current_buffer->enable_multibyte_characters);
3887 coding.eol_type = CODING_EOL_LF;
3888 coding_system_decided = 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 Lisp_Object val;
3896 val = Qnil;
3898 if (!NILP (Vcoding_system_for_read))
3899 val = Vcoding_system_for_read;
3900 else
3902 /* Don't try looking inside a file for a coding system
3903 specification if it is not seekable. */
3904 if (! not_regular && ! NILP (Vset_auto_coding_function))
3906 /* Find a coding system specified in the heading two
3907 lines or in the tailing several lines of the file.
3908 We assume that the 1K-byte and 3K-byte for heading
3909 and tailing respectively are sufficient for this
3910 purpose. */
3911 int nread;
3913 if (st.st_size <= (1024 * 4))
3914 nread = emacs_read (fd, read_buf, 1024 * 4);
3915 else
3917 nread = emacs_read (fd, read_buf, 1024);
3918 if (nread >= 0)
3920 if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
3921 report_file_error ("Setting file position",
3922 Fcons (orig_filename, Qnil));
3923 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3927 if (nread < 0)
3928 error ("IO error reading %s: %s",
3929 SDATA (orig_filename), emacs_strerror (errno));
3930 else if (nread > 0)
3932 struct buffer *prev = current_buffer;
3933 Lisp_Object buffer;
3934 struct buffer *buf;
3936 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3938 buffer = Fget_buffer_create (build_string (" *code-converting-work*"));
3939 buf = XBUFFER (buffer);
3941 delete_all_overlays (buf);
3942 buf->directory = current_buffer->directory;
3943 buf->read_only = Qnil;
3944 buf->filename = Qnil;
3945 buf->undo_list = Qt;
3946 eassert (buf->overlays_before == NULL);
3947 eassert (buf->overlays_after == NULL);
3949 set_buffer_internal (buf);
3950 Ferase_buffer ();
3951 buf->enable_multibyte_characters = Qnil;
3953 insert_1_both (read_buf, nread, nread, 0, 0, 0);
3954 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3955 val = call2 (Vset_auto_coding_function,
3956 filename, make_number (nread));
3957 set_buffer_internal (prev);
3959 /* Discard the unwind protect for recovering the
3960 current buffer. */
3961 specpdl_ptr--;
3963 /* Rewind the file for the actual read done later. */
3964 if (lseek (fd, 0, 0) < 0)
3965 report_file_error ("Setting file position",
3966 Fcons (orig_filename, Qnil));
3970 if (NILP (val))
3972 /* If we have not yet decided a coding system, check
3973 file-coding-system-alist. */
3974 Lisp_Object args[6], coding_systems;
3976 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3977 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3978 coding_systems = Ffind_operation_coding_system (6, args);
3979 if (CONSP (coding_systems))
3980 val = XCAR (coding_systems);
3984 setup_coding_system (Fcheck_coding_system (val), &coding);
3985 /* Ensure we set Vlast_coding_system_used. */
3986 set_coding_system = 1;
3988 if (NILP (current_buffer->enable_multibyte_characters)
3989 && ! NILP (val))
3990 /* We must suppress all character code conversion except for
3991 end-of-line conversion. */
3992 setup_raw_text_coding_system (&coding);
3994 coding.src_multibyte = 0;
3995 coding.dst_multibyte
3996 = !NILP (current_buffer->enable_multibyte_characters);
3997 coding_system_decided = 1;
4000 /* If requested, replace the accessible part of the buffer
4001 with the file contents. Avoid replacing text at the
4002 beginning or end of the buffer that matches the file contents;
4003 that preserves markers pointing to the unchanged parts.
4005 Here we implement this feature in an optimized way
4006 for the case where code conversion is NOT needed.
4007 The following if-statement handles the case of conversion
4008 in a less optimal way.
4010 If the code conversion is "automatic" then we try using this
4011 method and hope for the best.
4012 But if we discover the need for conversion, we give up on this method
4013 and let the following if-statement handle the replace job. */
4014 if (!NILP (replace)
4015 && BEGV < ZV
4016 && !(coding.common_flags & CODING_REQUIRE_DECODING_MASK))
4018 /* same_at_start and same_at_end count bytes,
4019 because file access counts bytes
4020 and BEG and END count bytes. */
4021 int same_at_start = BEGV_BYTE;
4022 int same_at_end = ZV_BYTE;
4023 int overlap;
4024 /* There is still a possibility we will find the need to do code
4025 conversion. If that happens, we set this variable to 1 to
4026 give up on handling REPLACE in the optimized way. */
4027 int giveup_match_end = 0;
4029 if (XINT (beg) != 0)
4031 if (lseek (fd, XINT (beg), 0) < 0)
4032 report_file_error ("Setting file position",
4033 Fcons (orig_filename, Qnil));
4036 immediate_quit = 1;
4037 QUIT;
4038 /* Count how many chars at the start of the file
4039 match the text at the beginning of the buffer. */
4040 while (1)
4042 int nread, bufpos;
4044 nread = emacs_read (fd, buffer, sizeof buffer);
4045 if (nread < 0)
4046 error ("IO error reading %s: %s",
4047 SDATA (orig_filename), emacs_strerror (errno));
4048 else if (nread == 0)
4049 break;
4051 if (coding.type == coding_type_undecided)
4052 detect_coding (&coding, buffer, nread);
4053 if (coding.common_flags & CODING_REQUIRE_DECODING_MASK)
4054 /* We found that the file should be decoded somehow.
4055 Let's give up here. */
4057 giveup_match_end = 1;
4058 break;
4061 if (coding.eol_type == CODING_EOL_UNDECIDED)
4062 detect_eol (&coding, buffer, nread);
4063 if (coding.eol_type != CODING_EOL_UNDECIDED
4064 && coding.eol_type != CODING_EOL_LF)
4065 /* We found that the format of eol should be decoded.
4066 Let's give up here. */
4068 giveup_match_end = 1;
4069 break;
4072 bufpos = 0;
4073 while (bufpos < nread && same_at_start < ZV_BYTE
4074 && FETCH_BYTE (same_at_start) == buffer[bufpos])
4075 same_at_start++, bufpos++;
4076 /* If we found a discrepancy, stop the scan.
4077 Otherwise loop around and scan the next bufferful. */
4078 if (bufpos != nread)
4079 break;
4081 immediate_quit = 0;
4082 /* If the file matches the buffer completely,
4083 there's no need to replace anything. */
4084 if (same_at_start - BEGV_BYTE == XINT (end))
4086 emacs_close (fd);
4087 specpdl_ptr--;
4088 /* Truncate the buffer to the size of the file. */
4089 del_range_1 (same_at_start, same_at_end, 0, 0);
4090 goto handled;
4092 immediate_quit = 1;
4093 QUIT;
4094 /* Count how many chars at the end of the file
4095 match the text at the end of the buffer. But, if we have
4096 already found that decoding is necessary, don't waste time. */
4097 while (!giveup_match_end)
4099 int total_read, nread, bufpos, curpos, trial;
4101 /* At what file position are we now scanning? */
4102 curpos = XINT (end) - (ZV_BYTE - same_at_end);
4103 /* If the entire file matches the buffer tail, stop the scan. */
4104 if (curpos == 0)
4105 break;
4106 /* How much can we scan in the next step? */
4107 trial = min (curpos, sizeof buffer);
4108 if (lseek (fd, curpos - trial, 0) < 0)
4109 report_file_error ("Setting file position",
4110 Fcons (orig_filename, Qnil));
4112 total_read = nread = 0;
4113 while (total_read < trial)
4115 nread = emacs_read (fd, buffer + total_read, trial - total_read);
4116 if (nread < 0)
4117 error ("IO error reading %s: %s",
4118 SDATA (orig_filename), emacs_strerror (errno));
4119 else if (nread == 0)
4120 break;
4121 total_read += nread;
4124 /* Scan this bufferful from the end, comparing with
4125 the Emacs buffer. */
4126 bufpos = total_read;
4128 /* Compare with same_at_start to avoid counting some buffer text
4129 as matching both at the file's beginning and at the end. */
4130 while (bufpos > 0 && same_at_end > same_at_start
4131 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
4132 same_at_end--, bufpos--;
4134 /* If we found a discrepancy, stop the scan.
4135 Otherwise loop around and scan the preceding bufferful. */
4136 if (bufpos != 0)
4138 /* If this discrepancy is because of code conversion,
4139 we cannot use this method; giveup and try the other. */
4140 if (same_at_end > same_at_start
4141 && FETCH_BYTE (same_at_end - 1) >= 0200
4142 && ! NILP (current_buffer->enable_multibyte_characters)
4143 && (CODING_MAY_REQUIRE_DECODING (&coding)))
4144 giveup_match_end = 1;
4145 break;
4148 if (nread == 0)
4149 break;
4151 immediate_quit = 0;
4153 if (! giveup_match_end)
4155 int temp;
4157 /* We win! We can handle REPLACE the optimized way. */
4159 /* Extend the start of non-matching text area to multibyte
4160 character boundary. */
4161 if (! NILP (current_buffer->enable_multibyte_characters))
4162 while (same_at_start > BEGV_BYTE
4163 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4164 same_at_start--;
4166 /* Extend the end of non-matching text area to multibyte
4167 character boundary. */
4168 if (! NILP (current_buffer->enable_multibyte_characters))
4169 while (same_at_end < ZV_BYTE
4170 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4171 same_at_end++;
4173 /* Don't try to reuse the same piece of text twice. */
4174 overlap = (same_at_start - BEGV_BYTE
4175 - (same_at_end + st.st_size - ZV));
4176 if (overlap > 0)
4177 same_at_end += overlap;
4179 /* Arrange to read only the nonmatching middle part of the file. */
4180 XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV_BYTE));
4181 XSETFASTINT (end, XINT (end) - (ZV_BYTE - same_at_end));
4183 del_range_byte (same_at_start, same_at_end, 0);
4184 /* Insert from the file at the proper position. */
4185 temp = BYTE_TO_CHAR (same_at_start);
4186 SET_PT_BOTH (temp, same_at_start);
4188 /* If display currently starts at beginning of line,
4189 keep it that way. */
4190 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
4191 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
4193 replace_handled = 1;
4197 /* If requested, replace the accessible part of the buffer
4198 with the file contents. Avoid replacing text at the
4199 beginning or end of the buffer that matches the file contents;
4200 that preserves markers pointing to the unchanged parts.
4202 Here we implement this feature for the case where code conversion
4203 is needed, in a simple way that needs a lot of memory.
4204 The preceding if-statement handles the case of no conversion
4205 in a more optimized way. */
4206 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
4208 int same_at_start = BEGV_BYTE;
4209 int same_at_end = ZV_BYTE;
4210 int overlap;
4211 int bufpos;
4212 /* Make sure that the gap is large enough. */
4213 int bufsize = 2 * st.st_size;
4214 unsigned char *conversion_buffer = (unsigned char *) xmalloc (bufsize);
4215 int temp;
4217 /* First read the whole file, performing code conversion into
4218 CONVERSION_BUFFER. */
4220 if (lseek (fd, XINT (beg), 0) < 0)
4222 xfree (conversion_buffer);
4223 report_file_error ("Setting file position",
4224 Fcons (orig_filename, Qnil));
4227 total = st.st_size; /* Total bytes in the file. */
4228 how_much = 0; /* Bytes read from file so far. */
4229 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
4230 unprocessed = 0; /* Bytes not processed in previous loop. */
4232 while (how_much < total)
4234 /* try is reserved in some compilers (Microsoft C) */
4235 int trytry = min (total - how_much, READ_BUF_SIZE - unprocessed);
4236 unsigned char *destination = read_buf + unprocessed;
4237 int this;
4239 /* Allow quitting out of the actual I/O. */
4240 immediate_quit = 1;
4241 QUIT;
4242 this = emacs_read (fd, destination, trytry);
4243 immediate_quit = 0;
4245 if (this < 0 || this + unprocessed == 0)
4247 how_much = this;
4248 break;
4251 how_much += this;
4253 if (CODING_MAY_REQUIRE_DECODING (&coding))
4255 int require, result;
4257 this += unprocessed;
4259 /* If we are using more space than estimated,
4260 make CONVERSION_BUFFER bigger. */
4261 require = decoding_buffer_size (&coding, this);
4262 if (inserted + require + 2 * (total - how_much) > bufsize)
4264 bufsize = inserted + require + 2 * (total - how_much);
4265 conversion_buffer = (unsigned char *) xrealloc (conversion_buffer, bufsize);
4268 /* Convert this batch with results in CONVERSION_BUFFER. */
4269 if (how_much >= total) /* This is the last block. */
4270 coding.mode |= CODING_MODE_LAST_BLOCK;
4271 if (coding.composing != COMPOSITION_DISABLED)
4272 coding_allocate_composition_data (&coding, BEGV);
4273 result = decode_coding (&coding, read_buf,
4274 conversion_buffer + inserted,
4275 this, bufsize - inserted);
4277 /* Save for next iteration whatever we didn't convert. */
4278 unprocessed = this - coding.consumed;
4279 bcopy (read_buf + coding.consumed, read_buf, unprocessed);
4280 if (!NILP (current_buffer->enable_multibyte_characters))
4281 this = coding.produced;
4282 else
4283 this = str_as_unibyte (conversion_buffer + inserted,
4284 coding.produced);
4287 inserted += this;
4290 /* At this point, INSERTED is how many characters (i.e. bytes)
4291 are present in CONVERSION_BUFFER.
4292 HOW_MUCH should equal TOTAL,
4293 or should be <= 0 if we couldn't read the file. */
4295 if (how_much < 0)
4297 xfree (conversion_buffer);
4298 coding_free_composition_data (&coding);
4299 error ("IO error reading %s: %s",
4300 SDATA (orig_filename), emacs_strerror (errno));
4303 /* Compare the beginning of the converted file
4304 with the buffer text. */
4306 bufpos = 0;
4307 while (bufpos < inserted && same_at_start < same_at_end
4308 && FETCH_BYTE (same_at_start) == conversion_buffer[bufpos])
4309 same_at_start++, bufpos++;
4311 /* If the file matches the buffer completely,
4312 there's no need to replace anything. */
4314 if (bufpos == inserted)
4316 xfree (conversion_buffer);
4317 coding_free_composition_data (&coding);
4318 emacs_close (fd);
4319 specpdl_ptr--;
4320 /* Truncate the buffer to the size of the file. */
4321 del_range_byte (same_at_start, same_at_end, 0);
4322 inserted = 0;
4323 goto handled;
4326 /* Extend the start of non-matching text area to multibyte
4327 character boundary. */
4328 if (! NILP (current_buffer->enable_multibyte_characters))
4329 while (same_at_start > BEGV_BYTE
4330 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4331 same_at_start--;
4333 /* Scan this bufferful from the end, comparing with
4334 the Emacs buffer. */
4335 bufpos = inserted;
4337 /* Compare with same_at_start to avoid counting some buffer text
4338 as matching both at the file's beginning and at the end. */
4339 while (bufpos > 0 && same_at_end > same_at_start
4340 && FETCH_BYTE (same_at_end - 1) == conversion_buffer[bufpos - 1])
4341 same_at_end--, bufpos--;
4343 /* Extend the end of non-matching text area to multibyte
4344 character boundary. */
4345 if (! NILP (current_buffer->enable_multibyte_characters))
4346 while (same_at_end < ZV_BYTE
4347 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4348 same_at_end++;
4350 /* Don't try to reuse the same piece of text twice. */
4351 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4352 if (overlap > 0)
4353 same_at_end += overlap;
4355 /* If display currently starts at beginning of line,
4356 keep it that way. */
4357 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
4358 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
4360 /* Replace the chars that we need to replace,
4361 and update INSERTED to equal the number of bytes
4362 we are taking from the file. */
4363 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4365 if (same_at_end != same_at_start)
4367 del_range_byte (same_at_start, same_at_end, 0);
4368 temp = GPT;
4369 same_at_start = GPT_BYTE;
4371 else
4373 temp = BYTE_TO_CHAR (same_at_start);
4375 /* Insert from the file at the proper position. */
4376 SET_PT_BOTH (temp, same_at_start);
4377 insert_1 (conversion_buffer + same_at_start - BEGV_BYTE, inserted,
4378 0, 0, 0);
4379 if (coding.cmp_data && coding.cmp_data->used)
4380 coding_restore_composition (&coding, Fcurrent_buffer ());
4381 coding_free_composition_data (&coding);
4383 /* Set `inserted' to the number of inserted characters. */
4384 inserted = PT - temp;
4385 /* Set point before the inserted characters. */
4386 SET_PT_BOTH (temp, same_at_start);
4388 xfree (conversion_buffer);
4389 emacs_close (fd);
4390 specpdl_ptr--;
4392 goto handled;
4395 if (! not_regular)
4397 register Lisp_Object temp;
4399 total = XINT (end) - XINT (beg);
4401 /* Make sure point-max won't overflow after this insertion. */
4402 XSETINT (temp, total);
4403 if (total != XINT (temp))
4404 error ("Maximum buffer size exceeded");
4406 else
4407 /* For a special file, all we can do is guess. */
4408 total = READ_BUF_SIZE;
4410 if (NILP (visit) && inserted > 0)
4412 #ifdef CLASH_DETECTION
4413 if (!NILP (current_buffer->file_truename)
4414 /* Make binding buffer-file-name to nil effective. */
4415 && !NILP (current_buffer->filename)
4416 && SAVE_MODIFF >= MODIFF)
4417 we_locked_file = 1;
4418 #endif /* CLASH_DETECTION */
4419 prepare_to_modify_buffer (GPT, GPT, NULL);
4422 move_gap (PT);
4423 if (GAP_SIZE < total)
4424 make_gap (total - GAP_SIZE);
4426 if (XINT (beg) != 0 || !NILP (replace))
4428 if (lseek (fd, XINT (beg), 0) < 0)
4429 report_file_error ("Setting file position",
4430 Fcons (orig_filename, Qnil));
4433 /* In the following loop, HOW_MUCH contains the total bytes read so
4434 far for a regular file, and not changed for a special file. But,
4435 before exiting the loop, it is set to a negative value if I/O
4436 error occurs. */
4437 how_much = 0;
4439 /* Total bytes inserted. */
4440 inserted = 0;
4442 /* Here, we don't do code conversion in the loop. It is done by
4443 code_convert_region after all data are read into the buffer. */
4445 int gap_size = GAP_SIZE;
4447 while (how_much < total)
4449 /* try is reserved in some compilers (Microsoft C) */
4450 int trytry = min (total - how_much, READ_BUF_SIZE);
4451 int this;
4453 if (not_regular)
4455 Lisp_Object val;
4457 /* Maybe make more room. */
4458 if (gap_size < trytry)
4460 make_gap (total - gap_size);
4461 gap_size = GAP_SIZE;
4464 /* Read from the file, capturing `quit'. When an
4465 error occurs, end the loop, and arrange for a quit
4466 to be signaled after decoding the text we read. */
4467 non_regular_fd = fd;
4468 non_regular_inserted = inserted;
4469 non_regular_nbytes = trytry;
4470 val = internal_condition_case_1 (read_non_regular, Qnil, Qerror,
4471 read_non_regular_quit);
4472 if (NILP (val))
4474 read_quit = 1;
4475 break;
4478 this = XINT (val);
4480 else
4482 /* Allow quitting out of the actual I/O. We don't make text
4483 part of the buffer until all the reading is done, so a C-g
4484 here doesn't do any harm. */
4485 immediate_quit = 1;
4486 QUIT;
4487 this = emacs_read (fd, BEG_ADDR + PT_BYTE - BEG_BYTE + inserted, trytry);
4488 immediate_quit = 0;
4491 if (this <= 0)
4493 how_much = this;
4494 break;
4497 gap_size -= this;
4499 /* For a regular file, where TOTAL is the real size,
4500 count HOW_MUCH to compare with it.
4501 For a special file, where TOTAL is just a buffer size,
4502 so don't bother counting in HOW_MUCH.
4503 (INSERTED is where we count the number of characters inserted.) */
4504 if (! not_regular)
4505 how_much += this;
4506 inserted += this;
4510 /* Now we have read all the file data into the gap.
4511 If it was empty, undo marking the buffer modified. */
4513 if (inserted == 0)
4515 #ifdef CLASH_DETECTION
4516 if (we_locked_file)
4517 unlock_file (current_buffer->file_truename);
4518 #endif
4519 Vdeactivate_mark = old_Vdeactivate_mark;
4521 else
4522 Vdeactivate_mark = Qt;
4524 /* Make the text read part of the buffer. */
4525 GAP_SIZE -= inserted;
4526 GPT += inserted;
4527 GPT_BYTE += inserted;
4528 ZV += inserted;
4529 ZV_BYTE += inserted;
4530 Z += inserted;
4531 Z_BYTE += inserted;
4533 if (GAP_SIZE > 0)
4534 /* Put an anchor to ensure multi-byte form ends at gap. */
4535 *GPT_ADDR = 0;
4537 emacs_close (fd);
4539 /* Discard the unwind protect for closing the file. */
4540 specpdl_ptr--;
4542 if (how_much < 0)
4543 error ("IO error reading %s: %s",
4544 SDATA (orig_filename), emacs_strerror (errno));
4546 notfound:
4548 if (! coding_system_decided)
4550 /* The coding system is not yet decided. Decide it by an
4551 optimized method for handling `coding:' tag.
4553 Note that we can get here only if the buffer was empty
4554 before the insertion. */
4555 Lisp_Object val;
4556 val = Qnil;
4558 if (!NILP (Vcoding_system_for_read))
4559 val = Vcoding_system_for_read;
4560 else
4562 /* Since we are sure that the current buffer was empty
4563 before the insertion, we can toggle
4564 enable-multibyte-characters directly here without taking
4565 care of marker adjustment and byte combining problem. By
4566 this way, we can run Lisp program safely before decoding
4567 the inserted text. */
4568 Lisp_Object unwind_data;
4569 int count = SPECPDL_INDEX ();
4571 unwind_data = Fcons (current_buffer->enable_multibyte_characters,
4572 Fcons (current_buffer->undo_list,
4573 Fcurrent_buffer ()));
4574 current_buffer->enable_multibyte_characters = Qnil;
4575 current_buffer->undo_list = Qt;
4576 record_unwind_protect (decide_coding_unwind, unwind_data);
4578 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4580 val = call2 (Vset_auto_coding_function,
4581 filename, make_number (inserted));
4584 if (NILP (val))
4586 /* If the coding system is not yet decided, check
4587 file-coding-system-alist. */
4588 Lisp_Object args[6], coding_systems;
4590 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4591 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4592 coding_systems = Ffind_operation_coding_system (6, args);
4593 if (CONSP (coding_systems))
4594 val = XCAR (coding_systems);
4596 unbind_to (count, Qnil);
4597 inserted = Z_BYTE - BEG_BYTE;
4600 /* The following kludgy code is to avoid some compiler bug.
4601 We can't simply do
4602 setup_coding_system (val, &coding);
4603 on some system. */
4605 struct coding_system temp_coding;
4606 setup_coding_system (Fcheck_coding_system (val), &temp_coding);
4607 bcopy (&temp_coding, &coding, sizeof coding);
4609 /* Ensure we set Vlast_coding_system_used. */
4610 set_coding_system = 1;
4612 if (NILP (current_buffer->enable_multibyte_characters)
4613 && ! NILP (val))
4614 /* We must suppress all character code conversion except for
4615 end-of-line conversion. */
4616 setup_raw_text_coding_system (&coding);
4617 coding.src_multibyte = 0;
4618 coding.dst_multibyte
4619 = !NILP (current_buffer->enable_multibyte_characters);
4622 if (!NILP (visit)
4623 /* Can't do this if part of the buffer might be preserved. */
4624 && NILP (replace)
4625 && (coding.type == coding_type_no_conversion
4626 || coding.type == coding_type_raw_text))
4628 /* Visiting a file with these coding system makes the buffer
4629 unibyte. */
4630 current_buffer->enable_multibyte_characters = Qnil;
4631 coding.dst_multibyte = 0;
4634 if (inserted > 0 || coding.type == coding_type_ccl)
4636 if (CODING_MAY_REQUIRE_DECODING (&coding))
4638 code_convert_region (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4639 &coding, 0, 0);
4640 inserted = coding.produced_char;
4642 else
4643 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4644 inserted);
4647 /* Now INSERTED is measured in characters. */
4649 #ifdef DOS_NT
4650 /* Use the conversion type to determine buffer-file-type
4651 (find-buffer-file-type is now used to help determine the
4652 conversion). */
4653 if ((coding.eol_type == CODING_EOL_UNDECIDED
4654 || coding.eol_type == CODING_EOL_LF)
4655 && ! CODING_REQUIRE_DECODING (&coding))
4656 current_buffer->buffer_file_type = Qt;
4657 else
4658 current_buffer->buffer_file_type = Qnil;
4659 #endif
4661 handled:
4663 if (!NILP (visit))
4665 if (!EQ (current_buffer->undo_list, Qt))
4666 current_buffer->undo_list = Qnil;
4667 #ifdef APOLLO
4668 stat (SDATA (filename), &st);
4669 #endif
4671 if (NILP (handler))
4673 current_buffer->modtime = st.st_mtime;
4674 current_buffer->filename = orig_filename;
4677 SAVE_MODIFF = MODIFF;
4678 current_buffer->auto_save_modified = MODIFF;
4679 XSETFASTINT (current_buffer->save_length, Z - BEG);
4680 #ifdef CLASH_DETECTION
4681 if (NILP (handler))
4683 if (!NILP (current_buffer->file_truename))
4684 unlock_file (current_buffer->file_truename);
4685 unlock_file (filename);
4687 #endif /* CLASH_DETECTION */
4688 if (not_regular)
4689 xsignal2 (Qfile_error,
4690 build_string ("not a regular file"), orig_filename);
4693 if (set_coding_system)
4694 Vlast_coding_system_used = coding.symbol;
4696 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4698 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4699 visit);
4700 if (! NILP (insval))
4702 CHECK_NUMBER (insval);
4703 inserted = XFASTINT (insval);
4707 /* Decode file format */
4708 if (inserted > 0)
4710 /* Don't run point motion or modification hooks when decoding. */
4711 int count = SPECPDL_INDEX ();
4712 specbind (Qinhibit_point_motion_hooks, Qt);
4713 specbind (Qinhibit_modification_hooks, Qt);
4715 /* Save old undo list and don't record undo for decoding. */
4716 old_undo = current_buffer->undo_list;
4717 current_buffer->undo_list = Qt;
4719 if (NILP (replace))
4721 insval = call3 (Qformat_decode,
4722 Qnil, make_number (inserted), visit);
4723 CHECK_NUMBER (insval);
4724 inserted = XFASTINT (insval);
4726 else
4728 /* If REPLACE is non-nil and we succeeded in not replacing the
4729 beginning or end of the buffer text with the file's contents,
4730 call format-decode with `point' positioned at the beginning of
4731 the buffer and `inserted' equalling the number of characters
4732 in the buffer. Otherwise, format-decode might fail to
4733 correctly analyze the beginning or end of the buffer. Hence
4734 we temporarily save `point' and `inserted' here and restore
4735 `point' iff format-decode did not insert or delete any text.
4736 Otherwise we leave `point' at point-min. */
4737 int opoint = PT;
4738 int opoint_byte = PT_BYTE;
4739 int oinserted = ZV - BEGV;
4740 int ochars_modiff = CHARS_MODIFF;
4742 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4743 insval = call3 (Qformat_decode,
4744 Qnil, make_number (oinserted), visit);
4745 CHECK_NUMBER (insval);
4746 if (ochars_modiff == CHARS_MODIFF)
4747 /* format_decode didn't modify buffer's characters => move
4748 point back to position before inserted text and leave
4749 value of inserted alone. */
4750 SET_PT_BOTH (opoint, opoint_byte);
4751 else
4752 /* format_decode modified buffer's characters => consider
4753 entire buffer changed and leave point at point-min. */
4754 inserted = XFASTINT (insval);
4757 /* For consistency with format-decode call these now iff inserted > 0
4758 (martin 2007-06-28) */
4759 p = Vafter_insert_file_functions;
4760 while (CONSP (p))
4762 if (NILP (replace))
4764 insval = call1 (XCAR (p), make_number (inserted));
4765 if (!NILP (insval))
4767 CHECK_NUMBER (insval);
4768 inserted = XFASTINT (insval);
4771 else
4773 /* For the rationale of this see the comment on format-decode above. */
4774 int opoint = PT;
4775 int opoint_byte = PT_BYTE;
4776 int oinserted = ZV - BEGV;
4777 int ochars_modiff = CHARS_MODIFF;
4779 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4780 insval = call1 (XCAR (p), make_number (oinserted));
4781 if (!NILP (insval))
4783 CHECK_NUMBER (insval);
4784 if (ochars_modiff == CHARS_MODIFF)
4785 /* after_insert_file_functions didn't modify
4786 buffer's characters => move point back to
4787 position before inserted text and leave value of
4788 inserted alone. */
4789 SET_PT_BOTH (opoint, opoint_byte);
4790 else
4791 /* after_insert_file_functions did modify buffer's
4792 characters => consider entire buffer changed and
4793 leave point at point-min. */
4794 inserted = XFASTINT (insval);
4798 QUIT;
4799 p = XCDR (p);
4802 if (NILP (visit))
4804 Lisp_Object lbeg, lend;
4805 XSETINT (lbeg, PT);
4806 XSETINT (lend, PT + inserted);
4807 if (CONSP (old_undo))
4809 Lisp_Object tem = XCAR (old_undo);
4810 if (CONSP (tem) && INTEGERP (XCAR (tem)) &&
4811 INTEGERP (XCDR (tem)) && EQ (XCAR (tem), lbeg))
4812 /* In the non-visiting case record only the final insertion. */
4813 current_buffer->undo_list =
4814 Fcons (Fcons (lbeg, lend), Fcdr (old_undo));
4817 else
4818 /* If undo_list was Qt before, keep it that way.
4819 Otherwise start with an empty undo_list. */
4820 current_buffer->undo_list = EQ (old_undo, Qt) ? Qt : Qnil;
4822 unbind_to (count, Qnil);
4825 /* Call after-change hooks for the inserted text, aside from the case
4826 of normal visiting (not with REPLACE), which is done in a new buffer
4827 "before" the buffer is changed. */
4828 if (inserted > 0 && total > 0
4829 && (NILP (visit) || !NILP (replace)))
4831 signal_after_change (PT, 0, inserted);
4832 update_compositions (PT, PT, CHECK_BORDER);
4835 if (!NILP (visit)
4836 && current_buffer->modtime == -1)
4838 /* If visiting nonexistent file, return nil. */
4839 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4842 if (read_quit)
4843 Fsignal (Qquit, Qnil);
4845 /* ??? Retval needs to be dealt with in all cases consistently. */
4846 if (NILP (val))
4847 val = Fcons (orig_filename,
4848 Fcons (make_number (inserted),
4849 Qnil));
4851 RETURN_UNGCPRO (unbind_to (count, val));
4854 static Lisp_Object build_annotations P_ ((Lisp_Object, Lisp_Object));
4855 static Lisp_Object build_annotations_2 P_ ((Lisp_Object, Lisp_Object,
4856 Lisp_Object, Lisp_Object));
4858 /* If build_annotations switched buffers, switch back to BUF.
4859 Kill the temporary buffer that was selected in the meantime.
4861 Since this kill only the last temporary buffer, some buffers remain
4862 not killed if build_annotations switched buffers more than once.
4863 -- K.Handa */
4865 static Lisp_Object
4866 build_annotations_unwind (buf)
4867 Lisp_Object buf;
4869 Lisp_Object tembuf;
4871 if (XBUFFER (buf) == current_buffer)
4872 return Qnil;
4873 tembuf = Fcurrent_buffer ();
4874 Fset_buffer (buf);
4875 Fkill_buffer (tembuf);
4876 return Qnil;
4879 /* Decide the coding-system to encode the data with. */
4881 void
4882 choose_write_coding_system (start, end, filename,
4883 append, visit, lockname, coding)
4884 Lisp_Object start, end, filename, append, visit, lockname;
4885 struct coding_system *coding;
4887 Lisp_Object val;
4889 if (auto_saving
4890 && NILP (Fstring_equal (current_buffer->filename,
4891 current_buffer->auto_save_file_name)))
4893 /* We use emacs-mule for auto saving... */
4894 setup_coding_system (Qemacs_mule, coding);
4895 /* ... but with the special flag to indicate not to strip off
4896 leading code of eight-bit-control chars. */
4897 coding->flags = 1;
4898 /* We force LF for end-of-line because that is faster. */
4899 coding->eol_type = CODING_EOL_LF;
4900 goto done_setup_coding;
4902 else if (!NILP (Vcoding_system_for_write))
4904 val = Vcoding_system_for_write;
4905 if (coding_system_require_warning
4906 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4907 /* Confirm that VAL can surely encode the current region. */
4908 val = call5 (Vselect_safe_coding_system_function,
4909 start, end, Fcons (Qt, Fcons (val, Qnil)),
4910 Qnil, filename);
4912 else
4914 /* If the variable `buffer-file-coding-system' is set locally,
4915 it means that the file was read with some kind of code
4916 conversion or the variable is explicitly set by users. We
4917 had better write it out with the same coding system even if
4918 `enable-multibyte-characters' is nil.
4920 If it is not set locally, we anyway have to convert EOL
4921 format if the default value of `buffer-file-coding-system'
4922 tells that it is not Unix-like (LF only) format. */
4923 int using_default_coding = 0;
4924 int force_raw_text = 0;
4926 val = current_buffer->buffer_file_coding_system;
4927 if (NILP (val)
4928 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4930 val = Qnil;
4931 if (NILP (current_buffer->enable_multibyte_characters))
4932 force_raw_text = 1;
4935 if (NILP (val))
4937 /* Check file-coding-system-alist. */
4938 Lisp_Object args[7], coding_systems;
4940 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4941 args[3] = filename; args[4] = append; args[5] = visit;
4942 args[6] = lockname;
4943 coding_systems = Ffind_operation_coding_system (7, args);
4944 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4945 val = XCDR (coding_systems);
4948 if (NILP (val)
4949 && !NILP (current_buffer->buffer_file_coding_system))
4951 /* If we still have not decided a coding system, use the
4952 default value of buffer-file-coding-system. */
4953 val = current_buffer->buffer_file_coding_system;
4954 using_default_coding = 1;
4957 if (!force_raw_text
4958 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4959 /* Confirm that VAL can surely encode the current region. */
4960 val = call5 (Vselect_safe_coding_system_function,
4961 start, end, val, Qnil, filename);
4963 setup_coding_system (Fcheck_coding_system (val), coding);
4964 if (coding->eol_type == CODING_EOL_UNDECIDED
4965 && !using_default_coding)
4967 if (! EQ (default_buffer_file_coding.symbol,
4968 buffer_defaults.buffer_file_coding_system))
4969 setup_coding_system (buffer_defaults.buffer_file_coding_system,
4970 &default_buffer_file_coding);
4971 if (default_buffer_file_coding.eol_type != CODING_EOL_UNDECIDED)
4973 Lisp_Object subsidiaries;
4975 coding->eol_type = default_buffer_file_coding.eol_type;
4976 subsidiaries = Fget (coding->symbol, Qeol_type);
4977 if (VECTORP (subsidiaries)
4978 && XVECTOR (subsidiaries)->size == 3)
4979 coding->symbol
4980 = XVECTOR (subsidiaries)->contents[coding->eol_type];
4984 if (force_raw_text)
4985 setup_raw_text_coding_system (coding);
4986 goto done_setup_coding;
4989 setup_coding_system (Fcheck_coding_system (val), coding);
4991 done_setup_coding:
4992 if (coding->eol_type == CODING_EOL_UNDECIDED)
4993 coding->eol_type = system_eol_type;
4994 if (!STRINGP (start) && !NILP (current_buffer->selective_display))
4995 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4998 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4999 "r\nFWrite region to file: \ni\ni\ni\np",
5000 doc: /* Write current region into specified file.
5001 When called from a program, requires three arguments:
5002 START, END and FILENAME. START and END are normally buffer positions
5003 specifying the part of the buffer to write.
5004 If START is nil, that means to use the entire buffer contents.
5005 If START is a string, then output that string to the file
5006 instead of any buffer contents; END is ignored.
5008 Optional fourth argument APPEND if non-nil means
5009 append to existing file contents (if any). If it is an integer,
5010 seek to that offset in the file before writing.
5011 Optional fifth argument VISIT, if t or a string, means
5012 set the last-save-file-modtime of buffer to this file's modtime
5013 and mark buffer not modified.
5014 If VISIT is a string, it is a second file name;
5015 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
5016 VISIT is also the file name to lock and unlock for clash detection.
5017 If VISIT is neither t nor nil nor a string,
5018 that means do not display the \"Wrote file\" message.
5019 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
5020 use for locking and unlocking, overriding FILENAME and VISIT.
5021 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
5022 for an existing file with the same name. If MUSTBENEW is `excl',
5023 that means to get an error if the file already exists; never overwrite.
5024 If MUSTBENEW is neither nil nor `excl', that means ask for
5025 confirmation before overwriting, but do go ahead and overwrite the file
5026 if the user confirms.
5028 This does code conversion according to the value of
5029 `coding-system-for-write', `buffer-file-coding-system', or
5030 `file-coding-system-alist', and sets the variable
5031 `last-coding-system-used' to the coding system actually used. */)
5032 (start, end, filename, append, visit, lockname, mustbenew)
5033 Lisp_Object start, end, filename, append, visit, lockname, mustbenew;
5035 register int desc;
5036 int failure;
5037 int save_errno = 0;
5038 const unsigned char *fn;
5039 struct stat st;
5040 int tem;
5041 int count = SPECPDL_INDEX ();
5042 int count1;
5043 #ifdef VMS
5044 unsigned char *fname = 0; /* If non-0, original filename (must rename) */
5045 #endif /* VMS */
5046 Lisp_Object handler;
5047 Lisp_Object visit_file;
5048 Lisp_Object annotations;
5049 Lisp_Object encoded_filename;
5050 int visiting = (EQ (visit, Qt) || STRINGP (visit));
5051 int quietly = !NILP (visit);
5052 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
5053 struct buffer *given_buffer;
5054 #ifdef DOS_NT
5055 int buffer_file_type = O_BINARY;
5056 #endif /* DOS_NT */
5057 struct coding_system coding;
5059 if (current_buffer->base_buffer && visiting)
5060 error ("Cannot do file visiting in an indirect buffer");
5062 if (!NILP (start) && !STRINGP (start))
5063 validate_region (&start, &end);
5065 visit_file = Qnil;
5066 GCPRO5 (start, filename, visit, visit_file, lockname);
5068 filename = Fexpand_file_name (filename, Qnil);
5070 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
5071 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
5073 if (STRINGP (visit))
5074 visit_file = Fexpand_file_name (visit, Qnil);
5075 else
5076 visit_file = filename;
5078 if (NILP (lockname))
5079 lockname = visit_file;
5081 annotations = Qnil;
5083 /* If the file name has special constructs in it,
5084 call the corresponding file handler. */
5085 handler = Ffind_file_name_handler (filename, Qwrite_region);
5086 /* If FILENAME has no handler, see if VISIT has one. */
5087 if (NILP (handler) && STRINGP (visit))
5088 handler = Ffind_file_name_handler (visit, Qwrite_region);
5090 if (!NILP (handler))
5092 Lisp_Object val;
5093 val = call6 (handler, Qwrite_region, start, end,
5094 filename, append, visit);
5096 if (visiting)
5098 SAVE_MODIFF = MODIFF;
5099 XSETFASTINT (current_buffer->save_length, Z - BEG);
5100 current_buffer->filename = visit_file;
5102 UNGCPRO;
5103 return val;
5106 record_unwind_protect (save_restriction_restore, save_restriction_save ());
5108 /* Special kludge to simplify auto-saving. */
5109 if (NILP (start))
5111 XSETFASTINT (start, BEG);
5112 XSETFASTINT (end, Z);
5113 Fwiden ();
5116 record_unwind_protect (build_annotations_unwind, Fcurrent_buffer ());
5117 count1 = SPECPDL_INDEX ();
5119 given_buffer = current_buffer;
5121 if (!STRINGP (start))
5123 annotations = build_annotations (start, end);
5125 if (current_buffer != given_buffer)
5127 XSETFASTINT (start, BEGV);
5128 XSETFASTINT (end, ZV);
5132 UNGCPRO;
5134 GCPRO5 (start, filename, annotations, visit_file, lockname);
5136 /* Decide the coding-system to encode the data with.
5137 We used to make this choice before calling build_annotations, but that
5138 leads to problems when a write-annotate-function takes care of
5139 unsavable chars (as was the case with X-Symbol). */
5140 choose_write_coding_system (start, end, filename,
5141 append, visit, lockname, &coding);
5142 Vlast_coding_system_used = coding.symbol;
5144 given_buffer = current_buffer;
5145 if (! STRINGP (start))
5147 annotations = build_annotations_2 (start, end,
5148 coding.pre_write_conversion, annotations);
5149 if (current_buffer != given_buffer)
5151 XSETFASTINT (start, BEGV);
5152 XSETFASTINT (end, ZV);
5156 #ifdef CLASH_DETECTION
5157 if (!auto_saving)
5159 #if 0 /* This causes trouble for GNUS. */
5160 /* If we've locked this file for some other buffer,
5161 query before proceeding. */
5162 if (!visiting && EQ (Ffile_locked_p (lockname), Qt))
5163 call2 (intern ("ask-user-about-lock"), filename, Vuser_login_name);
5164 #endif
5166 lock_file (lockname);
5168 #endif /* CLASH_DETECTION */
5170 encoded_filename = ENCODE_FILE (filename);
5172 fn = SDATA (encoded_filename);
5173 desc = -1;
5174 if (!NILP (append))
5175 #ifdef DOS_NT
5176 desc = emacs_open (fn, O_WRONLY | buffer_file_type, 0);
5177 #else /* not DOS_NT */
5178 desc = emacs_open (fn, O_WRONLY, 0);
5179 #endif /* not DOS_NT */
5181 if (desc < 0 && (NILP (append) || errno == ENOENT))
5182 #ifdef VMS
5183 if (auto_saving) /* Overwrite any previous version of autosave file */
5185 vms_truncate (fn); /* if fn exists, truncate to zero length */
5186 desc = emacs_open (fn, O_RDWR, 0);
5187 if (desc < 0)
5188 desc = creat_copy_attrs (STRINGP (current_buffer->filename)
5189 ? SDATA (current_buffer->filename) : 0,
5190 fn);
5192 else /* Write to temporary name and rename if no errors */
5194 Lisp_Object temp_name;
5195 temp_name = Ffile_name_directory (filename);
5197 if (!NILP (temp_name))
5199 temp_name = Fmake_temp_name (concat2 (temp_name,
5200 build_string ("$$SAVE$$")));
5201 fname = SDATA (filename);
5202 fn = SDATA (temp_name);
5203 desc = creat_copy_attrs (fname, fn);
5204 if (desc < 0)
5206 /* If we can't open the temporary file, try creating a new
5207 version of the original file. VMS "creat" creates a
5208 new version rather than truncating an existing file. */
5209 fn = fname;
5210 fname = 0;
5211 desc = creat (fn, 0666);
5212 #if 0 /* This can clobber an existing file and fail to replace it,
5213 if the user runs out of space. */
5214 if (desc < 0)
5216 /* We can't make a new version;
5217 try to truncate and rewrite existing version if any. */
5218 vms_truncate (fn);
5219 desc = emacs_open (fn, O_RDWR, 0);
5221 #endif
5224 else
5225 desc = creat (fn, 0666);
5227 #else /* not VMS */
5228 #ifdef DOS_NT
5229 desc = emacs_open (fn,
5230 O_WRONLY | O_CREAT | buffer_file_type
5231 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
5232 S_IREAD | S_IWRITE);
5233 #else /* not DOS_NT */
5234 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
5235 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
5236 auto_saving ? auto_save_mode_bits : 0666);
5237 #endif /* not DOS_NT */
5238 #endif /* not VMS */
5240 if (desc < 0)
5242 #ifdef CLASH_DETECTION
5243 save_errno = errno;
5244 if (!auto_saving) unlock_file (lockname);
5245 errno = save_errno;
5246 #endif /* CLASH_DETECTION */
5247 UNGCPRO;
5248 report_file_error ("Opening output file", Fcons (filename, Qnil));
5251 record_unwind_protect (close_file_unwind, make_number (desc));
5253 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
5255 long ret;
5257 if (NUMBERP (append))
5258 ret = lseek (desc, XINT (append), 1);
5259 else
5260 ret = lseek (desc, 0, 2);
5261 if (ret < 0)
5263 #ifdef CLASH_DETECTION
5264 if (!auto_saving) unlock_file (lockname);
5265 #endif /* CLASH_DETECTION */
5266 UNGCPRO;
5267 report_file_error ("Lseek error", Fcons (filename, Qnil));
5271 UNGCPRO;
5273 #ifdef VMS
5275 * Kludge Warning: The VMS C RTL likes to insert carriage returns
5276 * if we do writes that don't end with a carriage return. Furthermore
5277 * it cannot handle writes of more then 16K. The modified
5278 * version of "sys_write" in SYSDEP.C (see comment there) copes with
5279 * this EXCEPT for the last record (if it doesn't end with a carriage
5280 * return). This implies that if your buffer doesn't end with a carriage
5281 * return, you get one free... tough. However it also means that if
5282 * we make two calls to sys_write (a la the following code) you can
5283 * get one at the gap as well. The easiest way to fix this (honest)
5284 * is to move the gap to the next newline (or the end of the buffer).
5285 * Thus this change.
5287 * Yech!
5289 if (GPT > BEG && GPT_ADDR[-1] != '\n')
5290 move_gap (find_next_newline (GPT, 1));
5291 #else
5292 /* Whether VMS or not, we must move the gap to the next of newline
5293 when we must put designation sequences at beginning of line. */
5294 if (INTEGERP (start)
5295 && coding.type == coding_type_iso2022
5296 && coding.flags & CODING_FLAG_ISO_DESIGNATE_AT_BOL
5297 && GPT > BEG && GPT_ADDR[-1] != '\n')
5299 int opoint = PT, opoint_byte = PT_BYTE;
5300 scan_newline (PT, PT_BYTE, ZV, ZV_BYTE, 1, 0);
5301 move_gap_both (PT, PT_BYTE);
5302 SET_PT_BOTH (opoint, opoint_byte);
5304 #endif
5306 failure = 0;
5307 immediate_quit = 1;
5309 if (STRINGP (start))
5311 failure = 0 > a_write (desc, start, 0, SCHARS (start),
5312 &annotations, &coding);
5313 save_errno = errno;
5315 else if (XINT (start) != XINT (end))
5317 tem = CHAR_TO_BYTE (XINT (start));
5319 if (XINT (start) < GPT)
5321 failure = 0 > a_write (desc, Qnil, XINT (start),
5322 min (GPT, XINT (end)) - XINT (start),
5323 &annotations, &coding);
5324 save_errno = errno;
5327 if (XINT (end) > GPT && !failure)
5329 tem = max (XINT (start), GPT);
5330 failure = 0 > a_write (desc, Qnil, tem , XINT (end) - tem,
5331 &annotations, &coding);
5332 save_errno = errno;
5335 else
5337 /* If file was empty, still need to write the annotations */
5338 coding.mode |= CODING_MODE_LAST_BLOCK;
5339 failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
5340 save_errno = errno;
5343 if (CODING_REQUIRE_FLUSHING (&coding)
5344 && !(coding.mode & CODING_MODE_LAST_BLOCK)
5345 && ! failure)
5347 /* We have to flush out a data. */
5348 coding.mode |= CODING_MODE_LAST_BLOCK;
5349 failure = 0 > e_write (desc, Qnil, 0, 0, &coding);
5350 save_errno = errno;
5353 immediate_quit = 0;
5355 #ifdef HAVE_FSYNC
5356 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
5357 Disk full in NFS may be reported here. */
5358 /* mib says that closing the file will try to write as fast as NFS can do
5359 it, and that means the fsync here is not crucial for autosave files. */
5360 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
5362 /* If fsync fails with EINTR, don't treat that as serious. Also
5363 ignore EINVAL which happens when fsync is not supported on this
5364 file. */
5365 if (errno != EINTR && errno != EINVAL)
5366 failure = 1, save_errno = errno;
5368 #endif
5370 /* Spurious "file has changed on disk" warnings have been
5371 observed on Suns as well.
5372 It seems that `close' can change the modtime, under nfs.
5374 (This has supposedly been fixed in Sunos 4,
5375 but who knows about all the other machines with NFS?) */
5376 #if 0
5378 /* On VMS and APOLLO, must do the stat after the close
5379 since closing changes the modtime. */
5380 #ifndef VMS
5381 #ifndef APOLLO
5382 /* Recall that #if defined does not work on VMS. */
5383 #define FOO
5384 fstat (desc, &st);
5385 #endif
5386 #endif
5387 #endif
5389 /* NFS can report a write failure now. */
5390 if (emacs_close (desc) < 0)
5391 failure = 1, save_errno = errno;
5393 #ifdef VMS
5394 /* If we wrote to a temporary name and had no errors, rename to real name. */
5395 if (fname)
5397 if (!failure)
5398 failure = (rename (fn, fname) != 0), save_errno = errno;
5399 fn = fname;
5401 #endif /* VMS */
5403 #ifndef FOO
5404 stat (fn, &st);
5405 #endif
5406 /* Discard the unwind protect for close_file_unwind. */
5407 specpdl_ptr = specpdl + count1;
5408 /* Restore the original current buffer. */
5409 visit_file = unbind_to (count, visit_file);
5411 #ifdef CLASH_DETECTION
5412 if (!auto_saving)
5413 unlock_file (lockname);
5414 #endif /* CLASH_DETECTION */
5416 /* Do this before reporting IO error
5417 to avoid a "file has changed on disk" warning on
5418 next attempt to save. */
5419 if (visiting)
5420 current_buffer->modtime = st.st_mtime;
5422 if (failure)
5423 error ("IO error writing %s: %s", SDATA (filename),
5424 emacs_strerror (save_errno));
5426 if (visiting)
5428 SAVE_MODIFF = MODIFF;
5429 XSETFASTINT (current_buffer->save_length, Z - BEG);
5430 current_buffer->filename = visit_file;
5431 update_mode_lines++;
5433 else if (quietly)
5435 if (auto_saving
5436 && ! NILP (Fstring_equal (current_buffer->filename,
5437 current_buffer->auto_save_file_name)))
5438 SAVE_MODIFF = MODIFF;
5440 return Qnil;
5443 if (!auto_saving)
5444 message_with_string ((INTEGERP (append)
5445 ? "Updated %s"
5446 : ! NILP (append)
5447 ? "Added to %s"
5448 : "Wrote %s"),
5449 visit_file, 1);
5451 return Qnil;
5454 Lisp_Object merge ();
5456 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5457 doc: /* Return t if (car A) is numerically less than (car B). */)
5458 (a, b)
5459 Lisp_Object a, b;
5461 return Flss (Fcar (a), Fcar (b));
5464 /* Build the complete list of annotations appropriate for writing out
5465 the text between START and END, by calling all the functions in
5466 write-region-annotate-functions and merging the lists they return.
5467 If one of these functions switches to a different buffer, we assume
5468 that buffer contains altered text. Therefore, the caller must
5469 make sure to restore the current buffer in all cases,
5470 as save-excursion would do. */
5472 static Lisp_Object
5473 build_annotations (start, end)
5474 Lisp_Object start, end;
5476 Lisp_Object annotations;
5477 Lisp_Object p, res;
5478 struct gcpro gcpro1, gcpro2;
5479 Lisp_Object original_buffer;
5480 int i, used_global = 0;
5482 XSETBUFFER (original_buffer, current_buffer);
5484 annotations = Qnil;
5485 p = Vwrite_region_annotate_functions;
5486 GCPRO2 (annotations, p);
5487 while (CONSP (p))
5489 struct buffer *given_buffer = current_buffer;
5490 if (EQ (Qt, XCAR (p)) && !used_global)
5491 { /* Use the global value of the hook. */
5492 Lisp_Object arg[2];
5493 used_global = 1;
5494 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
5495 arg[1] = XCDR (p);
5496 p = Fappend (2, arg);
5497 continue;
5499 Vwrite_region_annotations_so_far = annotations;
5500 res = call2 (XCAR (p), start, end);
5501 /* If the function makes a different buffer current,
5502 assume that means this buffer contains altered text to be output.
5503 Reset START and END from the buffer bounds
5504 and discard all previous annotations because they should have
5505 been dealt with by this function. */
5506 if (current_buffer != given_buffer)
5508 XSETFASTINT (start, BEGV);
5509 XSETFASTINT (end, ZV);
5510 annotations = Qnil;
5512 Flength (res); /* Check basic validity of return value */
5513 annotations = merge (annotations, res, Qcar_less_than_car);
5514 p = XCDR (p);
5517 /* Now do the same for annotation functions implied by the file-format */
5518 if (auto_saving && (!EQ (current_buffer->auto_save_file_format, Qt)))
5519 p = current_buffer->auto_save_file_format;
5520 else
5521 p = current_buffer->file_format;
5522 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5524 struct buffer *given_buffer = current_buffer;
5526 Vwrite_region_annotations_so_far = annotations;
5528 /* Value is either a list of annotations or nil if the function
5529 has written annotations to a temporary buffer, which is now
5530 current. */
5531 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5532 original_buffer, make_number (i));
5533 if (current_buffer != given_buffer)
5535 XSETFASTINT (start, BEGV);
5536 XSETFASTINT (end, ZV);
5537 annotations = Qnil;
5540 if (CONSP (res))
5541 annotations = merge (annotations, res, Qcar_less_than_car);
5544 UNGCPRO;
5545 return annotations;
5548 static Lisp_Object
5549 build_annotations_2 (start, end, pre_write_conversion, annotations)
5550 Lisp_Object start, end, pre_write_conversion, annotations;
5552 struct gcpro gcpro1;
5553 Lisp_Object res;
5555 GCPRO1 (annotations);
5556 /* At last, do the same for the function PRE_WRITE_CONVERSION
5557 implied by the current coding-system. */
5558 if (!NILP (pre_write_conversion))
5560 struct buffer *given_buffer = current_buffer;
5561 Vwrite_region_annotations_so_far = annotations;
5562 res = call2 (pre_write_conversion, start, end);
5563 Flength (res);
5564 annotations = (current_buffer != given_buffer
5565 ? res
5566 : merge (annotations, res, Qcar_less_than_car));
5569 UNGCPRO;
5570 return annotations;
5573 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5574 If STRING is nil, POS is the character position in the current buffer.
5575 Intersperse with them the annotations from *ANNOT
5576 which fall within the range of POS to POS + NCHARS,
5577 each at its appropriate position.
5579 We modify *ANNOT by discarding elements as we use them up.
5581 The return value is negative in case of system call failure. */
5583 static int
5584 a_write (desc, string, pos, nchars, annot, coding)
5585 int desc;
5586 Lisp_Object string;
5587 register int nchars;
5588 int pos;
5589 Lisp_Object *annot;
5590 struct coding_system *coding;
5592 Lisp_Object tem;
5593 int nextpos;
5594 int lastpos = pos + nchars;
5596 while (NILP (*annot) || CONSP (*annot))
5598 tem = Fcar_safe (Fcar (*annot));
5599 nextpos = pos - 1;
5600 if (INTEGERP (tem))
5601 nextpos = XFASTINT (tem);
5603 /* If there are no more annotations in this range,
5604 output the rest of the range all at once. */
5605 if (! (nextpos >= pos && nextpos <= lastpos))
5606 return e_write (desc, string, pos, lastpos, coding);
5608 /* Output buffer text up to the next annotation's position. */
5609 if (nextpos > pos)
5611 if (0 > e_write (desc, string, pos, nextpos, coding))
5612 return -1;
5613 pos = nextpos;
5615 /* Output the annotation. */
5616 tem = Fcdr (Fcar (*annot));
5617 if (STRINGP (tem))
5619 if (0 > e_write (desc, tem, 0, SCHARS (tem), coding))
5620 return -1;
5622 *annot = Fcdr (*annot);
5624 return 0;
5627 #ifndef WRITE_BUF_SIZE
5628 #define WRITE_BUF_SIZE (16 * 1024)
5629 #endif
5631 /* Write text in the range START and END into descriptor DESC,
5632 encoding them with coding system CODING. If STRING is nil, START
5633 and END are character positions of the current buffer, else they
5634 are indexes to the string STRING. */
5636 static int
5637 e_write (desc, string, start, end, coding)
5638 int desc;
5639 Lisp_Object string;
5640 int start, end;
5641 struct coding_system *coding;
5643 register char *addr;
5644 register int nbytes;
5645 char buf[WRITE_BUF_SIZE];
5646 int return_val = 0;
5648 if (start >= end)
5649 coding->composing = COMPOSITION_DISABLED;
5650 if (coding->composing != COMPOSITION_DISABLED)
5651 coding_save_composition (coding, start, end, string);
5653 if (STRINGP (string))
5655 addr = SDATA (string);
5656 nbytes = SBYTES (string);
5657 coding->src_multibyte = STRING_MULTIBYTE (string);
5659 else if (start < end)
5661 /* It is assured that the gap is not in the range START and END-1. */
5662 addr = CHAR_POS_ADDR (start);
5663 nbytes = CHAR_TO_BYTE (end) - CHAR_TO_BYTE (start);
5664 coding->src_multibyte
5665 = !NILP (current_buffer->enable_multibyte_characters);
5667 else
5669 addr = "";
5670 nbytes = 0;
5671 coding->src_multibyte = 1;
5674 /* We used to have a code for handling selective display here. But,
5675 now it is handled within encode_coding. */
5676 while (1)
5678 int result;
5680 result = encode_coding (coding, addr, buf, nbytes, WRITE_BUF_SIZE);
5681 if (coding->produced > 0)
5683 coding->produced -= emacs_write (desc, buf, coding->produced);
5684 if (coding->produced)
5686 return_val = -1;
5687 break;
5690 nbytes -= coding->consumed;
5691 addr += coding->consumed;
5692 if (result == CODING_FINISH_INSUFFICIENT_SRC
5693 && nbytes > 0)
5695 /* The source text ends by an incomplete multibyte form.
5696 There's no way other than write it out as is. */
5697 nbytes -= emacs_write (desc, addr, nbytes);
5698 if (nbytes)
5700 return_val = -1;
5701 break;
5704 if (nbytes <= 0)
5705 break;
5706 start += coding->consumed_char;
5707 if (coding->cmp_data)
5708 coding_adjust_composition_offset (coding, start);
5711 if (coding->cmp_data)
5712 coding_free_composition_data (coding);
5714 return return_val;
5717 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5718 Sverify_visited_file_modtime, 1, 1, 0,
5719 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5720 This means that the file has not been changed since it was visited or saved.
5721 See Info node `(elisp)Modification Time' for more details. */)
5722 (buf)
5723 Lisp_Object buf;
5725 struct buffer *b;
5726 struct stat st;
5727 Lisp_Object handler;
5728 Lisp_Object filename;
5730 CHECK_BUFFER (buf);
5731 b = XBUFFER (buf);
5733 if (!STRINGP (b->filename)) return Qt;
5734 if (b->modtime == 0) return Qt;
5736 /* If the file name has special constructs in it,
5737 call the corresponding file handler. */
5738 handler = Ffind_file_name_handler (b->filename,
5739 Qverify_visited_file_modtime);
5740 if (!NILP (handler))
5741 return call2 (handler, Qverify_visited_file_modtime, buf);
5743 filename = ENCODE_FILE (b->filename);
5745 if (stat (SDATA (filename), &st) < 0)
5747 /* If the file doesn't exist now and didn't exist before,
5748 we say that it isn't modified, provided the error is a tame one. */
5749 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
5750 st.st_mtime = -1;
5751 else
5752 st.st_mtime = 0;
5754 if (st.st_mtime == b->modtime
5755 /* If both are positive, accept them if they are off by one second. */
5756 || (st.st_mtime > 0 && b->modtime > 0
5757 && (st.st_mtime == b->modtime + 1
5758 || st.st_mtime == b->modtime - 1)))
5759 return Qt;
5760 return Qnil;
5763 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5764 Sclear_visited_file_modtime, 0, 0, 0,
5765 doc: /* Clear out records of last mod time of visited file.
5766 Next attempt to save will certainly not complain of a discrepancy. */)
5769 current_buffer->modtime = 0;
5770 return Qnil;
5773 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5774 Svisited_file_modtime, 0, 0, 0,
5775 doc: /* Return the current buffer's recorded visited file modification time.
5776 The value is a list of the form (HIGH LOW), like the time values
5777 that `file-attributes' returns. If the current buffer has no recorded
5778 file modification time, this function returns 0.
5779 See Info node `(elisp)Modification Time' for more details. */)
5782 if (! current_buffer->modtime)
5783 return make_number (0);
5784 return make_time ((time_t) current_buffer->modtime);
5787 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5788 Sset_visited_file_modtime, 0, 1, 0,
5789 doc: /* Update buffer's recorded modification time from the visited file's time.
5790 Useful if the buffer was not read from the file normally
5791 or if the file itself has been changed for some known benign reason.
5792 An argument specifies the modification time value to use
5793 \(instead of that of the visited file), in the form of a list
5794 \(HIGH . LOW) or (HIGH LOW). */)
5795 (time_list)
5796 Lisp_Object time_list;
5798 if (!NILP (time_list))
5799 current_buffer->modtime = cons_to_long (time_list);
5800 else
5802 register Lisp_Object filename;
5803 struct stat st;
5804 Lisp_Object handler;
5806 filename = Fexpand_file_name (current_buffer->filename, Qnil);
5808 /* If the file name has special constructs in it,
5809 call the corresponding file handler. */
5810 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5811 if (!NILP (handler))
5812 /* The handler can find the file name the same way we did. */
5813 return call2 (handler, Qset_visited_file_modtime, Qnil);
5815 filename = ENCODE_FILE (filename);
5817 if (stat (SDATA (filename), &st) >= 0)
5818 current_buffer->modtime = st.st_mtime;
5821 return Qnil;
5824 Lisp_Object
5825 auto_save_error (error)
5826 Lisp_Object error;
5828 Lisp_Object args[3], msg;
5829 int i, nbytes;
5830 struct gcpro gcpro1;
5831 char *msgbuf;
5832 USE_SAFE_ALLOCA;
5834 ring_bell (XFRAME (selected_frame));
5836 args[0] = build_string ("Auto-saving %s: %s");
5837 args[1] = current_buffer->name;
5838 args[2] = Ferror_message_string (error);
5839 msg = Fformat (3, args);
5840 GCPRO1 (msg);
5841 nbytes = SBYTES (msg);
5842 SAFE_ALLOCA (msgbuf, char *, nbytes);
5843 bcopy (SDATA (msg), msgbuf, nbytes);
5845 for (i = 0; i < 3; ++i)
5847 if (i == 0)
5848 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5849 else
5850 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5851 Fsleep_for (make_number (1), Qnil);
5854 SAFE_FREE ();
5855 UNGCPRO;
5856 return Qnil;
5859 Lisp_Object
5860 auto_save_1 ()
5862 struct stat st;
5863 Lisp_Object modes;
5865 auto_save_mode_bits = 0666;
5867 /* Get visited file's mode to become the auto save file's mode. */
5868 if (! NILP (current_buffer->filename))
5870 if (stat (SDATA (current_buffer->filename), &st) >= 0)
5871 /* But make sure we can overwrite it later! */
5872 auto_save_mode_bits = st.st_mode | 0600;
5873 else if ((modes = Ffile_modes (current_buffer->filename),
5874 INTEGERP (modes)))
5875 /* Remote files don't cooperate with stat. */
5876 auto_save_mode_bits = XINT (modes) | 0600;
5879 return
5880 Fwrite_region (Qnil, Qnil,
5881 current_buffer->auto_save_file_name,
5882 Qnil, Qlambda, Qnil, Qnil);
5885 static Lisp_Object
5886 do_auto_save_unwind (arg) /* used as unwind-protect function */
5887 Lisp_Object arg;
5889 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5890 auto_saving = 0;
5891 if (stream != NULL)
5893 BLOCK_INPUT;
5894 fclose (stream);
5895 UNBLOCK_INPUT;
5897 return Qnil;
5900 static Lisp_Object
5901 do_auto_save_unwind_1 (value) /* used as unwind-protect function */
5902 Lisp_Object value;
5904 minibuffer_auto_raise = XINT (value);
5905 return Qnil;
5908 static Lisp_Object
5909 do_auto_save_make_dir (dir)
5910 Lisp_Object dir;
5912 Lisp_Object mode;
5914 call2 (Qmake_directory, dir, Qt);
5915 XSETFASTINT (mode, 0700);
5916 return Fset_file_modes (dir, mode);
5919 static Lisp_Object
5920 do_auto_save_eh (ignore)
5921 Lisp_Object ignore;
5923 return Qnil;
5926 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5927 doc: /* Auto-save all buffers that need it.
5928 This is all buffers that have auto-saving enabled
5929 and are changed since last auto-saved.
5930 Auto-saving writes the buffer into a file
5931 so that your editing is not lost if the system crashes.
5932 This file is not the file you visited; that changes only when you save.
5933 Normally we run the normal hook `auto-save-hook' before saving.
5935 A non-nil NO-MESSAGE argument means do not print any message if successful.
5936 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5937 (no_message, current_only)
5938 Lisp_Object no_message, current_only;
5940 struct buffer *old = current_buffer, *b;
5941 Lisp_Object tail, buf;
5942 int auto_saved = 0;
5943 int do_handled_files;
5944 Lisp_Object oquit;
5945 FILE *stream = NULL;
5946 int count = SPECPDL_INDEX ();
5947 int orig_minibuffer_auto_raise = minibuffer_auto_raise;
5948 int old_message_p = 0;
5949 struct gcpro gcpro1, gcpro2;
5951 if (max_specpdl_size < specpdl_size + 40)
5952 max_specpdl_size = specpdl_size + 40;
5954 if (minibuf_level)
5955 no_message = Qt;
5957 if (NILP (no_message))
5959 old_message_p = push_message ();
5960 record_unwind_protect (pop_message_unwind, Qnil);
5963 /* Ordinarily don't quit within this function,
5964 but don't make it impossible to quit (in case we get hung in I/O). */
5965 oquit = Vquit_flag;
5966 Vquit_flag = Qnil;
5968 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5969 point to non-strings reached from Vbuffer_alist. */
5971 if (!NILP (Vrun_hooks))
5972 call1 (Vrun_hooks, intern ("auto-save-hook"));
5974 if (STRINGP (Vauto_save_list_file_name))
5976 Lisp_Object listfile;
5978 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5980 /* Don't try to create the directory when shutting down Emacs,
5981 because creating the directory might signal an error, and
5982 that would leave Emacs in a strange state. */
5983 if (!NILP (Vrun_hooks))
5985 Lisp_Object dir;
5986 dir = Qnil;
5987 GCPRO2 (dir, listfile);
5988 dir = Ffile_name_directory (listfile);
5989 if (NILP (Ffile_directory_p (dir)))
5990 internal_condition_case_1 (do_auto_save_make_dir,
5991 dir, Fcons (Fcons (Qfile_error, Qnil), Qnil),
5992 do_auto_save_eh);
5993 UNGCPRO;
5996 stream = fopen (SDATA (listfile), "w");
5999 record_unwind_protect (do_auto_save_unwind,
6000 make_save_value (stream, 0));
6001 record_unwind_protect (do_auto_save_unwind_1,
6002 make_number (minibuffer_auto_raise));
6003 minibuffer_auto_raise = 0;
6004 auto_saving = 1;
6006 /* On first pass, save all files that don't have handlers.
6007 On second pass, save all files that do have handlers.
6009 If Emacs is crashing, the handlers may tweak what is causing
6010 Emacs to crash in the first place, and it would be a shame if
6011 Emacs failed to autosave perfectly ordinary files because it
6012 couldn't handle some ange-ftp'd file. */
6014 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
6015 for (tail = Vbuffer_alist; GC_CONSP (tail); tail = XCDR (tail))
6017 buf = XCDR (XCAR (tail));
6018 b = XBUFFER (buf);
6020 /* Record all the buffers that have auto save mode
6021 in the special file that lists them. For each of these buffers,
6022 Record visited name (if any) and auto save name. */
6023 if (STRINGP (b->auto_save_file_name)
6024 && stream != NULL && do_handled_files == 0)
6026 BLOCK_INPUT;
6027 if (!NILP (b->filename))
6029 fwrite (SDATA (b->filename), 1,
6030 SBYTES (b->filename), stream);
6032 putc ('\n', stream);
6033 fwrite (SDATA (b->auto_save_file_name), 1,
6034 SBYTES (b->auto_save_file_name), stream);
6035 putc ('\n', stream);
6036 UNBLOCK_INPUT;
6039 if (!NILP (current_only)
6040 && b != current_buffer)
6041 continue;
6043 /* Don't auto-save indirect buffers.
6044 The base buffer takes care of it. */
6045 if (b->base_buffer)
6046 continue;
6048 /* Check for auto save enabled
6049 and file changed since last auto save
6050 and file changed since last real save. */
6051 if (STRINGP (b->auto_save_file_name)
6052 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
6053 && b->auto_save_modified < BUF_MODIFF (b)
6054 /* -1 means we've turned off autosaving for a while--see below. */
6055 && XINT (b->save_length) >= 0
6056 && (do_handled_files
6057 || NILP (Ffind_file_name_handler (b->auto_save_file_name,
6058 Qwrite_region))))
6060 EMACS_TIME before_time, after_time;
6062 EMACS_GET_TIME (before_time);
6064 /* If we had a failure, don't try again for 20 minutes. */
6065 if (b->auto_save_failure_time >= 0
6066 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
6067 continue;
6069 if ((XFASTINT (b->save_length) * 10
6070 > (BUF_Z (b) - BUF_BEG (b)) * 13)
6071 /* A short file is likely to change a large fraction;
6072 spare the user annoying messages. */
6073 && XFASTINT (b->save_length) > 5000
6074 /* These messages are frequent and annoying for `*mail*'. */
6075 && !EQ (b->filename, Qnil)
6076 && NILP (no_message))
6078 /* It has shrunk too much; turn off auto-saving here. */
6079 minibuffer_auto_raise = orig_minibuffer_auto_raise;
6080 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
6081 b->name, 1);
6082 minibuffer_auto_raise = 0;
6083 /* Turn off auto-saving until there's a real save,
6084 and prevent any more warnings. */
6085 XSETINT (b->save_length, -1);
6086 Fsleep_for (make_number (1), Qnil);
6087 continue;
6089 set_buffer_internal (b);
6090 if (!auto_saved && NILP (no_message))
6091 message1 ("Auto-saving...");
6092 internal_condition_case (auto_save_1, Qt, auto_save_error);
6093 auto_saved++;
6094 b->auto_save_modified = BUF_MODIFF (b);
6095 XSETFASTINT (current_buffer->save_length, Z - BEG);
6096 set_buffer_internal (old);
6098 EMACS_GET_TIME (after_time);
6100 /* If auto-save took more than 60 seconds,
6101 assume it was an NFS failure that got a timeout. */
6102 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
6103 b->auto_save_failure_time = EMACS_SECS (after_time);
6107 /* Prevent another auto save till enough input events come in. */
6108 record_auto_save ();
6110 if (auto_saved && NILP (no_message))
6112 if (old_message_p)
6114 /* If we are going to restore an old message,
6115 give time to read ours. */
6116 sit_for (make_number (1), 0, 0);
6117 restore_message ();
6119 else
6120 /* If we displayed a message and then restored a state
6121 with no message, leave a "done" message on the screen. */
6122 message1 ("Auto-saving...done");
6125 Vquit_flag = oquit;
6127 /* This restores the message-stack status. */
6128 unbind_to (count, Qnil);
6129 return Qnil;
6132 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
6133 Sset_buffer_auto_saved, 0, 0, 0,
6134 doc: /* Mark current buffer as auto-saved with its current text.
6135 No auto-save file will be written until the buffer changes again. */)
6138 current_buffer->auto_save_modified = MODIFF;
6139 XSETFASTINT (current_buffer->save_length, Z - BEG);
6140 current_buffer->auto_save_failure_time = -1;
6141 return Qnil;
6144 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
6145 Sclear_buffer_auto_save_failure, 0, 0, 0,
6146 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
6149 current_buffer->auto_save_failure_time = -1;
6150 return Qnil;
6153 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
6154 0, 0, 0,
6155 doc: /* Return t if current buffer has been auto-saved recently.
6156 More precisely, if it has been auto-saved since last read from or saved
6157 in the visited file. If the buffer has no visited file,
6158 then any auto-save counts as "recent". */)
6161 return (SAVE_MODIFF < current_buffer->auto_save_modified) ? Qt : Qnil;
6164 /* Reading and completing file names */
6165 extern Lisp_Object Ffile_name_completion (), Ffile_name_all_completions ();
6166 extern Lisp_Object Qcompletion_ignore_case;
6168 /* In the string VAL, change each $ to $$ and return the result. */
6170 static Lisp_Object
6171 double_dollars (val)
6172 Lisp_Object val;
6174 register const unsigned char *old;
6175 register unsigned char *new;
6176 register int n;
6177 int osize, count;
6179 osize = SBYTES (val);
6181 /* Count the number of $ characters. */
6182 for (n = osize, count = 0, old = SDATA (val); n > 0; n--)
6183 if (*old++ == '$') count++;
6184 if (count > 0)
6186 old = SDATA (val);
6187 val = make_uninit_multibyte_string (SCHARS (val) + count,
6188 osize + count);
6189 new = SDATA (val);
6190 for (n = osize; n > 0; n--)
6191 if (*old != '$')
6192 *new++ = *old++;
6193 else
6195 *new++ = '$';
6196 *new++ = '$';
6197 old++;
6200 return val;
6203 static Lisp_Object
6204 read_file_name_cleanup (arg)
6205 Lisp_Object arg;
6207 return (current_buffer->directory = arg);
6210 DEFUN ("read-file-name-internal", Fread_file_name_internal, Sread_file_name_internal,
6211 3, 3, 0,
6212 doc: /* Internal subroutine for read-file-name. Do not call this. */)
6213 (string, dir, action)
6214 Lisp_Object string, dir, action;
6215 /* action is nil for complete, t for return list of completions,
6216 lambda for verify final value */
6218 Lisp_Object name, specdir, realdir, val, orig_string;
6219 int changed;
6220 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
6222 CHECK_STRING (string);
6224 realdir = dir;
6225 name = string;
6226 orig_string = Qnil;
6227 specdir = Qnil;
6228 changed = 0;
6229 /* No need to protect ACTION--we only compare it with t and nil. */
6230 GCPRO5 (string, realdir, name, specdir, orig_string);
6232 if (SCHARS (string) == 0)
6234 if (EQ (action, Qlambda))
6236 UNGCPRO;
6237 return Qnil;
6240 else
6242 orig_string = string;
6243 string = Fsubstitute_in_file_name (string);
6244 changed = NILP (Fstring_equal (string, orig_string));
6245 name = Ffile_name_nondirectory (string);
6246 val = Ffile_name_directory (string);
6247 if (! NILP (val))
6248 realdir = Fexpand_file_name (val, realdir);
6251 if (NILP (action))
6253 specdir = Ffile_name_directory (string);
6254 val = Ffile_name_completion (name, realdir, Vread_file_name_predicate);
6255 UNGCPRO;
6256 if (!STRINGP (val))
6258 if (changed)
6259 return double_dollars (string);
6260 return val;
6263 if (!NILP (specdir))
6264 val = concat2 (specdir, val);
6265 #ifndef VMS
6266 return double_dollars (val);
6267 #else /* not VMS */
6268 return val;
6269 #endif /* not VMS */
6271 UNGCPRO;
6273 if (EQ (action, Qt))
6275 Lisp_Object all = Ffile_name_all_completions (name, realdir);
6276 Lisp_Object comp;
6277 int count;
6279 if (NILP (Vread_file_name_predicate)
6280 || EQ (Vread_file_name_predicate, Qfile_exists_p))
6281 return all;
6283 #ifndef VMS
6284 if (EQ (Vread_file_name_predicate, Qfile_directory_p))
6286 /* Brute-force speed up for directory checking:
6287 Discard strings which don't end in a slash. */
6288 for (comp = Qnil; CONSP (all); all = XCDR (all))
6290 Lisp_Object tem = XCAR (all);
6291 int len;
6292 if (STRINGP (tem)
6293 && (len = SBYTES (tem), len > 0)
6294 && IS_DIRECTORY_SEP (SREF (tem, len-1)))
6295 comp = Fcons (tem, comp);
6298 else
6299 #endif
6301 /* Must do it the hard (and slow) way. */
6302 Lisp_Object tem;
6303 GCPRO3 (all, comp, specdir);
6304 count = SPECPDL_INDEX ();
6305 record_unwind_protect (read_file_name_cleanup, current_buffer->directory);
6306 current_buffer->directory = realdir;
6307 for (comp = Qnil; CONSP (all); all = XCDR (all))
6309 tem = call1 (Vread_file_name_predicate, XCAR (all));
6310 if (!NILP (tem))
6311 comp = Fcons (XCAR (all), comp);
6313 unbind_to (count, Qnil);
6314 UNGCPRO;
6316 return Fnreverse (comp);
6319 /* Only other case actually used is ACTION = lambda */
6320 #ifdef VMS
6321 /* Supposedly this helps commands such as `cd' that read directory names,
6322 but can someone explain how it helps them? -- RMS */
6323 if (SCHARS (name) == 0)
6324 return Qt;
6325 #endif /* VMS */
6326 string = Fexpand_file_name (string, dir);
6327 if (!NILP (Vread_file_name_predicate))
6328 return call1 (Vread_file_name_predicate, string);
6329 return Ffile_exists_p (string);
6332 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
6333 Snext_read_file_uses_dialog_p, 0, 0, 0,
6334 doc: /* Return t if a call to `read-file-name' will use a dialog.
6335 The return value is only relevant for a call to `read-file-name' that happens
6336 before any other event (mouse or keypress) is handeled. */)
6339 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) || defined (HAVE_CARBON)
6340 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
6341 && use_dialog_box
6342 && use_file_dialog
6343 && have_menus_p ())
6344 return Qt;
6345 #endif
6346 return Qnil;
6349 DEFUN ("read-file-name", Fread_file_name, Sread_file_name, 1, 6, 0,
6350 doc: /* Read file name, prompting with PROMPT and completing in directory DIR.
6351 Value is not expanded---you must call `expand-file-name' yourself.
6352 Default name to DEFAULT-FILENAME if user exits the minibuffer with
6353 the same non-empty string that was inserted by this function.
6354 (If DEFAULT-FILENAME is omitted, the visited file name is used,
6355 except that if INITIAL is specified, that combined with DIR is used.)
6356 If the user exits with an empty minibuffer, this function returns
6357 an empty string. (This can only happen if the user erased the
6358 pre-inserted contents or if `insert-default-directory' is nil.)
6359 Fourth arg MUSTMATCH non-nil means require existing file's name.
6360 Non-nil and non-t means also require confirmation after completion.
6361 Fifth arg INITIAL specifies text to start with.
6362 If optional sixth arg PREDICATE is non-nil, possible completions and
6363 the resulting file name must satisfy (funcall PREDICATE NAME).
6364 DIR should be an absolute directory name. It defaults to the value of
6365 `default-directory'.
6367 If this command was invoked with the mouse, use a file dialog box if
6368 `use-dialog-box' is non-nil, and the window system or X toolkit in use
6369 provides a file dialog box.
6371 See also `read-file-name-completion-ignore-case'
6372 and `read-file-name-function'. */)
6373 (prompt, dir, default_filename, mustmatch, initial, predicate)
6374 Lisp_Object prompt, dir, default_filename, mustmatch, initial, predicate;
6376 Lisp_Object val, insdef, tem;
6377 struct gcpro gcpro1, gcpro2;
6378 register char *homedir;
6379 Lisp_Object decoded_homedir;
6380 int replace_in_history = 0;
6381 int add_to_history = 0;
6382 int count;
6384 if (NILP (dir))
6385 dir = current_buffer->directory;
6386 if (NILP (Ffile_name_absolute_p (dir)))
6387 dir = Fexpand_file_name (dir, Qnil);
6388 if (NILP (default_filename))
6389 default_filename
6390 = (!NILP (initial)
6391 ? Fexpand_file_name (initial, dir)
6392 : current_buffer->filename);
6394 /* If dir starts with user's homedir, change that to ~. */
6395 homedir = (char *) egetenv ("HOME");
6396 #ifdef DOS_NT
6397 /* homedir can be NULL in temacs, since Vglobal_environment is not
6398 yet set up. We shouldn't crash in that case. */
6399 if (homedir != 0)
6401 homedir = strcpy (alloca (strlen (homedir) + 1), homedir);
6402 CORRECT_DIR_SEPS (homedir);
6404 #endif
6405 if (homedir != 0)
6406 decoded_homedir
6407 = DECODE_FILE (make_unibyte_string (homedir, strlen (homedir)));
6408 if (homedir != 0
6409 && STRINGP (dir)
6410 && !strncmp (SDATA (decoded_homedir), SDATA (dir),
6411 SBYTES (decoded_homedir))
6412 && IS_DIRECTORY_SEP (SREF (dir, SBYTES (decoded_homedir))))
6414 dir = Fsubstring (dir, make_number (SCHARS (decoded_homedir)), Qnil);
6415 dir = concat2 (build_string ("~"), dir);
6417 /* Likewise for default_filename. */
6418 if (homedir != 0
6419 && STRINGP (default_filename)
6420 && !strncmp (SDATA (decoded_homedir), SDATA (default_filename),
6421 SBYTES (decoded_homedir))
6422 && IS_DIRECTORY_SEP (SREF (default_filename, SBYTES (decoded_homedir))))
6424 default_filename
6425 = Fsubstring (default_filename,
6426 make_number (SCHARS (decoded_homedir)), Qnil);
6427 default_filename = concat2 (build_string ("~"), default_filename);
6429 if (!NILP (default_filename))
6431 CHECK_STRING (default_filename);
6432 default_filename = double_dollars (default_filename);
6435 if (insert_default_directory && STRINGP (dir))
6437 insdef = dir;
6438 if (!NILP (initial))
6440 Lisp_Object args[2], pos;
6442 args[0] = insdef;
6443 args[1] = initial;
6444 insdef = Fconcat (2, args);
6445 pos = make_number (SCHARS (double_dollars (dir)));
6446 insdef = Fcons (double_dollars (insdef), pos);
6448 else
6449 insdef = double_dollars (insdef);
6451 else if (STRINGP (initial))
6452 insdef = Fcons (double_dollars (initial), make_number (0));
6453 else
6454 insdef = Qnil;
6456 if (!NILP (Vread_file_name_function))
6458 Lisp_Object args[7];
6460 GCPRO2 (insdef, default_filename);
6461 args[0] = Vread_file_name_function;
6462 args[1] = prompt;
6463 args[2] = dir;
6464 args[3] = default_filename;
6465 args[4] = mustmatch;
6466 args[5] = initial;
6467 args[6] = predicate;
6468 RETURN_UNGCPRO (Ffuncall (7, args));
6471 count = SPECPDL_INDEX ();
6472 specbind (Qcompletion_ignore_case,
6473 read_file_name_completion_ignore_case ? Qt : Qnil);
6474 specbind (intern ("minibuffer-completing-file-name"), Qt);
6475 specbind (intern ("read-file-name-predicate"),
6476 (NILP (predicate) ? Qfile_exists_p : predicate));
6478 GCPRO2 (insdef, default_filename);
6480 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) || defined (HAVE_CARBON)
6481 if (! NILP (Fnext_read_file_uses_dialog_p ()))
6483 /* If DIR contains a file name, split it. */
6484 Lisp_Object file;
6485 file = Ffile_name_nondirectory (dir);
6486 if (SCHARS (file) && NILP (default_filename))
6488 default_filename = file;
6489 dir = Ffile_name_directory (dir);
6491 if (!NILP(default_filename))
6492 default_filename = Fexpand_file_name (default_filename, dir);
6493 val = Fx_file_dialog (prompt, dir, default_filename, mustmatch,
6494 EQ (predicate, Qfile_directory_p) ? Qt : Qnil);
6495 add_to_history = 1;
6497 else
6498 #endif
6499 val = Fcompleting_read (prompt, intern ("read-file-name-internal"),
6500 dir, mustmatch, insdef,
6501 Qfile_name_history, default_filename, Qnil);
6503 tem = Fsymbol_value (Qfile_name_history);
6504 if (CONSP (tem) && EQ (XCAR (tem), val))
6505 replace_in_history = 1;
6507 /* If Fcompleting_read returned the inserted default string itself
6508 (rather than a new string with the same contents),
6509 it has to mean that the user typed RET with the minibuffer empty.
6510 In that case, we really want to return ""
6511 so that commands such as set-visited-file-name can distinguish. */
6512 if (EQ (val, default_filename))
6514 /* In this case, Fcompleting_read has not added an element
6515 to the history. Maybe we should. */
6516 if (! replace_in_history)
6517 add_to_history = 1;
6519 val = empty_unibyte_string;
6522 unbind_to (count, Qnil);
6523 UNGCPRO;
6524 if (NILP (val))
6525 error ("No file name specified");
6527 tem = Fstring_equal (val, CONSP (insdef) ? XCAR (insdef) : insdef);
6529 if (!NILP (tem) && !NILP (default_filename))
6530 val = default_filename;
6531 val = Fsubstitute_in_file_name (val);
6533 if (replace_in_history)
6534 /* Replace what Fcompleting_read added to the history
6535 with what we will actually return. */
6537 Lisp_Object val1 = double_dollars (val);
6538 tem = Fsymbol_value (Qfile_name_history);
6539 if (history_delete_duplicates)
6540 XSETCDR (tem, Fdelete (val1, XCDR(tem)));
6541 XSETCAR (tem, val1);
6543 else if (add_to_history)
6545 /* Add the value to the history--but not if it matches
6546 the last value already there. */
6547 Lisp_Object val1 = double_dollars (val);
6548 tem = Fsymbol_value (Qfile_name_history);
6549 if (! CONSP (tem) || NILP (Fequal (XCAR (tem), val1)))
6551 if (history_delete_duplicates) tem = Fdelete (val1, tem);
6552 Fset (Qfile_name_history, Fcons (val1, tem));
6556 return val;
6560 void
6561 init_fileio_once ()
6563 /* Must be set before any path manipulation is performed. */
6564 XSETFASTINT (Vdirectory_sep_char, '/');
6568 void
6569 syms_of_fileio ()
6571 Qoperations = intern ("operations");
6572 Qexpand_file_name = intern ("expand-file-name");
6573 Qsubstitute_in_file_name = intern ("substitute-in-file-name");
6574 Qdirectory_file_name = intern ("directory-file-name");
6575 Qfile_name_directory = intern ("file-name-directory");
6576 Qfile_name_nondirectory = intern ("file-name-nondirectory");
6577 Qunhandled_file_name_directory = intern ("unhandled-file-name-directory");
6578 Qfile_name_as_directory = intern ("file-name-as-directory");
6579 Qcopy_file = intern ("copy-file");
6580 Qmake_directory_internal = intern ("make-directory-internal");
6581 Qmake_directory = intern ("make-directory");
6582 Qdelete_directory = intern ("delete-directory");
6583 Qdelete_file = intern ("delete-file");
6584 Qrename_file = intern ("rename-file");
6585 Qadd_name_to_file = intern ("add-name-to-file");
6586 Qmake_symbolic_link = intern ("make-symbolic-link");
6587 Qfile_exists_p = intern ("file-exists-p");
6588 Qfile_executable_p = intern ("file-executable-p");
6589 Qfile_readable_p = intern ("file-readable-p");
6590 Qfile_writable_p = intern ("file-writable-p");
6591 Qfile_symlink_p = intern ("file-symlink-p");
6592 Qaccess_file = intern ("access-file");
6593 Qfile_directory_p = intern ("file-directory-p");
6594 Qfile_regular_p = intern ("file-regular-p");
6595 Qfile_accessible_directory_p = intern ("file-accessible-directory-p");
6596 Qfile_modes = intern ("file-modes");
6597 Qset_file_modes = intern ("set-file-modes");
6598 Qset_file_times = intern ("set-file-times");
6599 Qfile_newer_than_file_p = intern ("file-newer-than-file-p");
6600 Qinsert_file_contents = intern ("insert-file-contents");
6601 Qwrite_region = intern ("write-region");
6602 Qverify_visited_file_modtime = intern ("verify-visited-file-modtime");
6603 Qset_visited_file_modtime = intern ("set-visited-file-modtime");
6604 Qauto_save_coding = intern ("auto-save-coding");
6606 staticpro (&Qoperations);
6607 staticpro (&Qexpand_file_name);
6608 staticpro (&Qsubstitute_in_file_name);
6609 staticpro (&Qdirectory_file_name);
6610 staticpro (&Qfile_name_directory);
6611 staticpro (&Qfile_name_nondirectory);
6612 staticpro (&Qunhandled_file_name_directory);
6613 staticpro (&Qfile_name_as_directory);
6614 staticpro (&Qcopy_file);
6615 staticpro (&Qmake_directory_internal);
6616 staticpro (&Qmake_directory);
6617 staticpro (&Qdelete_directory);
6618 staticpro (&Qdelete_file);
6619 staticpro (&Qrename_file);
6620 staticpro (&Qadd_name_to_file);
6621 staticpro (&Qmake_symbolic_link);
6622 staticpro (&Qfile_exists_p);
6623 staticpro (&Qfile_executable_p);
6624 staticpro (&Qfile_readable_p);
6625 staticpro (&Qfile_writable_p);
6626 staticpro (&Qaccess_file);
6627 staticpro (&Qfile_symlink_p);
6628 staticpro (&Qfile_directory_p);
6629 staticpro (&Qfile_regular_p);
6630 staticpro (&Qfile_accessible_directory_p);
6631 staticpro (&Qfile_modes);
6632 staticpro (&Qset_file_modes);
6633 staticpro (&Qset_file_times);
6634 staticpro (&Qfile_newer_than_file_p);
6635 staticpro (&Qinsert_file_contents);
6636 staticpro (&Qwrite_region);
6637 staticpro (&Qverify_visited_file_modtime);
6638 staticpro (&Qset_visited_file_modtime);
6639 staticpro (&Qauto_save_coding);
6641 Qfile_name_history = intern ("file-name-history");
6642 Fset (Qfile_name_history, Qnil);
6643 staticpro (&Qfile_name_history);
6645 Qfile_error = intern ("file-error");
6646 staticpro (&Qfile_error);
6647 Qfile_already_exists = intern ("file-already-exists");
6648 staticpro (&Qfile_already_exists);
6649 Qfile_date_error = intern ("file-date-error");
6650 staticpro (&Qfile_date_error);
6651 Qexcl = intern ("excl");
6652 staticpro (&Qexcl);
6654 #ifdef DOS_NT
6655 Qfind_buffer_file_type = intern ("find-buffer-file-type");
6656 staticpro (&Qfind_buffer_file_type);
6657 #endif /* DOS_NT */
6659 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system,
6660 doc: /* *Coding system for encoding file names.
6661 If it is nil, `default-file-name-coding-system' (which see) is used. */);
6662 Vfile_name_coding_system = Qnil;
6664 DEFVAR_LISP ("default-file-name-coding-system",
6665 &Vdefault_file_name_coding_system,
6666 doc: /* Default coding system for encoding file names.
6667 This variable is used only when `file-name-coding-system' is nil.
6669 This variable is set/changed by the command `set-language-environment'.
6670 User should not set this variable manually,
6671 instead use `file-name-coding-system' to get a constant encoding
6672 of file names regardless of the current language environment. */);
6673 Vdefault_file_name_coding_system = Qnil;
6675 Qformat_decode = intern ("format-decode");
6676 staticpro (&Qformat_decode);
6677 Qformat_annotate_function = intern ("format-annotate-function");
6678 staticpro (&Qformat_annotate_function);
6679 Qafter_insert_file_set_coding = intern ("after-insert-file-set-coding");
6680 staticpro (&Qafter_insert_file_set_coding);
6682 Qcar_less_than_car = intern ("car-less-than-car");
6683 staticpro (&Qcar_less_than_car);
6685 Fput (Qfile_error, Qerror_conditions,
6686 list2 (Qfile_error, Qerror));
6687 Fput (Qfile_error, Qerror_message,
6688 build_string ("File error"));
6690 Fput (Qfile_already_exists, Qerror_conditions,
6691 list3 (Qfile_already_exists, Qfile_error, Qerror));
6692 Fput (Qfile_already_exists, Qerror_message,
6693 build_string ("File already exists"));
6695 Fput (Qfile_date_error, Qerror_conditions,
6696 list3 (Qfile_date_error, Qfile_error, Qerror));
6697 Fput (Qfile_date_error, Qerror_message,
6698 build_string ("Cannot set file date"));
6700 DEFVAR_LISP ("read-file-name-function", &Vread_file_name_function,
6701 doc: /* If this is non-nil, `read-file-name' does its work by calling this function. */);
6702 Vread_file_name_function = Qnil;
6704 DEFVAR_LISP ("read-file-name-predicate", &Vread_file_name_predicate,
6705 doc: /* Current predicate used by `read-file-name-internal'. */);
6706 Vread_file_name_predicate = Qnil;
6708 DEFVAR_BOOL ("read-file-name-completion-ignore-case", &read_file_name_completion_ignore_case,
6709 doc: /* *Non-nil means when reading a file name completion ignores case. */);
6710 #if defined VMS || defined DOS_NT || defined MAC_OS
6711 read_file_name_completion_ignore_case = 1;
6712 #else
6713 read_file_name_completion_ignore_case = 0;
6714 #endif
6716 DEFVAR_BOOL ("insert-default-directory", &insert_default_directory,
6717 doc: /* *Non-nil means when reading a filename start with default dir in minibuffer.
6718 If the initial minibuffer contents are non-empty, you can usually
6719 request a default filename by typing RETURN without editing. For some
6720 commands, exiting with an empty minibuffer has a special meaning,
6721 such as making the current buffer visit no file in the case of
6722 `set-visited-file-name'.
6723 If this variable is non-nil, the minibuffer contents are always
6724 initially non-empty and typing RETURN without editing will fetch the
6725 default name, if one is provided. Note however that this default name
6726 is not necessarily the name originally inserted in the minibuffer, if
6727 that is just the default directory.
6728 If this variable is nil, the minibuffer often starts out empty. In
6729 that case you may have to explicitly fetch the next history element to
6730 request the default name. */);
6731 insert_default_directory = 1;
6733 DEFVAR_BOOL ("vms-stmlf-recfm", &vms_stmlf_recfm,
6734 doc: /* *Non-nil means write new files with record format `stmlf'.
6735 nil means use format `var'. This variable is meaningful only on VMS. */);
6736 vms_stmlf_recfm = 0;
6738 DEFVAR_LISP ("directory-sep-char", &Vdirectory_sep_char,
6739 doc: /* Directory separator character for built-in functions that return file names.
6740 The value is always ?/. Don't use this variable, just use `/'. */);
6742 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
6743 doc: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
6744 If a file name matches REGEXP, then all I/O on that file is done by calling
6745 HANDLER.
6747 The first argument given to HANDLER is the name of the I/O primitive
6748 to be handled; the remaining arguments are the arguments that were
6749 passed to that primitive. For example, if you do
6750 (file-exists-p FILENAME)
6751 and FILENAME is handled by HANDLER, then HANDLER is called like this:
6752 (funcall HANDLER 'file-exists-p FILENAME)
6753 The function `find-file-name-handler' checks this list for a handler
6754 for its argument. */);
6755 Vfile_name_handler_alist = Qnil;
6757 DEFVAR_LISP ("set-auto-coding-function",
6758 &Vset_auto_coding_function,
6759 doc: /* If non-nil, a function to call to decide a coding system of file.
6760 Two arguments are passed to this function: the file name
6761 and the length of a file contents following the point.
6762 This function should return a coding system to decode the file contents.
6763 It should check the file name against `auto-coding-alist'.
6764 If no coding system is decided, it should check a coding system
6765 specified in the heading lines with the format:
6766 -*- ... coding: CODING-SYSTEM; ... -*-
6767 or local variable spec of the tailing lines with `coding:' tag. */);
6768 Vset_auto_coding_function = Qnil;
6770 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
6771 doc: /* A list of functions to be called at the end of `insert-file-contents'.
6772 Each is passed one argument, the number of characters inserted,
6773 with point at the start of the inserted text. Each function
6774 should leave point the same, and return the new character count.
6775 If `insert-file-contents' is intercepted by a handler from
6776 `file-name-handler-alist', that handler is responsible for calling the
6777 functions in `after-insert-file-functions' if appropriate. */);
6778 Vafter_insert_file_functions = Qnil;
6780 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
6781 doc: /* A list of functions to be called at the start of `write-region'.
6782 Each is passed two arguments, START and END as for `write-region'.
6783 These are usually two numbers but not always; see the documentation
6784 for `write-region'. The function should return a list of pairs
6785 of the form (POSITION . STRING), consisting of strings to be effectively
6786 inserted at the specified positions of the file being written (1 means to
6787 insert before the first byte written). The POSITIONs must be sorted into
6788 increasing order. If there are several functions in the list, the several
6789 lists are merged destructively. Alternatively, the function can return
6790 with a different buffer current; in that case it should pay attention
6791 to the annotations returned by previous functions and listed in
6792 `write-region-annotations-so-far'.*/);
6793 Vwrite_region_annotate_functions = Qnil;
6794 staticpro (&Qwrite_region_annotate_functions);
6795 Qwrite_region_annotate_functions
6796 = intern ("write-region-annotate-functions");
6798 DEFVAR_LISP ("write-region-annotations-so-far",
6799 &Vwrite_region_annotations_so_far,
6800 doc: /* When an annotation function is called, this holds the previous annotations.
6801 These are the annotations made by other annotation functions
6802 that were already called. See also `write-region-annotate-functions'. */);
6803 Vwrite_region_annotations_so_far = Qnil;
6805 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
6806 doc: /* A list of file name handlers that temporarily should not be used.
6807 This applies only to the operation `inhibit-file-name-operation'. */);
6808 Vinhibit_file_name_handlers = Qnil;
6810 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
6811 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6812 Vinhibit_file_name_operation = Qnil;
6814 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
6815 doc: /* File name in which we write a list of all auto save file names.
6816 This variable is initialized automatically from `auto-save-list-file-prefix'
6817 shortly after Emacs reads your `.emacs' file, if you have not yet given it
6818 a non-nil value. */);
6819 Vauto_save_list_file_name = Qnil;
6821 #ifdef HAVE_FSYNC
6822 DEFVAR_BOOL ("write-region-inhibit-fsync", &write_region_inhibit_fsync,
6823 doc: /* *Non-nil means don't call fsync in `write-region'.
6824 This variable affects calls to `write-region' as well as save commands.
6825 A non-nil value may result in data loss! */);
6826 write_region_inhibit_fsync = 0;
6827 #endif
6829 defsubr (&Sfind_file_name_handler);
6830 defsubr (&Sfile_name_directory);
6831 defsubr (&Sfile_name_nondirectory);
6832 defsubr (&Sunhandled_file_name_directory);
6833 defsubr (&Sfile_name_as_directory);
6834 defsubr (&Sdirectory_file_name);
6835 defsubr (&Smake_temp_name);
6836 defsubr (&Sexpand_file_name);
6837 defsubr (&Ssubstitute_in_file_name);
6838 defsubr (&Scopy_file);
6839 defsubr (&Smake_directory_internal);
6840 defsubr (&Sdelete_directory);
6841 defsubr (&Sdelete_file);
6842 defsubr (&Srename_file);
6843 defsubr (&Sadd_name_to_file);
6844 #ifdef S_IFLNK
6845 defsubr (&Smake_symbolic_link);
6846 #endif /* S_IFLNK */
6847 #ifdef VMS
6848 defsubr (&Sdefine_logical_name);
6849 #endif /* VMS */
6850 #ifdef HPUX_NET
6851 defsubr (&Ssysnetunam);
6852 #endif /* HPUX_NET */
6853 defsubr (&Sfile_name_absolute_p);
6854 defsubr (&Sfile_exists_p);
6855 defsubr (&Sfile_executable_p);
6856 defsubr (&Sfile_readable_p);
6857 defsubr (&Sfile_writable_p);
6858 defsubr (&Saccess_file);
6859 defsubr (&Sfile_symlink_p);
6860 defsubr (&Sfile_directory_p);
6861 defsubr (&Sfile_accessible_directory_p);
6862 defsubr (&Sfile_regular_p);
6863 defsubr (&Sfile_modes);
6864 defsubr (&Sset_file_modes);
6865 defsubr (&Sset_file_times);
6866 defsubr (&Sset_default_file_modes);
6867 defsubr (&Sdefault_file_modes);
6868 defsubr (&Sfile_newer_than_file_p);
6869 defsubr (&Sinsert_file_contents);
6870 defsubr (&Swrite_region);
6871 defsubr (&Scar_less_than_car);
6872 defsubr (&Sverify_visited_file_modtime);
6873 defsubr (&Sclear_visited_file_modtime);
6874 defsubr (&Svisited_file_modtime);
6875 defsubr (&Sset_visited_file_modtime);
6876 defsubr (&Sdo_auto_save);
6877 defsubr (&Sset_buffer_auto_saved);
6878 defsubr (&Sclear_buffer_auto_save_failure);
6879 defsubr (&Srecent_auto_save_p);
6881 defsubr (&Sread_file_name_internal);
6882 defsubr (&Sread_file_name);
6883 defsubr (&Snext_read_file_uses_dialog_p);
6885 #ifdef HAVE_SYNC
6886 defsubr (&Sunix_sync);
6887 #endif
6890 /* arch-tag: 64ba3fd7-f844-4fb2-ba4b-427eb928786c
6891 (do not change this comment) */