1 /* File IO for GNU Emacs.
2 Copyright (C) 1985,86,87,88,93,94,95,96,97,98,99,2000, 2001
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #define _GNU_SOURCE /* for euidaccess */
26 #if defined (USG5) || defined (BSD_SYSTEM) || defined (GNU_LINUX)
31 #include <sys/types.h>
38 #if !defined (S_ISLNK) && defined (S_IFLNK)
39 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
42 #if !defined (S_ISFIFO) && defined (S_IFIFO)
43 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
46 #if !defined (S_ISREG) && defined (S_IFREG)
47 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
88 #include "intervals.h"
90 #include "character.h"
99 #endif /* not WINDOWSNT */
103 #include <sys/param.h>
111 #define CORRECT_DIR_SEPS(s) \
112 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
113 else unixtodos_filename (s); \
115 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
116 redirector allows the six letters between 'Z' and 'a' as well. */
118 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
121 #define IS_DRIVE(x) isalpha (x)
123 /* Need to lower-case the drive letter, or else expanded
124 filenames will sometimes compare inequal, because
125 `expand-file-name' doesn't always down-case the drive letter. */
126 #define DRIVE_LETTER(x) (tolower (x))
147 #include "commands.h"
148 extern int use_dialog_box
;
162 /* Nonzero during writing of auto-save files */
165 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
166 a new file with the same mode as the original */
167 int auto_save_mode_bits
;
169 /* Coding system for file names, or nil if none. */
170 Lisp_Object Vfile_name_coding_system
;
172 /* Coding system for file names used only when
173 Vfile_name_coding_system is nil. */
174 Lisp_Object Vdefault_file_name_coding_system
;
176 /* Alist of elements (REGEXP . HANDLER) for file names
177 whose I/O is done with a special handler. */
178 Lisp_Object Vfile_name_handler_alist
;
180 /* Format for auto-save files */
181 Lisp_Object Vauto_save_file_format
;
183 /* Lisp functions for translating file formats */
184 Lisp_Object Qformat_decode
, Qformat_annotate_function
;
186 /* Function to be called to decide a coding system of a reading file. */
187 Lisp_Object Vset_auto_coding_function
;
189 /* Functions to be called to process text properties in inserted file. */
190 Lisp_Object Vafter_insert_file_functions
;
192 /* Functions to be called to create text property annotations for file. */
193 Lisp_Object Vwrite_region_annotate_functions
;
195 /* During build_annotations, each time an annotation function is called,
196 this holds the annotations made by the previous functions. */
197 Lisp_Object Vwrite_region_annotations_so_far
;
199 /* File name in which we write a list of all our auto save files. */
200 Lisp_Object Vauto_save_list_file_name
;
202 /* Nonzero means, when reading a filename in the minibuffer,
203 start out by inserting the default directory into the minibuffer. */
204 int insert_default_directory
;
206 /* On VMS, nonzero means write new files with record format stmlf.
207 Zero means use var format. */
210 /* On NT, specifies the directory separator character, used (eg.) when
211 expanding file names. This can be bound to / or \. */
212 Lisp_Object Vdirectory_sep_char
;
214 extern Lisp_Object Vuser_login_name
;
217 extern Lisp_Object Vw32_get_true_file_attributes
;
220 extern int minibuf_level
;
222 extern int minibuffer_auto_raise
;
224 /* These variables describe handlers that have "already" had a chance
225 to handle the current operation.
227 Vinhibit_file_name_handlers is a list of file name handlers.
228 Vinhibit_file_name_operation is the operation being handled.
229 If we try to handle that operation, we ignore those handlers. */
231 static Lisp_Object Vinhibit_file_name_handlers
;
232 static Lisp_Object Vinhibit_file_name_operation
;
234 Lisp_Object Qfile_error
, Qfile_already_exists
, Qfile_date_error
;
236 Lisp_Object Qfile_name_history
;
238 Lisp_Object Qcar_less_than_car
;
240 static int a_write
P_ ((int, Lisp_Object
, int, int,
241 Lisp_Object
*, struct coding_system
*));
242 static int e_write
P_ ((int, Lisp_Object
, int, int, struct coding_system
*));
246 report_file_error (string
, data
)
250 Lisp_Object errstring
;
253 synchronize_system_messages_locale ();
254 errstring
= code_convert_string_norecord (build_string (strerror (errorno
)),
255 Vlocale_coding_system
, 0);
261 Fsignal (Qfile_already_exists
, Fcons (errstring
, data
));
264 /* System error messages are capitalized. Downcase the initial
265 unless it is followed by a slash. */
266 if (XSTRING (errstring
)->data
[1] != '/')
267 XSTRING (errstring
)->data
[0] = DOWNCASE (XSTRING (errstring
)->data
[0]);
269 Fsignal (Qfile_error
,
270 Fcons (build_string (string
), Fcons (errstring
, data
)));
275 close_file_unwind (fd
)
278 emacs_close (XFASTINT (fd
));
282 /* Restore point, having saved it as a marker. */
285 restore_point_unwind (location
)
286 Lisp_Object location
;
288 Fgoto_char (location
);
289 Fset_marker (location
, Qnil
, Qnil
);
293 Lisp_Object Qexpand_file_name
;
294 Lisp_Object Qsubstitute_in_file_name
;
295 Lisp_Object Qdirectory_file_name
;
296 Lisp_Object Qfile_name_directory
;
297 Lisp_Object Qfile_name_nondirectory
;
298 Lisp_Object Qunhandled_file_name_directory
;
299 Lisp_Object Qfile_name_as_directory
;
300 Lisp_Object Qcopy_file
;
301 Lisp_Object Qmake_directory_internal
;
302 Lisp_Object Qmake_directory
;
303 Lisp_Object Qdelete_directory
;
304 Lisp_Object Qdelete_file
;
305 Lisp_Object Qrename_file
;
306 Lisp_Object Qadd_name_to_file
;
307 Lisp_Object Qmake_symbolic_link
;
308 Lisp_Object Qfile_exists_p
;
309 Lisp_Object Qfile_executable_p
;
310 Lisp_Object Qfile_readable_p
;
311 Lisp_Object Qfile_writable_p
;
312 Lisp_Object Qfile_symlink_p
;
313 Lisp_Object Qaccess_file
;
314 Lisp_Object Qfile_directory_p
;
315 Lisp_Object Qfile_regular_p
;
316 Lisp_Object Qfile_accessible_directory_p
;
317 Lisp_Object Qfile_modes
;
318 Lisp_Object Qset_file_modes
;
319 Lisp_Object Qfile_newer_than_file_p
;
320 Lisp_Object Qinsert_file_contents
;
321 Lisp_Object Qwrite_region
;
322 Lisp_Object Qverify_visited_file_modtime
;
323 Lisp_Object Qset_visited_file_modtime
;
325 DEFUN ("find-file-name-handler", Ffind_file_name_handler
, Sfind_file_name_handler
, 2, 2, 0,
326 doc
: /* Return FILENAME's handler function for OPERATION, if it has one.
327 Otherwise, return nil.
328 A file name is handled if one of the regular expressions in
329 `file-name-handler-alist' matches it.
331 If OPERATION equals `inhibit-file-name-operation', then we ignore
332 any handlers that are members of `inhibit-file-name-handlers',
333 but we still do run any other handlers. This lets handlers
334 use the standard functions without calling themselves recursively. */)
335 (filename
, operation
)
336 Lisp_Object filename
, operation
;
338 /* This function must not munge the match data. */
339 Lisp_Object chain
, inhibited_handlers
, result
;
343 CHECK_STRING (filename
);
345 if (EQ (operation
, Vinhibit_file_name_operation
))
346 inhibited_handlers
= Vinhibit_file_name_handlers
;
348 inhibited_handlers
= Qnil
;
350 for (chain
= Vfile_name_handler_alist
; CONSP (chain
);
351 chain
= XCDR (chain
))
361 && (match_pos
= fast_string_match (string
, filename
)) > pos
)
363 Lisp_Object handler
, tem
;
365 handler
= XCDR (elt
);
366 tem
= Fmemq (handler
, inhibited_handlers
);
380 DEFUN ("file-name-directory", Ffile_name_directory
, Sfile_name_directory
,
382 doc
: /* Return the directory component in file name FILENAME.
383 Return nil if FILENAME does not include a directory.
384 Otherwise return a directory spec.
385 Given a Unix syntax file name, returns a string ending in slash;
386 on VMS, perhaps instead a string ending in `:', `]' or `>'. */)
388 Lisp_Object filename
;
390 register unsigned char *beg
;
391 register unsigned char *p
;
394 CHECK_STRING (filename
);
396 /* If the file name has special constructs in it,
397 call the corresponding file handler. */
398 handler
= Ffind_file_name_handler (filename
, Qfile_name_directory
);
400 return call2 (handler
, Qfile_name_directory
, filename
);
402 #ifdef FILE_SYSTEM_CASE
403 filename
= FILE_SYSTEM_CASE (filename
);
405 beg
= XSTRING (filename
)->data
;
407 beg
= strcpy (alloca (strlen (beg
) + 1), beg
);
409 p
= beg
+ STRING_BYTES (XSTRING (filename
));
411 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
413 && p
[-1] != ':' && p
[-1] != ']' && p
[-1] != '>'
416 /* only recognise drive specifier at the beginning */
418 /* handle the "/:d:foo" and "/:foo" cases correctly */
419 && ((p
== beg
+ 2 && !IS_DIRECTORY_SEP (*beg
))
420 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
427 /* Expansion of "c:" to drive and default directory. */
430 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
431 unsigned char *res
= alloca (MAXPATHLEN
+ 1);
432 unsigned char *r
= res
;
434 if (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
) && beg
[1] == ':')
436 strncpy (res
, beg
, 2);
441 if (getdefdir (toupper (*beg
) - 'A' + 1, r
))
443 if (!IS_DIRECTORY_SEP (res
[strlen (res
) - 1]))
446 p
= beg
+ strlen (beg
);
449 CORRECT_DIR_SEPS (beg
);
452 if (STRING_MULTIBYTE (filename
))
453 return make_string (beg
, p
- beg
);
454 return make_unibyte_string (beg
, p
- beg
);
457 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory
,
458 Sfile_name_nondirectory
, 1, 1, 0,
459 doc
: /* Return file name FILENAME sans its directory.
460 For example, in a Unix-syntax file name,
461 this is everything after the last slash,
462 or the entire name if it contains no slash. */)
464 Lisp_Object filename
;
466 register unsigned char *beg
, *p
, *end
;
469 CHECK_STRING (filename
);
471 /* If the file name has special constructs in it,
472 call the corresponding file handler. */
473 handler
= Ffind_file_name_handler (filename
, Qfile_name_nondirectory
);
475 return call2 (handler
, Qfile_name_nondirectory
, filename
);
477 beg
= XSTRING (filename
)->data
;
478 end
= p
= beg
+ STRING_BYTES (XSTRING (filename
));
480 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
482 && p
[-1] != ':' && p
[-1] != ']' && p
[-1] != '>'
485 /* only recognise drive specifier at beginning */
487 /* handle the "/:d:foo" case correctly */
488 && (p
== beg
+ 2 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
493 if (STRING_MULTIBYTE (filename
))
494 return make_string (p
, end
- p
);
495 return make_unibyte_string (p
, end
- p
);
498 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory
,
499 Sunhandled_file_name_directory
, 1, 1, 0,
500 doc
: /* Return a directly usable directory name somehow associated with FILENAME.
501 A `directly usable' directory name is one that may be used without the
502 intervention of any file handler.
503 If FILENAME is a directly usable file itself, return
504 \(file-name-directory FILENAME).
505 The `call-process' and `start-process' functions use this function to
506 get a current directory to run processes in. */)
508 Lisp_Object filename
;
512 /* If the file name has special constructs in it,
513 call the corresponding file handler. */
514 handler
= Ffind_file_name_handler (filename
, Qunhandled_file_name_directory
);
516 return call2 (handler
, Qunhandled_file_name_directory
, filename
);
518 return Ffile_name_directory (filename
);
523 file_name_as_directory (out
, in
)
526 int size
= strlen (in
) - 1;
539 /* Is it already a directory string? */
540 if (in
[size
] == ':' || in
[size
] == ']' || in
[size
] == '>')
542 /* Is it a VMS directory file name? If so, hack VMS syntax. */
543 else if (! index (in
, '/')
544 && ((size
> 3 && ! strcmp (&in
[size
- 3], ".DIR"))
545 || (size
> 3 && ! strcmp (&in
[size
- 3], ".dir"))
546 || (size
> 5 && (! strncmp (&in
[size
- 5], ".DIR", 4)
547 || ! strncmp (&in
[size
- 5], ".dir", 4))
548 && (in
[size
- 1] == '.' || in
[size
- 1] == ';')
549 && in
[size
] == '1')))
551 register char *p
, *dot
;
555 dir:x.dir --> dir:[x]
556 dir:[x]y.dir --> dir:[x.y] */
558 while (p
!= in
&& *p
!= ':' && *p
!= '>' && *p
!= ']') p
--;
561 strncpy (out
, in
, p
- in
);
580 dot
= index (p
, '.');
583 /* blindly remove any extension */
584 size
= strlen (out
) + (dot
- p
);
585 strncat (out
, p
, dot
- p
);
596 /* For Unix syntax, Append a slash if necessary */
597 if (!IS_DIRECTORY_SEP (out
[size
]))
599 out
[size
+ 1] = DIRECTORY_SEP
;
600 out
[size
+ 2] = '\0';
603 CORRECT_DIR_SEPS (out
);
609 DEFUN ("file-name-as-directory", Ffile_name_as_directory
,
610 Sfile_name_as_directory
, 1, 1, 0,
611 doc
: /* Return a string representing file FILENAME interpreted as a directory.
612 This operation exists because a directory is also a file, but its name as
613 a directory is different from its name as a file.
614 The result can be used as the value of `default-directory'
615 or passed as second argument to `expand-file-name'.
616 For a Unix-syntax file name, just appends a slash.
617 On VMS, converts \"[X]FOO.DIR\" to \"[X.FOO]\", etc. */)
628 /* If the file name has special constructs in it,
629 call the corresponding file handler. */
630 handler
= Ffind_file_name_handler (file
, Qfile_name_as_directory
);
632 return call2 (handler
, Qfile_name_as_directory
, file
);
634 buf
= (char *) alloca (STRING_BYTES (XSTRING (file
)) + 10);
635 return build_string (file_name_as_directory (buf
, XSTRING (file
)->data
));
639 * Convert from directory name to filename.
641 * xyzzy:[mukesh.emacs] => xyzzy:[mukesh]emacs.dir.1
642 * xyzzy:[mukesh] => xyzzy:[000000]mukesh.dir.1
643 * On UNIX, it's simple: just make sure there isn't a terminating /
645 * Value is nonzero if the string output is different from the input.
649 directory_file_name (src
, dst
)
657 struct FAB fab
= cc$rms_fab
;
658 struct NAM nam
= cc$rms_nam
;
659 char esa
[NAM$C_MAXRSS
];
664 if (! index (src
, '/')
665 && (src
[slen
- 1] == ']'
666 || src
[slen
- 1] == ':'
667 || src
[slen
- 1] == '>'))
669 /* VMS style - convert [x.y.z] to [x.y]z, [x] to [000000]x */
671 fab
.fab$b_fns
= slen
;
672 fab
.fab$l_nam
= &nam
;
673 fab
.fab$l_fop
= FAB$M_NAM
;
676 nam
.nam$b_ess
= sizeof esa
;
677 nam
.nam$b_nop
|= NAM$M_SYNCHK
;
679 /* We call SYS$PARSE to handle such things as [--] for us. */
680 if (SYS$
PARSE (&fab
, 0, 0) == RMS$_NORMAL
)
682 slen
= nam
.nam$b_esl
;
683 if (esa
[slen
- 1] == ';' && esa
[slen
- 2] == '.')
688 if (src
[slen
- 1] != ']' && src
[slen
- 1] != '>')
690 /* what about when we have logical_name:???? */
691 if (src
[slen
- 1] == ':')
692 { /* Xlate logical name and see what we get */
693 ptr
= strcpy (dst
, src
); /* upper case for getenv */
696 if ('a' <= *ptr
&& *ptr
<= 'z')
700 dst
[slen
- 1] = 0; /* remove colon */
701 if (!(src
= egetenv (dst
)))
703 /* should we jump to the beginning of this procedure?
704 Good points: allows us to use logical names that xlate
706 Bad points: can be a problem if we just translated to a device
708 For now, I'll punt and always expect VMS names, and hope for
711 if (src
[slen
- 1] != ']' && src
[slen
- 1] != '>')
712 { /* no recursion here! */
718 { /* not a directory spec */
723 bracket
= src
[slen
- 1];
725 /* If bracket is ']' or '>', bracket - 2 is the corresponding
727 ptr
= index (src
, bracket
- 2);
729 { /* no opening bracket */
733 if (!(rptr
= rindex (src
, '.')))
736 strncpy (dst
, src
, slen
);
740 dst
[slen
++] = bracket
;
745 /* If we have the top-level of a rooted directory (i.e. xx:[000000]),
746 then translate the device and recurse. */
747 if (dst
[slen
- 1] == ':'
748 && dst
[slen
- 2] != ':' /* skip decnet nodes */
749 && strcmp (src
+ slen
, "[000000]") == 0)
751 dst
[slen
- 1] = '\0';
752 if ((ptr
= egetenv (dst
))
753 && (rlen
= strlen (ptr
) - 1) > 0
754 && (ptr
[rlen
] == ']' || ptr
[rlen
] == '>')
755 && ptr
[rlen
- 1] == '.')
757 char * buf
= (char *) alloca (strlen (ptr
) + 1);
761 return directory_file_name (buf
, dst
);
766 strcat (dst
, "[000000]");
770 rlen
= strlen (rptr
) - 1;
771 strncat (dst
, rptr
, rlen
);
772 dst
[slen
+ rlen
] = '\0';
773 strcat (dst
, ".DIR.1");
777 /* Process as Unix format: just remove any final slash.
778 But leave "/" unchanged; do not change it to "". */
781 /* Handle // as root for apollo's. */
782 if ((slen
> 2 && dst
[slen
- 1] == '/')
783 || (slen
> 1 && dst
[0] != '/' && dst
[slen
- 1] == '/'))
787 && IS_DIRECTORY_SEP (dst
[slen
- 1])
789 && !IS_ANY_SEP (dst
[slen
- 2])
795 CORRECT_DIR_SEPS (dst
);
800 DEFUN ("directory-file-name", Fdirectory_file_name
, Sdirectory_file_name
,
802 doc
: /* Returns the file name of the directory named DIRECTORY.
803 This is the name of the file that holds the data for the directory DIRECTORY.
804 This operation exists because a directory is also a file, but its name as
805 a directory is different from its name as a file.
806 In Unix-syntax, this function just removes the final slash.
807 On VMS, given a VMS-syntax directory name such as \"[X.Y]\",
808 it returns a file name such as \"[X]Y.DIR.1\". */)
810 Lisp_Object directory
;
815 CHECK_STRING (directory
);
817 if (NILP (directory
))
820 /* If the file name has special constructs in it,
821 call the corresponding file handler. */
822 handler
= Ffind_file_name_handler (directory
, Qdirectory_file_name
);
824 return call2 (handler
, Qdirectory_file_name
, directory
);
827 /* 20 extra chars is insufficient for VMS, since we might perform a
828 logical name translation. an equivalence string can be up to 255
829 chars long, so grab that much extra space... - sss */
830 buf
= (char *) alloca (STRING_BYTES (XSTRING (directory
)) + 20 + 255);
832 buf
= (char *) alloca (STRING_BYTES (XSTRING (directory
)) + 20);
834 directory_file_name (XSTRING (directory
)->data
, buf
);
835 return build_string (buf
);
838 static char make_temp_name_tbl
[64] =
840 'A','B','C','D','E','F','G','H',
841 'I','J','K','L','M','N','O','P',
842 'Q','R','S','T','U','V','W','X',
843 'Y','Z','a','b','c','d','e','f',
844 'g','h','i','j','k','l','m','n',
845 'o','p','q','r','s','t','u','v',
846 'w','x','y','z','0','1','2','3',
847 '4','5','6','7','8','9','-','_'
850 static unsigned make_temp_name_count
, make_temp_name_count_initialized_p
;
852 /* Value is a temporary file name starting with PREFIX, a string.
854 The Emacs process number forms part of the result, so there is
855 no danger of generating a name being used by another process.
856 In addition, this function makes an attempt to choose a name
857 which has no existing file. To make this work, PREFIX should be
858 an absolute file name.
860 BASE64_P non-zero means add the pid as 3 characters in base64
861 encoding. In this case, 6 characters will be added to PREFIX to
862 form the file name. Otherwise, if Emacs is running on a system
863 with long file names, add the pid as a decimal number.
865 This function signals an error if no unique file name could be
869 make_temp_name (prefix
, base64_p
)
876 unsigned char *p
, *data
;
880 CHECK_STRING (prefix
);
882 /* VAL is created by adding 6 characters to PREFIX. The first
883 three are the PID of this process, in base 64, and the second
884 three are incremented if the file already exists. This ensures
885 262144 unique file names per PID per PREFIX. */
887 pid
= (int) getpid ();
891 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
892 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
893 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
898 #ifdef HAVE_LONG_FILE_NAMES
899 sprintf (pidbuf
, "%d", pid
);
900 pidlen
= strlen (pidbuf
);
902 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
903 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
904 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
909 len
= XSTRING (prefix
)->size
;
910 val
= make_uninit_string (len
+ 3 + pidlen
);
911 data
= XSTRING (val
)->data
;
912 bcopy(XSTRING (prefix
)->data
, data
, len
);
915 bcopy (pidbuf
, p
, pidlen
);
918 /* Here we try to minimize useless stat'ing when this function is
919 invoked many times successively with the same PREFIX. We achieve
920 this by initializing count to a random value, and incrementing it
923 We don't want make-temp-name to be called while dumping,
924 because then make_temp_name_count_initialized_p would get set
925 and then make_temp_name_count would not be set when Emacs starts. */
927 if (!make_temp_name_count_initialized_p
)
929 make_temp_name_count
= (unsigned) time (NULL
);
930 make_temp_name_count_initialized_p
= 1;
936 unsigned num
= make_temp_name_count
;
938 p
[0] = make_temp_name_tbl
[num
& 63], num
>>= 6;
939 p
[1] = make_temp_name_tbl
[num
& 63], num
>>= 6;
940 p
[2] = make_temp_name_tbl
[num
& 63], num
>>= 6;
942 /* Poor man's congruential RN generator. Replace with
943 ++make_temp_name_count for debugging. */
944 make_temp_name_count
+= 25229;
945 make_temp_name_count
%= 225307;
947 if (stat (data
, &ignored
) < 0)
949 /* We want to return only if errno is ENOENT. */
953 /* The error here is dubious, but there is little else we
954 can do. The alternatives are to return nil, which is
955 as bad as (and in many cases worse than) throwing the
956 error, or to ignore the error, which will likely result
957 in looping through 225307 stat's, which is not only
958 dog-slow, but also useless since it will fallback to
959 the errow below, anyway. */
960 report_file_error ("Cannot create temporary name for prefix",
961 Fcons (prefix
, Qnil
));
966 error ("Cannot create temporary name for prefix `%s'",
967 XSTRING (prefix
)->data
);
972 DEFUN ("make-temp-name", Fmake_temp_name
, Smake_temp_name
, 1, 1, 0,
973 doc
: /* Generate temporary file name (string) starting with PREFIX (a string).
974 The Emacs process number forms part of the result,
975 so there is no danger of generating a name being used by another process.
977 In addition, this function makes an attempt to choose a name
978 which has no existing file. To make this work,
979 PREFIX should be an absolute file name.
981 There is a race condition between calling `make-temp-name' and creating the
982 file which opens all kinds of security holes. For that reason, you should
983 probably use `make-temp-file' instead. */)
987 return make_temp_name (prefix
, 0);
992 DEFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
993 doc
: /* Convert filename NAME to absolute, and canonicalize it.
994 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
995 (does not start with slash); if DEFAULT-DIRECTORY is nil or missing,
996 the current buffer's value of default-directory is used.
997 File name components that are `.' are removed, and
998 so are file name components followed by `..', along with the `..' itself;
999 note that these simplifications are done without checking the resulting
1000 file names in the file system.
1001 An initial `~/' expands to your home directory.
1002 An initial `~USER/' expands to USER's home directory.
1003 See also the function `substitute-in-file-name'. */)
1004 (name
, default_directory
)
1005 Lisp_Object name
, default_directory
;
1009 register unsigned char *newdir
, *p
, *o
;
1011 unsigned char *target
;
1014 unsigned char * colon
= 0;
1015 unsigned char * close
= 0;
1016 unsigned char * slash
= 0;
1017 unsigned char * brack
= 0;
1018 int lbrack
= 0, rbrack
= 0;
1023 int collapse_newdir
= 1;
1027 Lisp_Object handler
;
1029 CHECK_STRING (name
);
1031 /* If the file name has special constructs in it,
1032 call the corresponding file handler. */
1033 handler
= Ffind_file_name_handler (name
, Qexpand_file_name
);
1034 if (!NILP (handler
))
1035 return call3 (handler
, Qexpand_file_name
, name
, default_directory
);
1037 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
1038 if (NILP (default_directory
))
1039 default_directory
= current_buffer
->directory
;
1040 if (! STRINGP (default_directory
))
1043 /* "/" is not considered a root directory on DOS_NT, so using "/"
1044 here causes an infinite recursion in, e.g., the following:
1046 (let (default-directory)
1047 (expand-file-name "a"))
1049 To avoid this, we set default_directory to the root of the
1051 extern char *emacs_root_dir (void);
1053 default_directory
= build_string (emacs_root_dir ());
1055 default_directory
= build_string ("/");
1059 if (!NILP (default_directory
))
1061 handler
= Ffind_file_name_handler (default_directory
, Qexpand_file_name
);
1062 if (!NILP (handler
))
1063 return call3 (handler
, Qexpand_file_name
, name
, default_directory
);
1066 o
= XSTRING (default_directory
)->data
;
1068 /* Make sure DEFAULT_DIRECTORY is properly expanded.
1069 It would be better to do this down below where we actually use
1070 default_directory. Unfortunately, calling Fexpand_file_name recursively
1071 could invoke GC, and the strings might be relocated. This would
1072 be annoying because we have pointers into strings lying around
1073 that would need adjusting, and people would add new pointers to
1074 the code and forget to adjust them, resulting in intermittent bugs.
1075 Putting this call here avoids all that crud.
1077 The EQ test avoids infinite recursion. */
1078 if (! NILP (default_directory
) && !EQ (default_directory
, name
)
1079 /* Save time in some common cases - as long as default_directory
1080 is not relative, it can be canonicalized with name below (if it
1081 is needed at all) without requiring it to be expanded now. */
1083 /* Detect MSDOS file names with drive specifiers. */
1084 && ! (IS_DRIVE (o
[0]) && IS_DEVICE_SEP (o
[1]) && IS_DIRECTORY_SEP (o
[2]))
1086 /* Detect Windows file names in UNC format. */
1087 && ! (IS_DIRECTORY_SEP (o
[0]) && IS_DIRECTORY_SEP (o
[1]))
1089 #else /* not DOS_NT */
1090 /* Detect Unix absolute file names (/... alone is not absolute on
1092 && ! (IS_DIRECTORY_SEP (o
[0]))
1093 #endif /* not DOS_NT */
1096 struct gcpro gcpro1
;
1099 default_directory
= Fexpand_file_name (default_directory
, Qnil
);
1104 /* Filenames on VMS are always upper case. */
1105 name
= Fupcase (name
);
1107 #ifdef FILE_SYSTEM_CASE
1108 name
= FILE_SYSTEM_CASE (name
);
1111 nm
= XSTRING (name
)->data
;
1114 /* We will force directory separators to be either all \ or /, so make
1115 a local copy to modify, even if there ends up being no change. */
1116 nm
= strcpy (alloca (strlen (nm
) + 1), nm
);
1118 /* Note if special escape prefix is present, but remove for now. */
1119 if (nm
[0] == '/' && nm
[1] == ':')
1125 /* Find and remove drive specifier if present; this makes nm absolute
1126 even if the rest of the name appears to be relative. Only look for
1127 drive specifier at the beginning. */
1128 if (IS_DRIVE (nm
[0]) && IS_DEVICE_SEP (nm
[1]))
1135 /* If we see "c://somedir", we want to strip the first slash after the
1136 colon when stripping the drive letter. Otherwise, this expands to
1138 if (drive
&& IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
1140 #endif /* WINDOWSNT */
1144 /* Discard any previous drive specifier if nm is now in UNC format. */
1145 if (IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
1151 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
1152 none are found, we can probably return right away. We will avoid
1153 allocating a new string if name is already fully expanded. */
1155 IS_DIRECTORY_SEP (nm
[0])
1157 && drive
&& !is_escaped
1160 && (drive
|| IS_DIRECTORY_SEP (nm
[1])) && !is_escaped
1167 /* If it turns out that the filename we want to return is just a
1168 suffix of FILENAME, we don't need to go through and edit
1169 things; we just need to construct a new string using data
1170 starting at the middle of FILENAME. If we set lose to a
1171 non-zero value, that means we've discovered that we can't do
1178 /* Since we know the name is absolute, we can assume that each
1179 element starts with a "/". */
1181 /* "." and ".." are hairy. */
1182 if (IS_DIRECTORY_SEP (p
[0])
1184 && (IS_DIRECTORY_SEP (p
[2])
1186 || (p
[2] == '.' && (IS_DIRECTORY_SEP (p
[3])
1189 /* We want to replace multiple `/' in a row with a single
1192 && IS_DIRECTORY_SEP (p
[0])
1193 && IS_DIRECTORY_SEP (p
[1]))
1200 /* if dev:[dir]/, move nm to / */
1201 if (!slash
&& p
> nm
&& (brack
|| colon
)) {
1202 nm
= (brack
? brack
+ 1 : colon
+ 1);
1203 lbrack
= rbrack
= 0;
1211 /* VMS pre V4.4,convert '-'s in filenames. */
1212 if (lbrack
== rbrack
)
1214 if (dots
< 2) /* this is to allow negative version numbers */
1219 if (lbrack
> rbrack
&&
1220 ((p
[-1] == '.' || p
[-1] == '[' || p
[-1] == '<') &&
1221 (p
[1] == '.' || p
[1] == ']' || p
[1] == '>')))
1227 /* count open brackets, reset close bracket pointer */
1228 if (p
[0] == '[' || p
[0] == '<')
1229 lbrack
++, brack
= 0;
1230 /* count close brackets, set close bracket pointer */
1231 if (p
[0] == ']' || p
[0] == '>')
1232 rbrack
++, brack
= p
;
1233 /* detect ][ or >< */
1234 if ((p
[0] == ']' || p
[0] == '>') && (p
[1] == '[' || p
[1] == '<'))
1236 if ((p
[0] == ':' || p
[0] == ']' || p
[0] == '>') && p
[1] == '~')
1237 nm
= p
+ 1, lose
= 1;
1238 if (p
[0] == ':' && (colon
|| slash
))
1239 /* if dev1:[dir]dev2:, move nm to dev2: */
1245 /* if /name/dev:, move nm to dev: */
1248 /* if node::dev:, move colon following dev */
1249 else if (colon
&& colon
[-1] == ':')
1251 /* if dev1:dev2:, move nm to dev2: */
1252 else if (colon
&& colon
[-1] != ':')
1257 if (p
[0] == ':' && !colon
)
1263 if (lbrack
== rbrack
)
1266 else if (p
[0] == '.')
1274 if (index (nm
, '/'))
1275 return build_string (sys_translate_unix (nm
));
1278 /* Make sure directories are all separated with / or \ as
1279 desired, but avoid allocation of a new string when not
1281 CORRECT_DIR_SEPS (nm
);
1283 if (IS_DIRECTORY_SEP (nm
[1]))
1285 if (strcmp (nm
, XSTRING (name
)->data
) != 0)
1286 name
= build_string (nm
);
1290 /* drive must be set, so this is okay */
1291 if (strcmp (nm
- 2, XSTRING (name
)->data
) != 0)
1293 name
= make_string (nm
- 2, p
- nm
+ 2);
1294 XSTRING (name
)->data
[0] = DRIVE_LETTER (drive
);
1295 XSTRING (name
)->data
[1] = ':';
1298 #else /* not DOS_NT */
1299 if (nm
== XSTRING (name
)->data
)
1301 return build_string (nm
);
1302 #endif /* not DOS_NT */
1306 /* At this point, nm might or might not be an absolute file name. We
1307 need to expand ~ or ~user if present, otherwise prefix nm with
1308 default_directory if nm is not absolute, and finally collapse /./
1309 and /foo/../ sequences.
1311 We set newdir to be the appropriate prefix if one is needed:
1312 - the relevant user directory if nm starts with ~ or ~user
1313 - the specified drive's working dir (DOS/NT only) if nm does not
1315 - the value of default_directory.
1317 Note that these prefixes are not guaranteed to be absolute (except
1318 for the working dir of a drive). Therefore, to ensure we always
1319 return an absolute name, if the final prefix is not absolute we
1320 append it to the current working directory. */
1324 if (nm
[0] == '~') /* prefix ~ */
1326 if (IS_DIRECTORY_SEP (nm
[1])
1330 || nm
[1] == 0) /* ~ by itself */
1332 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1333 newdir
= (unsigned char *) "";
1336 collapse_newdir
= 0;
1339 nm
++; /* Don't leave the slash in nm. */
1342 else /* ~user/filename */
1344 for (p
= nm
; *p
&& (!IS_DIRECTORY_SEP (*p
)
1349 o
= (unsigned char *) alloca (p
- nm
+ 1);
1350 bcopy ((char *) nm
, o
, p
- nm
);
1353 pw
= (struct passwd
*) getpwnam (o
+ 1);
1356 newdir
= (unsigned char *) pw
-> pw_dir
;
1358 nm
= p
+ 1; /* skip the terminator */
1362 collapse_newdir
= 0;
1367 /* If we don't find a user of that name, leave the name
1368 unchanged; don't move nm forward to p. */
1373 /* On DOS and Windows, nm is absolute if a drive name was specified;
1374 use the drive's current directory as the prefix if needed. */
1375 if (!newdir
&& drive
)
1377 /* Get default directory if needed to make nm absolute. */
1378 if (!IS_DIRECTORY_SEP (nm
[0]))
1380 newdir
= alloca (MAXPATHLEN
+ 1);
1381 if (!getdefdir (toupper (drive
) - 'A' + 1, newdir
))
1386 /* Either nm starts with /, or drive isn't mounted. */
1387 newdir
= alloca (4);
1388 newdir
[0] = DRIVE_LETTER (drive
);
1396 /* Finally, if no prefix has been specified and nm is not absolute,
1397 then it must be expanded relative to default_directory. */
1401 /* /... alone is not absolute on DOS and Windows. */
1402 && !IS_DIRECTORY_SEP (nm
[0])
1405 && !(IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
1412 newdir
= XSTRING (default_directory
)->data
;
1414 /* Note if special escape prefix is present, but remove for now. */
1415 if (newdir
[0] == '/' && newdir
[1] == ':')
1426 /* First ensure newdir is an absolute name. */
1428 /* Detect MSDOS file names with drive specifiers. */
1429 ! (IS_DRIVE (newdir
[0])
1430 && IS_DEVICE_SEP (newdir
[1]) && IS_DIRECTORY_SEP (newdir
[2]))
1432 /* Detect Windows file names in UNC format. */
1433 && ! (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1]))
1437 /* Effectively, let newdir be (expand-file-name newdir cwd).
1438 Because of the admonition against calling expand-file-name
1439 when we have pointers into lisp strings, we accomplish this
1440 indirectly by prepending newdir to nm if necessary, and using
1441 cwd (or the wd of newdir's drive) as the new newdir. */
1443 if (IS_DRIVE (newdir
[0]) && newdir
[1] == ':')
1448 if (!IS_DIRECTORY_SEP (nm
[0]))
1450 char * tmp
= alloca (strlen (newdir
) + strlen (nm
) + 2);
1451 file_name_as_directory (tmp
, newdir
);
1455 newdir
= alloca (MAXPATHLEN
+ 1);
1458 if (!getdefdir (toupper (drive
) - 'A' + 1, newdir
))
1465 /* Strip off drive name from prefix, if present. */
1466 if (IS_DRIVE (newdir
[0]) && newdir
[1] == ':')
1472 /* Keep only a prefix from newdir if nm starts with slash
1473 (//server/share for UNC, nothing otherwise). */
1474 if (IS_DIRECTORY_SEP (nm
[0]) && collapse_newdir
)
1477 if (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1]))
1479 newdir
= strcpy (alloca (strlen (newdir
) + 1), newdir
);
1481 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1483 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1495 /* Get rid of any slash at the end of newdir, unless newdir is
1496 just / or // (an incomplete UNC name). */
1497 length
= strlen (newdir
);
1498 if (length
> 1 && IS_DIRECTORY_SEP (newdir
[length
- 1])
1500 && !(length
== 2 && IS_DIRECTORY_SEP (newdir
[0]))
1504 unsigned char *temp
= (unsigned char *) alloca (length
);
1505 bcopy (newdir
, temp
, length
- 1);
1506 temp
[length
- 1] = 0;
1514 /* Now concatenate the directory and name to new space in the stack frame */
1515 tlen
+= strlen (nm
) + 1;
1517 /* Reserve space for drive specifier and escape prefix, since either
1518 or both may need to be inserted. (The Microsoft x86 compiler
1519 produces incorrect code if the following two lines are combined.) */
1520 target
= (unsigned char *) alloca (tlen
+ 4);
1522 #else /* not DOS_NT */
1523 target
= (unsigned char *) alloca (tlen
);
1524 #endif /* not DOS_NT */
1530 if (nm
[0] == 0 || IS_DIRECTORY_SEP (nm
[0]))
1533 /* If newdir is effectively "C:/", then the drive letter will have
1534 been stripped and newdir will be "/". Concatenating with an
1535 absolute directory in nm produces "//", which will then be
1536 incorrectly treated as a network share. Ignore newdir in
1537 this case (keeping the drive letter). */
1538 if (!(drive
&& nm
[0] && IS_DIRECTORY_SEP (newdir
[0])
1539 && newdir
[1] == '\0'))
1541 strcpy (target
, newdir
);
1545 file_name_as_directory (target
, newdir
);
1548 strcat (target
, nm
);
1550 if (index (target
, '/'))
1551 strcpy (target
, sys_translate_unix (target
));
1554 /* ASSERT (IS_DIRECTORY_SEP (target[0])) if not VMS */
1556 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1565 if (*p
!= ']' && *p
!= '>' && *p
!= '-')
1571 else if ((p
[0] == ']' || p
[0] == '>') && p
[0] == p
[1] + 2)
1572 /* brackets are offset from each other by 2 */
1575 if (*p
!= '.' && *p
!= '-' && o
[-1] != '.')
1576 /* convert [foo][bar] to [bar] */
1577 while (o
[-1] != '[' && o
[-1] != '<')
1579 else if (*p
== '-' && *o
!= '.')
1582 else if (p
[0] == '-' && o
[-1] == '.' &&
1583 (p
[1] == '.' || p
[1] == ']' || p
[1] == '>'))
1584 /* flush .foo.- ; leave - if stopped by '[' or '<' */
1588 while (o
[-1] != '.' && o
[-1] != '[' && o
[-1] != '<');
1589 if (p
[1] == '.') /* foo.-.bar ==> bar. */
1591 else if (o
[-1] == '.') /* '.foo.-]' ==> ']' */
1593 /* else [foo.-] ==> [-] */
1599 o
[-1] != '[' && o
[-1] != '<' && o
[-1] != '.' &&
1600 p
[1] != ']' && p
[1] != '>' && p
[1] != '.')
1606 if (!IS_DIRECTORY_SEP (*p
))
1610 else if (IS_DIRECTORY_SEP (p
[0])
1612 && (IS_DIRECTORY_SEP (p
[2])
1615 /* If "/." is the entire filename, keep the "/". Otherwise,
1616 just delete the whole "/.". */
1617 if (o
== target
&& p
[2] == '\0')
1621 else if (IS_DIRECTORY_SEP (p
[0]) && p
[1] == '.' && p
[2] == '.'
1622 /* `/../' is the "superroot" on certain file systems. */
1624 && (IS_DIRECTORY_SEP (p
[3]) || p
[3] == 0))
1626 while (o
!= target
&& (--o
) && !IS_DIRECTORY_SEP (*o
))
1628 /* Keep initial / only if this is the whole name. */
1629 if (o
== target
&& IS_ANY_SEP (*o
) && p
[3] == 0)
1634 && IS_DIRECTORY_SEP (p
[0]) && IS_DIRECTORY_SEP (p
[1]))
1636 /* Collapse multiple `/' in a row. */
1638 while (IS_DIRECTORY_SEP (*p
))
1645 #endif /* not VMS */
1649 /* At last, set drive name. */
1651 /* Except for network file name. */
1652 if (!(IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1])))
1653 #endif /* WINDOWSNT */
1655 if (!drive
) abort ();
1657 target
[0] = DRIVE_LETTER (drive
);
1660 /* Reinsert the escape prefix if required. */
1667 CORRECT_DIR_SEPS (target
);
1670 return make_string (target
, o
- target
);
1674 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1675 This is the old version of expand-file-name, before it was thoroughly
1676 rewritten for Emacs 10.31. We leave this version here commented-out,
1677 because the code is very complex and likely to have subtle bugs. If
1678 bugs _are_ found, it might be of interest to look at the old code and
1679 see what did it do in the relevant situation.
1681 Don't remove this code: it's true that it will be accessible via CVS,
1682 but a few years from deletion, people will forget it is there. */
1684 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1685 DEAFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
1686 "Convert FILENAME to absolute, and canonicalize it.\n\
1687 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1688 (does not start with slash); if DEFAULT is nil or missing,\n\
1689 the current buffer's value of default-directory is used.\n\
1690 Filenames containing `.' or `..' as components are simplified;\n\
1691 initial `~/' expands to your home directory.\n\
1692 See also the function `substitute-in-file-name'.")
1694 Lisp_Object name
, defalt
;
1698 register unsigned char *newdir
, *p
, *o
;
1700 unsigned char *target
;
1704 unsigned char * colon
= 0;
1705 unsigned char * close
= 0;
1706 unsigned char * slash
= 0;
1707 unsigned char * brack
= 0;
1708 int lbrack
= 0, rbrack
= 0;
1712 CHECK_STRING (name
);
1715 /* Filenames on VMS are always upper case. */
1716 name
= Fupcase (name
);
1719 nm
= XSTRING (name
)->data
;
1721 /* If nm is absolute, flush ...// and detect /./ and /../.
1722 If no /./ or /../ we can return right away. */
1734 if (p
[0] == '/' && p
[1] == '/'
1736 /* // at start of filename is meaningful on Apollo system. */
1741 if (p
[0] == '/' && p
[1] == '~')
1742 nm
= p
+ 1, lose
= 1;
1743 if (p
[0] == '/' && p
[1] == '.'
1744 && (p
[2] == '/' || p
[2] == 0
1745 || (p
[2] == '.' && (p
[3] == '/' || p
[3] == 0))))
1751 /* if dev:[dir]/, move nm to / */
1752 if (!slash
&& p
> nm
&& (brack
|| colon
)) {
1753 nm
= (brack
? brack
+ 1 : colon
+ 1);
1754 lbrack
= rbrack
= 0;
1762 /* VMS pre V4.4,convert '-'s in filenames. */
1763 if (lbrack
== rbrack
)
1765 if (dots
< 2) /* this is to allow negative version numbers */
1770 if (lbrack
> rbrack
&&
1771 ((p
[-1] == '.' || p
[-1] == '[' || p
[-1] == '<') &&
1772 (p
[1] == '.' || p
[1] == ']' || p
[1] == '>')))
1778 /* count open brackets, reset close bracket pointer */
1779 if (p
[0] == '[' || p
[0] == '<')
1780 lbrack
++, brack
= 0;
1781 /* count close brackets, set close bracket pointer */
1782 if (p
[0] == ']' || p
[0] == '>')
1783 rbrack
++, brack
= p
;
1784 /* detect ][ or >< */
1785 if ((p
[0] == ']' || p
[0] == '>') && (p
[1] == '[' || p
[1] == '<'))
1787 if ((p
[0] == ':' || p
[0] == ']' || p
[0] == '>') && p
[1] == '~')
1788 nm
= p
+ 1, lose
= 1;
1789 if (p
[0] == ':' && (colon
|| slash
))
1790 /* if dev1:[dir]dev2:, move nm to dev2: */
1796 /* If /name/dev:, move nm to dev: */
1799 /* If node::dev:, move colon following dev */
1800 else if (colon
&& colon
[-1] == ':')
1802 /* If dev1:dev2:, move nm to dev2: */
1803 else if (colon
&& colon
[-1] != ':')
1808 if (p
[0] == ':' && !colon
)
1814 if (lbrack
== rbrack
)
1817 else if (p
[0] == '.')
1825 if (index (nm
, '/'))
1826 return build_string (sys_translate_unix (nm
));
1828 if (nm
== XSTRING (name
)->data
)
1830 return build_string (nm
);
1834 /* Now determine directory to start with and put it in NEWDIR */
1838 if (nm
[0] == '~') /* prefix ~ */
1843 || nm
[1] == 0)/* ~/filename */
1845 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1846 newdir
= (unsigned char *) "";
1849 nm
++; /* Don't leave the slash in nm. */
1852 else /* ~user/filename */
1854 /* Get past ~ to user */
1855 unsigned char *user
= nm
+ 1;
1856 /* Find end of name. */
1857 unsigned char *ptr
= (unsigned char *) index (user
, '/');
1858 int len
= ptr
? ptr
- user
: strlen (user
);
1860 unsigned char *ptr1
= index (user
, ':');
1861 if (ptr1
!= 0 && ptr1
- user
< len
)
1864 /* Copy the user name into temp storage. */
1865 o
= (unsigned char *) alloca (len
+ 1);
1866 bcopy ((char *) user
, o
, len
);
1869 /* Look up the user name. */
1870 pw
= (struct passwd
*) getpwnam (o
+ 1);
1872 error ("\"%s\" isn't a registered user", o
+ 1);
1874 newdir
= (unsigned char *) pw
->pw_dir
;
1876 /* Discard the user name from NM. */
1883 #endif /* not VMS */
1887 defalt
= current_buffer
->directory
;
1888 CHECK_STRING (defalt
);
1889 newdir
= XSTRING (defalt
)->data
;
1892 /* Now concatenate the directory and name to new space in the stack frame */
1894 tlen
= (newdir
? strlen (newdir
) + 1 : 0) + strlen (nm
) + 1;
1895 target
= (unsigned char *) alloca (tlen
);
1901 if (nm
[0] == 0 || nm
[0] == '/')
1902 strcpy (target
, newdir
);
1905 file_name_as_directory (target
, newdir
);
1908 strcat (target
, nm
);
1910 if (index (target
, '/'))
1911 strcpy (target
, sys_translate_unix (target
));
1914 /* Now canonicalize by removing /. and /foo/.. if they appear */
1922 if (*p
!= ']' && *p
!= '>' && *p
!= '-')
1928 else if ((p
[0] == ']' || p
[0] == '>') && p
[0] == p
[1] + 2)
1929 /* brackets are offset from each other by 2 */
1932 if (*p
!= '.' && *p
!= '-' && o
[-1] != '.')
1933 /* convert [foo][bar] to [bar] */
1934 while (o
[-1] != '[' && o
[-1] != '<')
1936 else if (*p
== '-' && *o
!= '.')
1939 else if (p
[0] == '-' && o
[-1] == '.' &&
1940 (p
[1] == '.' || p
[1] == ']' || p
[1] == '>'))
1941 /* flush .foo.- ; leave - if stopped by '[' or '<' */
1945 while (o
[-1] != '.' && o
[-1] != '[' && o
[-1] != '<');
1946 if (p
[1] == '.') /* foo.-.bar ==> bar. */
1948 else if (o
[-1] == '.') /* '.foo.-]' ==> ']' */
1950 /* else [foo.-] ==> [-] */
1956 o
[-1] != '[' && o
[-1] != '<' && o
[-1] != '.' &&
1957 p
[1] != ']' && p
[1] != '>' && p
[1] != '.')
1967 else if (!strncmp (p
, "//", 2)
1969 /* // at start of filename is meaningful in Apollo system. */
1977 else if (p
[0] == '/' && p
[1] == '.' &&
1978 (p
[2] == '/' || p
[2] == 0))
1980 else if (!strncmp (p
, "/..", 3)
1981 /* `/../' is the "superroot" on certain file systems. */
1983 && (p
[3] == '/' || p
[3] == 0))
1985 while (o
!= target
&& *--o
!= '/')
1988 if (o
== target
+ 1 && o
[-1] == '/' && o
[0] == '/')
1992 if (o
== target
&& *o
== '/')
2000 #endif /* not VMS */
2003 return make_string (target
, o
- target
);
2007 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name
,
2008 Ssubstitute_in_file_name
, 1, 1, 0,
2009 doc
: /* Substitute environment variables referred to in FILENAME.
2010 `$FOO' where FOO is an environment variable name means to substitute
2011 the value of that variable. The variable name should be terminated
2012 with a character not a letter, digit or underscore; otherwise, enclose
2013 the entire variable name in braces.
2014 If `/~' appears, all of FILENAME through that `/' is discarded.
2016 On VMS, `$' substitution is not done; this function does little and only
2017 duplicates what `expand-file-name' does. */)
2019 Lisp_Object filename
;
2023 register unsigned char *s
, *p
, *o
, *x
, *endp
;
2024 unsigned char *target
= NULL
;
2026 int substituted
= 0;
2029 Lisp_Object handler
;
2031 CHECK_STRING (filename
);
2033 /* If the file name has special constructs in it,
2034 call the corresponding file handler. */
2035 handler
= Ffind_file_name_handler (filename
, Qsubstitute_in_file_name
);
2036 if (!NILP (handler
))
2037 return call2 (handler
, Qsubstitute_in_file_name
, filename
);
2039 nm
= XSTRING (filename
)->data
;
2041 nm
= strcpy (alloca (strlen (nm
) + 1), nm
);
2042 CORRECT_DIR_SEPS (nm
);
2043 substituted
= (strcmp (nm
, XSTRING (filename
)->data
) != 0);
2045 endp
= nm
+ STRING_BYTES (XSTRING (filename
));
2047 /* If /~ or // appears, discard everything through first slash. */
2049 for (p
= nm
; p
!= endp
; p
++)
2052 #if defined (APOLLO) || defined (WINDOWSNT)
2053 /* // at start of file name is meaningful in Apollo and
2054 WindowsNT systems. */
2055 || (IS_DIRECTORY_SEP (p
[0]) && p
- 1 != nm
)
2056 #else /* not (APOLLO || WINDOWSNT) */
2057 || IS_DIRECTORY_SEP (p
[0])
2058 #endif /* not (APOLLO || WINDOWSNT) */
2063 || p
[-1] == ':' || p
[-1] == ']' || p
[-1] == '>'
2065 || IS_DIRECTORY_SEP (p
[-1])))
2067 for (s
= p
; *s
&& (!IS_DIRECTORY_SEP (*s
)
2072 if (p
[0] == '~' && s
> p
+ 1) /* we've got "/~something/" */
2074 o
= (unsigned char *) alloca (s
- p
+ 1);
2075 bcopy ((char *) p
, o
, s
- p
);
2078 pw
= (struct passwd
*) getpwnam (o
+ 1);
2080 /* If we have ~/ or ~user and `user' exists, discard
2081 everything up to ~. But if `user' does not exist, leave
2082 ~user alone, it might be a literal file name. */
2083 if (IS_DIRECTORY_SEP (p
[0]) || s
== p
+ 1 || pw
)
2090 /* see comment in expand-file-name about drive specifiers */
2091 else if (IS_DRIVE (p
[0]) && p
[1] == ':'
2092 && p
> nm
&& IS_DIRECTORY_SEP (p
[-1]))
2101 return build_string (nm
);
2104 /* See if any variables are substituted into the string
2105 and find the total length of their values in `total' */
2107 for (p
= nm
; p
!= endp
;)
2117 /* "$$" means a single "$" */
2126 while (p
!= endp
&& *p
!= '}') p
++;
2127 if (*p
!= '}') goto missingclose
;
2133 while (p
!= endp
&& (isalnum (*p
) || *p
== '_')) p
++;
2137 /* Copy out the variable name */
2138 target
= (unsigned char *) alloca (s
- o
+ 1);
2139 strncpy (target
, o
, s
- o
);
2142 strupr (target
); /* $home == $HOME etc. */
2145 /* Get variable value */
2146 o
= (unsigned char *) egetenv (target
);
2149 total
+= strlen (o
);
2159 /* If substitution required, recopy the string and do it */
2160 /* Make space in stack frame for the new copy */
2161 xnm
= (unsigned char *) alloca (STRING_BYTES (XSTRING (filename
)) + total
+ 1);
2164 /* Copy the rest of the name through, replacing $ constructs with values */
2181 while (p
!= endp
&& *p
!= '}') p
++;
2182 if (*p
!= '}') goto missingclose
;
2188 while (p
!= endp
&& (isalnum (*p
) || *p
== '_')) p
++;
2192 /* Copy out the variable name */
2193 target
= (unsigned char *) alloca (s
- o
+ 1);
2194 strncpy (target
, o
, s
- o
);
2197 strupr (target
); /* $home == $HOME etc. */
2200 /* Get variable value */
2201 o
= (unsigned char *) egetenv (target
);
2205 strcpy (x
, target
); x
+= strlen (target
);
2207 else if (STRING_MULTIBYTE (filename
))
2209 /* If the original string is multibyte,
2210 convert what we substitute into multibyte. */
2213 int c
= unibyte_char_to_multibyte (*o
++);
2214 x
+= CHAR_STRING (c
, x
);
2226 /* If /~ or // appears, discard everything through first slash. */
2228 for (p
= xnm
; p
!= x
; p
++)
2230 #if defined (APOLLO) || defined (WINDOWSNT)
2231 || (IS_DIRECTORY_SEP (p
[0]) && p
- 1 != xnm
)
2232 #else /* not (APOLLO || WINDOWSNT) */
2233 || IS_DIRECTORY_SEP (p
[0])
2234 #endif /* not (APOLLO || WINDOWSNT) */
2236 && p
!= xnm
&& IS_DIRECTORY_SEP (p
[-1]))
2239 else if (IS_DRIVE (p
[0]) && p
[1] == ':'
2240 && p
> xnm
&& IS_DIRECTORY_SEP (p
[-1]))
2244 if (STRING_MULTIBYTE (filename
))
2245 return make_string (xnm
, x
- xnm
);
2246 return make_unibyte_string (xnm
, x
- xnm
);
2249 error ("Bad format environment-variable substitution");
2251 error ("Missing \"}\" in environment-variable substitution");
2253 error ("Substituting nonexistent environment variable \"%s\"", target
);
2256 #endif /* not VMS */
2260 /* A slightly faster and more convenient way to get
2261 (directory-file-name (expand-file-name FOO)). */
2264 expand_and_dir_to_file (filename
, defdir
)
2265 Lisp_Object filename
, defdir
;
2267 register Lisp_Object absname
;
2269 absname
= Fexpand_file_name (filename
, defdir
);
2272 register int c
= XSTRING (absname
)->data
[STRING_BYTES (XSTRING (absname
)) - 1];
2273 if (c
== ':' || c
== ']' || c
== '>')
2274 absname
= Fdirectory_file_name (absname
);
2277 /* Remove final slash, if any (unless this is the root dir).
2278 stat behaves differently depending! */
2279 if (XSTRING (absname
)->size
> 1
2280 && IS_DIRECTORY_SEP (XSTRING (absname
)->data
[STRING_BYTES (XSTRING (absname
)) - 1])
2281 && !IS_DEVICE_SEP (XSTRING (absname
)->data
[STRING_BYTES (XSTRING (absname
))-2]))
2282 /* We cannot take shortcuts; they might be wrong for magic file names. */
2283 absname
= Fdirectory_file_name (absname
);
2288 /* Signal an error if the file ABSNAME already exists.
2289 If INTERACTIVE is nonzero, ask the user whether to proceed,
2290 and bypass the error if the user says to go ahead.
2291 QUERYSTRING is a name for the action that is being considered
2294 *STATPTR is used to store the stat information if the file exists.
2295 If the file does not exist, STATPTR->st_mode is set to 0.
2296 If STATPTR is null, we don't store into it.
2298 If QUICK is nonzero, we ask for y or n, not yes or no. */
2301 barf_or_query_if_file_exists (absname
, querystring
, interactive
, statptr
, quick
)
2302 Lisp_Object absname
;
2303 unsigned char *querystring
;
2305 struct stat
*statptr
;
2308 register Lisp_Object tem
, encoded_filename
;
2309 struct stat statbuf
;
2310 struct gcpro gcpro1
;
2312 encoded_filename
= ENCODE_FILE (absname
);
2314 /* stat is a good way to tell whether the file exists,
2315 regardless of what access permissions it has. */
2316 if (stat (XSTRING (encoded_filename
)->data
, &statbuf
) >= 0)
2319 Fsignal (Qfile_already_exists
,
2320 Fcons (build_string ("File already exists"),
2321 Fcons (absname
, Qnil
)));
2323 tem
= format1 ("File %s already exists; %s anyway? ",
2324 XSTRING (absname
)->data
, querystring
);
2326 tem
= Fy_or_n_p (tem
);
2328 tem
= do_yes_or_no_p (tem
);
2331 Fsignal (Qfile_already_exists
,
2332 Fcons (build_string ("File already exists"),
2333 Fcons (absname
, Qnil
)));
2340 statptr
->st_mode
= 0;
2345 DEFUN ("copy-file", Fcopy_file
, Scopy_file
, 2, 4,
2346 "fCopy file: \nFCopy %s to file: \np\nP",
2347 doc
: /* Copy FILE to NEWNAME. Both args must be strings.
2348 If NEWNAME names a directory, copy FILE there.
2349 Signals a `file-already-exists' error if file NEWNAME already exists,
2350 unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil.
2351 A number as third arg means request confirmation if NEWNAME already exists.
2352 This is what happens in interactive use with M-x.
2353 Fourth arg KEEP-TIME non-nil means give the new file the same
2354 last-modified time as the old one. (This works on only some systems.)
2355 A prefix arg makes KEEP-TIME non-nil. */)
2356 (file
, newname
, ok_if_already_exists
, keep_time
)
2357 Lisp_Object file
, newname
, ok_if_already_exists
, keep_time
;
2360 char buf
[16 * 1024];
2361 struct stat st
, out_st
;
2362 Lisp_Object handler
;
2363 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2364 int count
= specpdl_ptr
- specpdl
;
2365 int input_file_statable_p
;
2366 Lisp_Object encoded_file
, encoded_newname
;
2368 encoded_file
= encoded_newname
= Qnil
;
2369 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
2370 CHECK_STRING (file
);
2371 CHECK_STRING (newname
);
2373 if (!NILP (Ffile_directory_p (newname
)))
2374 newname
= Fexpand_file_name (file
, newname
);
2376 newname
= Fexpand_file_name (newname
, Qnil
);
2378 file
= Fexpand_file_name (file
, Qnil
);
2380 /* If the input file name has special constructs in it,
2381 call the corresponding file handler. */
2382 handler
= Ffind_file_name_handler (file
, Qcopy_file
);
2383 /* Likewise for output file name. */
2385 handler
= Ffind_file_name_handler (newname
, Qcopy_file
);
2386 if (!NILP (handler
))
2387 RETURN_UNGCPRO (call5 (handler
, Qcopy_file
, file
, newname
,
2388 ok_if_already_exists
, keep_time
));
2390 encoded_file
= ENCODE_FILE (file
);
2391 encoded_newname
= ENCODE_FILE (newname
);
2393 if (NILP (ok_if_already_exists
)
2394 || INTEGERP (ok_if_already_exists
))
2395 barf_or_query_if_file_exists (encoded_newname
, "copy to it",
2396 INTEGERP (ok_if_already_exists
), &out_st
, 0);
2397 else if (stat (XSTRING (encoded_newname
)->data
, &out_st
) < 0)
2401 if (!CopyFile (XSTRING (encoded_file
)->data
,
2402 XSTRING (encoded_newname
)->data
,
2404 report_file_error ("Copying file", Fcons (file
, Fcons (newname
, Qnil
)));
2405 else if (NILP (keep_time
))
2408 EMACS_GET_TIME (now
);
2409 if (set_file_times (XSTRING (encoded_newname
)->data
,
2411 Fsignal (Qfile_date_error
,
2412 Fcons (build_string ("Cannot set file date"),
2413 Fcons (newname
, Qnil
)));
2415 #else /* not WINDOWSNT */
2416 ifd
= emacs_open (XSTRING (encoded_file
)->data
, O_RDONLY
, 0);
2418 report_file_error ("Opening input file", Fcons (file
, Qnil
));
2420 record_unwind_protect (close_file_unwind
, make_number (ifd
));
2422 /* We can only copy regular files and symbolic links. Other files are not
2424 input_file_statable_p
= (fstat (ifd
, &st
) >= 0);
2426 #if !defined (DOS_NT) || __DJGPP__ > 1
2427 if (out_st
.st_mode
!= 0
2428 && st
.st_dev
== out_st
.st_dev
&& st
.st_ino
== out_st
.st_ino
)
2431 report_file_error ("Input and output files are the same",
2432 Fcons (file
, Fcons (newname
, Qnil
)));
2436 #if defined (S_ISREG) && defined (S_ISLNK)
2437 if (input_file_statable_p
)
2439 if (!(S_ISREG (st
.st_mode
)) && !(S_ISLNK (st
.st_mode
)))
2441 #if defined (EISDIR)
2442 /* Get a better looking error message. */
2445 report_file_error ("Non-regular file", Fcons (file
, Qnil
));
2448 #endif /* S_ISREG && S_ISLNK */
2451 /* Create the copy file with the same record format as the input file */
2452 ofd
= sys_creat (XSTRING (encoded_newname
)->data
, 0666, ifd
);
2455 /* System's default file type was set to binary by _fmode in emacs.c. */
2456 ofd
= creat (XSTRING (encoded_newname
)->data
, S_IREAD
| S_IWRITE
);
2457 #else /* not MSDOS */
2458 ofd
= creat (XSTRING (encoded_newname
)->data
, 0666);
2459 #endif /* not MSDOS */
2462 report_file_error ("Opening output file", Fcons (newname
, Qnil
));
2464 record_unwind_protect (close_file_unwind
, make_number (ofd
));
2468 while ((n
= emacs_read (ifd
, buf
, sizeof buf
)) > 0)
2469 if (emacs_write (ofd
, buf
, n
) != n
)
2470 report_file_error ("I/O error", Fcons (newname
, Qnil
));
2473 /* Closing the output clobbers the file times on some systems. */
2474 if (emacs_close (ofd
) < 0)
2475 report_file_error ("I/O error", Fcons (newname
, Qnil
));
2477 if (input_file_statable_p
)
2479 if (!NILP (keep_time
))
2481 EMACS_TIME atime
, mtime
;
2482 EMACS_SET_SECS_USECS (atime
, st
.st_atime
, 0);
2483 EMACS_SET_SECS_USECS (mtime
, st
.st_mtime
, 0);
2484 if (set_file_times (XSTRING (encoded_newname
)->data
,
2486 Fsignal (Qfile_date_error
,
2487 Fcons (build_string ("Cannot set file date"),
2488 Fcons (newname
, Qnil
)));
2491 chmod (XSTRING (encoded_newname
)->data
, st
.st_mode
& 07777);
2493 #if defined (__DJGPP__) && __DJGPP__ > 1
2494 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2495 and if it can't, it tells so. Otherwise, under MSDOS we usually
2496 get only the READ bit, which will make the copied file read-only,
2497 so it's better not to chmod at all. */
2498 if ((_djstat_flags
& _STFAIL_WRITEBIT
) == 0)
2499 chmod (XSTRING (encoded_newname
)->data
, st
.st_mode
& 07777);
2500 #endif /* DJGPP version 2 or newer */
2505 #endif /* WINDOWSNT */
2507 /* Discard the unwind protects. */
2508 specpdl_ptr
= specpdl
+ count
;
2514 DEFUN ("make-directory-internal", Fmake_directory_internal
,
2515 Smake_directory_internal
, 1, 1, 0,
2516 doc
: /* Create a new directory named DIRECTORY. */)
2518 Lisp_Object directory
;
2521 Lisp_Object handler
;
2522 Lisp_Object encoded_dir
;
2524 CHECK_STRING (directory
);
2525 directory
= Fexpand_file_name (directory
, Qnil
);
2527 handler
= Ffind_file_name_handler (directory
, Qmake_directory_internal
);
2528 if (!NILP (handler
))
2529 return call2 (handler
, Qmake_directory_internal
, directory
);
2531 encoded_dir
= ENCODE_FILE (directory
);
2533 dir
= XSTRING (encoded_dir
)->data
;
2536 if (mkdir (dir
) != 0)
2538 if (mkdir (dir
, 0777) != 0)
2540 report_file_error ("Creating directory", Flist (1, &directory
));
2545 DEFUN ("delete-directory", Fdelete_directory
, Sdelete_directory
, 1, 1, "FDelete directory: ",
2546 doc
: /* Delete the directory named DIRECTORY. */)
2548 Lisp_Object directory
;
2551 Lisp_Object handler
;
2552 Lisp_Object encoded_dir
;
2554 CHECK_STRING (directory
);
2555 directory
= Fdirectory_file_name (Fexpand_file_name (directory
, Qnil
));
2557 handler
= Ffind_file_name_handler (directory
, Qdelete_directory
);
2558 if (!NILP (handler
))
2559 return call2 (handler
, Qdelete_directory
, directory
);
2561 encoded_dir
= ENCODE_FILE (directory
);
2563 dir
= XSTRING (encoded_dir
)->data
;
2565 if (rmdir (dir
) != 0)
2566 report_file_error ("Removing directory", Flist (1, &directory
));
2571 DEFUN ("delete-file", Fdelete_file
, Sdelete_file
, 1, 1, "fDelete file: ",
2572 doc
: /* Delete file named FILENAME.
2573 If file has multiple names, it continues to exist with the other names. */)
2575 Lisp_Object filename
;
2577 Lisp_Object handler
;
2578 Lisp_Object encoded_file
;
2580 CHECK_STRING (filename
);
2581 filename
= Fexpand_file_name (filename
, Qnil
);
2583 handler
= Ffind_file_name_handler (filename
, Qdelete_file
);
2584 if (!NILP (handler
))
2585 return call2 (handler
, Qdelete_file
, filename
);
2587 encoded_file
= ENCODE_FILE (filename
);
2589 if (0 > unlink (XSTRING (encoded_file
)->data
))
2590 report_file_error ("Removing old name", Flist (1, &filename
));
2595 internal_delete_file_1 (ignore
)
2601 /* Delete file FILENAME, returning 1 if successful and 0 if failed. */
2604 internal_delete_file (filename
)
2605 Lisp_Object filename
;
2607 return NILP (internal_condition_case_1 (Fdelete_file
, filename
,
2608 Qt
, internal_delete_file_1
));
2611 DEFUN ("rename-file", Frename_file
, Srename_file
, 2, 3,
2612 "fRename file: \nFRename %s to file: \np",
2613 doc
: /* Rename FILE as NEWNAME. Both args strings.
2614 If file has names other than FILE, it continues to have those names.
2615 Signals a `file-already-exists' error if a file NEWNAME already exists
2616 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2617 A number as third arg means request confirmation if NEWNAME already exists.
2618 This is what happens in interactive use with M-x. */)
2619 (file
, newname
, ok_if_already_exists
)
2620 Lisp_Object file
, newname
, ok_if_already_exists
;
2623 Lisp_Object args
[2];
2625 Lisp_Object handler
;
2626 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2627 Lisp_Object encoded_file
, encoded_newname
;
2629 encoded_file
= encoded_newname
= Qnil
;
2630 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
2631 CHECK_STRING (file
);
2632 CHECK_STRING (newname
);
2633 file
= Fexpand_file_name (file
, Qnil
);
2634 newname
= Fexpand_file_name (newname
, Qnil
);
2636 /* If the file name has special constructs in it,
2637 call the corresponding file handler. */
2638 handler
= Ffind_file_name_handler (file
, Qrename_file
);
2640 handler
= Ffind_file_name_handler (newname
, Qrename_file
);
2641 if (!NILP (handler
))
2642 RETURN_UNGCPRO (call4 (handler
, Qrename_file
,
2643 file
, newname
, ok_if_already_exists
));
2645 encoded_file
= ENCODE_FILE (file
);
2646 encoded_newname
= ENCODE_FILE (newname
);
2649 /* If the file names are identical but for the case, don't ask for
2650 confirmation: they simply want to change the letter-case of the
2652 if (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2654 if (NILP (ok_if_already_exists
)
2655 || INTEGERP (ok_if_already_exists
))
2656 barf_or_query_if_file_exists (encoded_newname
, "rename to it",
2657 INTEGERP (ok_if_already_exists
), 0, 0);
2659 if (0 > rename (XSTRING (encoded_file
)->data
, XSTRING (encoded_newname
)->data
))
2661 if (0 > link (XSTRING (encoded_file
)->data
, XSTRING (encoded_newname
)->data
)
2662 || 0 > unlink (XSTRING (encoded_file
)->data
))
2667 Fcopy_file (file
, newname
,
2668 /* We have already prompted if it was an integer,
2669 so don't have copy-file prompt again. */
2670 NILP (ok_if_already_exists
) ? Qnil
: Qt
, Qt
);
2671 Fdelete_file (file
);
2678 report_file_error ("Renaming", Flist (2, args
));
2681 report_file_error ("Renaming", Flist (2, &file
));
2688 DEFUN ("add-name-to-file", Fadd_name_to_file
, Sadd_name_to_file
, 2, 3,
2689 "fAdd name to file: \nFName to add to %s: \np",
2690 doc
: /* Give FILE additional name NEWNAME. Both args strings.
2691 Signals a `file-already-exists' error if a file NEWNAME already exists
2692 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2693 A number as third arg means request confirmation if NEWNAME already exists.
2694 This is what happens in interactive use with M-x. */)
2695 (file
, newname
, ok_if_already_exists
)
2696 Lisp_Object file
, newname
, ok_if_already_exists
;
2699 Lisp_Object args
[2];
2701 Lisp_Object handler
;
2702 Lisp_Object encoded_file
, encoded_newname
;
2703 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2705 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
2706 encoded_file
= encoded_newname
= Qnil
;
2707 CHECK_STRING (file
);
2708 CHECK_STRING (newname
);
2709 file
= Fexpand_file_name (file
, Qnil
);
2710 newname
= Fexpand_file_name (newname
, Qnil
);
2712 /* If the file name has special constructs in it,
2713 call the corresponding file handler. */
2714 handler
= Ffind_file_name_handler (file
, Qadd_name_to_file
);
2715 if (!NILP (handler
))
2716 RETURN_UNGCPRO (call4 (handler
, Qadd_name_to_file
, file
,
2717 newname
, ok_if_already_exists
));
2719 /* If the new name has special constructs in it,
2720 call the corresponding file handler. */
2721 handler
= Ffind_file_name_handler (newname
, Qadd_name_to_file
);
2722 if (!NILP (handler
))
2723 RETURN_UNGCPRO (call4 (handler
, Qadd_name_to_file
, file
,
2724 newname
, ok_if_already_exists
));
2726 encoded_file
= ENCODE_FILE (file
);
2727 encoded_newname
= ENCODE_FILE (newname
);
2729 if (NILP (ok_if_already_exists
)
2730 || INTEGERP (ok_if_already_exists
))
2731 barf_or_query_if_file_exists (encoded_newname
, "make it a new name",
2732 INTEGERP (ok_if_already_exists
), 0, 0);
2734 unlink (XSTRING (newname
)->data
);
2735 if (0 > link (XSTRING (encoded_file
)->data
, XSTRING (encoded_newname
)->data
))
2740 report_file_error ("Adding new name", Flist (2, args
));
2742 report_file_error ("Adding new name", Flist (2, &file
));
2751 DEFUN ("make-symbolic-link", Fmake_symbolic_link
, Smake_symbolic_link
, 2, 3,
2752 "FMake symbolic link to file: \nFMake symbolic link to file %s: \np",
2753 doc
: /* Make a symbolic link to FILENAME, named LINKNAME. Both args strings.
2754 Signals a `file-already-exists' error if a file LINKNAME already exists
2755 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2756 A number as third arg means request confirmation if LINKNAME already exists.
2757 This happens for interactive use with M-x. */)
2758 (filename
, linkname
, ok_if_already_exists
)
2759 Lisp_Object filename
, linkname
, ok_if_already_exists
;
2762 Lisp_Object args
[2];
2764 Lisp_Object handler
;
2765 Lisp_Object encoded_filename
, encoded_linkname
;
2766 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2768 GCPRO4 (filename
, linkname
, encoded_filename
, encoded_linkname
);
2769 encoded_filename
= encoded_linkname
= Qnil
;
2770 CHECK_STRING (filename
);
2771 CHECK_STRING (linkname
);
2772 /* If the link target has a ~, we must expand it to get
2773 a truly valid file name. Otherwise, do not expand;
2774 we want to permit links to relative file names. */
2775 if (XSTRING (filename
)->data
[0] == '~')
2776 filename
= Fexpand_file_name (filename
, Qnil
);
2777 linkname
= Fexpand_file_name (linkname
, Qnil
);
2779 /* If the file name has special constructs in it,
2780 call the corresponding file handler. */
2781 handler
= Ffind_file_name_handler (filename
, Qmake_symbolic_link
);
2782 if (!NILP (handler
))
2783 RETURN_UNGCPRO (call4 (handler
, Qmake_symbolic_link
, filename
,
2784 linkname
, ok_if_already_exists
));
2786 /* If the new link name has special constructs in it,
2787 call the corresponding file handler. */
2788 handler
= Ffind_file_name_handler (linkname
, Qmake_symbolic_link
);
2789 if (!NILP (handler
))
2790 RETURN_UNGCPRO (call4 (handler
, Qmake_symbolic_link
, filename
,
2791 linkname
, ok_if_already_exists
));
2793 encoded_filename
= ENCODE_FILE (filename
);
2794 encoded_linkname
= ENCODE_FILE (linkname
);
2796 if (NILP (ok_if_already_exists
)
2797 || INTEGERP (ok_if_already_exists
))
2798 barf_or_query_if_file_exists (encoded_linkname
, "make it a link",
2799 INTEGERP (ok_if_already_exists
), 0, 0);
2800 if (0 > symlink (XSTRING (encoded_filename
)->data
,
2801 XSTRING (encoded_linkname
)->data
))
2803 /* If we didn't complain already, silently delete existing file. */
2804 if (errno
== EEXIST
)
2806 unlink (XSTRING (encoded_linkname
)->data
);
2807 if (0 <= symlink (XSTRING (encoded_filename
)->data
,
2808 XSTRING (encoded_linkname
)->data
))
2818 report_file_error ("Making symbolic link", Flist (2, args
));
2820 report_file_error ("Making symbolic link", Flist (2, &filename
));
2826 #endif /* S_IFLNK */
2830 DEFUN ("define-logical-name", Fdefine_logical_name
, Sdefine_logical_name
,
2831 2, 2, "sDefine logical name: \nsDefine logical name %s as: ",
2832 doc
: /* Define the job-wide logical name NAME to have the value STRING.
2833 If STRING is nil or a null string, the logical name NAME is deleted. */)
2838 CHECK_STRING (name
);
2840 delete_logical_name (XSTRING (name
)->data
);
2843 CHECK_STRING (string
);
2845 if (XSTRING (string
)->size
== 0)
2846 delete_logical_name (XSTRING (name
)->data
);
2848 define_logical_name (XSTRING (name
)->data
, XSTRING (string
)->data
);
2857 DEFUN ("sysnetunam", Fsysnetunam
, Ssysnetunam
, 2, 2, 0,
2858 doc
: /* Open a network connection to PATH using LOGIN as the login string. */)
2860 Lisp_Object path
, login
;
2864 CHECK_STRING (path
);
2865 CHECK_STRING (login
);
2867 netresult
= netunam (XSTRING (path
)->data
, XSTRING (login
)->data
);
2869 if (netresult
== -1)
2874 #endif /* HPUX_NET */
2876 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p
, Sfile_name_absolute_p
,
2878 doc
: /* Return t if file FILENAME specifies an absolute file name.
2879 On Unix, this is a name starting with a `/' or a `~'. */)
2881 Lisp_Object filename
;
2885 CHECK_STRING (filename
);
2886 ptr
= XSTRING (filename
)->data
;
2887 if (IS_DIRECTORY_SEP (*ptr
) || *ptr
== '~'
2889 /* ??? This criterion is probably wrong for '<'. */
2890 || index (ptr
, ':') || index (ptr
, '<')
2891 || (*ptr
== '[' && (ptr
[1] != '-' || (ptr
[2] != '.' && ptr
[2] != ']'))
2895 || (IS_DRIVE (*ptr
) && ptr
[1] == ':' && IS_DIRECTORY_SEP (ptr
[2]))
2903 /* Return nonzero if file FILENAME exists and can be executed. */
2906 check_executable (filename
)
2910 int len
= strlen (filename
);
2913 if (stat (filename
, &st
) < 0)
2915 #if defined (WINDOWSNT) || (defined (MSDOS) && __DJGPP__ > 1)
2916 return ((st
.st_mode
& S_IEXEC
) != 0);
2918 return (S_ISREG (st
.st_mode
)
2920 && (stricmp ((suffix
= filename
+ len
-4), ".com") == 0
2921 || stricmp (suffix
, ".exe") == 0
2922 || stricmp (suffix
, ".bat") == 0)
2923 || (st
.st_mode
& S_IFMT
) == S_IFDIR
);
2924 #endif /* not WINDOWSNT */
2925 #else /* not DOS_NT */
2926 #ifdef HAVE_EUIDACCESS
2927 return (euidaccess (filename
, 1) >= 0);
2929 /* Access isn't quite right because it uses the real uid
2930 and we really want to test with the effective uid.
2931 But Unix doesn't give us a right way to do it. */
2932 return (access (filename
, 1) >= 0);
2934 #endif /* not DOS_NT */
2937 /* Return nonzero if file FILENAME exists and can be written. */
2940 check_writable (filename
)
2945 if (stat (filename
, &st
) < 0)
2947 return (st
.st_mode
& S_IWRITE
|| (st
.st_mode
& S_IFMT
) == S_IFDIR
);
2948 #else /* not MSDOS */
2949 #ifdef HAVE_EUIDACCESS
2950 return (euidaccess (filename
, 2) >= 0);
2952 /* Access isn't quite right because it uses the real uid
2953 and we really want to test with the effective uid.
2954 But Unix doesn't give us a right way to do it.
2955 Opening with O_WRONLY could work for an ordinary file,
2956 but would lose for directories. */
2957 return (access (filename
, 2) >= 0);
2959 #endif /* not MSDOS */
2962 DEFUN ("file-exists-p", Ffile_exists_p
, Sfile_exists_p
, 1, 1, 0,
2963 doc
: /* Return t if file FILENAME exists. (This does not mean you can read it.)
2964 See also `file-readable-p' and `file-attributes'. */)
2966 Lisp_Object filename
;
2968 Lisp_Object absname
;
2969 Lisp_Object handler
;
2970 struct stat statbuf
;
2972 CHECK_STRING (filename
);
2973 absname
= Fexpand_file_name (filename
, Qnil
);
2975 /* If the file name has special constructs in it,
2976 call the corresponding file handler. */
2977 handler
= Ffind_file_name_handler (absname
, Qfile_exists_p
);
2978 if (!NILP (handler
))
2979 return call2 (handler
, Qfile_exists_p
, absname
);
2981 absname
= ENCODE_FILE (absname
);
2983 return (stat (XSTRING (absname
)->data
, &statbuf
) >= 0) ? Qt
: Qnil
;
2986 DEFUN ("file-executable-p", Ffile_executable_p
, Sfile_executable_p
, 1, 1, 0,
2987 doc
: /* Return t if FILENAME can be executed by you.
2988 For a directory, this means you can access files in that directory. */)
2990 Lisp_Object filename
;
2992 Lisp_Object absname
;
2993 Lisp_Object handler
;
2995 CHECK_STRING (filename
);
2996 absname
= Fexpand_file_name (filename
, Qnil
);
2998 /* If the file name has special constructs in it,
2999 call the corresponding file handler. */
3000 handler
= Ffind_file_name_handler (absname
, Qfile_executable_p
);
3001 if (!NILP (handler
))
3002 return call2 (handler
, Qfile_executable_p
, absname
);
3004 absname
= ENCODE_FILE (absname
);
3006 return (check_executable (XSTRING (absname
)->data
) ? Qt
: Qnil
);
3009 DEFUN ("file-readable-p", Ffile_readable_p
, Sfile_readable_p
, 1, 1, 0,
3010 doc
: /* Return t if file FILENAME exists and you can read it.
3011 See also `file-exists-p' and `file-attributes'. */)
3013 Lisp_Object filename
;
3015 Lisp_Object absname
;
3016 Lisp_Object handler
;
3019 struct stat statbuf
;
3021 CHECK_STRING (filename
);
3022 absname
= Fexpand_file_name (filename
, Qnil
);
3024 /* If the file name has special constructs in it,
3025 call the corresponding file handler. */
3026 handler
= Ffind_file_name_handler (absname
, Qfile_readable_p
);
3027 if (!NILP (handler
))
3028 return call2 (handler
, Qfile_readable_p
, absname
);
3030 absname
= ENCODE_FILE (absname
);
3032 #if defined(DOS_NT) || defined(macintosh)
3033 /* Under MS-DOS, Windows, and Macintosh, open does not work for
3035 if (access (XSTRING (absname
)->data
, 0) == 0)
3038 #else /* not DOS_NT and not macintosh */
3040 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
3041 /* Opening a fifo without O_NONBLOCK can wait.
3042 We don't want to wait. But we don't want to mess wth O_NONBLOCK
3043 except in the case of a fifo, on a system which handles it. */
3044 desc
= stat (XSTRING (absname
)->data
, &statbuf
);
3047 if (S_ISFIFO (statbuf
.st_mode
))
3048 flags
|= O_NONBLOCK
;
3050 desc
= emacs_open (XSTRING (absname
)->data
, flags
, 0);
3055 #endif /* not DOS_NT and not macintosh */
3058 /* Having this before file-symlink-p mysteriously caused it to be forgotten
3060 DEFUN ("file-writable-p", Ffile_writable_p
, Sfile_writable_p
, 1, 1, 0,
3061 doc
: /* Return t if file FILENAME can be written or created by you. */)
3063 Lisp_Object filename
;
3065 Lisp_Object absname
, dir
, encoded
;
3066 Lisp_Object handler
;
3067 struct stat statbuf
;
3069 CHECK_STRING (filename
);
3070 absname
= Fexpand_file_name (filename
, Qnil
);
3072 /* If the file name has special constructs in it,
3073 call the corresponding file handler. */
3074 handler
= Ffind_file_name_handler (absname
, Qfile_writable_p
);
3075 if (!NILP (handler
))
3076 return call2 (handler
, Qfile_writable_p
, absname
);
3078 encoded
= ENCODE_FILE (absname
);
3079 if (stat (XSTRING (encoded
)->data
, &statbuf
) >= 0)
3080 return (check_writable (XSTRING (encoded
)->data
)
3083 dir
= Ffile_name_directory (absname
);
3086 dir
= Fdirectory_file_name (dir
);
3090 dir
= Fdirectory_file_name (dir
);
3093 dir
= ENCODE_FILE (dir
);
3095 /* The read-only attribute of the parent directory doesn't affect
3096 whether a file or directory can be created within it. Some day we
3097 should check ACLs though, which do affect this. */
3098 if (stat (XSTRING (dir
)->data
, &statbuf
) < 0)
3100 return (statbuf
.st_mode
& S_IFMT
) == S_IFDIR
? Qt
: Qnil
;
3102 return (check_writable (!NILP (dir
) ? (char *) XSTRING (dir
)->data
: "")
3107 DEFUN ("access-file", Faccess_file
, Saccess_file
, 2, 2, 0,
3108 doc
: /* Access file FILENAME, and get an error if that does not work.
3109 The second argument STRING is used in the error message.
3110 If there is no error, we return nil. */)
3112 Lisp_Object filename
, string
;
3114 Lisp_Object handler
, encoded_filename
, absname
;
3117 CHECK_STRING (filename
);
3118 absname
= Fexpand_file_name (filename
, Qnil
);
3120 CHECK_STRING (string
);
3122 /* If the file name has special constructs in it,
3123 call the corresponding file handler. */
3124 handler
= Ffind_file_name_handler (absname
, Qaccess_file
);
3125 if (!NILP (handler
))
3126 return call3 (handler
, Qaccess_file
, absname
, string
);
3128 encoded_filename
= ENCODE_FILE (absname
);
3130 fd
= emacs_open (XSTRING (encoded_filename
)->data
, O_RDONLY
, 0);
3132 report_file_error (XSTRING (string
)->data
, Fcons (filename
, Qnil
));
3138 DEFUN ("file-symlink-p", Ffile_symlink_p
, Sfile_symlink_p
, 1, 1, 0,
3139 doc
: /* Return non-nil if file FILENAME is the name of a symbolic link.
3140 The value is the name of the file to which it is linked.
3141 Otherwise returns nil. */)
3143 Lisp_Object filename
;
3150 Lisp_Object handler
;
3152 CHECK_STRING (filename
);
3153 filename
= Fexpand_file_name (filename
, Qnil
);
3155 /* If the file name has special constructs in it,
3156 call the corresponding file handler. */
3157 handler
= Ffind_file_name_handler (filename
, Qfile_symlink_p
);
3158 if (!NILP (handler
))
3159 return call2 (handler
, Qfile_symlink_p
, filename
);
3161 filename
= ENCODE_FILE (filename
);
3168 buf
= (char *) xrealloc (buf
, bufsize
);
3169 bzero (buf
, bufsize
);
3172 valsize
= readlink (XSTRING (filename
)->data
, buf
, bufsize
);
3176 /* HP-UX reports ERANGE if buffer is too small. */
3177 if (errno
== ERANGE
)
3187 while (valsize
>= bufsize
);
3189 val
= make_string (buf
, valsize
);
3190 if (buf
[0] == '/' && index (buf
, ':'))
3191 val
= concat2 (build_string ("/:"), val
);
3193 val
= DECODE_FILE (val
);
3195 #else /* not S_IFLNK */
3197 #endif /* not S_IFLNK */
3200 DEFUN ("file-directory-p", Ffile_directory_p
, Sfile_directory_p
, 1, 1, 0,
3201 doc
: /* Return t if FILENAME names an existing directory.
3202 Symbolic links to directories count as directories.
3203 See `file-symlink-p' to distinguish symlinks. */)
3205 Lisp_Object filename
;
3207 register Lisp_Object absname
;
3209 Lisp_Object handler
;
3211 absname
= expand_and_dir_to_file (filename
, current_buffer
->directory
);
3213 /* If the file name has special constructs in it,
3214 call the corresponding file handler. */
3215 handler
= Ffind_file_name_handler (absname
, Qfile_directory_p
);
3216 if (!NILP (handler
))
3217 return call2 (handler
, Qfile_directory_p
, absname
);
3219 absname
= ENCODE_FILE (absname
);
3221 if (stat (XSTRING (absname
)->data
, &st
) < 0)
3223 return (st
.st_mode
& S_IFMT
) == S_IFDIR
? Qt
: Qnil
;
3226 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p
, Sfile_accessible_directory_p
, 1, 1, 0,
3227 doc
: /* Return t if file FILENAME names a directory you can open.
3228 For the value to be t, FILENAME must specify the name of a directory as a file,
3229 and the directory must allow you to open files in it. In order to use a
3230 directory as a buffer's current directory, this predicate must return true.
3231 A directory name spec may be given instead; then the value is t
3232 if the directory so specified exists and really is a readable and
3233 searchable directory. */)
3235 Lisp_Object filename
;
3237 Lisp_Object handler
;
3239 struct gcpro gcpro1
;
3241 /* If the file name has special constructs in it,
3242 call the corresponding file handler. */
3243 handler
= Ffind_file_name_handler (filename
, Qfile_accessible_directory_p
);
3244 if (!NILP (handler
))
3245 return call2 (handler
, Qfile_accessible_directory_p
, filename
);
3247 /* It's an unlikely combination, but yes we really do need to gcpro:
3248 Suppose that file-accessible-directory-p has no handler, but
3249 file-directory-p does have a handler; this handler causes a GC which
3250 relocates the string in `filename'; and finally file-directory-p
3251 returns non-nil. Then we would end up passing a garbaged string
3252 to file-executable-p. */
3254 tem
= (NILP (Ffile_directory_p (filename
))
3255 || NILP (Ffile_executable_p (filename
)));
3257 return tem
? Qnil
: Qt
;
3260 DEFUN ("file-regular-p", Ffile_regular_p
, Sfile_regular_p
, 1, 1, 0,
3261 doc
: /* Return t if file FILENAME is the name of a regular file.
3262 This is the sort of file that holds an ordinary stream of data bytes. */)
3264 Lisp_Object filename
;
3266 register Lisp_Object absname
;
3268 Lisp_Object handler
;
3270 absname
= expand_and_dir_to_file (filename
, current_buffer
->directory
);
3272 /* If the file name has special constructs in it,
3273 call the corresponding file handler. */
3274 handler
= Ffind_file_name_handler (absname
, Qfile_regular_p
);
3275 if (!NILP (handler
))
3276 return call2 (handler
, Qfile_regular_p
, absname
);
3278 absname
= ENCODE_FILE (absname
);
3283 Lisp_Object tem
= Vw32_get_true_file_attributes
;
3285 /* Tell stat to use expensive method to get accurate info. */
3286 Vw32_get_true_file_attributes
= Qt
;
3287 result
= stat (XSTRING (absname
)->data
, &st
);
3288 Vw32_get_true_file_attributes
= tem
;
3292 return (st
.st_mode
& S_IFMT
) == S_IFREG
? Qt
: Qnil
;
3295 if (stat (XSTRING (absname
)->data
, &st
) < 0)
3297 return (st
.st_mode
& S_IFMT
) == S_IFREG
? Qt
: Qnil
;
3301 DEFUN ("file-modes", Ffile_modes
, Sfile_modes
, 1, 1, 0,
3302 doc
: /* Return mode bits of file named FILENAME, as an integer. */)
3304 Lisp_Object filename
;
3306 Lisp_Object absname
;
3308 Lisp_Object handler
;
3310 absname
= expand_and_dir_to_file (filename
, current_buffer
->directory
);
3312 /* If the file name has special constructs in it,
3313 call the corresponding file handler. */
3314 handler
= Ffind_file_name_handler (absname
, Qfile_modes
);
3315 if (!NILP (handler
))
3316 return call2 (handler
, Qfile_modes
, absname
);
3318 absname
= ENCODE_FILE (absname
);
3320 if (stat (XSTRING (absname
)->data
, &st
) < 0)
3322 #if defined (MSDOS) && __DJGPP__ < 2
3323 if (check_executable (XSTRING (absname
)->data
))
3324 st
.st_mode
|= S_IEXEC
;
3325 #endif /* MSDOS && __DJGPP__ < 2 */
3327 return make_number (st
.st_mode
& 07777);
3330 DEFUN ("set-file-modes", Fset_file_modes
, Sset_file_modes
, 2, 2, 0,
3331 doc
: /* Set mode bits of file named FILENAME to MODE (an integer).
3332 Only the 12 low bits of MODE are used. */)
3334 Lisp_Object filename
, mode
;
3336 Lisp_Object absname
, encoded_absname
;
3337 Lisp_Object handler
;
3339 absname
= Fexpand_file_name (filename
, current_buffer
->directory
);
3340 CHECK_NUMBER (mode
);
3342 /* If the file name has special constructs in it,
3343 call the corresponding file handler. */
3344 handler
= Ffind_file_name_handler (absname
, Qset_file_modes
);
3345 if (!NILP (handler
))
3346 return call3 (handler
, Qset_file_modes
, absname
, mode
);
3348 encoded_absname
= ENCODE_FILE (absname
);
3350 if (chmod (XSTRING (encoded_absname
)->data
, XINT (mode
)) < 0)
3351 report_file_error ("Doing chmod", Fcons (absname
, Qnil
));
3356 DEFUN ("set-default-file-modes", Fset_default_file_modes
, Sset_default_file_modes
, 1, 1, 0,
3357 doc
: /* Set the file permission bits for newly created files.
3358 The argument MODE should be an integer; only the low 9 bits are used.
3359 This setting is inherited by subprocesses. */)
3363 CHECK_NUMBER (mode
);
3365 umask ((~ XINT (mode
)) & 0777);
3370 DEFUN ("default-file-modes", Fdefault_file_modes
, Sdefault_file_modes
, 0, 0, 0,
3371 doc
: /* Return the default file protection for created files.
3372 The value is an integer. */)
3378 realmask
= umask (0);
3381 XSETINT (value
, (~ realmask
) & 0777);
3391 DEFUN ("unix-sync", Funix_sync
, Sunix_sync
, 0, 0, "",
3392 doc
: /* Tell Unix to finish all pending disk updates. */)
3401 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p
, Sfile_newer_than_file_p
, 2, 2, 0,
3402 doc
: /* Return t if file FILE1 is newer than file FILE2.
3403 If FILE1 does not exist, the answer is nil;
3404 otherwise, if FILE2 does not exist, the answer is t. */)
3406 Lisp_Object file1
, file2
;
3408 Lisp_Object absname1
, absname2
;
3411 Lisp_Object handler
;
3412 struct gcpro gcpro1
, gcpro2
;
3414 CHECK_STRING (file1
);
3415 CHECK_STRING (file2
);
3418 GCPRO2 (absname1
, file2
);
3419 absname1
= expand_and_dir_to_file (file1
, current_buffer
->directory
);
3420 absname2
= expand_and_dir_to_file (file2
, current_buffer
->directory
);
3423 /* If the file name has special constructs in it,
3424 call the corresponding file handler. */
3425 handler
= Ffind_file_name_handler (absname1
, Qfile_newer_than_file_p
);
3427 handler
= Ffind_file_name_handler (absname2
, Qfile_newer_than_file_p
);
3428 if (!NILP (handler
))
3429 return call3 (handler
, Qfile_newer_than_file_p
, absname1
, absname2
);
3431 GCPRO2 (absname1
, absname2
);
3432 absname1
= ENCODE_FILE (absname1
);
3433 absname2
= ENCODE_FILE (absname2
);
3436 if (stat (XSTRING (absname1
)->data
, &st
) < 0)
3439 mtime1
= st
.st_mtime
;
3441 if (stat (XSTRING (absname2
)->data
, &st
) < 0)
3444 return (mtime1
> st
.st_mtime
) ? Qt
: Qnil
;
3448 Lisp_Object Qfind_buffer_file_type
;
3451 #ifndef READ_BUF_SIZE
3452 #define READ_BUF_SIZE (64 << 10)
3455 extern void adjust_markers_for_delete
P_ ((int, int, int, int));
3457 /* This function is called after Lisp functions to decide a coding
3458 system are called, or when they cause an error. Before they are
3459 called, the current buffer is set unibyte and it contains only a
3460 newly inserted text (thus the buffer was empty before the
3463 The functions may set markers, overlays, text properties, or even
3464 alter the buffer contents, change the current buffer.
3466 Here, we reset all those changes by:
3467 o set back the current buffer.
3468 o move all markers and overlays to BEG.
3469 o remove all text properties.
3470 o set back the buffer multibyteness. */
3473 decide_coding_unwind (unwind_data
)
3474 Lisp_Object unwind_data
;
3476 Lisp_Object multibyte
, undo_list
, buffer
;
3478 multibyte
= XCAR (unwind_data
);
3479 unwind_data
= XCDR (unwind_data
);
3480 undo_list
= XCAR (unwind_data
);
3481 buffer
= XCDR (unwind_data
);
3483 if (current_buffer
!= XBUFFER (buffer
))
3484 set_buffer_internal (XBUFFER (buffer
));
3485 adjust_markers_for_delete (BEG
, BEG_BYTE
, Z
, Z_BYTE
);
3486 adjust_overlays_for_delete (BEG
, Z
- BEG
);
3487 BUF_INTERVALS (current_buffer
) = 0;
3488 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3490 /* Now we are safe to change the buffer's multibyteness directly. */
3491 current_buffer
->enable_multibyte_characters
= multibyte
;
3492 current_buffer
->undo_list
= undo_list
;
3498 /* Used to pass values from insert-file-contents to read_non_regular. */
3500 static int non_regular_fd
;
3501 static int non_regular_inserted
;
3502 static int non_regular_nbytes
;
3505 /* Read from a non-regular file.
3506 Read non_regular_trytry bytes max from non_regular_fd.
3507 Non_regular_inserted specifies where to put the read bytes.
3508 Value is the number of bytes read. */
3517 nbytes
= emacs_read (non_regular_fd
,
3518 BEG_ADDR
+ PT_BYTE
- 1 + non_regular_inserted
,
3519 non_regular_nbytes
);
3521 return make_number (nbytes
);
3525 /* Condition-case handler used when reading from non-regular files
3526 in insert-file-contents. */
3529 read_non_regular_quit ()
3535 DEFUN ("insert-file-contents", Finsert_file_contents
, Sinsert_file_contents
,
3537 doc
: /* Insert contents of file FILENAME after point.
3538 Returns list of absolute file name and number of bytes inserted.
3539 If second argument VISIT is non-nil, the buffer's visited filename
3540 and last save file modtime are set, and it is marked unmodified.
3541 If visiting and the file does not exist, visiting is completed
3542 before the error is signaled.
3543 The optional third and fourth arguments BEG and END
3544 specify what portion of the file to insert.
3545 These arguments count bytes in the file, not characters in the buffer.
3546 If VISIT is non-nil, BEG and END must be nil.
3548 If optional fifth argument REPLACE is non-nil,
3549 it means replace the current buffer contents (in the accessible portion)
3550 with the file contents. This is better than simply deleting and inserting
3551 the whole thing because (1) it preserves some marker positions
3552 and (2) it puts less data in the undo list.
3553 When REPLACE is non-nil, the value is the number of characters actually read,
3554 which is often less than the number of characters to be read.
3556 This does code conversion according to the value of
3557 `coding-system-for-read' or `file-coding-system-alist',
3558 and sets the variable `last-coding-system-used' to the coding system
3560 (filename
, visit
, beg
, end
, replace
)
3561 Lisp_Object filename
, visit
, beg
, end
, replace
;
3566 register int how_much
;
3567 register int unprocessed
;
3568 int count
= BINDING_STACK_SIZE ();
3569 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
3570 Lisp_Object handler
, val
, insval
, orig_filename
;
3573 int not_regular
= 0;
3574 unsigned char read_buf
[READ_BUF_SIZE
];
3575 struct coding_system coding
;
3576 unsigned char buffer
[1 << 14];
3577 int replace_handled
= 0;
3578 int set_coding_system
= 0;
3579 Lisp_Object coding_system
;
3582 if (current_buffer
->base_buffer
&& ! NILP (visit
))
3583 error ("Cannot do file visiting in an indirect buffer");
3585 if (!NILP (current_buffer
->read_only
))
3586 Fbarf_if_buffer_read_only ();
3590 orig_filename
= Qnil
;
3592 GCPRO4 (filename
, val
, p
, orig_filename
);
3594 CHECK_STRING (filename
);
3595 filename
= Fexpand_file_name (filename
, Qnil
);
3597 /* The value Qnil means that the coding system is not yet
3599 coding_system
= Qnil
;
3601 /* If the file name has special constructs in it,
3602 call the corresponding file handler. */
3603 handler
= Ffind_file_name_handler (filename
, Qinsert_file_contents
);
3604 if (!NILP (handler
))
3606 val
= call6 (handler
, Qinsert_file_contents
, filename
,
3607 visit
, beg
, end
, replace
);
3608 if (CONSP (val
) && CONSP (XCDR (val
)))
3609 inserted
= XINT (XCAR (XCDR (val
)));
3613 orig_filename
= filename
;
3614 filename
= ENCODE_FILE (filename
);
3620 Lisp_Object tem
= Vw32_get_true_file_attributes
;
3622 /* Tell stat to use expensive method to get accurate info. */
3623 Vw32_get_true_file_attributes
= Qt
;
3624 total
= stat (XSTRING (filename
)->data
, &st
);
3625 Vw32_get_true_file_attributes
= tem
;
3630 if (stat (XSTRING (filename
)->data
, &st
) < 0)
3632 if ((fd
= emacs_open (XSTRING (filename
)->data
, O_RDONLY
, 0)) < 0
3633 || fstat (fd
, &st
) < 0)
3634 #endif /* not APOLLO */
3635 #endif /* WINDOWSNT */
3637 if (fd
>= 0) emacs_close (fd
);
3640 report_file_error ("Opening input file", Fcons (orig_filename
, Qnil
));
3643 if (!NILP (Vcoding_system_for_read
))
3644 Fset (Qbuffer_file_coding_system
, Vcoding_system_for_read
);
3649 /* This code will need to be changed in order to work on named
3650 pipes, and it's probably just not worth it. So we should at
3651 least signal an error. */
3652 if (!S_ISREG (st
.st_mode
))
3659 if (! NILP (replace
) || ! NILP (beg
) || ! NILP (end
))
3660 Fsignal (Qfile_error
,
3661 Fcons (build_string ("not a regular file"),
3662 Fcons (orig_filename
, Qnil
)));
3667 if ((fd
= emacs_open (XSTRING (filename
)->data
, O_RDONLY
, 0)) < 0)
3670 /* Replacement should preserve point as it preserves markers. */
3671 if (!NILP (replace
))
3672 record_unwind_protect (restore_point_unwind
, Fpoint_marker ());
3674 record_unwind_protect (close_file_unwind
, make_number (fd
));
3676 /* Supposedly happens on VMS. */
3677 if (! not_regular
&& st
.st_size
< 0)
3678 error ("File size is negative");
3680 /* Prevent redisplay optimizations. */
3681 current_buffer
->clip_changed
= 1;
3685 if (!NILP (beg
) || !NILP (end
))
3686 error ("Attempt to visit less than an entire file");
3687 if (BEG
< Z
&& NILP (replace
))
3688 error ("Cannot do file visiting in a non-empty buffer");
3694 XSETFASTINT (beg
, 0);
3702 XSETINT (end
, st
.st_size
);
3704 /* Arithmetic overflow can occur if an Emacs integer cannot
3705 represent the file size, or if the calculations below
3706 overflow. The calculations below double the file size
3707 twice, so check that it can be multiplied by 4 safely. */
3708 if (XINT (end
) != st
.st_size
3709 || ((int) st
.st_size
* 4) / 4 != st
.st_size
)
3710 error ("Maximum buffer size exceeded");
3712 /* The file size returned from stat may be zero, but data
3713 may be readable nonetheless, for example when this is a
3714 file in the /proc filesystem. */
3715 if (st
.st_size
== 0)
3716 XSETINT (end
, READ_BUF_SIZE
);
3722 /* Decide the coding system to use for reading the file now
3723 because we can't use an optimized method for handling
3724 `coding:' tag if the current buffer is not empty. */
3725 if (!NILP (Vcoding_system_for_read
))
3726 coding_system
= Vcoding_system_for_read
;
3727 else if (! NILP (replace
))
3728 /* In REPLACE mode, we can use the same coding system
3729 that was used to visit the file. */
3730 coding_system
= current_buffer
->buffer_file_coding_system
;
3733 /* Don't try looking inside a file for a coding system
3734 specification if it is not seekable. */
3735 if (! not_regular
&& ! NILP (Vset_auto_coding_function
))
3737 /* Find a coding system specified in the heading two
3738 lines or in the tailing several lines of the file.
3739 We assume that the 1K-byte and 3K-byte for heading
3740 and tailing respectively are sufficient for this
3744 if (st
.st_size
<= (1024 * 4))
3745 nread
= emacs_read (fd
, read_buf
, 1024 * 4);
3748 nread
= emacs_read (fd
, read_buf
, 1024);
3751 if (lseek (fd
, st
.st_size
- (1024 * 3), 0) < 0)
3752 report_file_error ("Setting file position",
3753 Fcons (orig_filename
, Qnil
));
3754 nread
+= emacs_read (fd
, read_buf
+ nread
, 1024 * 3);
3759 error ("IO error reading %s: %s",
3760 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
3763 struct buffer
*prev
= current_buffer
;
3766 record_unwind_protect (Fset_buffer
, Fcurrent_buffer ());
3768 /* The call to temp_output_buffer_setup binds
3770 count1
= specpdl_ptr
- specpdl
;
3771 temp_output_buffer_setup (" *code-converting-work*");
3773 set_buffer_internal (XBUFFER (Vstandard_output
));
3774 current_buffer
->enable_multibyte_characters
= Qnil
;
3775 insert_1_both (read_buf
, nread
, nread
, 0, 0, 0);
3776 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3777 coding_system
= call2 (Vset_auto_coding_function
,
3778 filename
, make_number (nread
));
3779 set_buffer_internal (prev
);
3781 /* Remove the binding for standard-output. */
3782 unbind_to (count1
, Qnil
);
3784 /* Discard the unwind protect for recovering the
3788 /* Rewind the file for the actual read done later. */
3789 if (lseek (fd
, 0, 0) < 0)
3790 report_file_error ("Setting file position",
3791 Fcons (orig_filename
, Qnil
));
3795 if (NILP (coding_system
))
3797 /* If we have not yet decided a coding system, check
3798 file-coding-system-alist. */
3799 Lisp_Object args
[6], coding_systems
;
3801 args
[0] = Qinsert_file_contents
, args
[1] = orig_filename
;
3802 args
[2] = visit
, args
[3] = beg
, args
[4] = end
, args
[5] = replace
;
3803 coding_systems
= Ffind_operation_coding_system (6, args
);
3804 if (CONSP (coding_systems
))
3805 coding_system
= XCAR (coding_systems
);
3809 if (NILP (coding_system
))
3810 coding_system
= Qundecided
;
3812 CHECK_CODING_SYSTEM (coding_system
);
3814 if (NILP (current_buffer
->enable_multibyte_characters
))
3815 /* We must suppress all character code conversion except for
3816 end-of-line conversion. */
3817 coding_system
= raw_text_coding_system (coding_system
);
3819 setup_coding_system (coding_system
, &coding
);
3820 /* Ensure we set Vlast_coding_system_used. */
3821 set_coding_system
= 1;
3824 /* If requested, replace the accessible part of the buffer
3825 with the file contents. Avoid replacing text at the
3826 beginning or end of the buffer that matches the file contents;
3827 that preserves markers pointing to the unchanged parts.
3829 Here we implement this feature in an optimized way
3830 for the case where code conversion is NOT needed.
3831 The following if-statement handles the case of conversion
3832 in a less optimal way.
3834 If the code conversion is "automatic" then we try using this
3835 method and hope for the best.
3836 But if we discover the need for conversion, we give up on this method
3837 and let the following if-statement handle the replace job. */
3840 && (NILP (coding_system
)
3841 || ! CODING_REQUIRE_DECODING (&coding
)))
3843 /* same_at_start and same_at_end count bytes,
3844 because file access counts bytes
3845 and BEG and END count bytes. */
3846 int same_at_start
= BEGV_BYTE
;
3847 int same_at_end
= ZV_BYTE
;
3849 /* There is still a possibility we will find the need to do code
3850 conversion. If that happens, we set this variable to 1 to
3851 give up on handling REPLACE in the optimized way. */
3852 int giveup_match_end
= 0;
3854 if (XINT (beg
) != 0)
3856 if (lseek (fd
, XINT (beg
), 0) < 0)
3857 report_file_error ("Setting file position",
3858 Fcons (orig_filename
, Qnil
));
3863 /* Count how many chars at the start of the file
3864 match the text at the beginning of the buffer. */
3869 nread
= emacs_read (fd
, buffer
, sizeof buffer
);
3871 error ("IO error reading %s: %s",
3872 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
3873 else if (nread
== 0)
3876 if (CODING_REQUIRE_DETECTION (&coding
))
3878 coding_system
= detect_coding_system (buffer
, nread
, 1, 0,
3880 setup_coding_system (coding_system
, &coding
);
3882 if (CODING_REQUIRE_DECODING (&coding
))
3883 /* We found that the file should be decoded somehow.
3884 Let's give up here. */
3886 giveup_match_end
= 1;
3891 while (bufpos
< nread
&& same_at_start
< ZV_BYTE
3892 && FETCH_BYTE (same_at_start
) == buffer
[bufpos
])
3893 same_at_start
++, bufpos
++;
3894 /* If we found a discrepancy, stop the scan.
3895 Otherwise loop around and scan the next bufferful. */
3896 if (bufpos
!= nread
)
3900 /* If the file matches the buffer completely,
3901 there's no need to replace anything. */
3902 if (same_at_start
- BEGV_BYTE
== XINT (end
))
3906 /* Truncate the buffer to the size of the file. */
3907 del_range_1 (same_at_start
, same_at_end
, 0, 0);
3912 /* Count how many chars at the end of the file
3913 match the text at the end of the buffer. But, if we have
3914 already found that decoding is necessary, don't waste time. */
3915 while (!giveup_match_end
)
3917 int total_read
, nread
, bufpos
, curpos
, trial
;
3919 /* At what file position are we now scanning? */
3920 curpos
= XINT (end
) - (ZV_BYTE
- same_at_end
);
3921 /* If the entire file matches the buffer tail, stop the scan. */
3924 /* How much can we scan in the next step? */
3925 trial
= min (curpos
, sizeof buffer
);
3926 if (lseek (fd
, curpos
- trial
, 0) < 0)
3927 report_file_error ("Setting file position",
3928 Fcons (orig_filename
, Qnil
));
3930 total_read
= nread
= 0;
3931 while (total_read
< trial
)
3933 nread
= emacs_read (fd
, buffer
+ total_read
, trial
- total_read
);
3935 error ("IO error reading %s: %s",
3936 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
3937 else if (nread
== 0)
3939 total_read
+= nread
;
3942 /* Scan this bufferful from the end, comparing with
3943 the Emacs buffer. */
3944 bufpos
= total_read
;
3946 /* Compare with same_at_start to avoid counting some buffer text
3947 as matching both at the file's beginning and at the end. */
3948 while (bufpos
> 0 && same_at_end
> same_at_start
3949 && FETCH_BYTE (same_at_end
- 1) == buffer
[bufpos
- 1])
3950 same_at_end
--, bufpos
--;
3952 /* If we found a discrepancy, stop the scan.
3953 Otherwise loop around and scan the preceding bufferful. */
3956 /* If this discrepancy is because of code conversion,
3957 we cannot use this method; giveup and try the other. */
3958 if (same_at_end
> same_at_start
3959 && FETCH_BYTE (same_at_end
- 1) >= 0200
3960 && ! NILP (current_buffer
->enable_multibyte_characters
)
3961 && (CODING_MAY_REQUIRE_DECODING (&coding
)))
3962 giveup_match_end
= 1;
3971 if (! giveup_match_end
)
3975 /* We win! We can handle REPLACE the optimized way. */
3977 /* Extend the start of non-matching text area to multibyte
3978 character boundary. */
3979 if (! NILP (current_buffer
->enable_multibyte_characters
))
3980 while (same_at_start
> BEGV_BYTE
3981 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3984 /* Extend the end of non-matching text area to multibyte
3985 character boundary. */
3986 if (! NILP (current_buffer
->enable_multibyte_characters
))
3987 while (same_at_end
< ZV_BYTE
3988 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3991 /* Don't try to reuse the same piece of text twice. */
3992 overlap
= (same_at_start
- BEGV_BYTE
3993 - (same_at_end
+ st
.st_size
- ZV
));
3995 same_at_end
+= overlap
;
3997 /* Arrange to read only the nonmatching middle part of the file. */
3998 XSETFASTINT (beg
, XINT (beg
) + (same_at_start
- BEGV_BYTE
));
3999 XSETFASTINT (end
, XINT (end
) - (ZV_BYTE
- same_at_end
));
4001 del_range_byte (same_at_start
, same_at_end
, 0);
4002 /* Insert from the file at the proper position. */
4003 temp
= BYTE_TO_CHAR (same_at_start
);
4004 SET_PT_BOTH (temp
, same_at_start
);
4006 /* If display currently starts at beginning of line,
4007 keep it that way. */
4008 if (XBUFFER (XWINDOW (selected_window
)->buffer
) == current_buffer
)
4009 XWINDOW (selected_window
)->start_at_line_beg
= Fbolp ();
4011 replace_handled
= 1;
4015 /* If requested, replace the accessible part of the buffer
4016 with the file contents. Avoid replacing text at the
4017 beginning or end of the buffer that matches the file contents;
4018 that preserves markers pointing to the unchanged parts.
4020 Here we implement this feature for the case where code conversion
4021 is needed, in a simple way that needs a lot of memory.
4022 The preceding if-statement handles the case of no conversion
4023 in a more optimized way. */
4024 if (!NILP (replace
) && ! replace_handled
&& BEGV
< ZV
)
4026 int same_at_start
= BEGV_BYTE
;
4027 int same_at_end
= ZV_BYTE
;
4028 int same_at_start_charpos
;
4032 unsigned char *decoded
;
4034 int this_count
= BINDING_STACK_SIZE ();
4035 Lisp_Object conversion_buffer
4036 = make_conversion_work_buffer (! NILP (current_buffer
4037 ->enable_multibyte_characters
));
4039 record_unwind_protect (code_conversion_restore
, save_excursion_save ());
4041 /* First read the whole file, performing code conversion into
4042 CONVERSION_BUFFER. */
4044 if (lseek (fd
, XINT (beg
), 0) < 0)
4046 report_file_error ("Setting file position",
4047 Fcons (orig_filename
, Qnil
));
4050 total
= st
.st_size
; /* Total bytes in the file. */
4051 how_much
= 0; /* Bytes read from file so far. */
4052 inserted
= 0; /* Bytes put into CONVERSION_BUFFER so far. */
4053 unprocessed
= 0; /* Bytes not processed in previous loop. */
4055 while (how_much
< total
)
4057 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
4058 quitting while reading a huge while. */
4059 /* try is reserved in some compilers (Microsoft C) */
4060 int trytry
= min (total
- how_much
, READ_BUF_SIZE
- unprocessed
);
4063 /* Allow quitting out of the actual I/O. */
4066 this = emacs_read (fd
, read_buf
+ unprocessed
, trytry
);
4078 decode_coding_c_string (&coding
, read_buf
, unprocessed
+ this,
4080 unprocessed
= coding
.carryover_bytes
;
4081 if (coding
.carryover_bytes
> 0)
4082 bcopy (coding
.carryover
, read_buf
, unprocessed
);
4087 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
4088 if we couldn't read the file. */
4093 error ("IO error reading %s: %s",
4094 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
4095 else if (how_much
== -2)
4096 error ("maximum buffer size exceeded");
4099 if (unprocessed
> 0)
4101 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4102 decode_coding_c_string (&coding
, read_buf
, unprocessed
,
4104 coding
.mode
&= ~CODING_MODE_LAST_BLOCK
;
4107 decoded
= BUF_BEG_ADDR (XBUFFER (conversion_buffer
));
4108 inserted
= (BUF_Z_BYTE (XBUFFER (conversion_buffer
))
4109 - BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
4111 /* Compare the beginning of the converted string with the buffer
4115 while (bufpos
< inserted
&& same_at_start
< same_at_end
4116 && FETCH_BYTE (same_at_start
) == decoded
[bufpos
])
4117 same_at_start
++, bufpos
++;
4119 /* If the file matches the head of buffer completely,
4120 there's no need to replace anything. */
4122 if (bufpos
== inserted
)
4125 /* Truncate the buffer to the size of the file. */
4126 del_range_byte (same_at_start
, same_at_end
, 0);
4131 /* Extend the start of non-matching text area to the previous
4132 multibyte character boundary. */
4133 if (! NILP (current_buffer
->enable_multibyte_characters
))
4134 while (same_at_start
> BEGV_BYTE
4135 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
4138 /* Scan this bufferful from the end, comparing with
4139 the Emacs buffer. */
4142 /* Compare with same_at_start to avoid counting some buffer text
4143 as matching both at the file's beginning and at the end. */
4144 while (bufpos
> 0 && same_at_end
> same_at_start
4145 && FETCH_BYTE (same_at_end
- 1) == decoded
[bufpos
- 1])
4146 same_at_end
--, bufpos
--;
4148 /* Extend the end of non-matching text area to the next
4149 multibyte character boundary. */
4150 if (! NILP (current_buffer
->enable_multibyte_characters
))
4151 while (same_at_end
< ZV_BYTE
4152 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
4155 /* Don't try to reuse the same piece of text twice. */
4156 overlap
= same_at_start
- BEGV_BYTE
- (same_at_end
+ inserted
- ZV_BYTE
);
4158 same_at_end
+= overlap
;
4160 /* If display currently starts at beginning of line,
4161 keep it that way. */
4162 if (XBUFFER (XWINDOW (selected_window
)->buffer
) == current_buffer
)
4163 XWINDOW (selected_window
)->start_at_line_beg
= Fbolp ();
4165 /* Replace the chars that we need to replace,
4166 and update INSERTED to equal the number of bytes
4167 we are taking from the decoded string. */
4168 inserted
-= (Z_BYTE
- same_at_end
) + (same_at_start
- BEG_BYTE
);
4170 if (same_at_end
!= same_at_start
)
4172 del_range_byte (same_at_start
, same_at_end
, 0);
4174 same_at_start
= GPT_BYTE
;
4178 temp
= BYTE_TO_CHAR (same_at_start
);
4180 /* Insert from the file at the proper position. */
4181 SET_PT_BOTH (temp
, same_at_start
);
4182 same_at_start_charpos
4183 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4186 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4187 same_at_start
+ inserted
)
4188 - same_at_start_charpos
);
4189 insert_from_buffer (XBUFFER (conversion_buffer
),
4190 same_at_start_charpos
, inserted_chars
, 0);
4191 /* Set `inserted' to the number of inserted characters. */
4192 inserted
= PT
- temp
;
4194 unbind_to (this_count
, Qnil
);
4201 register Lisp_Object temp
;
4203 total
= XINT (end
) - XINT (beg
);
4205 /* Make sure point-max won't overflow after this insertion. */
4206 XSETINT (temp
, total
);
4207 if (total
!= XINT (temp
))
4208 error ("Maximum buffer size exceeded");
4211 /* For a special file, all we can do is guess. */
4212 total
= READ_BUF_SIZE
;
4214 if (NILP (visit
) && total
> 0)
4215 prepare_to_modify_buffer (PT
, PT
, NULL
);
4218 if (GAP_SIZE
< total
)
4219 make_gap (total
- GAP_SIZE
);
4221 if (XINT (beg
) != 0 || !NILP (replace
))
4223 if (lseek (fd
, XINT (beg
), 0) < 0)
4224 report_file_error ("Setting file position",
4225 Fcons (orig_filename
, Qnil
));
4228 /* In the following loop, HOW_MUCH contains the total bytes read so
4229 far for a regular file, and not changed for a special file. But,
4230 before exiting the loop, it is set to a negative value if I/O
4234 /* Total bytes inserted. */
4237 /* Here, we don't do code conversion in the loop. It is done by
4238 decode_coding_gap after all data are read into the buffer. */
4240 int gap_size
= GAP_SIZE
;
4242 while (how_much
< total
)
4244 /* try is reserved in some compilers (Microsoft C) */
4245 int trytry
= min (total
- how_much
, READ_BUF_SIZE
);
4252 /* Maybe make more room. */
4253 if (gap_size
< trytry
)
4255 make_gap (total
- gap_size
);
4256 gap_size
= GAP_SIZE
;
4259 /* Read from the file, capturing `quit'. When an
4260 error occurs, end the loop, and arrange for a quit
4261 to be signaled after decoding the text we read. */
4262 non_regular_fd
= fd
;
4263 non_regular_inserted
= inserted
;
4264 non_regular_nbytes
= trytry
;
4265 val
= internal_condition_case_1 (read_non_regular
, Qnil
, Qerror
,
4266 read_non_regular_quit
);
4277 /* Allow quitting out of the actual I/O. We don't make text
4278 part of the buffer until all the reading is done, so a C-g
4279 here doesn't do any harm. */
4282 this = emacs_read (fd
, BEG_ADDR
+ PT_BYTE
- 1 + inserted
, trytry
);
4294 /* For a regular file, where TOTAL is the real size,
4295 count HOW_MUCH to compare with it.
4296 For a special file, where TOTAL is just a buffer size,
4297 so don't bother counting in HOW_MUCH.
4298 (INSERTED is where we count the number of characters inserted.) */
4305 /* Make the text read part of the buffer. */
4306 GAP_SIZE
-= inserted
;
4308 GPT_BYTE
+= inserted
;
4310 ZV_BYTE
+= inserted
;
4315 /* Put an anchor to ensure multi-byte form ends at gap. */
4320 /* Discard the unwind protect for closing the file. */
4324 error ("IO error reading %s: %s",
4325 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
4329 if (NILP (coding_system
))
4331 /* The coding system is not yet decided. Decide it by an
4332 optimized method for handling `coding:' tag.
4334 Note that we can get here only if the buffer was empty
4335 before the insertion. */
4337 if (!NILP (Vcoding_system_for_read
))
4338 coding_system
= Vcoding_system_for_read
;
4341 /* Since we are sure that the current buffer was empty
4342 before the insertion, we can toggle
4343 enable-multibyte-characters directly here without taking
4344 care of marker adjustment and byte combining problem. By
4345 this way, we can run Lisp program safely before decoding
4346 the inserted text. */
4347 Lisp_Object unwind_data
;
4348 int count
= specpdl_ptr
- specpdl
;
4350 unwind_data
= Fcons (current_buffer
->enable_multibyte_characters
,
4351 Fcons (current_buffer
->undo_list
,
4352 Fcurrent_buffer ()));
4353 current_buffer
->enable_multibyte_characters
= Qnil
;
4354 current_buffer
->undo_list
= Qt
;
4355 record_unwind_protect (decide_coding_unwind
, unwind_data
);
4357 if (inserted
> 0 && ! NILP (Vset_auto_coding_function
))
4359 coding_system
= call2 (Vset_auto_coding_function
,
4360 filename
, make_number (inserted
));
4363 if (NILP (coding_system
))
4365 /* If the coding system is not yet decided, check
4366 file-coding-system-alist. */
4367 Lisp_Object args
[6], coding_systems
;
4369 args
[0] = Qinsert_file_contents
, args
[1] = orig_filename
;
4370 args
[2] = visit
, args
[3] = beg
, args
[4] = end
, args
[5] = Qnil
;
4371 coding_systems
= Ffind_operation_coding_system (6, args
);
4372 if (CONSP (coding_systems
))
4373 coding_system
= XCAR (coding_systems
);
4376 unbind_to (count
, Qnil
);
4377 inserted
= Z_BYTE
- BEG_BYTE
;
4380 if (NILP (coding_system
))
4381 coding_system
= Qundecided
;
4383 CHECK_CODING_SYSTEM (coding_system
);
4385 if (NILP (current_buffer
->enable_multibyte_characters
))
4386 /* We must suppress all character code conversion except for
4387 end-of-line conversion. */
4388 coding_system
= raw_text_coding_system (coding_system
);
4390 setup_coding_system (coding_system
, &coding
);
4391 /* Ensure we set Vlast_coding_system_used. */
4392 set_coding_system
= 1;
4397 /* When we visit a file by raw-text, we change the buffer to
4398 unibyte. If we have not yet decided how to decode a text,
4399 decide it at first by detecting the file's encoding. */
4400 if (CODING_REQUIRE_DETECTION (&coding
))
4402 coding_system
= detect_coding_system (PT_ADDR
, inserted
, 1, 0,
4404 setup_coding_system (coding_system
, &coding
);
4407 if (CODING_FOR_UNIBYTE (&coding
)
4408 /* Can't do this if part of the buffer might be preserved. */
4410 /* Visiting a file with these coding system makes the buffer
4412 current_buffer
->enable_multibyte_characters
= Qnil
;
4415 if ((! NILP (current_buffer
->enable_multibyte_characters
)
4416 || CODING_REQUIRE_DETECTION (&coding
)
4417 || CODING_REQUIRE_DECODING (&coding
))
4418 && (inserted
> 0 || CODING_REQUIRE_FLUSHING (&coding
)))
4420 move_gap_both (PT
, PT_BYTE
);
4421 GAP_SIZE
+= inserted
;
4422 ZV_BYTE
-= inserted
;
4426 decode_coding_gap (&coding
, inserted
, inserted
);
4427 inserted
= coding
.produced_char
;
4429 else if (inserted
> 0)
4430 adjust_after_insert (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4434 /* Use the conversion type to determine buffer-file-type
4435 (find-buffer-file-type is now used to help determine the
4437 if ((coding
.eol_type
== eol_type_undecided
4438 || coding
.eol_type
== eol_type_lf
)
4439 && ! CODING_REQUIRE_DECODING (&coding
))
4440 current_buffer
->buffer_file_type
= Qt
;
4442 current_buffer
->buffer_file_type
= Qnil
;
4449 if (!EQ (current_buffer
->undo_list
, Qt
))
4450 current_buffer
->undo_list
= Qnil
;
4452 stat (XSTRING (filename
)->data
, &st
);
4457 current_buffer
->modtime
= st
.st_mtime
;
4458 current_buffer
->filename
= orig_filename
;
4461 SAVE_MODIFF
= MODIFF
;
4462 current_buffer
->auto_save_modified
= MODIFF
;
4463 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
4464 #ifdef CLASH_DETECTION
4467 if (!NILP (current_buffer
->file_truename
))
4468 unlock_file (current_buffer
->file_truename
);
4469 unlock_file (filename
);
4471 #endif /* CLASH_DETECTION */
4473 Fsignal (Qfile_error
,
4474 Fcons (build_string ("not a regular file"),
4475 Fcons (orig_filename
, Qnil
)));
4478 /* Decode file format */
4481 int empty_undo_list_p
= 0;
4483 /* If we're anyway going to discard undo information, don't
4484 record it in the first place. The buffer's undo list at this
4485 point is either nil or t when visiting a file. */
4488 empty_undo_list_p
= NILP (current_buffer
->undo_list
);
4489 current_buffer
->undo_list
= Qt
;
4492 insval
= call3 (Qformat_decode
,
4493 Qnil
, make_number (inserted
), visit
);
4494 CHECK_NUMBER (insval
);
4495 inserted
= XFASTINT (insval
);
4498 current_buffer
->undo_list
= empty_undo_list_p
? Qnil
: Qt
;
4501 if (set_coding_system
)
4502 Vlast_coding_system_used
= coding_system
;
4504 /* Call after-change hooks for the inserted text, aside from the case
4505 of normal visiting (not with REPLACE), which is done in a new buffer
4506 "before" the buffer is changed. */
4507 if (inserted
> 0 && total
> 0
4508 && (NILP (visit
) || !NILP (replace
)))
4510 signal_after_change (PT
, 0, inserted
);
4511 update_compositions (PT
, PT
, CHECK_BORDER
);
4514 p
= Vafter_insert_file_functions
;
4517 insval
= call1 (Fcar (p
), make_number (inserted
));
4520 CHECK_NUMBER (insval
);
4521 inserted
= XFASTINT (insval
);
4528 && current_buffer
->modtime
== -1)
4530 /* If visiting nonexistent file, return nil. */
4531 report_file_error ("Opening input file", Fcons (orig_filename
, Qnil
));
4535 Fsignal (Qquit
, Qnil
);
4537 /* ??? Retval needs to be dealt with in all cases consistently. */
4539 val
= Fcons (orig_filename
,
4540 Fcons (make_number (inserted
),
4543 RETURN_UNGCPRO (unbind_to (count
, val
));
4546 static Lisp_Object build_annotations
P_ ((Lisp_Object
, Lisp_Object
));
4548 /* If build_annotations switched buffers, switch back to BUF.
4549 Kill the temporary buffer that was selected in the meantime.
4551 Since this kill only the last temporary buffer, some buffers remain
4552 not killed if build_annotations switched buffers more than once.
4556 build_annotations_unwind (buf
)
4561 if (XBUFFER (buf
) == current_buffer
)
4563 tembuf
= Fcurrent_buffer ();
4565 Fkill_buffer (tembuf
);
4569 /* Decide the coding-system to encode the data with. */
4572 choose_write_coding_system (start
, end
, filename
,
4573 append
, visit
, lockname
, coding
)
4574 Lisp_Object start
, end
, filename
, append
, visit
, lockname
;
4575 struct coding_system
*coding
;
4581 else if (!NILP (Vcoding_system_for_write
))
4582 val
= Vcoding_system_for_write
;
4585 /* If the variable `buffer-file-coding-system' is set locally,
4586 it means that the file was read with some kind of code
4587 conversion or the variable is explicitly set by users. We
4588 had better write it out with the same coding system even if
4589 `enable-multibyte-characters' is nil.
4591 If it is not set locally, we anyway have to convert EOL
4592 format if the default value of `buffer-file-coding-system'
4593 tells that it is not Unix-like (LF only) format. */
4594 int using_default_coding
= 0;
4595 int force_raw_text
= 0;
4597 val
= current_buffer
->buffer_file_coding_system
;
4599 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4602 if (NILP (current_buffer
->enable_multibyte_characters
))
4608 /* Check file-coding-system-alist. */
4609 Lisp_Object args
[7], coding_systems
;
4611 args
[0] = Qwrite_region
; args
[1] = start
; args
[2] = end
;
4612 args
[3] = filename
; args
[4] = append
; args
[5] = visit
;
4614 coding_systems
= Ffind_operation_coding_system (7, args
);
4615 if (CONSP (coding_systems
) && !NILP (XCDR (coding_systems
)))
4616 val
= XCDR (coding_systems
);
4620 && !NILP (current_buffer
->buffer_file_coding_system
))
4622 /* If we still have not decided a coding system, use the
4623 default value of buffer-file-coding-system. */
4624 val
= current_buffer
->buffer_file_coding_system
;
4625 using_default_coding
= 1;
4628 if (! NILP (val
) && ! force_raw_text
)
4630 Lisp_Object spec
, attrs
;
4632 CHECK_CODING_SYSTEM_GET_SPEC (val
, spec
);
4633 attrs
= AREF (spec
, 0);
4634 if (EQ (CODING_ATTR_TYPE (attrs
), Qraw_text
))
4639 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4640 /* Confirm that VAL can surely encode the current region. */
4641 val
= call3 (Vselect_safe_coding_system_function
, start
, end
, val
);
4643 /* If the decided coding-system doesn't specify end-of-line
4644 format, we use that of
4645 `default-buffer-file-coding-system'. */
4646 if (! using_default_coding
)
4647 val
= (coding_inherit_eol_type
4648 (val
, buffer_defaults
.buffer_file_coding_system
));
4650 /* If we decide not to encode text, use `raw-text' or one of its
4653 val
= raw_text_coding_system (val
);
4656 setup_coding_system (Fcheck_coding_system (val
), coding
);
4658 if (!STRINGP (start
) && !NILP (current_buffer
->selective_display
))
4659 coding
->mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
4662 DEFUN ("write-region", Fwrite_region
, Swrite_region
, 3, 7,
4663 "r\nFWrite region to file: \ni\ni\ni\np",
4664 doc
: /* Write current region into specified file.
4665 When called from a program, requires three arguments:
4666 START, END and FILENAME. START and END are normally buffer positions
4667 specifying the part of the buffer to write.
4668 If START is nil, that means to use the entire buffer contents.
4669 If START is a string, then output that string to the file
4670 instead of any buffer contents; END is ignored.
4672 Optional fourth argument APPEND if non-nil means
4673 append to existing file contents (if any). If it is an integer,
4674 seek to that offset in the file before writing.
4675 Optional fifth argument VISIT if t means
4676 set the last-save-file-modtime of buffer to this file's modtime
4677 and mark buffer not modified.
4678 If VISIT is a string, it is a second file name;
4679 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4680 VISIT is also the file name to lock and unlock for clash detection.
4681 If VISIT is neither t nor nil nor a string,
4682 that means do not print the \"Wrote file\" message.
4683 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4684 use for locking and unlocking, overriding FILENAME and VISIT.
4685 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4686 for an existing file with the same name. If MUSTBENEW is `excl',
4687 that means to get an error if the file already exists; never overwrite.
4688 If MUSTBENEW is neither nil nor `excl', that means ask for
4689 confirmation before overwriting, but do go ahead and overwrite the file
4690 if the user confirms.
4692 This does code conversion according to the value of
4693 `coding-system-for-write', `buffer-file-coding-system', or
4694 `file-coding-system-alist', and sets the variable
4695 `last-coding-system-used' to the coding system actually used. */)
4696 (start
, end
, filename
, append
, visit
, lockname
, mustbenew
)
4697 Lisp_Object start
, end
, filename
, append
, visit
, lockname
, mustbenew
;
4705 int count
= specpdl_ptr
- specpdl
;
4708 unsigned char *fname
= 0; /* If non-0, original filename (must rename) */
4710 Lisp_Object handler
;
4711 Lisp_Object visit_file
;
4712 Lisp_Object annotations
;
4713 Lisp_Object encoded_filename
;
4714 int visiting
= (EQ (visit
, Qt
) || STRINGP (visit
));
4715 int quietly
= !NILP (visit
);
4716 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
4717 struct buffer
*given_buffer
;
4719 int buffer_file_type
= O_BINARY
;
4721 struct coding_system coding
;
4723 if (current_buffer
->base_buffer
&& visiting
)
4724 error ("Cannot do file visiting in an indirect buffer");
4726 if (!NILP (start
) && !STRINGP (start
))
4727 validate_region (&start
, &end
);
4729 GCPRO5 (start
, filename
, visit
, visit_file
, lockname
);
4731 filename
= Fexpand_file_name (filename
, Qnil
);
4733 if (!NILP (mustbenew
) && !EQ (mustbenew
, Qexcl
))
4734 barf_or_query_if_file_exists (filename
, "overwrite", 1, 0, 1);
4736 if (STRINGP (visit
))
4737 visit_file
= Fexpand_file_name (visit
, Qnil
);
4739 visit_file
= filename
;
4741 if (NILP (lockname
))
4742 lockname
= visit_file
;
4746 /* If the file name has special constructs in it,
4747 call the corresponding file handler. */
4748 handler
= Ffind_file_name_handler (filename
, Qwrite_region
);
4749 /* If FILENAME has no handler, see if VISIT has one. */
4750 if (NILP (handler
) && STRINGP (visit
))
4751 handler
= Ffind_file_name_handler (visit
, Qwrite_region
);
4753 if (!NILP (handler
))
4756 val
= call6 (handler
, Qwrite_region
, start
, end
,
4757 filename
, append
, visit
);
4761 SAVE_MODIFF
= MODIFF
;
4762 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
4763 current_buffer
->filename
= visit_file
;
4769 /* Special kludge to simplify auto-saving. */
4772 XSETFASTINT (start
, BEG
);
4773 XSETFASTINT (end
, Z
);
4776 record_unwind_protect (build_annotations_unwind
, Fcurrent_buffer ());
4777 count1
= specpdl_ptr
- specpdl
;
4779 given_buffer
= current_buffer
;
4780 annotations
= build_annotations (start
, end
);
4781 if (current_buffer
!= given_buffer
)
4783 XSETFASTINT (start
, BEGV
);
4784 XSETFASTINT (end
, ZV
);
4789 GCPRO5 (start
, filename
, annotations
, visit_file
, lockname
);
4791 /* Decide the coding-system to encode the data with.
4792 We used to make this choice before calling build_annotations, but that
4793 leads to problems when a write-annotate-function takes care of
4794 unsavable chars (as was the case with X-Symbol). */
4795 choose_write_coding_system (start
, end
, filename
,
4796 append
, visit
, lockname
, &coding
);
4797 Vlast_coding_system_used
= CODING_ID_NAME (coding
.id
);
4799 given_buffer
= current_buffer
;
4800 if (current_buffer
!= given_buffer
)
4802 XSETFASTINT (start
, BEGV
);
4803 XSETFASTINT (end
, ZV
);
4806 #ifdef CLASH_DETECTION
4809 #if 0 /* This causes trouble for GNUS. */
4810 /* If we've locked this file for some other buffer,
4811 query before proceeding. */
4812 if (!visiting
&& EQ (Ffile_locked_p (lockname
), Qt
))
4813 call2 (intern ("ask-user-about-lock"), filename
, Vuser_login_name
);
4816 lock_file (lockname
);
4818 #endif /* CLASH_DETECTION */
4820 encoded_filename
= ENCODE_FILE (filename
);
4822 fn
= XSTRING (encoded_filename
)->data
;
4826 desc
= emacs_open (fn
, O_WRONLY
| buffer_file_type
, 0);
4827 #else /* not DOS_NT */
4828 desc
= emacs_open (fn
, O_WRONLY
, 0);
4829 #endif /* not DOS_NT */
4831 if (desc
< 0 && (NILP (append
) || errno
== ENOENT
))
4833 if (auto_saving
) /* Overwrite any previous version of autosave file */
4835 vms_truncate (fn
); /* if fn exists, truncate to zero length */
4836 desc
= emacs_open (fn
, O_RDWR
, 0);
4838 desc
= creat_copy_attrs (STRINGP (current_buffer
->filename
)
4839 ? XSTRING (current_buffer
->filename
)->data
: 0,
4842 else /* Write to temporary name and rename if no errors */
4844 Lisp_Object temp_name
;
4845 temp_name
= Ffile_name_directory (filename
);
4847 if (!NILP (temp_name
))
4849 temp_name
= Fmake_temp_name (concat2 (temp_name
,
4850 build_string ("$$SAVE$$")));
4851 fname
= XSTRING (filename
)->data
;
4852 fn
= XSTRING (temp_name
)->data
;
4853 desc
= creat_copy_attrs (fname
, fn
);
4856 /* If we can't open the temporary file, try creating a new
4857 version of the original file. VMS "creat" creates a
4858 new version rather than truncating an existing file. */
4861 desc
= creat (fn
, 0666);
4862 #if 0 /* This can clobber an existing file and fail to replace it,
4863 if the user runs out of space. */
4866 /* We can't make a new version;
4867 try to truncate and rewrite existing version if any. */
4869 desc
= emacs_open (fn
, O_RDWR
, 0);
4875 desc
= creat (fn
, 0666);
4879 desc
= emacs_open (fn
,
4880 O_WRONLY
| O_CREAT
| buffer_file_type
4881 | (EQ (mustbenew
, Qexcl
) ? O_EXCL
: O_TRUNC
),
4882 S_IREAD
| S_IWRITE
);
4883 #else /* not DOS_NT */
4884 desc
= emacs_open (fn
, O_WRONLY
| O_TRUNC
| O_CREAT
4885 | (EQ (mustbenew
, Qexcl
) ? O_EXCL
: 0),
4886 auto_saving
? auto_save_mode_bits
: 0666);
4887 #endif /* not DOS_NT */
4888 #endif /* not VMS */
4892 #ifdef CLASH_DETECTION
4894 if (!auto_saving
) unlock_file (lockname
);
4896 #endif /* CLASH_DETECTION */
4898 report_file_error ("Opening output file", Fcons (filename
, Qnil
));
4901 record_unwind_protect (close_file_unwind
, make_number (desc
));
4903 if (!NILP (append
) && !NILP (Ffile_regular_p (filename
)))
4907 if (NUMBERP (append
))
4908 ret
= lseek (desc
, XINT (append
), 1);
4910 ret
= lseek (desc
, 0, 2);
4913 #ifdef CLASH_DETECTION
4914 if (!auto_saving
) unlock_file (lockname
);
4915 #endif /* CLASH_DETECTION */
4917 report_file_error ("Lseek error", Fcons (filename
, Qnil
));
4925 * Kludge Warning: The VMS C RTL likes to insert carriage returns
4926 * if we do writes that don't end with a carriage return. Furthermore
4927 * it cannot handle writes of more then 16K. The modified
4928 * version of "sys_write" in SYSDEP.C (see comment there) copes with
4929 * this EXCEPT for the last record (iff it doesn't end with a carriage
4930 * return). This implies that if your buffer doesn't end with a carriage
4931 * return, you get one free... tough. However it also means that if
4932 * we make two calls to sys_write (a la the following code) you can
4933 * get one at the gap as well. The easiest way to fix this (honest)
4934 * is to move the gap to the next newline (or the end of the buffer).
4939 if (GPT
> BEG
&& GPT_ADDR
[-1] != '\n')
4940 move_gap (find_next_newline (GPT
, 1));
4943 /* The new encoding routine doesn't require the following. */
4945 /* Whether VMS or not, we must move the gap to the next of newline
4946 when we must put designation sequences at beginning of line. */
4947 if (INTEGERP (start
)
4948 && coding
.type
== coding_type_iso2022
4949 && coding
.flags
& CODING_FLAG_ISO_DESIGNATE_AT_BOL
4950 && GPT
> BEG
&& GPT_ADDR
[-1] != '\n')
4952 int opoint
= PT
, opoint_byte
= PT_BYTE
;
4953 scan_newline (PT
, PT_BYTE
, ZV
, ZV_BYTE
, 1, 0);
4954 move_gap_both (PT
, PT_BYTE
);
4955 SET_PT_BOTH (opoint
, opoint_byte
);
4963 if (STRINGP (start
))
4965 failure
= 0 > a_write (desc
, start
, 0, XSTRING (start
)->size
,
4966 &annotations
, &coding
);
4969 else if (XINT (start
) != XINT (end
))
4971 failure
= 0 > a_write (desc
, Qnil
,
4972 XINT (start
), XINT (end
) - XINT (start
),
4973 &annotations
, &coding
);
4978 /* If file was empty, still need to write the annotations */
4979 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4980 failure
= 0 > a_write (desc
, Qnil
, XINT (end
), 0, &annotations
, &coding
);
4984 if (CODING_REQUIRE_FLUSHING (&coding
)
4985 && !(coding
.mode
& CODING_MODE_LAST_BLOCK
)
4988 /* We have to flush out a data. */
4989 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4990 failure
= 0 > e_write (desc
, Qnil
, 1, 1, &coding
);
4997 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4998 Disk full in NFS may be reported here. */
4999 /* mib says that closing the file will try to write as fast as NFS can do
5000 it, and that means the fsync here is not crucial for autosave files. */
5001 if (!auto_saving
&& fsync (desc
) < 0)
5003 /* If fsync fails with EINTR, don't treat that as serious. */
5005 failure
= 1, save_errno
= errno
;
5009 /* Spurious "file has changed on disk" warnings have been
5010 observed on Suns as well.
5011 It seems that `close' can change the modtime, under nfs.
5013 (This has supposedly been fixed in Sunos 4,
5014 but who knows about all the other machines with NFS?) */
5017 /* On VMS and APOLLO, must do the stat after the close
5018 since closing changes the modtime. */
5021 /* Recall that #if defined does not work on VMS. */
5028 /* NFS can report a write failure now. */
5029 if (emacs_close (desc
) < 0)
5030 failure
= 1, save_errno
= errno
;
5033 /* If we wrote to a temporary name and had no errors, rename to real name. */
5037 failure
= (rename (fn
, fname
) != 0), save_errno
= errno
;
5045 /* Discard the unwind protect for close_file_unwind. */
5046 specpdl_ptr
= specpdl
+ count1
;
5047 /* Restore the original current buffer. */
5048 visit_file
= unbind_to (count
, visit_file
);
5050 #ifdef CLASH_DETECTION
5052 unlock_file (lockname
);
5053 #endif /* CLASH_DETECTION */
5055 /* Do this before reporting IO error
5056 to avoid a "file has changed on disk" warning on
5057 next attempt to save. */
5059 current_buffer
->modtime
= st
.st_mtime
;
5062 error ("IO error writing %s: %s", XSTRING (filename
)->data
,
5063 emacs_strerror (save_errno
));
5067 SAVE_MODIFF
= MODIFF
;
5068 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
5069 current_buffer
->filename
= visit_file
;
5070 update_mode_lines
++;
5076 message_with_string ("Wrote %s", visit_file
, 1);
5081 Lisp_Object
merge ();
5083 DEFUN ("car-less-than-car", Fcar_less_than_car
, Scar_less_than_car
, 2, 2, 0,
5084 doc
: /* Return t if (car A) is numerically less than (car B). */)
5088 return Flss (Fcar (a
), Fcar (b
));
5091 /* Build the complete list of annotations appropriate for writing out
5092 the text between START and END, by calling all the functions in
5093 write-region-annotate-functions and merging the lists they return.
5094 If one of these functions switches to a different buffer, we assume
5095 that buffer contains altered text. Therefore, the caller must
5096 make sure to restore the current buffer in all cases,
5097 as save-excursion would do. */
5100 build_annotations (start
, end
)
5101 Lisp_Object start
, end
;
5103 Lisp_Object annotations
;
5105 struct gcpro gcpro1
, gcpro2
;
5106 Lisp_Object original_buffer
;
5109 XSETBUFFER (original_buffer
, current_buffer
);
5112 p
= Vwrite_region_annotate_functions
;
5113 GCPRO2 (annotations
, p
);
5116 struct buffer
*given_buffer
= current_buffer
;
5117 Vwrite_region_annotations_so_far
= annotations
;
5118 res
= call2 (Fcar (p
), start
, end
);
5119 /* If the function makes a different buffer current,
5120 assume that means this buffer contains altered text to be output.
5121 Reset START and END from the buffer bounds
5122 and discard all previous annotations because they should have
5123 been dealt with by this function. */
5124 if (current_buffer
!= given_buffer
)
5126 XSETFASTINT (start
, BEGV
);
5127 XSETFASTINT (end
, ZV
);
5130 Flength (res
); /* Check basic validity of return value */
5131 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5135 /* Now do the same for annotation functions implied by the file-format */
5136 if (auto_saving
&& (!EQ (Vauto_save_file_format
, Qt
)))
5137 p
= Vauto_save_file_format
;
5139 p
= current_buffer
->file_format
;
5140 for (i
= 0; !NILP (p
); p
= Fcdr (p
), ++i
)
5142 struct buffer
*given_buffer
= current_buffer
;
5144 Vwrite_region_annotations_so_far
= annotations
;
5146 /* Value is either a list of annotations or nil if the function
5147 has written annotations to a temporary buffer, which is now
5149 res
= call5 (Qformat_annotate_function
, Fcar (p
), start
, end
,
5150 original_buffer
, make_number (i
));
5151 if (current_buffer
!= given_buffer
)
5153 XSETFASTINT (start
, BEGV
);
5154 XSETFASTINT (end
, ZV
);
5159 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5167 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5168 If STRING is nil, POS is the character position in the current buffer.
5169 Intersperse with them the annotations from *ANNOT
5170 which fall within the range of POS to POS + NCHARS,
5171 each at its appropriate position.
5173 We modify *ANNOT by discarding elements as we use them up.
5175 The return value is negative in case of system call failure. */
5178 a_write (desc
, string
, pos
, nchars
, annot
, coding
)
5181 register int nchars
;
5184 struct coding_system
*coding
;
5188 int lastpos
= pos
+ nchars
;
5190 while (NILP (*annot
) || CONSP (*annot
))
5192 tem
= Fcar_safe (Fcar (*annot
));
5195 nextpos
= XFASTINT (tem
);
5197 /* If there are no more annotations in this range,
5198 output the rest of the range all at once. */
5199 if (! (nextpos
>= pos
&& nextpos
<= lastpos
))
5200 return e_write (desc
, string
, pos
, lastpos
, coding
);
5202 /* Output buffer text up to the next annotation's position. */
5205 if (0 > e_write (desc
, string
, pos
, nextpos
, coding
))
5209 /* Output the annotation. */
5210 tem
= Fcdr (Fcar (*annot
));
5213 if (0 > e_write (desc
, tem
, 0, XSTRING (tem
)->size
, coding
))
5216 *annot
= Fcdr (*annot
);
5221 #ifndef WRITE_BUF_SIZE
5222 #define WRITE_BUF_SIZE (16 * 1024)
5225 /* Write text in the range START and END into descriptor DESC,
5226 encoding them with coding system CODING. If STRING is nil, START
5227 and END are character positions of the current buffer, else they
5228 are indexes to the string STRING. */
5231 e_write (desc
, string
, start
, end
, coding
)
5235 struct coding_system
*coding
;
5239 if (STRINGP (string
))
5242 end
= XSTRING (string
)->size
;
5245 coding
->mode
|= CODING_MODE_FIXED_DESTINATION
;
5246 if (! NILP (current_buffer
->selective_display
))
5247 coding
->mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
5249 /* We used to have a code for handling selective display here. But,
5250 now it is handled within encode_coding. */
5253 if (STRINGP (string
))
5254 encode_coding_object (coding
, string
,
5255 start
, string_char_to_byte (string
, start
),
5256 end
, string_char_to_byte (string
, end
), Qt
);
5258 encode_coding_object (coding
, Fcurrent_buffer (),
5259 start
, CHAR_TO_BYTE (start
),
5260 end
, CHAR_TO_BYTE (end
), Qt
);
5262 if (coding
->produced
> 0)
5264 coding
->produced
-= emacs_write (desc
,
5265 XSTRING (coding
->dst_object
)->data
,
5267 if (coding
->produced
)
5273 start
+= coding
->consumed_char
;
5275 while (start
< end
);
5280 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime
,
5281 Sverify_visited_file_modtime
, 1, 1, 0,
5282 doc
: /* Return t if last mod time of BUF's visited file matches what BUF records.
5283 This means that the file has not been changed since it was visited or saved. */)
5289 Lisp_Object handler
;
5290 Lisp_Object filename
;
5295 if (!STRINGP (b
->filename
)) return Qt
;
5296 if (b
->modtime
== 0) return Qt
;
5298 /* If the file name has special constructs in it,
5299 call the corresponding file handler. */
5300 handler
= Ffind_file_name_handler (b
->filename
,
5301 Qverify_visited_file_modtime
);
5302 if (!NILP (handler
))
5303 return call2 (handler
, Qverify_visited_file_modtime
, buf
);
5305 filename
= ENCODE_FILE (b
->filename
);
5307 if (stat (XSTRING (filename
)->data
, &st
) < 0)
5309 /* If the file doesn't exist now and didn't exist before,
5310 we say that it isn't modified, provided the error is a tame one. */
5311 if (errno
== ENOENT
|| errno
== EACCES
|| errno
== ENOTDIR
)
5316 if (st
.st_mtime
== b
->modtime
5317 /* If both are positive, accept them if they are off by one second. */
5318 || (st
.st_mtime
> 0 && b
->modtime
> 0
5319 && (st
.st_mtime
== b
->modtime
+ 1
5320 || st
.st_mtime
== b
->modtime
- 1)))
5325 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime
,
5326 Sclear_visited_file_modtime
, 0, 0, 0,
5327 doc
: /* Clear out records of last mod time of visited file.
5328 Next attempt to save will certainly not complain of a discrepancy. */)
5331 current_buffer
->modtime
= 0;
5335 DEFUN ("visited-file-modtime", Fvisited_file_modtime
,
5336 Svisited_file_modtime
, 0, 0, 0,
5337 doc
: /* Return the current buffer's recorded visited file modification time.
5338 The value is a list of the form (HIGH . LOW), like the time values
5339 that `file-attributes' returns. */)
5342 return long_to_cons ((unsigned long) current_buffer
->modtime
);
5345 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime
,
5346 Sset_visited_file_modtime
, 0, 1, 0,
5347 doc
: /* Update buffer's recorded modification time from the visited file's time.
5348 Useful if the buffer was not read from the file normally
5349 or if the file itself has been changed for some known benign reason.
5350 An argument specifies the modification time value to use
5351 \(instead of that of the visited file), in the form of a list
5352 \(HIGH . LOW) or (HIGH LOW). */)
5354 Lisp_Object time_list
;
5356 if (!NILP (time_list
))
5357 current_buffer
->modtime
= cons_to_long (time_list
);
5360 register Lisp_Object filename
;
5362 Lisp_Object handler
;
5364 filename
= Fexpand_file_name (current_buffer
->filename
, Qnil
);
5366 /* If the file name has special constructs in it,
5367 call the corresponding file handler. */
5368 handler
= Ffind_file_name_handler (filename
, Qset_visited_file_modtime
);
5369 if (!NILP (handler
))
5370 /* The handler can find the file name the same way we did. */
5371 return call2 (handler
, Qset_visited_file_modtime
, Qnil
);
5373 filename
= ENCODE_FILE (filename
);
5375 if (stat (XSTRING (filename
)->data
, &st
) >= 0)
5376 current_buffer
->modtime
= st
.st_mtime
;
5383 auto_save_error (error
)
5386 Lisp_Object args
[3], msg
;
5388 struct gcpro gcpro1
;
5392 args
[0] = build_string ("Auto-saving %s: %s");
5393 args
[1] = current_buffer
->name
;
5394 args
[2] = Ferror_message_string (error
);
5395 msg
= Fformat (3, args
);
5397 nbytes
= STRING_BYTES (XSTRING (msg
));
5399 for (i
= 0; i
< 3; ++i
)
5402 message2 (XSTRING (msg
)->data
, nbytes
, STRING_MULTIBYTE (msg
));
5404 message2_nolog (XSTRING (msg
)->data
, nbytes
, STRING_MULTIBYTE (msg
));
5405 Fsleep_for (make_number (1), Qnil
);
5417 /* Get visited file's mode to become the auto save file's mode. */
5418 if (! NILP (current_buffer
->filename
)
5419 && stat (XSTRING (current_buffer
->filename
)->data
, &st
) >= 0)
5420 /* But make sure we can overwrite it later! */
5421 auto_save_mode_bits
= st
.st_mode
| 0600;
5423 auto_save_mode_bits
= 0666;
5426 Fwrite_region (Qnil
, Qnil
,
5427 current_buffer
->auto_save_file_name
,
5428 Qnil
, Qlambda
, Qnil
, Qnil
);
5432 do_auto_save_unwind (stream
) /* used as unwind-protect function */
5437 fclose ((FILE *) (XFASTINT (XCAR (stream
)) << 16
5438 | XFASTINT (XCDR (stream
))));
5444 do_auto_save_unwind_1 (value
) /* used as unwind-protect function */
5447 minibuffer_auto_raise
= XINT (value
);
5451 DEFUN ("do-auto-save", Fdo_auto_save
, Sdo_auto_save
, 0, 2, "",
5452 doc
: /* Auto-save all buffers that need it.
5453 This is all buffers that have auto-saving enabled
5454 and are changed since last auto-saved.
5455 Auto-saving writes the buffer into a file
5456 so that your editing is not lost if the system crashes.
5457 This file is not the file you visited; that changes only when you save.
5458 Normally we run the normal hook `auto-save-hook' before saving.
5460 A non-nil NO-MESSAGE argument means do not print any message if successful.
5461 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5462 (no_message
, current_only
)
5463 Lisp_Object no_message
, current_only
;
5465 struct buffer
*old
= current_buffer
, *b
;
5466 Lisp_Object tail
, buf
;
5468 int do_handled_files
;
5471 Lisp_Object lispstream
;
5472 int count
= specpdl_ptr
- specpdl
;
5473 int orig_minibuffer_auto_raise
= minibuffer_auto_raise
;
5476 if (max_specpdl_size
< specpdl_size
+ 40)
5477 max_specpdl_size
= specpdl_size
+ 40;
5482 if (NILP (no_message
));
5483 message_p
= push_message ();
5485 /* Ordinarily don't quit within this function,
5486 but don't make it impossible to quit (in case we get hung in I/O). */
5490 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5491 point to non-strings reached from Vbuffer_alist. */
5493 if (!NILP (Vrun_hooks
))
5494 call1 (Vrun_hooks
, intern ("auto-save-hook"));
5496 if (STRINGP (Vauto_save_list_file_name
))
5498 Lisp_Object listfile
;
5500 listfile
= Fexpand_file_name (Vauto_save_list_file_name
, Qnil
);
5502 /* Don't try to create the directory when shutting down Emacs,
5503 because creating the directory might signal an error, and
5504 that would leave Emacs in a strange state. */
5505 if (!NILP (Vrun_hooks
))
5508 dir
= Ffile_name_directory (listfile
);
5509 if (NILP (Ffile_directory_p (dir
)))
5510 call2 (Qmake_directory
, dir
, Qt
);
5513 stream
= fopen (XSTRING (listfile
)->data
, "w");
5516 /* Arrange to close that file whether or not we get an error.
5517 Also reset auto_saving to 0. */
5518 lispstream
= Fcons (Qnil
, Qnil
);
5519 XSETCARFASTINT (lispstream
, (EMACS_UINT
)stream
>> 16);
5520 XSETCDRFASTINT (lispstream
, (EMACS_UINT
)stream
& 0xffff);
5531 record_unwind_protect (do_auto_save_unwind
, lispstream
);
5532 record_unwind_protect (do_auto_save_unwind_1
,
5533 make_number (minibuffer_auto_raise
));
5534 minibuffer_auto_raise
= 0;
5537 /* First, save all files which don't have handlers. If Emacs is
5538 crashing, the handlers may tweak what is causing Emacs to crash
5539 in the first place, and it would be a shame if Emacs failed to
5540 autosave perfectly ordinary files because it couldn't handle some
5542 for (do_handled_files
= 0; do_handled_files
< 2; do_handled_files
++)
5543 for (tail
= Vbuffer_alist
; GC_CONSP (tail
); tail
= XCDR (tail
))
5545 buf
= XCDR (XCAR (tail
));
5548 /* Record all the buffers that have auto save mode
5549 in the special file that lists them. For each of these buffers,
5550 Record visited name (if any) and auto save name. */
5551 if (STRINGP (b
->auto_save_file_name
)
5552 && stream
!= NULL
&& do_handled_files
== 0)
5554 if (!NILP (b
->filename
))
5556 fwrite (XSTRING (b
->filename
)->data
, 1,
5557 STRING_BYTES (XSTRING (b
->filename
)), stream
);
5559 putc ('\n', stream
);
5560 fwrite (XSTRING (b
->auto_save_file_name
)->data
, 1,
5561 STRING_BYTES (XSTRING (b
->auto_save_file_name
)), stream
);
5562 putc ('\n', stream
);
5565 if (!NILP (current_only
)
5566 && b
!= current_buffer
)
5569 /* Don't auto-save indirect buffers.
5570 The base buffer takes care of it. */
5574 /* Check for auto save enabled
5575 and file changed since last auto save
5576 and file changed since last real save. */
5577 if (STRINGP (b
->auto_save_file_name
)
5578 && BUF_SAVE_MODIFF (b
) < BUF_MODIFF (b
)
5579 && b
->auto_save_modified
< BUF_MODIFF (b
)
5580 /* -1 means we've turned off autosaving for a while--see below. */
5581 && XINT (b
->save_length
) >= 0
5582 && (do_handled_files
5583 || NILP (Ffind_file_name_handler (b
->auto_save_file_name
,
5586 EMACS_TIME before_time
, after_time
;
5588 EMACS_GET_TIME (before_time
);
5590 /* If we had a failure, don't try again for 20 minutes. */
5591 if (b
->auto_save_failure_time
>= 0
5592 && EMACS_SECS (before_time
) - b
->auto_save_failure_time
< 1200)
5595 if ((XFASTINT (b
->save_length
) * 10
5596 > (BUF_Z (b
) - BUF_BEG (b
)) * 13)
5597 /* A short file is likely to change a large fraction;
5598 spare the user annoying messages. */
5599 && XFASTINT (b
->save_length
) > 5000
5600 /* These messages are frequent and annoying for `*mail*'. */
5601 && !EQ (b
->filename
, Qnil
)
5602 && NILP (no_message
))
5604 /* It has shrunk too much; turn off auto-saving here. */
5605 minibuffer_auto_raise
= orig_minibuffer_auto_raise
;
5606 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5608 minibuffer_auto_raise
= 0;
5609 /* Turn off auto-saving until there's a real save,
5610 and prevent any more warnings. */
5611 XSETINT (b
->save_length
, -1);
5612 Fsleep_for (make_number (1), Qnil
);
5615 set_buffer_internal (b
);
5616 if (!auto_saved
&& NILP (no_message
))
5617 message1 ("Auto-saving...");
5618 internal_condition_case (auto_save_1
, Qt
, auto_save_error
);
5620 b
->auto_save_modified
= BUF_MODIFF (b
);
5621 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
5622 set_buffer_internal (old
);
5624 EMACS_GET_TIME (after_time
);
5626 /* If auto-save took more than 60 seconds,
5627 assume it was an NFS failure that got a timeout. */
5628 if (EMACS_SECS (after_time
) - EMACS_SECS (before_time
) > 60)
5629 b
->auto_save_failure_time
= EMACS_SECS (after_time
);
5633 /* Prevent another auto save till enough input events come in. */
5634 record_auto_save ();
5636 if (auto_saved
&& NILP (no_message
))
5640 sit_for (1, 0, 0, 0, 0);
5644 message1 ("Auto-saving...done");
5649 unbind_to (count
, Qnil
);
5653 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved
,
5654 Sset_buffer_auto_saved
, 0, 0, 0,
5655 doc
: /* Mark current buffer as auto-saved with its current text.
5656 No auto-save file will be written until the buffer changes again. */)
5659 current_buffer
->auto_save_modified
= MODIFF
;
5660 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
5661 current_buffer
->auto_save_failure_time
= -1;
5665 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure
,
5666 Sclear_buffer_auto_save_failure
, 0, 0, 0,
5667 doc
: /* Clear any record of a recent auto-save failure in the current buffer. */)
5670 current_buffer
->auto_save_failure_time
= -1;
5674 DEFUN ("recent-auto-save-p", Frecent_auto_save_p
, Srecent_auto_save_p
,
5676 doc
: /* Return t if buffer has been auto-saved since last read in or saved. */)
5679 return (SAVE_MODIFF
< current_buffer
->auto_save_modified
) ? Qt
: Qnil
;
5682 /* Reading and completing file names */
5683 extern Lisp_Object
Ffile_name_completion (), Ffile_name_all_completions ();
5685 /* In the string VAL, change each $ to $$ and return the result. */
5688 double_dollars (val
)
5691 register unsigned char *old
, *new;
5695 osize
= STRING_BYTES (XSTRING (val
));
5697 /* Count the number of $ characters. */
5698 for (n
= osize
, count
= 0, old
= XSTRING (val
)->data
; n
> 0; n
--)
5699 if (*old
++ == '$') count
++;
5702 old
= XSTRING (val
)->data
;
5703 val
= make_uninit_multibyte_string (XSTRING (val
)->size
+ count
,
5705 new = XSTRING (val
)->data
;
5706 for (n
= osize
; n
> 0; n
--)
5719 DEFUN ("read-file-name-internal", Fread_file_name_internal
, Sread_file_name_internal
,
5721 doc
: /* Internal subroutine for read-file-name. Do not call this. */)
5722 (string
, dir
, action
)
5723 Lisp_Object string
, dir
, action
;
5724 /* action is nil for complete, t for return list of completions,
5725 lambda for verify final value */
5727 Lisp_Object name
, specdir
, realdir
, val
, orig_string
;
5729 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
5731 CHECK_STRING (string
);
5738 /* No need to protect ACTION--we only compare it with t and nil. */
5739 GCPRO5 (string
, realdir
, name
, specdir
, orig_string
);
5741 if (XSTRING (string
)->size
== 0)
5743 if (EQ (action
, Qlambda
))
5751 orig_string
= string
;
5752 string
= Fsubstitute_in_file_name (string
);
5753 changed
= NILP (Fstring_equal (string
, orig_string
));
5754 name
= Ffile_name_nondirectory (string
);
5755 val
= Ffile_name_directory (string
);
5757 realdir
= Fexpand_file_name (val
, realdir
);
5762 specdir
= Ffile_name_directory (string
);
5763 val
= Ffile_name_completion (name
, realdir
);
5768 return double_dollars (string
);
5772 if (!NILP (specdir
))
5773 val
= concat2 (specdir
, val
);
5775 return double_dollars (val
);
5778 #endif /* not VMS */
5782 if (EQ (action
, Qt
))
5783 return Ffile_name_all_completions (name
, realdir
);
5784 /* Only other case actually used is ACTION = lambda */
5786 /* Supposedly this helps commands such as `cd' that read directory names,
5787 but can someone explain how it helps them? -- RMS */
5788 if (XSTRING (name
)->size
== 0)
5791 return Ffile_exists_p (string
);
5794 DEFUN ("read-file-name", Fread_file_name
, Sread_file_name
, 1, 5, 0,
5795 doc
: /* Read file name, prompting with PROMPT and completing in directory DIR.
5796 Value is not expanded---you must call `expand-file-name' yourself.
5797 Default name to DEFAULT-FILENAME if user enters a null string.
5798 (If DEFAULT-FILENAME is omitted, the visited file name is used,
5799 except that if INITIAL is specified, that combined with DIR is used.)
5800 Fourth arg MUSTMATCH non-nil means require existing file's name.
5801 Non-nil and non-t means also require confirmation after completion.
5802 Fifth arg INITIAL specifies text to start with.
5803 DIR defaults to current buffer's directory default.
5805 If this command was invoked with the mouse, use a file dialog box if
5806 `use-dialog-box' is non-nil, and the window system or X toolkit in use
5807 provides a file dialog box. */)
5808 (prompt
, dir
, default_filename
, mustmatch
, initial
)
5809 Lisp_Object prompt
, dir
, default_filename
, mustmatch
, initial
;
5811 Lisp_Object val
, insdef
, tem
;
5812 struct gcpro gcpro1
, gcpro2
;
5813 register char *homedir
;
5814 int replace_in_history
= 0;
5815 int add_to_history
= 0;
5819 dir
= current_buffer
->directory
;
5820 if (NILP (default_filename
))
5822 if (! NILP (initial
))
5823 default_filename
= Fexpand_file_name (initial
, dir
);
5825 default_filename
= current_buffer
->filename
;
5828 /* If dir starts with user's homedir, change that to ~. */
5829 homedir
= (char *) egetenv ("HOME");
5831 /* homedir can be NULL in temacs, since Vprocess_environment is not
5832 yet set up. We shouldn't crash in that case. */
5835 homedir
= strcpy (alloca (strlen (homedir
) + 1), homedir
);
5836 CORRECT_DIR_SEPS (homedir
);
5841 && !strncmp (homedir
, XSTRING (dir
)->data
, strlen (homedir
))
5842 && IS_DIRECTORY_SEP (XSTRING (dir
)->data
[strlen (homedir
)]))
5844 dir
= make_string (XSTRING (dir
)->data
+ strlen (homedir
) - 1,
5845 STRING_BYTES (XSTRING (dir
)) - strlen (homedir
) + 1);
5846 XSTRING (dir
)->data
[0] = '~';
5848 /* Likewise for default_filename. */
5850 && STRINGP (default_filename
)
5851 && !strncmp (homedir
, XSTRING (default_filename
)->data
, strlen (homedir
))
5852 && IS_DIRECTORY_SEP (XSTRING (default_filename
)->data
[strlen (homedir
)]))
5855 = make_string (XSTRING (default_filename
)->data
+ strlen (homedir
) - 1,
5856 STRING_BYTES (XSTRING (default_filename
)) - strlen (homedir
) + 1);
5857 XSTRING (default_filename
)->data
[0] = '~';
5859 if (!NILP (default_filename
))
5861 CHECK_STRING (default_filename
);
5862 default_filename
= double_dollars (default_filename
);
5865 if (insert_default_directory
&& STRINGP (dir
))
5868 if (!NILP (initial
))
5870 Lisp_Object args
[2], pos
;
5874 insdef
= Fconcat (2, args
);
5875 pos
= make_number (XSTRING (double_dollars (dir
))->size
);
5876 insdef
= Fcons (double_dollars (insdef
), pos
);
5879 insdef
= double_dollars (insdef
);
5881 else if (STRINGP (initial
))
5882 insdef
= Fcons (double_dollars (initial
), make_number (0));
5886 count
= specpdl_ptr
- specpdl
;
5888 specbind (intern ("completion-ignore-case"), Qt
);
5891 specbind (intern ("minibuffer-completing-file-name"), Qt
);
5893 GCPRO2 (insdef
, default_filename
);
5895 #if defined (USE_MOTIF) || defined (HAVE_NTGUI)
5896 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
5900 /* If DIR contains a file name, split it. */
5902 file
= Ffile_name_nondirectory (dir
);
5903 if (XSTRING (file
)->size
&& NILP (default_filename
))
5905 default_filename
= file
;
5906 dir
= Ffile_name_directory (dir
);
5908 if (!NILP(default_filename
))
5909 default_filename
= Fexpand_file_name (default_filename
, dir
);
5910 val
= Fx_file_dialog (prompt
, dir
, default_filename
, mustmatch
);
5915 val
= Fcompleting_read (prompt
, intern ("read-file-name-internal"),
5916 dir
, mustmatch
, insdef
,
5917 Qfile_name_history
, default_filename
, Qnil
);
5919 tem
= Fsymbol_value (Qfile_name_history
);
5920 if (CONSP (tem
) && EQ (XCAR (tem
), val
))
5921 replace_in_history
= 1;
5923 /* If Fcompleting_read returned the inserted default string itself
5924 (rather than a new string with the same contents),
5925 it has to mean that the user typed RET with the minibuffer empty.
5926 In that case, we really want to return ""
5927 so that commands such as set-visited-file-name can distinguish. */
5928 if (EQ (val
, default_filename
))
5930 /* In this case, Fcompleting_read has not added an element
5931 to the history. Maybe we should. */
5932 if (! replace_in_history
)
5935 val
= build_string ("");
5938 unbind_to (count
, Qnil
);
5941 error ("No file name specified");
5943 tem
= Fstring_equal (val
, CONSP (insdef
) ? XCAR (insdef
) : insdef
);
5945 if (!NILP (tem
) && !NILP (default_filename
))
5946 val
= default_filename
;
5947 else if (XSTRING (val
)->size
== 0 && NILP (insdef
))
5949 if (!NILP (default_filename
))
5950 val
= default_filename
;
5952 error ("No default file name");
5954 val
= Fsubstitute_in_file_name (val
);
5956 if (replace_in_history
)
5957 /* Replace what Fcompleting_read added to the history
5958 with what we will actually return. */
5959 XSETCAR (Fsymbol_value (Qfile_name_history
), double_dollars (val
));
5960 else if (add_to_history
)
5962 /* Add the value to the history--but not if it matches
5963 the last value already there. */
5964 Lisp_Object val1
= double_dollars (val
);
5965 tem
= Fsymbol_value (Qfile_name_history
);
5966 if (! CONSP (tem
) || NILP (Fequal (XCAR (tem
), val1
)))
5967 Fset (Qfile_name_history
,
5978 /* Must be set before any path manipulation is performed. */
5979 XSETFASTINT (Vdirectory_sep_char
, '/');
5986 Qexpand_file_name
= intern ("expand-file-name");
5987 Qsubstitute_in_file_name
= intern ("substitute-in-file-name");
5988 Qdirectory_file_name
= intern ("directory-file-name");
5989 Qfile_name_directory
= intern ("file-name-directory");
5990 Qfile_name_nondirectory
= intern ("file-name-nondirectory");
5991 Qunhandled_file_name_directory
= intern ("unhandled-file-name-directory");
5992 Qfile_name_as_directory
= intern ("file-name-as-directory");
5993 Qcopy_file
= intern ("copy-file");
5994 Qmake_directory_internal
= intern ("make-directory-internal");
5995 Qmake_directory
= intern ("make-directory");
5996 Qdelete_directory
= intern ("delete-directory");
5997 Qdelete_file
= intern ("delete-file");
5998 Qrename_file
= intern ("rename-file");
5999 Qadd_name_to_file
= intern ("add-name-to-file");
6000 Qmake_symbolic_link
= intern ("make-symbolic-link");
6001 Qfile_exists_p
= intern ("file-exists-p");
6002 Qfile_executable_p
= intern ("file-executable-p");
6003 Qfile_readable_p
= intern ("file-readable-p");
6004 Qfile_writable_p
= intern ("file-writable-p");
6005 Qfile_symlink_p
= intern ("file-symlink-p");
6006 Qaccess_file
= intern ("access-file");
6007 Qfile_directory_p
= intern ("file-directory-p");
6008 Qfile_regular_p
= intern ("file-regular-p");
6009 Qfile_accessible_directory_p
= intern ("file-accessible-directory-p");
6010 Qfile_modes
= intern ("file-modes");
6011 Qset_file_modes
= intern ("set-file-modes");
6012 Qfile_newer_than_file_p
= intern ("file-newer-than-file-p");
6013 Qinsert_file_contents
= intern ("insert-file-contents");
6014 Qwrite_region
= intern ("write-region");
6015 Qverify_visited_file_modtime
= intern ("verify-visited-file-modtime");
6016 Qset_visited_file_modtime
= intern ("set-visited-file-modtime");
6018 staticpro (&Qexpand_file_name
);
6019 staticpro (&Qsubstitute_in_file_name
);
6020 staticpro (&Qdirectory_file_name
);
6021 staticpro (&Qfile_name_directory
);
6022 staticpro (&Qfile_name_nondirectory
);
6023 staticpro (&Qunhandled_file_name_directory
);
6024 staticpro (&Qfile_name_as_directory
);
6025 staticpro (&Qcopy_file
);
6026 staticpro (&Qmake_directory_internal
);
6027 staticpro (&Qmake_directory
);
6028 staticpro (&Qdelete_directory
);
6029 staticpro (&Qdelete_file
);
6030 staticpro (&Qrename_file
);
6031 staticpro (&Qadd_name_to_file
);
6032 staticpro (&Qmake_symbolic_link
);
6033 staticpro (&Qfile_exists_p
);
6034 staticpro (&Qfile_executable_p
);
6035 staticpro (&Qfile_readable_p
);
6036 staticpro (&Qfile_writable_p
);
6037 staticpro (&Qaccess_file
);
6038 staticpro (&Qfile_symlink_p
);
6039 staticpro (&Qfile_directory_p
);
6040 staticpro (&Qfile_regular_p
);
6041 staticpro (&Qfile_accessible_directory_p
);
6042 staticpro (&Qfile_modes
);
6043 staticpro (&Qset_file_modes
);
6044 staticpro (&Qfile_newer_than_file_p
);
6045 staticpro (&Qinsert_file_contents
);
6046 staticpro (&Qwrite_region
);
6047 staticpro (&Qverify_visited_file_modtime
);
6048 staticpro (&Qset_visited_file_modtime
);
6050 Qfile_name_history
= intern ("file-name-history");
6051 Fset (Qfile_name_history
, Qnil
);
6052 staticpro (&Qfile_name_history
);
6054 Qfile_error
= intern ("file-error");
6055 staticpro (&Qfile_error
);
6056 Qfile_already_exists
= intern ("file-already-exists");
6057 staticpro (&Qfile_already_exists
);
6058 Qfile_date_error
= intern ("file-date-error");
6059 staticpro (&Qfile_date_error
);
6060 Qexcl
= intern ("excl");
6064 Qfind_buffer_file_type
= intern ("find-buffer-file-type");
6065 staticpro (&Qfind_buffer_file_type
);
6068 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system
,
6069 doc
: /* *Coding system for encoding file names.
6070 If it is nil, `default-file-name-coding-system' (which see) is used. */);
6071 Vfile_name_coding_system
= Qnil
;
6073 DEFVAR_LISP ("default-file-name-coding-system",
6074 &Vdefault_file_name_coding_system
,
6075 doc
: /* Default coding system for encoding file names.
6076 This variable is used only when `file-name-coding-system' is nil.
6078 This variable is set/changed by the command `set-language-environment'.
6079 User should not set this variable manually,
6080 instead use `file-name-coding-system' to get a constant encoding
6081 of file names regardless of the current language environment. */);
6082 Vdefault_file_name_coding_system
= Qnil
;
6084 DEFVAR_LISP ("auto-save-file-format", &Vauto_save_file_format
,
6085 doc
: /* *Format in which to write auto-save files.
6086 Should be a list of symbols naming formats that are defined in `format-alist'.
6087 If it is t, which is the default, auto-save files are written in the
6088 same format as a regular save would use. */);
6089 Vauto_save_file_format
= Qt
;
6091 Qformat_decode
= intern ("format-decode");
6092 staticpro (&Qformat_decode
);
6093 Qformat_annotate_function
= intern ("format-annotate-function");
6094 staticpro (&Qformat_annotate_function
);
6096 Qcar_less_than_car
= intern ("car-less-than-car");
6097 staticpro (&Qcar_less_than_car
);
6099 Fput (Qfile_error
, Qerror_conditions
,
6100 Fcons (Qfile_error
, Fcons (Qerror
, Qnil
)));
6101 Fput (Qfile_error
, Qerror_message
,
6102 build_string ("File error"));
6104 Fput (Qfile_already_exists
, Qerror_conditions
,
6105 Fcons (Qfile_already_exists
,
6106 Fcons (Qfile_error
, Fcons (Qerror
, Qnil
))));
6107 Fput (Qfile_already_exists
, Qerror_message
,
6108 build_string ("File already exists"));
6110 Fput (Qfile_date_error
, Qerror_conditions
,
6111 Fcons (Qfile_date_error
,
6112 Fcons (Qfile_error
, Fcons (Qerror
, Qnil
))));
6113 Fput (Qfile_date_error
, Qerror_message
,
6114 build_string ("Cannot set file date"));
6116 DEFVAR_BOOL ("insert-default-directory", &insert_default_directory
,
6117 doc
: /* *Non-nil means when reading a filename start with default dir in minibuffer. */);
6118 insert_default_directory
= 1;
6120 DEFVAR_BOOL ("vms-stmlf-recfm", &vms_stmlf_recfm
,
6121 doc
: /* *Non-nil means write new files with record format `stmlf'.
6122 nil means use format `var'. This variable is meaningful only on VMS. */);
6123 vms_stmlf_recfm
= 0;
6125 DEFVAR_LISP ("directory-sep-char", &Vdirectory_sep_char
,
6126 doc
: /* Directory separator character for built-in functions that return file names.
6127 The value should be either ?/ or ?\\ (any other value is treated as ?\\).
6128 This variable affects the built-in functions only on Windows,
6129 on other platforms, it is initialized so that Lisp code can find out
6130 what the normal separator is.
6132 WARNING: This variable is deprecated and will be removed in the near
6133 future. DO NOT USE IT. */);
6135 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist
,
6136 doc
: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
6137 If a file name matches REGEXP, then all I/O on that file is done by calling
6140 The first argument given to HANDLER is the name of the I/O primitive
6141 to be handled; the remaining arguments are the arguments that were
6142 passed to that primitive. For example, if you do
6143 (file-exists-p FILENAME)
6144 and FILENAME is handled by HANDLER, then HANDLER is called like this:
6145 (funcall HANDLER 'file-exists-p FILENAME)
6146 The function `find-file-name-handler' checks this list for a handler
6147 for its argument. */);
6148 Vfile_name_handler_alist
= Qnil
;
6150 DEFVAR_LISP ("set-auto-coding-function",
6151 &Vset_auto_coding_function
,
6152 doc
: /* If non-nil, a function to call to decide a coding system of file.
6153 Two arguments are passed to this function: the file name
6154 and the length of a file contents following the point.
6155 This function should return a coding system to decode the file contents.
6156 It should check the file name against `auto-coding-alist'.
6157 If no coding system is decided, it should check a coding system
6158 specified in the heading lines with the format:
6159 -*- ... coding: CODING-SYSTEM; ... -*-
6160 or local variable spec of the tailing lines with `coding:' tag. */);
6161 Vset_auto_coding_function
= Qnil
;
6163 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions
,
6164 doc
: /* A list of functions to be called at the end of `insert-file-contents'.
6165 Each is passed one argument, the number of bytes inserted. It should return
6166 the new byte count, and leave point the same. If `insert-file-contents' is
6167 intercepted by a handler from `file-name-handler-alist', that handler is
6168 responsible for calling the after-insert-file-functions if appropriate. */);
6169 Vafter_insert_file_functions
= Qnil
;
6171 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions
,
6172 doc
: /* A list of functions to be called at the start of `write-region'.
6173 Each is passed two arguments, START and END as for `write-region'.
6174 These are usually two numbers but not always; see the documentation
6175 for `write-region'. The function should return a list of pairs
6176 of the form (POSITION . STRING), consisting of strings to be effectively
6177 inserted at the specified positions of the file being written (1 means to
6178 insert before the first byte written). The POSITIONs must be sorted into
6179 increasing order. If there are several functions in the list, the several
6180 lists are merged destructively. */);
6181 Vwrite_region_annotate_functions
= Qnil
;
6183 DEFVAR_LISP ("write-region-annotations-so-far",
6184 &Vwrite_region_annotations_so_far
,
6185 doc
: /* When an annotation function is called, this holds the previous annotations.
6186 These are the annotations made by other annotation functions
6187 that were already called. See also `write-region-annotate-functions'. */);
6188 Vwrite_region_annotations_so_far
= Qnil
;
6190 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers
,
6191 doc
: /* A list of file name handlers that temporarily should not be used.
6192 This applies only to the operation `inhibit-file-name-operation'. */);
6193 Vinhibit_file_name_handlers
= Qnil
;
6195 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation
,
6196 doc
: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6197 Vinhibit_file_name_operation
= Qnil
;
6199 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name
,
6200 doc
: /* File name in which we write a list of all auto save file names.
6201 This variable is initialized automatically from `auto-save-list-file-prefix'
6202 shortly after Emacs reads your `.emacs' file, if you have not yet given it
6203 a non-nil value. */);
6204 Vauto_save_list_file_name
= Qnil
;
6206 defsubr (&Sfind_file_name_handler
);
6207 defsubr (&Sfile_name_directory
);
6208 defsubr (&Sfile_name_nondirectory
);
6209 defsubr (&Sunhandled_file_name_directory
);
6210 defsubr (&Sfile_name_as_directory
);
6211 defsubr (&Sdirectory_file_name
);
6212 defsubr (&Smake_temp_name
);
6213 defsubr (&Sexpand_file_name
);
6214 defsubr (&Ssubstitute_in_file_name
);
6215 defsubr (&Scopy_file
);
6216 defsubr (&Smake_directory_internal
);
6217 defsubr (&Sdelete_directory
);
6218 defsubr (&Sdelete_file
);
6219 defsubr (&Srename_file
);
6220 defsubr (&Sadd_name_to_file
);
6222 defsubr (&Smake_symbolic_link
);
6223 #endif /* S_IFLNK */
6225 defsubr (&Sdefine_logical_name
);
6228 defsubr (&Ssysnetunam
);
6229 #endif /* HPUX_NET */
6230 defsubr (&Sfile_name_absolute_p
);
6231 defsubr (&Sfile_exists_p
);
6232 defsubr (&Sfile_executable_p
);
6233 defsubr (&Sfile_readable_p
);
6234 defsubr (&Sfile_writable_p
);
6235 defsubr (&Saccess_file
);
6236 defsubr (&Sfile_symlink_p
);
6237 defsubr (&Sfile_directory_p
);
6238 defsubr (&Sfile_accessible_directory_p
);
6239 defsubr (&Sfile_regular_p
);
6240 defsubr (&Sfile_modes
);
6241 defsubr (&Sset_file_modes
);
6242 defsubr (&Sset_default_file_modes
);
6243 defsubr (&Sdefault_file_modes
);
6244 defsubr (&Sfile_newer_than_file_p
);
6245 defsubr (&Sinsert_file_contents
);
6246 defsubr (&Swrite_region
);
6247 defsubr (&Scar_less_than_car
);
6248 defsubr (&Sverify_visited_file_modtime
);
6249 defsubr (&Sclear_visited_file_modtime
);
6250 defsubr (&Svisited_file_modtime
);
6251 defsubr (&Sset_visited_file_modtime
);
6252 defsubr (&Sdo_auto_save
);
6253 defsubr (&Sset_buffer_auto_saved
);
6254 defsubr (&Sclear_buffer_auto_save_failure
);
6255 defsubr (&Srecent_auto_save_p
);
6257 defsubr (&Sread_file_name_internal
);
6258 defsubr (&Sread_file_name
);
6261 defsubr (&Sunix_sync
);