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 (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"
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 #define min(a, b) ((a) < (b) ? (a) : (b))
163 #define max(a, b) ((a) > (b) ? (a) : (b))
165 /* Nonzero during writing of auto-save files */
168 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
169 a new file with the same mode as the original */
170 int auto_save_mode_bits
;
172 /* Coding system for file names, or nil if none. */
173 Lisp_Object Vfile_name_coding_system
;
175 /* Coding system for file names used only when
176 Vfile_name_coding_system is nil. */
177 Lisp_Object Vdefault_file_name_coding_system
;
179 /* Alist of elements (REGEXP . HANDLER) for file names
180 whose I/O is done with a special handler. */
181 Lisp_Object Vfile_name_handler_alist
;
183 /* Format for auto-save files */
184 Lisp_Object Vauto_save_file_format
;
186 /* Lisp functions for translating file formats */
187 Lisp_Object Qformat_decode
, Qformat_annotate_function
;
189 /* Function to be called to decide a coding system of a reading file. */
190 Lisp_Object Vset_auto_coding_function
;
192 /* Functions to be called to process text properties in inserted file. */
193 Lisp_Object Vafter_insert_file_functions
;
195 /* Functions to be called to create text property annotations for file. */
196 Lisp_Object Vwrite_region_annotate_functions
;
198 /* During build_annotations, each time an annotation function is called,
199 this holds the annotations made by the previous functions. */
200 Lisp_Object Vwrite_region_annotations_so_far
;
202 /* File name in which we write a list of all our auto save files. */
203 Lisp_Object Vauto_save_list_file_name
;
205 /* Nonzero means, when reading a filename in the minibuffer,
206 start out by inserting the default directory into the minibuffer. */
207 int insert_default_directory
;
209 /* On VMS, nonzero means write new files with record format stmlf.
210 Zero means use var format. */
213 /* On NT, specifies the directory separator character, used (eg.) when
214 expanding file names. This can be bound to / or \. */
215 Lisp_Object Vdirectory_sep_char
;
217 extern Lisp_Object Vuser_login_name
;
220 extern Lisp_Object Vw32_get_true_file_attributes
;
223 extern int minibuf_level
;
225 extern int minibuffer_auto_raise
;
227 /* These variables describe handlers that have "already" had a chance
228 to handle the current operation.
230 Vinhibit_file_name_handlers is a list of file name handlers.
231 Vinhibit_file_name_operation is the operation being handled.
232 If we try to handle that operation, we ignore those handlers. */
234 static Lisp_Object Vinhibit_file_name_handlers
;
235 static Lisp_Object Vinhibit_file_name_operation
;
237 Lisp_Object Qfile_error
, Qfile_already_exists
, Qfile_date_error
;
239 Lisp_Object Qfile_name_history
;
241 Lisp_Object Qcar_less_than_car
;
243 static int a_write
P_ ((int, Lisp_Object
, int, int,
244 Lisp_Object
*, struct coding_system
*));
245 static int e_write
P_ ((int, Lisp_Object
, int, int, struct coding_system
*));
249 report_file_error (string
, data
)
253 Lisp_Object errstring
;
256 synchronize_system_messages_locale ();
257 errstring
= code_convert_string_norecord (build_string (strerror (errorno
)),
258 Vlocale_coding_system
, 0);
264 Fsignal (Qfile_already_exists
, Fcons (errstring
, data
));
267 /* System error messages are capitalized. Downcase the initial
268 unless it is followed by a slash. */
269 if (XSTRING (errstring
)->data
[1] != '/')
270 XSTRING (errstring
)->data
[0] = DOWNCASE (XSTRING (errstring
)->data
[0]);
272 Fsignal (Qfile_error
,
273 Fcons (build_string (string
), Fcons (errstring
, data
)));
278 close_file_unwind (fd
)
281 emacs_close (XFASTINT (fd
));
285 /* Restore point, having saved it as a marker. */
288 restore_point_unwind (location
)
289 Lisp_Object location
;
291 Fgoto_char (location
);
292 Fset_marker (location
, Qnil
, Qnil
);
296 Lisp_Object Qexpand_file_name
;
297 Lisp_Object Qsubstitute_in_file_name
;
298 Lisp_Object Qdirectory_file_name
;
299 Lisp_Object Qfile_name_directory
;
300 Lisp_Object Qfile_name_nondirectory
;
301 Lisp_Object Qunhandled_file_name_directory
;
302 Lisp_Object Qfile_name_as_directory
;
303 Lisp_Object Qcopy_file
;
304 Lisp_Object Qmake_directory_internal
;
305 Lisp_Object Qmake_directory
;
306 Lisp_Object Qdelete_directory
;
307 Lisp_Object Qdelete_file
;
308 Lisp_Object Qrename_file
;
309 Lisp_Object Qadd_name_to_file
;
310 Lisp_Object Qmake_symbolic_link
;
311 Lisp_Object Qfile_exists_p
;
312 Lisp_Object Qfile_executable_p
;
313 Lisp_Object Qfile_readable_p
;
314 Lisp_Object Qfile_writable_p
;
315 Lisp_Object Qfile_symlink_p
;
316 Lisp_Object Qaccess_file
;
317 Lisp_Object Qfile_directory_p
;
318 Lisp_Object Qfile_regular_p
;
319 Lisp_Object Qfile_accessible_directory_p
;
320 Lisp_Object Qfile_modes
;
321 Lisp_Object Qset_file_modes
;
322 Lisp_Object Qfile_newer_than_file_p
;
323 Lisp_Object Qinsert_file_contents
;
324 Lisp_Object Qwrite_region
;
325 Lisp_Object Qverify_visited_file_modtime
;
326 Lisp_Object Qset_visited_file_modtime
;
328 DEFUN ("find-file-name-handler", Ffind_file_name_handler
, Sfind_file_name_handler
, 2, 2, 0,
329 "Return FILENAME's handler function for OPERATION, if it has one.\n\
330 Otherwise, return nil.\n\
331 A file name is handled if one of the regular expressions in\n\
332 `file-name-handler-alist' matches it.\n\n\
333 If OPERATION equals `inhibit-file-name-operation', then we ignore\n\
334 any handlers that are members of `inhibit-file-name-handlers',\n\
335 but we still do run any other handlers. This lets handlers\n\
336 use the standard functions without calling themselves recursively.")
337 (filename
, operation
)
338 Lisp_Object filename
, operation
;
340 /* This function must not munge the match data. */
341 Lisp_Object chain
, inhibited_handlers
;
343 CHECK_STRING (filename
, 0);
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
))
359 if (STRINGP (string
) && fast_string_match (string
, filename
) >= 0)
361 Lisp_Object handler
, tem
;
363 handler
= XCDR (elt
);
364 tem
= Fmemq (handler
, inhibited_handlers
);
375 DEFUN ("file-name-directory", Ffile_name_directory
, Sfile_name_directory
,
377 "Return the directory component in file name FILENAME.\n\
378 Return nil if FILENAME does not include a directory.\n\
379 Otherwise return a directory spec.\n\
380 Given a Unix syntax file name, returns a string ending in slash;\n\
381 on VMS, perhaps instead a string ending in `:', `]' or `>'.")
383 Lisp_Object filename
;
385 register unsigned char *beg
;
386 register unsigned char *p
;
389 CHECK_STRING (filename
, 0);
391 /* If the file name has special constructs in it,
392 call the corresponding file handler. */
393 handler
= Ffind_file_name_handler (filename
, Qfile_name_directory
);
395 return call2 (handler
, Qfile_name_directory
, filename
);
397 #ifdef FILE_SYSTEM_CASE
398 filename
= FILE_SYSTEM_CASE (filename
);
400 beg
= XSTRING (filename
)->data
;
402 beg
= strcpy (alloca (strlen (beg
) + 1), beg
);
404 p
= beg
+ STRING_BYTES (XSTRING (filename
));
406 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
408 && p
[-1] != ':' && p
[-1] != ']' && p
[-1] != '>'
411 /* only recognise drive specifier at the beginning */
413 /* handle the "/:d:foo" and "/:foo" cases correctly */
414 && ((p
== beg
+ 2 && !IS_DIRECTORY_SEP (*beg
))
415 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
422 /* Expansion of "c:" to drive and default directory. */
425 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
426 unsigned char *res
= alloca (MAXPATHLEN
+ 1);
427 unsigned char *r
= res
;
429 if (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
) && beg
[1] == ':')
431 strncpy (res
, beg
, 2);
436 if (getdefdir (toupper (*beg
) - 'A' + 1, r
))
438 if (!IS_DIRECTORY_SEP (res
[strlen (res
) - 1]))
441 p
= beg
+ strlen (beg
);
444 CORRECT_DIR_SEPS (beg
);
447 if (STRING_MULTIBYTE (filename
))
448 return make_string (beg
, p
- beg
);
449 return make_unibyte_string (beg
, p
- beg
);
452 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory
,
453 Sfile_name_nondirectory
, 1, 1, 0,
454 "Return file name FILENAME sans its directory.\n\
455 For example, in a Unix-syntax file name,\n\
456 this is everything after the last slash,\n\
457 or the entire name if it contains no slash.")
459 Lisp_Object filename
;
461 register unsigned char *beg
, *p
, *end
;
464 CHECK_STRING (filename
, 0);
466 /* If the file name has special constructs in it,
467 call the corresponding file handler. */
468 handler
= Ffind_file_name_handler (filename
, Qfile_name_nondirectory
);
470 return call2 (handler
, Qfile_name_nondirectory
, filename
);
472 beg
= XSTRING (filename
)->data
;
473 end
= p
= beg
+ STRING_BYTES (XSTRING (filename
));
475 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
477 && p
[-1] != ':' && p
[-1] != ']' && p
[-1] != '>'
480 /* only recognise drive specifier at beginning */
482 /* handle the "/:d:foo" case correctly */
483 && (p
== beg
+ 2 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
488 if (STRING_MULTIBYTE (filename
))
489 return make_string (p
, end
- p
);
490 return make_unibyte_string (p
, end
- p
);
493 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory
,
494 Sunhandled_file_name_directory
, 1, 1, 0,
495 "Return a directly usable directory name somehow associated with FILENAME.\n\
496 A `directly usable' directory name is one that may be used without the\n\
497 intervention of any file handler.\n\
498 If FILENAME is a directly usable file itself, return\n\
499 \(file-name-directory FILENAME).\n\
500 The `call-process' and `start-process' functions use this function to\n\
501 get a current directory to run processes in.")
503 Lisp_Object filename
;
507 /* If the file name has special constructs in it,
508 call the corresponding file handler. */
509 handler
= Ffind_file_name_handler (filename
, Qunhandled_file_name_directory
);
511 return call2 (handler
, Qunhandled_file_name_directory
, filename
);
513 return Ffile_name_directory (filename
);
518 file_name_as_directory (out
, in
)
521 int size
= strlen (in
) - 1;
534 /* Is it already a directory string? */
535 if (in
[size
] == ':' || in
[size
] == ']' || in
[size
] == '>')
537 /* Is it a VMS directory file name? If so, hack VMS syntax. */
538 else if (! index (in
, '/')
539 && ((size
> 3 && ! strcmp (&in
[size
- 3], ".DIR"))
540 || (size
> 3 && ! strcmp (&in
[size
- 3], ".dir"))
541 || (size
> 5 && (! strncmp (&in
[size
- 5], ".DIR", 4)
542 || ! strncmp (&in
[size
- 5], ".dir", 4))
543 && (in
[size
- 1] == '.' || in
[size
- 1] == ';')
544 && in
[size
] == '1')))
546 register char *p
, *dot
;
550 dir:x.dir --> dir:[x]
551 dir:[x]y.dir --> dir:[x.y] */
553 while (p
!= in
&& *p
!= ':' && *p
!= '>' && *p
!= ']') p
--;
556 strncpy (out
, in
, p
- in
);
575 dot
= index (p
, '.');
578 /* blindly remove any extension */
579 size
= strlen (out
) + (dot
- p
);
580 strncat (out
, p
, dot
- p
);
591 /* For Unix syntax, Append a slash if necessary */
592 if (!IS_DIRECTORY_SEP (out
[size
]))
594 out
[size
+ 1] = DIRECTORY_SEP
;
595 out
[size
+ 2] = '\0';
598 CORRECT_DIR_SEPS (out
);
604 DEFUN ("file-name-as-directory", Ffile_name_as_directory
,
605 Sfile_name_as_directory
, 1, 1, 0,
606 "Return a string representing file FILENAME interpreted as a directory.\n\
607 This operation exists because a directory is also a file, but its name as\n\
608 a directory is different from its name as a file.\n\
609 The result can be used as the value of `default-directory'\n\
610 or passed as second argument to `expand-file-name'.\n\
611 For a Unix-syntax file name, just appends a slash.\n\
612 On VMS, converts \"[X]FOO.DIR\" to \"[X.FOO]\", etc.")
619 CHECK_STRING (file
, 0);
623 /* If the file name has special constructs in it,
624 call the corresponding file handler. */
625 handler
= Ffind_file_name_handler (file
, Qfile_name_as_directory
);
627 return call2 (handler
, Qfile_name_as_directory
, file
);
629 buf
= (char *) alloca (STRING_BYTES (XSTRING (file
)) + 10);
630 return build_string (file_name_as_directory (buf
, XSTRING (file
)->data
));
634 * Convert from directory name to filename.
636 * xyzzy:[mukesh.emacs] => xyzzy:[mukesh]emacs.dir.1
637 * xyzzy:[mukesh] => xyzzy:[000000]mukesh.dir.1
638 * On UNIX, it's simple: just make sure there isn't a terminating /
640 * Value is nonzero if the string output is different from the input.
644 directory_file_name (src
, dst
)
652 struct FAB fab
= cc$rms_fab
;
653 struct NAM nam
= cc$rms_nam
;
654 char esa
[NAM$C_MAXRSS
];
659 if (! index (src
, '/')
660 && (src
[slen
- 1] == ']'
661 || src
[slen
- 1] == ':'
662 || src
[slen
- 1] == '>'))
664 /* VMS style - convert [x.y.z] to [x.y]z, [x] to [000000]x */
666 fab
.fab$b_fns
= slen
;
667 fab
.fab$l_nam
= &nam
;
668 fab
.fab$l_fop
= FAB$M_NAM
;
671 nam
.nam$b_ess
= sizeof esa
;
672 nam
.nam$b_nop
|= NAM$M_SYNCHK
;
674 /* We call SYS$PARSE to handle such things as [--] for us. */
675 if (SYS$
PARSE (&fab
, 0, 0) == RMS$_NORMAL
)
677 slen
= nam
.nam$b_esl
;
678 if (esa
[slen
- 1] == ';' && esa
[slen
- 2] == '.')
683 if (src
[slen
- 1] != ']' && src
[slen
- 1] != '>')
685 /* what about when we have logical_name:???? */
686 if (src
[slen
- 1] == ':')
687 { /* Xlate logical name and see what we get */
688 ptr
= strcpy (dst
, src
); /* upper case for getenv */
691 if ('a' <= *ptr
&& *ptr
<= 'z')
695 dst
[slen
- 1] = 0; /* remove colon */
696 if (!(src
= egetenv (dst
)))
698 /* should we jump to the beginning of this procedure?
699 Good points: allows us to use logical names that xlate
701 Bad points: can be a problem if we just translated to a device
703 For now, I'll punt and always expect VMS names, and hope for
706 if (src
[slen
- 1] != ']' && src
[slen
- 1] != '>')
707 { /* no recursion here! */
713 { /* not a directory spec */
718 bracket
= src
[slen
- 1];
720 /* If bracket is ']' or '>', bracket - 2 is the corresponding
722 ptr
= index (src
, bracket
- 2);
724 { /* no opening bracket */
728 if (!(rptr
= rindex (src
, '.')))
731 strncpy (dst
, src
, slen
);
735 dst
[slen
++] = bracket
;
740 /* If we have the top-level of a rooted directory (i.e. xx:[000000]),
741 then translate the device and recurse. */
742 if (dst
[slen
- 1] == ':'
743 && dst
[slen
- 2] != ':' /* skip decnet nodes */
744 && strcmp (src
+ slen
, "[000000]") == 0)
746 dst
[slen
- 1] = '\0';
747 if ((ptr
= egetenv (dst
))
748 && (rlen
= strlen (ptr
) - 1) > 0
749 && (ptr
[rlen
] == ']' || ptr
[rlen
] == '>')
750 && ptr
[rlen
- 1] == '.')
752 char * buf
= (char *) alloca (strlen (ptr
) + 1);
756 return directory_file_name (buf
, dst
);
761 strcat (dst
, "[000000]");
765 rlen
= strlen (rptr
) - 1;
766 strncat (dst
, rptr
, rlen
);
767 dst
[slen
+ rlen
] = '\0';
768 strcat (dst
, ".DIR.1");
772 /* Process as Unix format: just remove any final slash.
773 But leave "/" unchanged; do not change it to "". */
776 /* Handle // as root for apollo's. */
777 if ((slen
> 2 && dst
[slen
- 1] == '/')
778 || (slen
> 1 && dst
[0] != '/' && dst
[slen
- 1] == '/'))
782 && IS_DIRECTORY_SEP (dst
[slen
- 1])
784 && !IS_ANY_SEP (dst
[slen
- 2])
790 CORRECT_DIR_SEPS (dst
);
795 DEFUN ("directory-file-name", Fdirectory_file_name
, Sdirectory_file_name
,
797 "Returns the file name of the directory named DIRECTORY.\n\
798 This is the name of the file that holds the data for the directory DIRECTORY.\n\
799 This operation exists because a directory is also a file, but its name as\n\
800 a directory is different from its name as a file.\n\
801 In Unix-syntax, this function just removes the final slash.\n\
802 On VMS, given a VMS-syntax directory name such as \"[X.Y]\",\n\
803 it returns a file name such as \"[X]Y.DIR.1\".")
805 Lisp_Object directory
;
810 CHECK_STRING (directory
, 0);
812 if (NILP (directory
))
815 /* If the file name has special constructs in it,
816 call the corresponding file handler. */
817 handler
= Ffind_file_name_handler (directory
, Qdirectory_file_name
);
819 return call2 (handler
, Qdirectory_file_name
, directory
);
822 /* 20 extra chars is insufficient for VMS, since we might perform a
823 logical name translation. an equivalence string can be up to 255
824 chars long, so grab that much extra space... - sss */
825 buf
= (char *) alloca (STRING_BYTES (XSTRING (directory
)) + 20 + 255);
827 buf
= (char *) alloca (STRING_BYTES (XSTRING (directory
)) + 20);
829 directory_file_name (XSTRING (directory
)->data
, buf
);
830 return build_string (buf
);
833 static char make_temp_name_tbl
[64] =
835 'A','B','C','D','E','F','G','H',
836 'I','J','K','L','M','N','O','P',
837 'Q','R','S','T','U','V','W','X',
838 'Y','Z','a','b','c','d','e','f',
839 'g','h','i','j','k','l','m','n',
840 'o','p','q','r','s','t','u','v',
841 'w','x','y','z','0','1','2','3',
842 '4','5','6','7','8','9','-','_'
845 static unsigned make_temp_name_count
, make_temp_name_count_initialized_p
;
847 /* Value is a temporary file name starting with PREFIX, a string.
849 The Emacs process number forms part of the result, so there is
850 no danger of generating a name being used by another process.
851 In addition, this function makes an attempt to choose a name
852 which has no existing file. To make this work, PREFIX should be
853 an absolute file name.
855 BASE64_P non-zero means add the pid as 3 characters in base64
856 encoding. In this case, 6 characters will be added to PREFIX to
857 form the file name. Otherwise, if Emacs is running on a system
858 with long file names, add the pid as a decimal number.
860 This function signals an error if no unique file name could be
864 make_temp_name (prefix
, base64_p
)
871 unsigned char *p
, *data
;
875 CHECK_STRING (prefix
, 0);
877 /* VAL is created by adding 6 characters to PREFIX. The first
878 three are the PID of this process, in base 64, and the second
879 three are incremented if the file already exists. This ensures
880 262144 unique file names per PID per PREFIX. */
882 pid
= (int) getpid ();
886 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
887 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
888 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
893 #ifdef HAVE_LONG_FILE_NAMES
894 sprintf (pidbuf
, "%d", pid
);
895 pidlen
= strlen (pidbuf
);
897 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
898 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
899 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
904 len
= XSTRING (prefix
)->size
;
905 val
= make_uninit_string (len
+ 3 + pidlen
);
906 data
= XSTRING (val
)->data
;
907 bcopy(XSTRING (prefix
)->data
, data
, len
);
910 bcopy (pidbuf
, p
, pidlen
);
913 /* Here we try to minimize useless stat'ing when this function is
914 invoked many times successively with the same PREFIX. We achieve
915 this by initializing count to a random value, and incrementing it
918 We don't want make-temp-name to be called while dumping,
919 because then make_temp_name_count_initialized_p would get set
920 and then make_temp_name_count would not be set when Emacs starts. */
922 if (!make_temp_name_count_initialized_p
)
924 make_temp_name_count
= (unsigned) time (NULL
);
925 make_temp_name_count_initialized_p
= 1;
931 unsigned num
= make_temp_name_count
;
933 p
[0] = make_temp_name_tbl
[num
& 63], num
>>= 6;
934 p
[1] = make_temp_name_tbl
[num
& 63], num
>>= 6;
935 p
[2] = make_temp_name_tbl
[num
& 63], num
>>= 6;
937 /* Poor man's congruential RN generator. Replace with
938 ++make_temp_name_count for debugging. */
939 make_temp_name_count
+= 25229;
940 make_temp_name_count
%= 225307;
942 if (stat (data
, &ignored
) < 0)
944 /* We want to return only if errno is ENOENT. */
948 /* The error here is dubious, but there is little else we
949 can do. The alternatives are to return nil, which is
950 as bad as (and in many cases worse than) throwing the
951 error, or to ignore the error, which will likely result
952 in looping through 225307 stat's, which is not only
953 dog-slow, but also useless since it will fallback to
954 the errow below, anyway. */
955 report_file_error ("Cannot create temporary name for prefix",
956 Fcons (prefix
, Qnil
));
961 error ("Cannot create temporary name for prefix `%s'",
962 XSTRING (prefix
)->data
);
967 DEFUN ("make-temp-name", Fmake_temp_name
, Smake_temp_name
, 1, 1, 0,
968 "Generate temporary file name (string) starting with PREFIX (a string).\n\
969 The Emacs process number forms part of the result,\n\
970 so there is no danger of generating a name being used by another process.\n\
972 In addition, this function makes an attempt to choose a name\n\
973 which has no existing file. To make this work,\n\
974 PREFIX should be an absolute file name.\n\
976 There is a race condition between calling `make-temp-name' and creating the\n\
977 file which opens all kinds of security holes. For that reason, you should\n\
978 probably use `make-temp-file' instead.")
982 return make_temp_name (prefix
, 0);
987 DEFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
988 "Convert filename NAME to absolute, and canonicalize it.\n\
989 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative\n\
990 (does not start with slash); if DEFAULT-DIRECTORY is nil or missing,\n\
991 the current buffer's value of default-directory is used.\n\
992 File name components that are `.' are removed, and \n\
993 so are file name components followed by `..', along with the `..' itself;\n\
994 note that these simplifications are done without checking the resulting\n\
995 file names in the file system.\n\
996 An initial `~/' expands to your home directory.\n\
997 An initial `~USER/' expands to USER's home directory.\n\
998 See also the function `substitute-in-file-name'.")
999 (name
, default_directory
)
1000 Lisp_Object name
, default_directory
;
1004 register unsigned char *newdir
, *p
, *o
;
1006 unsigned char *target
;
1009 unsigned char * colon
= 0;
1010 unsigned char * close
= 0;
1011 unsigned char * slash
= 0;
1012 unsigned char * brack
= 0;
1013 int lbrack
= 0, rbrack
= 0;
1018 int collapse_newdir
= 1;
1022 Lisp_Object handler
;
1024 CHECK_STRING (name
, 0);
1026 /* If the file name has special constructs in it,
1027 call the corresponding file handler. */
1028 handler
= Ffind_file_name_handler (name
, Qexpand_file_name
);
1029 if (!NILP (handler
))
1030 return call3 (handler
, Qexpand_file_name
, name
, default_directory
);
1032 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
1033 if (NILP (default_directory
))
1034 default_directory
= current_buffer
->directory
;
1035 if (! STRINGP (default_directory
))
1036 default_directory
= build_string ("/");
1038 if (!NILP (default_directory
))
1040 handler
= Ffind_file_name_handler (default_directory
, Qexpand_file_name
);
1041 if (!NILP (handler
))
1042 return call3 (handler
, Qexpand_file_name
, name
, default_directory
);
1045 o
= XSTRING (default_directory
)->data
;
1047 /* Make sure DEFAULT_DIRECTORY is properly expanded.
1048 It would be better to do this down below where we actually use
1049 default_directory. Unfortunately, calling Fexpand_file_name recursively
1050 could invoke GC, and the strings might be relocated. This would
1051 be annoying because we have pointers into strings lying around
1052 that would need adjusting, and people would add new pointers to
1053 the code and forget to adjust them, resulting in intermittent bugs.
1054 Putting this call here avoids all that crud.
1056 The EQ test avoids infinite recursion. */
1057 if (! NILP (default_directory
) && !EQ (default_directory
, name
)
1058 /* Save time in some common cases - as long as default_directory
1059 is not relative, it can be canonicalized with name below (if it
1060 is needed at all) without requiring it to be expanded now. */
1062 /* Detect MSDOS file names with drive specifiers. */
1063 && ! (IS_DRIVE (o
[0]) && IS_DEVICE_SEP (o
[1]) && IS_DIRECTORY_SEP (o
[2]))
1065 /* Detect Windows file names in UNC format. */
1066 && ! (IS_DIRECTORY_SEP (o
[0]) && IS_DIRECTORY_SEP (o
[1]))
1068 #else /* not DOS_NT */
1069 /* Detect Unix absolute file names (/... alone is not absolute on
1071 && ! (IS_DIRECTORY_SEP (o
[0]))
1072 #endif /* not DOS_NT */
1075 struct gcpro gcpro1
;
1078 default_directory
= Fexpand_file_name (default_directory
, Qnil
);
1083 /* Filenames on VMS are always upper case. */
1084 name
= Fupcase (name
);
1086 #ifdef FILE_SYSTEM_CASE
1087 name
= FILE_SYSTEM_CASE (name
);
1090 nm
= XSTRING (name
)->data
;
1093 /* We will force directory separators to be either all \ or /, so make
1094 a local copy to modify, even if there ends up being no change. */
1095 nm
= strcpy (alloca (strlen (nm
) + 1), nm
);
1097 /* Note if special escape prefix is present, but remove for now. */
1098 if (nm
[0] == '/' && nm
[1] == ':')
1104 /* Find and remove drive specifier if present; this makes nm absolute
1105 even if the rest of the name appears to be relative. Only look for
1106 drive specifier at the beginning. */
1107 if (IS_DRIVE (nm
[0]) && IS_DEVICE_SEP (nm
[1]))
1114 /* If we see "c://somedir", we want to strip the first slash after the
1115 colon when stripping the drive letter. Otherwise, this expands to
1117 if (drive
&& IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
1119 #endif /* WINDOWSNT */
1123 /* Discard any previous drive specifier if nm is now in UNC format. */
1124 if (IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
1130 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
1131 none are found, we can probably return right away. We will avoid
1132 allocating a new string if name is already fully expanded. */
1134 IS_DIRECTORY_SEP (nm
[0])
1136 && drive
&& !is_escaped
1139 && (drive
|| IS_DIRECTORY_SEP (nm
[1])) && !is_escaped
1146 /* If it turns out that the filename we want to return is just a
1147 suffix of FILENAME, we don't need to go through and edit
1148 things; we just need to construct a new string using data
1149 starting at the middle of FILENAME. If we set lose to a
1150 non-zero value, that means we've discovered that we can't do
1157 /* Since we know the name is absolute, we can assume that each
1158 element starts with a "/". */
1160 /* "." and ".." are hairy. */
1161 if (IS_DIRECTORY_SEP (p
[0])
1163 && (IS_DIRECTORY_SEP (p
[2])
1165 || (p
[2] == '.' && (IS_DIRECTORY_SEP (p
[3])
1168 /* We want to replace multiple `/' in a row with a single
1171 && IS_DIRECTORY_SEP (p
[0])
1172 && IS_DIRECTORY_SEP (p
[1]))
1179 /* if dev:[dir]/, move nm to / */
1180 if (!slash
&& p
> nm
&& (brack
|| colon
)) {
1181 nm
= (brack
? brack
+ 1 : colon
+ 1);
1182 lbrack
= rbrack
= 0;
1190 /* VMS pre V4.4,convert '-'s in filenames. */
1191 if (lbrack
== rbrack
)
1193 if (dots
< 2) /* this is to allow negative version numbers */
1198 if (lbrack
> rbrack
&&
1199 ((p
[-1] == '.' || p
[-1] == '[' || p
[-1] == '<') &&
1200 (p
[1] == '.' || p
[1] == ']' || p
[1] == '>')))
1206 /* count open brackets, reset close bracket pointer */
1207 if (p
[0] == '[' || p
[0] == '<')
1208 lbrack
++, brack
= 0;
1209 /* count close brackets, set close bracket pointer */
1210 if (p
[0] == ']' || p
[0] == '>')
1211 rbrack
++, brack
= p
;
1212 /* detect ][ or >< */
1213 if ((p
[0] == ']' || p
[0] == '>') && (p
[1] == '[' || p
[1] == '<'))
1215 if ((p
[0] == ':' || p
[0] == ']' || p
[0] == '>') && p
[1] == '~')
1216 nm
= p
+ 1, lose
= 1;
1217 if (p
[0] == ':' && (colon
|| slash
))
1218 /* if dev1:[dir]dev2:, move nm to dev2: */
1224 /* if /name/dev:, move nm to dev: */
1227 /* if node::dev:, move colon following dev */
1228 else if (colon
&& colon
[-1] == ':')
1230 /* if dev1:dev2:, move nm to dev2: */
1231 else if (colon
&& colon
[-1] != ':')
1236 if (p
[0] == ':' && !colon
)
1242 if (lbrack
== rbrack
)
1245 else if (p
[0] == '.')
1253 if (index (nm
, '/'))
1254 return build_string (sys_translate_unix (nm
));
1257 /* Make sure directories are all separated with / or \ as
1258 desired, but avoid allocation of a new string when not
1260 CORRECT_DIR_SEPS (nm
);
1262 if (IS_DIRECTORY_SEP (nm
[1]))
1264 if (strcmp (nm
, XSTRING (name
)->data
) != 0)
1265 name
= build_string (nm
);
1269 /* drive must be set, so this is okay */
1270 if (strcmp (nm
- 2, XSTRING (name
)->data
) != 0)
1272 name
= make_string (nm
- 2, p
- nm
+ 2);
1273 XSTRING (name
)->data
[0] = DRIVE_LETTER (drive
);
1274 XSTRING (name
)->data
[1] = ':';
1277 #else /* not DOS_NT */
1278 if (nm
== XSTRING (name
)->data
)
1280 return build_string (nm
);
1281 #endif /* not DOS_NT */
1285 /* At this point, nm might or might not be an absolute file name. We
1286 need to expand ~ or ~user if present, otherwise prefix nm with
1287 default_directory if nm is not absolute, and finally collapse /./
1288 and /foo/../ sequences.
1290 We set newdir to be the appropriate prefix if one is needed:
1291 - the relevant user directory if nm starts with ~ or ~user
1292 - the specified drive's working dir (DOS/NT only) if nm does not
1294 - the value of default_directory.
1296 Note that these prefixes are not guaranteed to be absolute (except
1297 for the working dir of a drive). Therefore, to ensure we always
1298 return an absolute name, if the final prefix is not absolute we
1299 append it to the current working directory. */
1303 if (nm
[0] == '~') /* prefix ~ */
1305 if (IS_DIRECTORY_SEP (nm
[1])
1309 || nm
[1] == 0) /* ~ by itself */
1311 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1312 newdir
= (unsigned char *) "";
1315 collapse_newdir
= 0;
1318 nm
++; /* Don't leave the slash in nm. */
1321 else /* ~user/filename */
1323 for (p
= nm
; *p
&& (!IS_DIRECTORY_SEP (*p
)
1328 o
= (unsigned char *) alloca (p
- nm
+ 1);
1329 bcopy ((char *) nm
, o
, p
- nm
);
1332 pw
= (struct passwd
*) getpwnam (o
+ 1);
1335 newdir
= (unsigned char *) pw
-> pw_dir
;
1337 nm
= p
+ 1; /* skip the terminator */
1341 collapse_newdir
= 0;
1346 /* If we don't find a user of that name, leave the name
1347 unchanged; don't move nm forward to p. */
1352 /* On DOS and Windows, nm is absolute if a drive name was specified;
1353 use the drive's current directory as the prefix if needed. */
1354 if (!newdir
&& drive
)
1356 /* Get default directory if needed to make nm absolute. */
1357 if (!IS_DIRECTORY_SEP (nm
[0]))
1359 newdir
= alloca (MAXPATHLEN
+ 1);
1360 if (!getdefdir (toupper (drive
) - 'A' + 1, newdir
))
1365 /* Either nm starts with /, or drive isn't mounted. */
1366 newdir
= alloca (4);
1367 newdir
[0] = DRIVE_LETTER (drive
);
1375 /* Finally, if no prefix has been specified and nm is not absolute,
1376 then it must be expanded relative to default_directory. */
1380 /* /... alone is not absolute on DOS and Windows. */
1381 && !IS_DIRECTORY_SEP (nm
[0])
1384 && !(IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
1391 newdir
= XSTRING (default_directory
)->data
;
1393 /* Note if special escape prefix is present, but remove for now. */
1394 if (newdir
[0] == '/' && newdir
[1] == ':')
1405 /* First ensure newdir is an absolute name. */
1407 /* Detect MSDOS file names with drive specifiers. */
1408 ! (IS_DRIVE (newdir
[0])
1409 && IS_DEVICE_SEP (newdir
[1]) && IS_DIRECTORY_SEP (newdir
[2]))
1411 /* Detect Windows file names in UNC format. */
1412 && ! (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1]))
1416 /* Effectively, let newdir be (expand-file-name newdir cwd).
1417 Because of the admonition against calling expand-file-name
1418 when we have pointers into lisp strings, we accomplish this
1419 indirectly by prepending newdir to nm if necessary, and using
1420 cwd (or the wd of newdir's drive) as the new newdir. */
1422 if (IS_DRIVE (newdir
[0]) && newdir
[1] == ':')
1427 if (!IS_DIRECTORY_SEP (nm
[0]))
1429 char * tmp
= alloca (strlen (newdir
) + strlen (nm
) + 2);
1430 file_name_as_directory (tmp
, newdir
);
1434 newdir
= alloca (MAXPATHLEN
+ 1);
1437 if (!getdefdir (toupper (drive
) - 'A' + 1, newdir
))
1444 /* Strip off drive name from prefix, if present. */
1445 if (IS_DRIVE (newdir
[0]) && newdir
[1] == ':')
1451 /* Keep only a prefix from newdir if nm starts with slash
1452 (//server/share for UNC, nothing otherwise). */
1453 if (IS_DIRECTORY_SEP (nm
[0]) && collapse_newdir
)
1456 if (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1]))
1458 newdir
= strcpy (alloca (strlen (newdir
) + 1), newdir
);
1460 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1462 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1474 /* Get rid of any slash at the end of newdir, unless newdir is
1475 just / or // (an incomplete UNC name). */
1476 length
= strlen (newdir
);
1477 if (length
> 1 && IS_DIRECTORY_SEP (newdir
[length
- 1])
1479 && !(length
== 2 && IS_DIRECTORY_SEP (newdir
[0]))
1483 unsigned char *temp
= (unsigned char *) alloca (length
);
1484 bcopy (newdir
, temp
, length
- 1);
1485 temp
[length
- 1] = 0;
1493 /* Now concatenate the directory and name to new space in the stack frame */
1494 tlen
+= strlen (nm
) + 1;
1496 /* Reserve space for drive specifier and escape prefix, since either
1497 or both may need to be inserted. (The Microsoft x86 compiler
1498 produces incorrect code if the following two lines are combined.) */
1499 target
= (unsigned char *) alloca (tlen
+ 4);
1501 #else /* not DOS_NT */
1502 target
= (unsigned char *) alloca (tlen
);
1503 #endif /* not DOS_NT */
1509 if (nm
[0] == 0 || IS_DIRECTORY_SEP (nm
[0]))
1512 /* If newdir is effectively "C:/", then the drive letter will have
1513 been stripped and newdir will be "/". Concatenating with an
1514 absolute directory in nm produces "//", which will then be
1515 incorrectly treated as a network share. Ignore newdir in
1516 this case (keeping the drive letter). */
1517 if (!(drive
&& nm
[0] && IS_DIRECTORY_SEP (newdir
[0])
1518 && newdir
[1] == '\0'))
1520 strcpy (target
, newdir
);
1524 file_name_as_directory (target
, newdir
);
1527 strcat (target
, nm
);
1529 if (index (target
, '/'))
1530 strcpy (target
, sys_translate_unix (target
));
1533 /* ASSERT (IS_DIRECTORY_SEP (target[0])) if not VMS */
1535 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1544 if (*p
!= ']' && *p
!= '>' && *p
!= '-')
1550 else if ((p
[0] == ']' || p
[0] == '>') && p
[0] == p
[1] + 2)
1551 /* brackets are offset from each other by 2 */
1554 if (*p
!= '.' && *p
!= '-' && o
[-1] != '.')
1555 /* convert [foo][bar] to [bar] */
1556 while (o
[-1] != '[' && o
[-1] != '<')
1558 else if (*p
== '-' && *o
!= '.')
1561 else if (p
[0] == '-' && o
[-1] == '.' &&
1562 (p
[1] == '.' || p
[1] == ']' || p
[1] == '>'))
1563 /* flush .foo.- ; leave - if stopped by '[' or '<' */
1567 while (o
[-1] != '.' && o
[-1] != '[' && o
[-1] != '<');
1568 if (p
[1] == '.') /* foo.-.bar ==> bar. */
1570 else if (o
[-1] == '.') /* '.foo.-]' ==> ']' */
1572 /* else [foo.-] ==> [-] */
1578 o
[-1] != '[' && o
[-1] != '<' && o
[-1] != '.' &&
1579 p
[1] != ']' && p
[1] != '>' && p
[1] != '.')
1585 if (!IS_DIRECTORY_SEP (*p
))
1589 else if (IS_DIRECTORY_SEP (p
[0])
1591 && (IS_DIRECTORY_SEP (p
[2])
1594 /* If "/." is the entire filename, keep the "/". Otherwise,
1595 just delete the whole "/.". */
1596 if (o
== target
&& p
[2] == '\0')
1600 else if (IS_DIRECTORY_SEP (p
[0]) && p
[1] == '.' && p
[2] == '.'
1601 /* `/../' is the "superroot" on certain file systems. */
1603 && (IS_DIRECTORY_SEP (p
[3]) || p
[3] == 0))
1605 while (o
!= target
&& (--o
) && !IS_DIRECTORY_SEP (*o
))
1607 /* Keep initial / only if this is the whole name. */
1608 if (o
== target
&& IS_ANY_SEP (*o
) && p
[3] == 0)
1613 && IS_DIRECTORY_SEP (p
[0]) && IS_DIRECTORY_SEP (p
[1]))
1615 /* Collapse multiple `/' in a row. */
1617 while (IS_DIRECTORY_SEP (*p
))
1624 #endif /* not VMS */
1628 /* At last, set drive name. */
1630 /* Except for network file name. */
1631 if (!(IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1])))
1632 #endif /* WINDOWSNT */
1634 if (!drive
) abort ();
1636 target
[0] = DRIVE_LETTER (drive
);
1639 /* Reinsert the escape prefix if required. */
1646 CORRECT_DIR_SEPS (target
);
1649 return make_string (target
, o
- target
);
1653 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1654 DEAFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
1655 "Convert FILENAME to absolute, and canonicalize it.\n\
1656 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1657 (does not start with slash); if DEFAULT is nil or missing,\n\
1658 the current buffer's value of default-directory is used.\n\
1659 Filenames containing `.' or `..' as components are simplified;\n\
1660 initial `~/' expands to your home directory.\n\
1661 See also the function `substitute-in-file-name'.")
1663 Lisp_Object name
, defalt
;
1667 register unsigned char *newdir
, *p
, *o
;
1669 unsigned char *target
;
1673 unsigned char * colon
= 0;
1674 unsigned char * close
= 0;
1675 unsigned char * slash
= 0;
1676 unsigned char * brack
= 0;
1677 int lbrack
= 0, rbrack
= 0;
1681 CHECK_STRING (name
, 0);
1684 /* Filenames on VMS are always upper case. */
1685 name
= Fupcase (name
);
1688 nm
= XSTRING (name
)->data
;
1690 /* If nm is absolute, flush ...// and detect /./ and /../.
1691 If no /./ or /../ we can return right away. */
1703 if (p
[0] == '/' && p
[1] == '/'
1705 /* // at start of filename is meaningful on Apollo system. */
1710 if (p
[0] == '/' && p
[1] == '~')
1711 nm
= p
+ 1, lose
= 1;
1712 if (p
[0] == '/' && p
[1] == '.'
1713 && (p
[2] == '/' || p
[2] == 0
1714 || (p
[2] == '.' && (p
[3] == '/' || p
[3] == 0))))
1720 /* if dev:[dir]/, move nm to / */
1721 if (!slash
&& p
> nm
&& (brack
|| colon
)) {
1722 nm
= (brack
? brack
+ 1 : colon
+ 1);
1723 lbrack
= rbrack
= 0;
1731 /* VMS pre V4.4,convert '-'s in filenames. */
1732 if (lbrack
== rbrack
)
1734 if (dots
< 2) /* this is to allow negative version numbers */
1739 if (lbrack
> rbrack
&&
1740 ((p
[-1] == '.' || p
[-1] == '[' || p
[-1] == '<') &&
1741 (p
[1] == '.' || p
[1] == ']' || p
[1] == '>')))
1747 /* count open brackets, reset close bracket pointer */
1748 if (p
[0] == '[' || p
[0] == '<')
1749 lbrack
++, brack
= 0;
1750 /* count close brackets, set close bracket pointer */
1751 if (p
[0] == ']' || p
[0] == '>')
1752 rbrack
++, brack
= p
;
1753 /* detect ][ or >< */
1754 if ((p
[0] == ']' || p
[0] == '>') && (p
[1] == '[' || p
[1] == '<'))
1756 if ((p
[0] == ':' || p
[0] == ']' || p
[0] == '>') && p
[1] == '~')
1757 nm
= p
+ 1, lose
= 1;
1758 if (p
[0] == ':' && (colon
|| slash
))
1759 /* if dev1:[dir]dev2:, move nm to dev2: */
1765 /* If /name/dev:, move nm to dev: */
1768 /* If node::dev:, move colon following dev */
1769 else if (colon
&& colon
[-1] == ':')
1771 /* If dev1:dev2:, move nm to dev2: */
1772 else if (colon
&& colon
[-1] != ':')
1777 if (p
[0] == ':' && !colon
)
1783 if (lbrack
== rbrack
)
1786 else if (p
[0] == '.')
1794 if (index (nm
, '/'))
1795 return build_string (sys_translate_unix (nm
));
1797 if (nm
== XSTRING (name
)->data
)
1799 return build_string (nm
);
1803 /* Now determine directory to start with and put it in NEWDIR */
1807 if (nm
[0] == '~') /* prefix ~ */
1812 || nm
[1] == 0)/* ~/filename */
1814 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1815 newdir
= (unsigned char *) "";
1818 nm
++; /* Don't leave the slash in nm. */
1821 else /* ~user/filename */
1823 /* Get past ~ to user */
1824 unsigned char *user
= nm
+ 1;
1825 /* Find end of name. */
1826 unsigned char *ptr
= (unsigned char *) index (user
, '/');
1827 int len
= ptr
? ptr
- user
: strlen (user
);
1829 unsigned char *ptr1
= index (user
, ':');
1830 if (ptr1
!= 0 && ptr1
- user
< len
)
1833 /* Copy the user name into temp storage. */
1834 o
= (unsigned char *) alloca (len
+ 1);
1835 bcopy ((char *) user
, o
, len
);
1838 /* Look up the user name. */
1839 pw
= (struct passwd
*) getpwnam (o
+ 1);
1841 error ("\"%s\" isn't a registered user", o
+ 1);
1843 newdir
= (unsigned char *) pw
->pw_dir
;
1845 /* Discard the user name from NM. */
1852 #endif /* not VMS */
1856 defalt
= current_buffer
->directory
;
1857 CHECK_STRING (defalt
, 1);
1858 newdir
= XSTRING (defalt
)->data
;
1861 /* Now concatenate the directory and name to new space in the stack frame */
1863 tlen
= (newdir
? strlen (newdir
) + 1 : 0) + strlen (nm
) + 1;
1864 target
= (unsigned char *) alloca (tlen
);
1870 if (nm
[0] == 0 || nm
[0] == '/')
1871 strcpy (target
, newdir
);
1874 file_name_as_directory (target
, newdir
);
1877 strcat (target
, nm
);
1879 if (index (target
, '/'))
1880 strcpy (target
, sys_translate_unix (target
));
1883 /* Now canonicalize by removing /. and /foo/.. if they appear */
1891 if (*p
!= ']' && *p
!= '>' && *p
!= '-')
1897 else if ((p
[0] == ']' || p
[0] == '>') && p
[0] == p
[1] + 2)
1898 /* brackets are offset from each other by 2 */
1901 if (*p
!= '.' && *p
!= '-' && o
[-1] != '.')
1902 /* convert [foo][bar] to [bar] */
1903 while (o
[-1] != '[' && o
[-1] != '<')
1905 else if (*p
== '-' && *o
!= '.')
1908 else if (p
[0] == '-' && o
[-1] == '.' &&
1909 (p
[1] == '.' || p
[1] == ']' || p
[1] == '>'))
1910 /* flush .foo.- ; leave - if stopped by '[' or '<' */
1914 while (o
[-1] != '.' && o
[-1] != '[' && o
[-1] != '<');
1915 if (p
[1] == '.') /* foo.-.bar ==> bar. */
1917 else if (o
[-1] == '.') /* '.foo.-]' ==> ']' */
1919 /* else [foo.-] ==> [-] */
1925 o
[-1] != '[' && o
[-1] != '<' && o
[-1] != '.' &&
1926 p
[1] != ']' && p
[1] != '>' && p
[1] != '.')
1936 else if (!strncmp (p
, "//", 2)
1938 /* // at start of filename is meaningful in Apollo system. */
1946 else if (p
[0] == '/' && p
[1] == '.' &&
1947 (p
[2] == '/' || p
[2] == 0))
1949 else if (!strncmp (p
, "/..", 3)
1950 /* `/../' is the "superroot" on certain file systems. */
1952 && (p
[3] == '/' || p
[3] == 0))
1954 while (o
!= target
&& *--o
!= '/')
1957 if (o
== target
+ 1 && o
[-1] == '/' && o
[0] == '/')
1961 if (o
== target
&& *o
== '/')
1969 #endif /* not VMS */
1972 return make_string (target
, o
- target
);
1976 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name
,
1977 Ssubstitute_in_file_name
, 1, 1, 0,
1978 "Substitute environment variables referred to in FILENAME.\n\
1979 `$FOO' where FOO is an environment variable name means to substitute\n\
1980 the value of that variable. The variable name should be terminated\n\
1981 with a character not a letter, digit or underscore; otherwise, enclose\n\
1982 the entire variable name in braces.\n\
1983 If `/~' appears, all of FILENAME through that `/' is discarded.\n\n\
1984 On VMS, `$' substitution is not done; this function does little and only\n\
1985 duplicates what `expand-file-name' does.")
1987 Lisp_Object filename
;
1991 register unsigned char *s
, *p
, *o
, *x
, *endp
;
1992 unsigned char *target
= NULL
;
1994 int substituted
= 0;
1996 Lisp_Object handler
;
1998 CHECK_STRING (filename
, 0);
2000 /* If the file name has special constructs in it,
2001 call the corresponding file handler. */
2002 handler
= Ffind_file_name_handler (filename
, Qsubstitute_in_file_name
);
2003 if (!NILP (handler
))
2004 return call2 (handler
, Qsubstitute_in_file_name
, filename
);
2006 nm
= XSTRING (filename
)->data
;
2008 nm
= strcpy (alloca (strlen (nm
) + 1), nm
);
2009 CORRECT_DIR_SEPS (nm
);
2010 substituted
= (strcmp (nm
, XSTRING (filename
)->data
) != 0);
2012 endp
= nm
+ STRING_BYTES (XSTRING (filename
));
2014 /* If /~ or // appears, discard everything through first slash. */
2016 for (p
= nm
; p
!= endp
; p
++)
2019 #if defined (APOLLO) || defined (WINDOWSNT)
2020 /* // at start of file name is meaningful in Apollo and
2021 WindowsNT systems. */
2022 || (IS_DIRECTORY_SEP (p
[0]) && p
- 1 != nm
)
2023 #else /* not (APOLLO || WINDOWSNT) */
2024 || IS_DIRECTORY_SEP (p
[0])
2025 #endif /* not (APOLLO || WINDOWSNT) */
2030 || p
[-1] == ':' || p
[-1] == ']' || p
[-1] == '>'
2032 || IS_DIRECTORY_SEP (p
[-1])))
2038 /* see comment in expand-file-name about drive specifiers */
2039 else if (IS_DRIVE (p
[0]) && p
[1] == ':'
2040 && p
> nm
&& IS_DIRECTORY_SEP (p
[-1]))
2049 return build_string (nm
);
2052 /* See if any variables are substituted into the string
2053 and find the total length of their values in `total' */
2055 for (p
= nm
; p
!= endp
;)
2065 /* "$$" means a single "$" */
2074 while (p
!= endp
&& *p
!= '}') p
++;
2075 if (*p
!= '}') goto missingclose
;
2081 while (p
!= endp
&& (isalnum (*p
) || *p
== '_')) p
++;
2085 /* Copy out the variable name */
2086 target
= (unsigned char *) alloca (s
- o
+ 1);
2087 strncpy (target
, o
, s
- o
);
2090 strupr (target
); /* $home == $HOME etc. */
2093 /* Get variable value */
2094 o
= (unsigned char *) egetenv (target
);
2095 if (!o
) goto badvar
;
2096 total
+= strlen (o
);
2103 /* If substitution required, recopy the string and do it */
2104 /* Make space in stack frame for the new copy */
2105 xnm
= (unsigned char *) alloca (STRING_BYTES (XSTRING (filename
)) + total
+ 1);
2108 /* Copy the rest of the name through, replacing $ constructs with values */
2125 while (p
!= endp
&& *p
!= '}') p
++;
2126 if (*p
!= '}') goto missingclose
;
2132 while (p
!= endp
&& (isalnum (*p
) || *p
== '_')) p
++;
2136 /* Copy out the variable name */
2137 target
= (unsigned char *) alloca (s
- o
+ 1);
2138 strncpy (target
, o
, s
- o
);
2141 strupr (target
); /* $home == $HOME etc. */
2144 /* Get variable value */
2145 o
= (unsigned char *) egetenv (target
);
2149 if (STRING_MULTIBYTE (filename
))
2151 /* If the original string is multibyte,
2152 convert what we substitute into multibyte. */
2155 int c
= unibyte_char_to_multibyte (*o
++);
2156 x
+= CHAR_STRING (c
, x
);
2168 /* If /~ or // appears, discard everything through first slash. */
2170 for (p
= xnm
; p
!= x
; p
++)
2172 #if defined (APOLLO) || defined (WINDOWSNT)
2173 || (IS_DIRECTORY_SEP (p
[0]) && p
- 1 != xnm
)
2174 #else /* not (APOLLO || WINDOWSNT) */
2175 || IS_DIRECTORY_SEP (p
[0])
2176 #endif /* not (APOLLO || WINDOWSNT) */
2178 && p
!= xnm
&& IS_DIRECTORY_SEP (p
[-1]))
2181 else if (IS_DRIVE (p
[0]) && p
[1] == ':'
2182 && p
> xnm
&& IS_DIRECTORY_SEP (p
[-1]))
2186 if (STRING_MULTIBYTE (filename
))
2187 return make_string (xnm
, x
- xnm
);
2188 return make_unibyte_string (xnm
, x
- xnm
);
2191 error ("Bad format environment-variable substitution");
2193 error ("Missing \"}\" in environment-variable substitution");
2195 error ("Substituting nonexistent environment variable \"%s\"", target
);
2198 #endif /* not VMS */
2202 /* A slightly faster and more convenient way to get
2203 (directory-file-name (expand-file-name FOO)). */
2206 expand_and_dir_to_file (filename
, defdir
)
2207 Lisp_Object filename
, defdir
;
2209 register Lisp_Object absname
;
2211 absname
= Fexpand_file_name (filename
, defdir
);
2214 register int c
= XSTRING (absname
)->data
[STRING_BYTES (XSTRING (absname
)) - 1];
2215 if (c
== ':' || c
== ']' || c
== '>')
2216 absname
= Fdirectory_file_name (absname
);
2219 /* Remove final slash, if any (unless this is the root dir).
2220 stat behaves differently depending! */
2221 if (XSTRING (absname
)->size
> 1
2222 && IS_DIRECTORY_SEP (XSTRING (absname
)->data
[STRING_BYTES (XSTRING (absname
)) - 1])
2223 && !IS_DEVICE_SEP (XSTRING (absname
)->data
[STRING_BYTES (XSTRING (absname
))-2]))
2224 /* We cannot take shortcuts; they might be wrong for magic file names. */
2225 absname
= Fdirectory_file_name (absname
);
2230 /* Signal an error if the file ABSNAME already exists.
2231 If INTERACTIVE is nonzero, ask the user whether to proceed,
2232 and bypass the error if the user says to go ahead.
2233 QUERYSTRING is a name for the action that is being considered
2236 *STATPTR is used to store the stat information if the file exists.
2237 If the file does not exist, STATPTR->st_mode is set to 0.
2238 If STATPTR is null, we don't store into it.
2240 If QUICK is nonzero, we ask for y or n, not yes or no. */
2243 barf_or_query_if_file_exists (absname
, querystring
, interactive
, statptr
, quick
)
2244 Lisp_Object absname
;
2245 unsigned char *querystring
;
2247 struct stat
*statptr
;
2250 register Lisp_Object tem
, encoded_filename
;
2251 struct stat statbuf
;
2252 struct gcpro gcpro1
;
2254 encoded_filename
= ENCODE_FILE (absname
);
2256 /* stat is a good way to tell whether the file exists,
2257 regardless of what access permissions it has. */
2258 if (stat (XSTRING (encoded_filename
)->data
, &statbuf
) >= 0)
2261 Fsignal (Qfile_already_exists
,
2262 Fcons (build_string ("File already exists"),
2263 Fcons (absname
, Qnil
)));
2265 tem
= format1 ("File %s already exists; %s anyway? ",
2266 XSTRING (absname
)->data
, querystring
);
2268 tem
= Fy_or_n_p (tem
);
2270 tem
= do_yes_or_no_p (tem
);
2273 Fsignal (Qfile_already_exists
,
2274 Fcons (build_string ("File already exists"),
2275 Fcons (absname
, Qnil
)));
2282 statptr
->st_mode
= 0;
2287 DEFUN ("copy-file", Fcopy_file
, Scopy_file
, 2, 4,
2288 "fCopy file: \nFCopy %s to file: \np\nP",
2289 "Copy FILE to NEWNAME. Both args must be strings.\n\
2290 Signals a `file-already-exists' error if file NEWNAME already exists,\n\
2291 unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil.\n\
2292 A number as third arg means request confirmation if NEWNAME already exists.\n\
2293 This is what happens in interactive use with M-x.\n\
2294 Fourth arg KEEP-TIME non-nil means give the new file the same\n\
2295 last-modified time as the old one. (This works on only some systems.)\n\
2296 A prefix arg makes KEEP-TIME non-nil.")
2297 (file
, newname
, ok_if_already_exists
, keep_time
)
2298 Lisp_Object file
, newname
, ok_if_already_exists
, keep_time
;
2301 char buf
[16 * 1024];
2302 struct stat st
, out_st
;
2303 Lisp_Object handler
;
2304 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2305 int count
= specpdl_ptr
- specpdl
;
2306 int input_file_statable_p
;
2307 Lisp_Object encoded_file
, encoded_newname
;
2309 encoded_file
= encoded_newname
= Qnil
;
2310 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
2311 CHECK_STRING (file
, 0);
2312 CHECK_STRING (newname
, 1);
2314 file
= Fexpand_file_name (file
, Qnil
);
2315 newname
= Fexpand_file_name (newname
, Qnil
);
2317 /* If the input file name has special constructs in it,
2318 call the corresponding file handler. */
2319 handler
= Ffind_file_name_handler (file
, Qcopy_file
);
2320 /* Likewise for output file name. */
2322 handler
= Ffind_file_name_handler (newname
, Qcopy_file
);
2323 if (!NILP (handler
))
2324 RETURN_UNGCPRO (call5 (handler
, Qcopy_file
, file
, newname
,
2325 ok_if_already_exists
, keep_time
));
2327 encoded_file
= ENCODE_FILE (file
);
2328 encoded_newname
= ENCODE_FILE (newname
);
2330 if (NILP (ok_if_already_exists
)
2331 || INTEGERP (ok_if_already_exists
))
2332 barf_or_query_if_file_exists (encoded_newname
, "copy to it",
2333 INTEGERP (ok_if_already_exists
), &out_st
, 0);
2334 else if (stat (XSTRING (encoded_newname
)->data
, &out_st
) < 0)
2338 if (!CopyFile (XSTRING (encoded_file
)->data
,
2339 XSTRING (encoded_newname
)->data
,
2341 report_file_error ("Copying file", Fcons (file
, Fcons (newname
, Qnil
)));
2342 else if (NILP (keep_time
))
2345 EMACS_GET_TIME (now
);
2346 if (set_file_times (XSTRING (encoded_newname
)->data
,
2348 Fsignal (Qfile_date_error
,
2349 Fcons (build_string ("Cannot set file date"),
2350 Fcons (newname
, Qnil
)));
2352 #else /* not WINDOWSNT */
2353 ifd
= emacs_open (XSTRING (encoded_file
)->data
, O_RDONLY
, 0);
2355 report_file_error ("Opening input file", Fcons (file
, Qnil
));
2357 record_unwind_protect (close_file_unwind
, make_number (ifd
));
2359 /* We can only copy regular files and symbolic links. Other files are not
2361 input_file_statable_p
= (fstat (ifd
, &st
) >= 0);
2363 #if !defined (DOS_NT) || __DJGPP__ > 1
2364 if (out_st
.st_mode
!= 0
2365 && st
.st_dev
== out_st
.st_dev
&& st
.st_ino
== out_st
.st_ino
)
2368 report_file_error ("Input and output files are the same",
2369 Fcons (file
, Fcons (newname
, Qnil
)));
2373 #if defined (S_ISREG) && defined (S_ISLNK)
2374 if (input_file_statable_p
)
2376 if (!(S_ISREG (st
.st_mode
)) && !(S_ISLNK (st
.st_mode
)))
2378 #if defined (EISDIR)
2379 /* Get a better looking error message. */
2382 report_file_error ("Non-regular file", Fcons (file
, Qnil
));
2385 #endif /* S_ISREG && S_ISLNK */
2388 /* Create the copy file with the same record format as the input file */
2389 ofd
= sys_creat (XSTRING (encoded_newname
)->data
, 0666, ifd
);
2392 /* System's default file type was set to binary by _fmode in emacs.c. */
2393 ofd
= creat (XSTRING (encoded_newname
)->data
, S_IREAD
| S_IWRITE
);
2394 #else /* not MSDOS */
2395 ofd
= creat (XSTRING (encoded_newname
)->data
, 0666);
2396 #endif /* not MSDOS */
2399 report_file_error ("Opening output file", Fcons (newname
, Qnil
));
2401 record_unwind_protect (close_file_unwind
, make_number (ofd
));
2405 while ((n
= emacs_read (ifd
, buf
, sizeof buf
)) > 0)
2406 if (emacs_write (ofd
, buf
, n
) != n
)
2407 report_file_error ("I/O error", Fcons (newname
, Qnil
));
2410 /* Closing the output clobbers the file times on some systems. */
2411 if (emacs_close (ofd
) < 0)
2412 report_file_error ("I/O error", Fcons (newname
, Qnil
));
2414 if (input_file_statable_p
)
2416 if (!NILP (keep_time
))
2418 EMACS_TIME atime
, mtime
;
2419 EMACS_SET_SECS_USECS (atime
, st
.st_atime
, 0);
2420 EMACS_SET_SECS_USECS (mtime
, st
.st_mtime
, 0);
2421 if (set_file_times (XSTRING (encoded_newname
)->data
,
2423 Fsignal (Qfile_date_error
,
2424 Fcons (build_string ("Cannot set file date"),
2425 Fcons (newname
, Qnil
)));
2428 chmod (XSTRING (encoded_newname
)->data
, st
.st_mode
& 07777);
2430 #if defined (__DJGPP__) && __DJGPP__ > 1
2431 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2432 and if it can't, it tells so. Otherwise, under MSDOS we usually
2433 get only the READ bit, which will make the copied file read-only,
2434 so it's better not to chmod at all. */
2435 if ((_djstat_flags
& _STFAIL_WRITEBIT
) == 0)
2436 chmod (XSTRING (encoded_newname
)->data
, st
.st_mode
& 07777);
2437 #endif /* DJGPP version 2 or newer */
2442 #endif /* WINDOWSNT */
2444 /* Discard the unwind protects. */
2445 specpdl_ptr
= specpdl
+ count
;
2451 DEFUN ("make-directory-internal", Fmake_directory_internal
,
2452 Smake_directory_internal
, 1, 1, 0,
2453 "Create a new directory named DIRECTORY.")
2455 Lisp_Object directory
;
2458 Lisp_Object handler
;
2459 Lisp_Object encoded_dir
;
2461 CHECK_STRING (directory
, 0);
2462 directory
= Fexpand_file_name (directory
, Qnil
);
2464 handler
= Ffind_file_name_handler (directory
, Qmake_directory_internal
);
2465 if (!NILP (handler
))
2466 return call2 (handler
, Qmake_directory_internal
, directory
);
2468 encoded_dir
= ENCODE_FILE (directory
);
2470 dir
= XSTRING (encoded_dir
)->data
;
2473 if (mkdir (dir
) != 0)
2475 if (mkdir (dir
, 0777) != 0)
2477 report_file_error ("Creating directory", Flist (1, &directory
));
2482 DEFUN ("delete-directory", Fdelete_directory
, Sdelete_directory
, 1, 1, "FDelete directory: ",
2483 "Delete the directory named DIRECTORY.")
2485 Lisp_Object directory
;
2488 Lisp_Object handler
;
2489 Lisp_Object encoded_dir
;
2491 CHECK_STRING (directory
, 0);
2492 directory
= Fdirectory_file_name (Fexpand_file_name (directory
, Qnil
));
2494 handler
= Ffind_file_name_handler (directory
, Qdelete_directory
);
2495 if (!NILP (handler
))
2496 return call2 (handler
, Qdelete_directory
, directory
);
2498 encoded_dir
= ENCODE_FILE (directory
);
2500 dir
= XSTRING (encoded_dir
)->data
;
2502 if (rmdir (dir
) != 0)
2503 report_file_error ("Removing directory", Flist (1, &directory
));
2508 DEFUN ("delete-file", Fdelete_file
, Sdelete_file
, 1, 1, "fDelete file: ",
2509 "Delete file named FILENAME.\n\
2510 If file has multiple names, it continues to exist with the other names.")
2512 Lisp_Object filename
;
2514 Lisp_Object handler
;
2515 Lisp_Object encoded_file
;
2517 CHECK_STRING (filename
, 0);
2518 filename
= Fexpand_file_name (filename
, Qnil
);
2520 handler
= Ffind_file_name_handler (filename
, Qdelete_file
);
2521 if (!NILP (handler
))
2522 return call2 (handler
, Qdelete_file
, filename
);
2524 encoded_file
= ENCODE_FILE (filename
);
2526 if (0 > unlink (XSTRING (encoded_file
)->data
))
2527 report_file_error ("Removing old name", Flist (1, &filename
));
2532 internal_delete_file_1 (ignore
)
2538 /* Delete file FILENAME, returning 1 if successful and 0 if failed. */
2541 internal_delete_file (filename
)
2542 Lisp_Object filename
;
2544 return NILP (internal_condition_case_1 (Fdelete_file
, filename
,
2545 Qt
, internal_delete_file_1
));
2548 DEFUN ("rename-file", Frename_file
, Srename_file
, 2, 3,
2549 "fRename file: \nFRename %s to file: \np",
2550 "Rename FILE as NEWNAME. Both args strings.\n\
2551 If file has names other than FILE, it continues to have those names.\n\
2552 Signals a `file-already-exists' error if a file NEWNAME already exists\n\
2553 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
2554 A number as third arg means request confirmation if NEWNAME already exists.\n\
2555 This is what happens in interactive use with M-x.")
2556 (file
, newname
, ok_if_already_exists
)
2557 Lisp_Object file
, newname
, ok_if_already_exists
;
2560 Lisp_Object args
[2];
2562 Lisp_Object handler
;
2563 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2564 Lisp_Object encoded_file
, encoded_newname
;
2566 encoded_file
= encoded_newname
= Qnil
;
2567 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
2568 CHECK_STRING (file
, 0);
2569 CHECK_STRING (newname
, 1);
2570 file
= Fexpand_file_name (file
, Qnil
);
2571 newname
= Fexpand_file_name (newname
, Qnil
);
2573 /* If the file name has special constructs in it,
2574 call the corresponding file handler. */
2575 handler
= Ffind_file_name_handler (file
, Qrename_file
);
2577 handler
= Ffind_file_name_handler (newname
, Qrename_file
);
2578 if (!NILP (handler
))
2579 RETURN_UNGCPRO (call4 (handler
, Qrename_file
,
2580 file
, newname
, ok_if_already_exists
));
2582 encoded_file
= ENCODE_FILE (file
);
2583 encoded_newname
= ENCODE_FILE (newname
);
2586 /* If the file names are identical but for the case, don't ask for
2587 confirmation: they simply want to change the letter-case of the
2589 if (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2591 if (NILP (ok_if_already_exists
)
2592 || INTEGERP (ok_if_already_exists
))
2593 barf_or_query_if_file_exists (encoded_newname
, "rename to it",
2594 INTEGERP (ok_if_already_exists
), 0, 0);
2596 if (0 > rename (XSTRING (encoded_file
)->data
, XSTRING (encoded_newname
)->data
))
2598 if (0 > link (XSTRING (encoded_file
)->data
, XSTRING (encoded_newname
)->data
)
2599 || 0 > unlink (XSTRING (encoded_file
)->data
))
2604 Fcopy_file (file
, newname
,
2605 /* We have already prompted if it was an integer,
2606 so don't have copy-file prompt again. */
2607 NILP (ok_if_already_exists
) ? Qnil
: Qt
, Qt
);
2608 Fdelete_file (file
);
2615 report_file_error ("Renaming", Flist (2, args
));
2618 report_file_error ("Renaming", Flist (2, &file
));
2625 DEFUN ("add-name-to-file", Fadd_name_to_file
, Sadd_name_to_file
, 2, 3,
2626 "fAdd name to file: \nFName to add to %s: \np",
2627 "Give FILE additional name NEWNAME. Both args strings.\n\
2628 Signals a `file-already-exists' error if a file NEWNAME already exists\n\
2629 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
2630 A number as third arg means request confirmation if NEWNAME already exists.\n\
2631 This is what happens in interactive use with M-x.")
2632 (file
, newname
, ok_if_already_exists
)
2633 Lisp_Object file
, newname
, ok_if_already_exists
;
2636 Lisp_Object args
[2];
2638 Lisp_Object handler
;
2639 Lisp_Object encoded_file
, encoded_newname
;
2640 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2642 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
2643 encoded_file
= encoded_newname
= Qnil
;
2644 CHECK_STRING (file
, 0);
2645 CHECK_STRING (newname
, 1);
2646 file
= Fexpand_file_name (file
, Qnil
);
2647 newname
= Fexpand_file_name (newname
, Qnil
);
2649 /* If the file name has special constructs in it,
2650 call the corresponding file handler. */
2651 handler
= Ffind_file_name_handler (file
, Qadd_name_to_file
);
2652 if (!NILP (handler
))
2653 RETURN_UNGCPRO (call4 (handler
, Qadd_name_to_file
, file
,
2654 newname
, ok_if_already_exists
));
2656 /* If the new name has special constructs in it,
2657 call the corresponding file handler. */
2658 handler
= Ffind_file_name_handler (newname
, Qadd_name_to_file
);
2659 if (!NILP (handler
))
2660 RETURN_UNGCPRO (call4 (handler
, Qadd_name_to_file
, file
,
2661 newname
, ok_if_already_exists
));
2663 encoded_file
= ENCODE_FILE (file
);
2664 encoded_newname
= ENCODE_FILE (newname
);
2666 if (NILP (ok_if_already_exists
)
2667 || INTEGERP (ok_if_already_exists
))
2668 barf_or_query_if_file_exists (encoded_newname
, "make it a new name",
2669 INTEGERP (ok_if_already_exists
), 0, 0);
2671 unlink (XSTRING (newname
)->data
);
2672 if (0 > link (XSTRING (encoded_file
)->data
, XSTRING (encoded_newname
)->data
))
2677 report_file_error ("Adding new name", Flist (2, args
));
2679 report_file_error ("Adding new name", Flist (2, &file
));
2688 DEFUN ("make-symbolic-link", Fmake_symbolic_link
, Smake_symbolic_link
, 2, 3,
2689 "FMake symbolic link to file: \nFMake symbolic link to file %s: \np",
2690 "Make a symbolic link to FILENAME, named LINKNAME. Both args strings.\n\
2691 Signals a `file-already-exists' error if a file LINKNAME already exists\n\
2692 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
2693 A number as third arg means request confirmation if LINKNAME already exists.\n\
2694 This happens for interactive use with M-x.")
2695 (filename
, linkname
, ok_if_already_exists
)
2696 Lisp_Object filename
, linkname
, ok_if_already_exists
;
2699 Lisp_Object args
[2];
2701 Lisp_Object handler
;
2702 Lisp_Object encoded_filename
, encoded_linkname
;
2703 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2705 GCPRO4 (filename
, linkname
, encoded_filename
, encoded_linkname
);
2706 encoded_filename
= encoded_linkname
= Qnil
;
2707 CHECK_STRING (filename
, 0);
2708 CHECK_STRING (linkname
, 1);
2709 /* If the link target has a ~, we must expand it to get
2710 a truly valid file name. Otherwise, do not expand;
2711 we want to permit links to relative file names. */
2712 if (XSTRING (filename
)->data
[0] == '~')
2713 filename
= Fexpand_file_name (filename
, Qnil
);
2714 linkname
= Fexpand_file_name (linkname
, Qnil
);
2716 /* If the file name has special constructs in it,
2717 call the corresponding file handler. */
2718 handler
= Ffind_file_name_handler (filename
, Qmake_symbolic_link
);
2719 if (!NILP (handler
))
2720 RETURN_UNGCPRO (call4 (handler
, Qmake_symbolic_link
, filename
,
2721 linkname
, ok_if_already_exists
));
2723 /* If the new link name has special constructs in it,
2724 call the corresponding file handler. */
2725 handler
= Ffind_file_name_handler (linkname
, Qmake_symbolic_link
);
2726 if (!NILP (handler
))
2727 RETURN_UNGCPRO (call4 (handler
, Qmake_symbolic_link
, filename
,
2728 linkname
, ok_if_already_exists
));
2730 encoded_filename
= ENCODE_FILE (filename
);
2731 encoded_linkname
= ENCODE_FILE (linkname
);
2733 if (NILP (ok_if_already_exists
)
2734 || INTEGERP (ok_if_already_exists
))
2735 barf_or_query_if_file_exists (encoded_linkname
, "make it a link",
2736 INTEGERP (ok_if_already_exists
), 0, 0);
2737 if (0 > symlink (XSTRING (encoded_filename
)->data
,
2738 XSTRING (encoded_linkname
)->data
))
2740 /* If we didn't complain already, silently delete existing file. */
2741 if (errno
== EEXIST
)
2743 unlink (XSTRING (encoded_linkname
)->data
);
2744 if (0 <= symlink (XSTRING (encoded_filename
)->data
,
2745 XSTRING (encoded_linkname
)->data
))
2755 report_file_error ("Making symbolic link", Flist (2, args
));
2757 report_file_error ("Making symbolic link", Flist (2, &filename
));
2763 #endif /* S_IFLNK */
2767 DEFUN ("define-logical-name", Fdefine_logical_name
, Sdefine_logical_name
,
2768 2, 2, "sDefine logical name: \nsDefine logical name %s as: ",
2769 "Define the job-wide logical name NAME to have the value STRING.\n\
2770 If STRING is nil or a null string, the logical name NAME is deleted.")
2775 CHECK_STRING (name
, 0);
2777 delete_logical_name (XSTRING (name
)->data
);
2780 CHECK_STRING (string
, 1);
2782 if (XSTRING (string
)->size
== 0)
2783 delete_logical_name (XSTRING (name
)->data
);
2785 define_logical_name (XSTRING (name
)->data
, XSTRING (string
)->data
);
2794 DEFUN ("sysnetunam", Fsysnetunam
, Ssysnetunam
, 2, 2, 0,
2795 "Open a network connection to PATH using LOGIN as the login string.")
2797 Lisp_Object path
, login
;
2801 CHECK_STRING (path
, 0);
2802 CHECK_STRING (login
, 0);
2804 netresult
= netunam (XSTRING (path
)->data
, XSTRING (login
)->data
);
2806 if (netresult
== -1)
2811 #endif /* HPUX_NET */
2813 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p
, Sfile_name_absolute_p
,
2815 "Return t if file FILENAME specifies an absolute file name.\n\
2816 On Unix, this is a name starting with a `/' or a `~'.")
2818 Lisp_Object filename
;
2822 CHECK_STRING (filename
, 0);
2823 ptr
= XSTRING (filename
)->data
;
2824 if (IS_DIRECTORY_SEP (*ptr
) || *ptr
== '~'
2826 /* ??? This criterion is probably wrong for '<'. */
2827 || index (ptr
, ':') || index (ptr
, '<')
2828 || (*ptr
== '[' && (ptr
[1] != '-' || (ptr
[2] != '.' && ptr
[2] != ']'))
2832 || (IS_DRIVE (*ptr
) && ptr
[1] == ':' && IS_DIRECTORY_SEP (ptr
[2]))
2840 /* Return nonzero if file FILENAME exists and can be executed. */
2843 check_executable (filename
)
2847 int len
= strlen (filename
);
2850 if (stat (filename
, &st
) < 0)
2852 #if defined (WINDOWSNT) || (defined (MSDOS) && __DJGPP__ > 1)
2853 return ((st
.st_mode
& S_IEXEC
) != 0);
2855 return (S_ISREG (st
.st_mode
)
2857 && (stricmp ((suffix
= filename
+ len
-4), ".com") == 0
2858 || stricmp (suffix
, ".exe") == 0
2859 || stricmp (suffix
, ".bat") == 0)
2860 || (st
.st_mode
& S_IFMT
) == S_IFDIR
);
2861 #endif /* not WINDOWSNT */
2862 #else /* not DOS_NT */
2863 #ifdef HAVE_EUIDACCESS
2864 return (euidaccess (filename
, 1) >= 0);
2866 /* Access isn't quite right because it uses the real uid
2867 and we really want to test with the effective uid.
2868 But Unix doesn't give us a right way to do it. */
2869 return (access (filename
, 1) >= 0);
2871 #endif /* not DOS_NT */
2874 /* Return nonzero if file FILENAME exists and can be written. */
2877 check_writable (filename
)
2882 if (stat (filename
, &st
) < 0)
2884 return (st
.st_mode
& S_IWRITE
|| (st
.st_mode
& S_IFMT
) == S_IFDIR
);
2885 #else /* not MSDOS */
2886 #ifdef HAVE_EUIDACCESS
2887 return (euidaccess (filename
, 2) >= 0);
2889 /* Access isn't quite right because it uses the real uid
2890 and we really want to test with the effective uid.
2891 But Unix doesn't give us a right way to do it.
2892 Opening with O_WRONLY could work for an ordinary file,
2893 but would lose for directories. */
2894 return (access (filename
, 2) >= 0);
2896 #endif /* not MSDOS */
2899 DEFUN ("file-exists-p", Ffile_exists_p
, Sfile_exists_p
, 1, 1, 0,
2900 "Return t if file FILENAME exists. (This does not mean you can read it.)\n\
2901 See also `file-readable-p' and `file-attributes'.")
2903 Lisp_Object filename
;
2905 Lisp_Object absname
;
2906 Lisp_Object handler
;
2907 struct stat statbuf
;
2909 CHECK_STRING (filename
, 0);
2910 absname
= Fexpand_file_name (filename
, Qnil
);
2912 /* If the file name has special constructs in it,
2913 call the corresponding file handler. */
2914 handler
= Ffind_file_name_handler (absname
, Qfile_exists_p
);
2915 if (!NILP (handler
))
2916 return call2 (handler
, Qfile_exists_p
, absname
);
2918 absname
= ENCODE_FILE (absname
);
2920 return (stat (XSTRING (absname
)->data
, &statbuf
) >= 0) ? Qt
: Qnil
;
2923 DEFUN ("file-executable-p", Ffile_executable_p
, Sfile_executable_p
, 1, 1, 0,
2924 "Return t if FILENAME can be executed by you.\n\
2925 For a directory, this means you can access files in that directory.")
2927 Lisp_Object filename
;
2930 Lisp_Object absname
;
2931 Lisp_Object handler
;
2933 CHECK_STRING (filename
, 0);
2934 absname
= Fexpand_file_name (filename
, Qnil
);
2936 /* If the file name has special constructs in it,
2937 call the corresponding file handler. */
2938 handler
= Ffind_file_name_handler (absname
, Qfile_executable_p
);
2939 if (!NILP (handler
))
2940 return call2 (handler
, Qfile_executable_p
, absname
);
2942 absname
= ENCODE_FILE (absname
);
2944 return (check_executable (XSTRING (absname
)->data
) ? Qt
: Qnil
);
2947 DEFUN ("file-readable-p", Ffile_readable_p
, Sfile_readable_p
, 1, 1, 0,
2948 "Return t if file FILENAME exists and you can read it.\n\
2949 See also `file-exists-p' and `file-attributes'.")
2951 Lisp_Object filename
;
2953 Lisp_Object absname
;
2954 Lisp_Object handler
;
2957 struct stat statbuf
;
2959 CHECK_STRING (filename
, 0);
2960 absname
= Fexpand_file_name (filename
, Qnil
);
2962 /* If the file name has special constructs in it,
2963 call the corresponding file handler. */
2964 handler
= Ffind_file_name_handler (absname
, Qfile_readable_p
);
2965 if (!NILP (handler
))
2966 return call2 (handler
, Qfile_readable_p
, absname
);
2968 absname
= ENCODE_FILE (absname
);
2970 #if defined(DOS_NT) || defined(macintosh)
2971 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2973 if (access (XSTRING (absname
)->data
, 0) == 0)
2976 #else /* not DOS_NT and not macintosh */
2978 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
2979 /* Opening a fifo without O_NONBLOCK can wait.
2980 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2981 except in the case of a fifo, on a system which handles it. */
2982 desc
= stat (XSTRING (absname
)->data
, &statbuf
);
2985 if (S_ISFIFO (statbuf
.st_mode
))
2986 flags
|= O_NONBLOCK
;
2988 desc
= emacs_open (XSTRING (absname
)->data
, flags
, 0);
2993 #endif /* not DOS_NT and not macintosh */
2996 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2998 DEFUN ("file-writable-p", Ffile_writable_p
, Sfile_writable_p
, 1, 1, 0,
2999 "Return t if file FILENAME can be written or created by you.")
3001 Lisp_Object filename
;
3003 Lisp_Object absname
, dir
, encoded
;
3004 Lisp_Object handler
;
3005 struct stat statbuf
;
3007 CHECK_STRING (filename
, 0);
3008 absname
= Fexpand_file_name (filename
, Qnil
);
3010 /* If the file name has special constructs in it,
3011 call the corresponding file handler. */
3012 handler
= Ffind_file_name_handler (absname
, Qfile_writable_p
);
3013 if (!NILP (handler
))
3014 return call2 (handler
, Qfile_writable_p
, absname
);
3016 encoded
= ENCODE_FILE (absname
);
3017 if (stat (XSTRING (encoded
)->data
, &statbuf
) >= 0)
3018 return (check_writable (XSTRING (encoded
)->data
)
3021 dir
= Ffile_name_directory (absname
);
3024 dir
= Fdirectory_file_name (dir
);
3028 dir
= Fdirectory_file_name (dir
);
3031 dir
= ENCODE_FILE (dir
);
3033 /* The read-only attribute of the parent directory doesn't affect
3034 whether a file or directory can be created within it. Some day we
3035 should check ACLs though, which do affect this. */
3036 if (stat (XSTRING (dir
)->data
, &statbuf
) < 0)
3038 return (statbuf
.st_mode
& S_IFMT
) == S_IFDIR
? Qt
: Qnil
;
3040 return (check_writable (!NILP (dir
) ? (char *) XSTRING (dir
)->data
: "")
3045 DEFUN ("access-file", Faccess_file
, Saccess_file
, 2, 2, 0,
3046 "Access file FILENAME, and get an error if that does not work.\n\
3047 The second argument STRING is used in the error message.\n\
3048 If there is no error, we return nil.")
3050 Lisp_Object filename
, string
;
3052 Lisp_Object handler
, encoded_filename
;
3055 CHECK_STRING (filename
, 0);
3056 CHECK_STRING (string
, 1);
3058 /* If the file name has special constructs in it,
3059 call the corresponding file handler. */
3060 handler
= Ffind_file_name_handler (filename
, Qaccess_file
);
3061 if (!NILP (handler
))
3062 return call3 (handler
, Qaccess_file
, filename
, string
);
3064 encoded_filename
= ENCODE_FILE (filename
);
3066 fd
= emacs_open (XSTRING (encoded_filename
)->data
, O_RDONLY
, 0);
3068 report_file_error (XSTRING (string
)->data
, Fcons (filename
, Qnil
));
3074 DEFUN ("file-symlink-p", Ffile_symlink_p
, Sfile_symlink_p
, 1, 1, 0,
3075 "Return non-nil if file FILENAME is the name of a symbolic link.\n\
3076 The value is the name of the file to which it is linked.\n\
3077 Otherwise returns nil.")
3079 Lisp_Object filename
;
3086 Lisp_Object handler
;
3088 CHECK_STRING (filename
, 0);
3089 filename
= Fexpand_file_name (filename
, Qnil
);
3091 /* If the file name has special constructs in it,
3092 call the corresponding file handler. */
3093 handler
= Ffind_file_name_handler (filename
, Qfile_symlink_p
);
3094 if (!NILP (handler
))
3095 return call2 (handler
, Qfile_symlink_p
, filename
);
3097 filename
= ENCODE_FILE (filename
);
3102 buf
= (char *) xmalloc (bufsize
);
3103 bzero (buf
, bufsize
);
3104 valsize
= readlink (XSTRING (filename
)->data
, buf
, bufsize
);
3105 if (valsize
< bufsize
) break;
3106 /* Buffer was not long enough */
3115 val
= make_string (buf
, valsize
);
3116 if (buf
[0] == '/' && index (buf
, ':'))
3117 val
= concat2 (build_string ("/:"), val
);
3119 val
= DECODE_FILE (val
);
3121 #else /* not S_IFLNK */
3123 #endif /* not S_IFLNK */
3126 DEFUN ("file-directory-p", Ffile_directory_p
, Sfile_directory_p
, 1, 1, 0,
3127 "Return t if FILENAME names an existing directory.\n\
3128 Symbolic links to directories count as directories.\n\
3129 See `file-symlink-p' to distinguish symlinks.")
3131 Lisp_Object filename
;
3133 register Lisp_Object absname
;
3135 Lisp_Object handler
;
3137 absname
= expand_and_dir_to_file (filename
, current_buffer
->directory
);
3139 /* If the file name has special constructs in it,
3140 call the corresponding file handler. */
3141 handler
= Ffind_file_name_handler (absname
, Qfile_directory_p
);
3142 if (!NILP (handler
))
3143 return call2 (handler
, Qfile_directory_p
, absname
);
3145 absname
= ENCODE_FILE (absname
);
3147 if (stat (XSTRING (absname
)->data
, &st
) < 0)
3149 return (st
.st_mode
& S_IFMT
) == S_IFDIR
? Qt
: Qnil
;
3152 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p
, Sfile_accessible_directory_p
, 1, 1, 0,
3153 "Return t if file FILENAME is the name of a directory as a file,\n\
3154 and files in that directory can be opened by you. In order to use a\n\
3155 directory as a buffer's current directory, this predicate must return true.\n\
3156 A directory name spec may be given instead; then the value is t\n\
3157 if the directory so specified exists and really is a readable and\n\
3158 searchable directory.")
3160 Lisp_Object filename
;
3162 Lisp_Object handler
;
3164 struct gcpro gcpro1
;
3166 /* If the file name has special constructs in it,
3167 call the corresponding file handler. */
3168 handler
= Ffind_file_name_handler (filename
, Qfile_accessible_directory_p
);
3169 if (!NILP (handler
))
3170 return call2 (handler
, Qfile_accessible_directory_p
, filename
);
3172 /* It's an unlikely combination, but yes we really do need to gcpro:
3173 Suppose that file-accessible-directory-p has no handler, but
3174 file-directory-p does have a handler; this handler causes a GC which
3175 relocates the string in `filename'; and finally file-directory-p
3176 returns non-nil. Then we would end up passing a garbaged string
3177 to file-executable-p. */
3179 tem
= (NILP (Ffile_directory_p (filename
))
3180 || NILP (Ffile_executable_p (filename
)));
3182 return tem
? Qnil
: Qt
;
3185 DEFUN ("file-regular-p", Ffile_regular_p
, Sfile_regular_p
, 1, 1, 0,
3186 "Return t if file FILENAME is the name of a regular file.\n\
3187 This is the sort of file that holds an ordinary stream of data bytes.")
3189 Lisp_Object filename
;
3191 register Lisp_Object absname
;
3193 Lisp_Object handler
;
3195 absname
= expand_and_dir_to_file (filename
, current_buffer
->directory
);
3197 /* If the file name has special constructs in it,
3198 call the corresponding file handler. */
3199 handler
= Ffind_file_name_handler (absname
, Qfile_regular_p
);
3200 if (!NILP (handler
))
3201 return call2 (handler
, Qfile_regular_p
, absname
);
3203 absname
= ENCODE_FILE (absname
);
3208 Lisp_Object tem
= Vw32_get_true_file_attributes
;
3210 /* Tell stat to use expensive method to get accurate info. */
3211 Vw32_get_true_file_attributes
= Qt
;
3212 result
= stat (XSTRING (absname
)->data
, &st
);
3213 Vw32_get_true_file_attributes
= tem
;
3217 return (st
.st_mode
& S_IFMT
) == S_IFREG
? Qt
: Qnil
;
3220 if (stat (XSTRING (absname
)->data
, &st
) < 0)
3222 return (st
.st_mode
& S_IFMT
) == S_IFREG
? Qt
: Qnil
;
3226 DEFUN ("file-modes", Ffile_modes
, Sfile_modes
, 1, 1, 0,
3227 "Return mode bits of file named FILENAME, as an integer.")
3229 Lisp_Object filename
;
3231 Lisp_Object absname
;
3233 Lisp_Object handler
;
3235 absname
= expand_and_dir_to_file (filename
, current_buffer
->directory
);
3237 /* If the file name has special constructs in it,
3238 call the corresponding file handler. */
3239 handler
= Ffind_file_name_handler (absname
, Qfile_modes
);
3240 if (!NILP (handler
))
3241 return call2 (handler
, Qfile_modes
, absname
);
3243 absname
= ENCODE_FILE (absname
);
3245 if (stat (XSTRING (absname
)->data
, &st
) < 0)
3247 #if defined (MSDOS) && __DJGPP__ < 2
3248 if (check_executable (XSTRING (absname
)->data
))
3249 st
.st_mode
|= S_IEXEC
;
3250 #endif /* MSDOS && __DJGPP__ < 2 */
3252 return make_number (st
.st_mode
& 07777);
3255 DEFUN ("set-file-modes", Fset_file_modes
, Sset_file_modes
, 2, 2, 0,
3256 "Set mode bits of file named FILENAME to MODE (an integer).\n\
3257 Only the 12 low bits of MODE are used.")
3259 Lisp_Object filename
, mode
;
3261 Lisp_Object absname
, encoded_absname
;
3262 Lisp_Object handler
;
3264 absname
= Fexpand_file_name (filename
, current_buffer
->directory
);
3265 CHECK_NUMBER (mode
, 1);
3267 /* If the file name has special constructs in it,
3268 call the corresponding file handler. */
3269 handler
= Ffind_file_name_handler (absname
, Qset_file_modes
);
3270 if (!NILP (handler
))
3271 return call3 (handler
, Qset_file_modes
, absname
, mode
);
3273 encoded_absname
= ENCODE_FILE (absname
);
3275 if (chmod (XSTRING (encoded_absname
)->data
, XINT (mode
)) < 0)
3276 report_file_error ("Doing chmod", Fcons (absname
, Qnil
));
3281 DEFUN ("set-default-file-modes", Fset_default_file_modes
, Sset_default_file_modes
, 1, 1, 0,
3282 "Set the file permission bits for newly created files.\n\
3283 The argument MODE should be an integer; only the low 9 bits are used.\n\
3284 This setting is inherited by subprocesses.")
3288 CHECK_NUMBER (mode
, 0);
3290 umask ((~ XINT (mode
)) & 0777);
3295 DEFUN ("default-file-modes", Fdefault_file_modes
, Sdefault_file_modes
, 0, 0, 0,
3296 "Return the default file protection for created files.\n\
3297 The value is an integer.")
3303 realmask
= umask (0);
3306 XSETINT (value
, (~ realmask
) & 0777);
3316 DEFUN ("unix-sync", Funix_sync
, Sunix_sync
, 0, 0, "",
3317 "Tell Unix to finish all pending disk updates.")
3326 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p
, Sfile_newer_than_file_p
, 2, 2, 0,
3327 "Return t if file FILE1 is newer than file FILE2.\n\
3328 If FILE1 does not exist, the answer is nil;\n\
3329 otherwise, if FILE2 does not exist, the answer is t.")
3331 Lisp_Object file1
, file2
;
3333 Lisp_Object absname1
, absname2
;
3336 Lisp_Object handler
;
3337 struct gcpro gcpro1
, gcpro2
;
3339 CHECK_STRING (file1
, 0);
3340 CHECK_STRING (file2
, 0);
3343 GCPRO2 (absname1
, file2
);
3344 absname1
= expand_and_dir_to_file (file1
, current_buffer
->directory
);
3345 absname2
= expand_and_dir_to_file (file2
, current_buffer
->directory
);
3348 /* If the file name has special constructs in it,
3349 call the corresponding file handler. */
3350 handler
= Ffind_file_name_handler (absname1
, Qfile_newer_than_file_p
);
3352 handler
= Ffind_file_name_handler (absname2
, Qfile_newer_than_file_p
);
3353 if (!NILP (handler
))
3354 return call3 (handler
, Qfile_newer_than_file_p
, absname1
, absname2
);
3356 GCPRO2 (absname1
, absname2
);
3357 absname1
= ENCODE_FILE (absname1
);
3358 absname2
= ENCODE_FILE (absname2
);
3361 if (stat (XSTRING (absname1
)->data
, &st
) < 0)
3364 mtime1
= st
.st_mtime
;
3366 if (stat (XSTRING (absname2
)->data
, &st
) < 0)
3369 return (mtime1
> st
.st_mtime
) ? Qt
: Qnil
;
3373 Lisp_Object Qfind_buffer_file_type
;
3376 #ifndef READ_BUF_SIZE
3377 #define READ_BUF_SIZE (64 << 10)
3380 extern void adjust_markers_for_delete
P_ ((int, int, int, int));
3382 /* This function is called after Lisp functions to decide a coding
3383 system are called, or when they cause an error. Before they are
3384 called, the current buffer is set unibyte and it contains only a
3385 newly inserted text (thus the buffer was empty before the
3388 The functions may set markers, overlays, text properties, or even
3389 alter the buffer contents, change the current buffer.
3391 Here, we reset all those changes by:
3392 o set back the current buffer.
3393 o move all markers and overlays to BEG.
3394 o remove all text properties.
3395 o set back the buffer multibyteness. */
3398 decide_coding_unwind (unwind_data
)
3399 Lisp_Object unwind_data
;
3401 Lisp_Object multibyte
, undo_list
, buffer
;
3403 multibyte
= XCAR (unwind_data
);
3404 unwind_data
= XCDR (unwind_data
);
3405 undo_list
= XCAR (unwind_data
);
3406 buffer
= XCDR (unwind_data
);
3408 if (current_buffer
!= XBUFFER (buffer
))
3409 set_buffer_internal (XBUFFER (buffer
));
3410 adjust_markers_for_delete (BEG
, BEG_BYTE
, Z
, Z_BYTE
);
3411 adjust_overlays_for_delete (BEG
, Z
- BEG
);
3412 BUF_INTERVALS (current_buffer
) = 0;
3413 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3415 /* Now we are safe to change the buffer's multibyteness directly. */
3416 current_buffer
->enable_multibyte_characters
= multibyte
;
3417 current_buffer
->undo_list
= undo_list
;
3423 /* Used to pass values from insert-file-contents to read_non_regular. */
3425 static int non_regular_fd
;
3426 static int non_regular_inserted
;
3427 static int non_regular_nbytes
;
3430 /* Read from a non-regular file.
3431 Read non_regular_trytry bytes max from non_regular_fd.
3432 Non_regular_inserted specifies where to put the read bytes.
3433 Value is the number of bytes read. */
3442 nbytes
= emacs_read (non_regular_fd
,
3443 BEG_ADDR
+ PT_BYTE
- 1 + non_regular_inserted
,
3444 non_regular_nbytes
);
3445 Fsignal (Qquit
, Qnil
);
3447 return make_number (nbytes
);
3451 /* Condition-case handler used when reading from non-regular files
3452 in insert-file-contents. */
3455 read_non_regular_quit ()
3461 DEFUN ("insert-file-contents", Finsert_file_contents
, Sinsert_file_contents
,
3463 "Insert contents of file FILENAME after point.\n\
3464 Returns list of absolute file name and number of bytes inserted.\n\
3465 If second argument VISIT is non-nil, the buffer's visited filename\n\
3466 and last save file modtime are set, and it is marked unmodified.\n\
3467 If visiting and the file does not exist, visiting is completed\n\
3468 before the error is signaled.\n\
3469 The optional third and fourth arguments BEG and END\n\
3470 specify what portion of the file to insert.\n\
3471 These arguments count bytes in the file, not characters in the buffer.\n\
3472 If VISIT is non-nil, BEG and END must be nil.\n\
3474 If optional fifth argument REPLACE is non-nil,\n\
3475 it means replace the current buffer contents (in the accessible portion)\n\
3476 with the file contents. This is better than simply deleting and inserting\n\
3477 the whole thing because (1) it preserves some marker positions\n\
3478 and (2) it puts less data in the undo list.\n\
3479 When REPLACE is non-nil, the value is the number of characters actually read,\n\
3480 which is often less than the number of characters to be read.\n\
3482 This does code conversion according to the value of\n\
3483 `coding-system-for-read' or `file-coding-system-alist',\n\
3484 and sets the variable `last-coding-system-used' to the coding system\n\
3486 (filename
, visit
, beg
, end
, replace
)
3487 Lisp_Object filename
, visit
, beg
, end
, replace
;
3492 register int how_much
;
3493 register int unprocessed
;
3494 int count
= BINDING_STACK_SIZE ();
3495 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
3496 Lisp_Object handler
, val
, insval
, orig_filename
;
3499 int not_regular
= 0;
3500 unsigned char read_buf
[READ_BUF_SIZE
];
3501 struct coding_system coding
;
3502 unsigned char buffer
[1 << 14];
3503 int replace_handled
= 0;
3504 int set_coding_system
= 0;
3505 int coding_system_decided
= 0;
3509 if (current_buffer
->base_buffer
&& ! NILP (visit
))
3510 error ("Cannot do file visiting in an indirect buffer");
3512 if (!NILP (current_buffer
->read_only
))
3513 Fbarf_if_buffer_read_only ();
3517 orig_filename
= Qnil
;
3519 GCPRO4 (filename
, val
, p
, orig_filename
);
3521 CHECK_STRING (filename
, 0);
3522 filename
= Fexpand_file_name (filename
, Qnil
);
3524 /* If the file name has special constructs in it,
3525 call the corresponding file handler. */
3526 handler
= Ffind_file_name_handler (filename
, Qinsert_file_contents
);
3527 if (!NILP (handler
))
3529 val
= call6 (handler
, Qinsert_file_contents
, filename
,
3530 visit
, beg
, end
, replace
);
3531 if (CONSP (val
) && CONSP (XCDR (val
)))
3532 inserted
= XINT (XCAR (XCDR (val
)));
3536 orig_filename
= filename
;
3537 filename
= ENCODE_FILE (filename
);
3543 Lisp_Object tem
= Vw32_get_true_file_attributes
;
3545 /* Tell stat to use expensive method to get accurate info. */
3546 Vw32_get_true_file_attributes
= Qt
;
3547 total
= stat (XSTRING (filename
)->data
, &st
);
3548 Vw32_get_true_file_attributes
= tem
;
3553 if (stat (XSTRING (filename
)->data
, &st
) < 0)
3555 if ((fd
= emacs_open (XSTRING (filename
)->data
, O_RDONLY
, 0)) < 0
3556 || fstat (fd
, &st
) < 0)
3557 #endif /* not APOLLO */
3558 #endif /* WINDOWSNT */
3560 if (fd
>= 0) emacs_close (fd
);
3563 report_file_error ("Opening input file", Fcons (orig_filename
, Qnil
));
3566 if (!NILP (Vcoding_system_for_read
))
3567 Fset (Qbuffer_file_coding_system
, Vcoding_system_for_read
);
3572 /* This code will need to be changed in order to work on named
3573 pipes, and it's probably just not worth it. So we should at
3574 least signal an error. */
3575 if (!S_ISREG (st
.st_mode
))
3582 if (! NILP (replace
) || ! NILP (beg
) || ! NILP (end
))
3583 Fsignal (Qfile_error
,
3584 Fcons (build_string ("not a regular file"),
3585 Fcons (orig_filename
, Qnil
)));
3590 if ((fd
= emacs_open (XSTRING (filename
)->data
, O_RDONLY
, 0)) < 0)
3593 /* Replacement should preserve point as it preserves markers. */
3594 if (!NILP (replace
))
3595 record_unwind_protect (restore_point_unwind
, Fpoint_marker ());
3597 record_unwind_protect (close_file_unwind
, make_number (fd
));
3599 /* Supposedly happens on VMS. */
3600 if (! not_regular
&& st
.st_size
< 0)
3601 error ("File size is negative");
3603 /* Prevent redisplay optimizations. */
3604 current_buffer
->clip_changed
= 1;
3608 if (!NILP (beg
) || !NILP (end
))
3609 error ("Attempt to visit less than an entire file");
3610 if (BEG
< Z
&& NILP (replace
))
3611 error ("Cannot do file visiting in a non-empty buffer");
3615 CHECK_NUMBER (beg
, 0);
3617 XSETFASTINT (beg
, 0);
3620 CHECK_NUMBER (end
, 0);
3625 XSETINT (end
, st
.st_size
);
3627 /* Arithmetic overflow can occur if an Emacs integer cannot
3628 represent the file size, or if the calculations below
3629 overflow. The calculations below double the file size
3630 twice, so check that it can be multiplied by 4 safely. */
3631 if (XINT (end
) != st
.st_size
3632 || ((int) st
.st_size
* 4) / 4 != st
.st_size
)
3633 error ("Maximum buffer size exceeded");
3635 /* The file size returned from stat may be zero, but data
3636 may be readable nonetheless, for example when this is a
3637 file in the /proc filesystem. */
3638 if (st
.st_size
== 0)
3639 XSETINT (end
, READ_BUF_SIZE
);
3645 /* Decide the coding system to use for reading the file now
3646 because we can't use an optimized method for handling
3647 `coding:' tag if the current buffer is not empty. */
3651 if (!NILP (Vcoding_system_for_read
))
3652 val
= Vcoding_system_for_read
;
3653 else if (! NILP (replace
))
3654 /* In REPLACE mode, we can use the same coding system
3655 that was used to visit the file. */
3656 val
= current_buffer
->buffer_file_coding_system
;
3659 /* Don't try looking inside a file for a coding system
3660 specification if it is not seekable. */
3661 if (! not_regular
&& ! NILP (Vset_auto_coding_function
))
3663 /* Find a coding system specified in the heading two
3664 lines or in the tailing several lines of the file.
3665 We assume that the 1K-byte and 3K-byte for heading
3666 and tailing respectively are sufficient for this
3670 if (st
.st_size
<= (1024 * 4))
3671 nread
= emacs_read (fd
, read_buf
, 1024 * 4);
3674 nread
= emacs_read (fd
, read_buf
, 1024);
3677 if (lseek (fd
, st
.st_size
- (1024 * 3), 0) < 0)
3678 report_file_error ("Setting file position",
3679 Fcons (orig_filename
, Qnil
));
3680 nread
+= emacs_read (fd
, read_buf
+ nread
, 1024 * 3);
3685 error ("IO error reading %s: %s",
3686 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
3689 struct buffer
*prev
= current_buffer
;
3692 record_unwind_protect (Fset_buffer
, Fcurrent_buffer ());
3694 /* The call to temp_output_buffer_setup binds
3696 count1
= specpdl_ptr
- specpdl
;
3697 temp_output_buffer_setup (" *code-converting-work*");
3699 set_buffer_internal (XBUFFER (Vstandard_output
));
3700 current_buffer
->enable_multibyte_characters
= Qnil
;
3701 insert_1_both (read_buf
, nread
, nread
, 0, 0, 0);
3702 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3703 val
= call2 (Vset_auto_coding_function
,
3704 filename
, make_number (nread
));
3705 set_buffer_internal (prev
);
3707 /* Remove the binding for standard-output. */
3708 unbind_to (count1
, Qnil
);
3710 /* Discard the unwind protect for recovering the
3714 /* Rewind the file for the actual read done later. */
3715 if (lseek (fd
, 0, 0) < 0)
3716 report_file_error ("Setting file position",
3717 Fcons (orig_filename
, Qnil
));
3723 /* If we have not yet decided a coding system, check
3724 file-coding-system-alist. */
3725 Lisp_Object args
[6], coding_systems
;
3727 args
[0] = Qinsert_file_contents
, args
[1] = orig_filename
;
3728 args
[2] = visit
, args
[3] = beg
, args
[4] = end
, args
[5] = replace
;
3729 coding_systems
= Ffind_operation_coding_system (6, args
);
3730 if (CONSP (coding_systems
))
3731 val
= XCAR (coding_systems
);
3735 setup_coding_system (Fcheck_coding_system (val
), &coding
);
3736 /* Ensure we set Vlast_coding_system_used. */
3737 set_coding_system
= 1;
3739 if (NILP (current_buffer
->enable_multibyte_characters
)
3741 /* We must suppress all character code conversion except for
3742 end-of-line conversion. */
3743 setup_raw_text_coding_system (&coding
);
3745 coding
.src_multibyte
= 0;
3746 coding
.dst_multibyte
3747 = !NILP (current_buffer
->enable_multibyte_characters
);
3748 coding_system_decided
= 1;
3751 /* If requested, replace the accessible part of the buffer
3752 with the file contents. Avoid replacing text at the
3753 beginning or end of the buffer that matches the file contents;
3754 that preserves markers pointing to the unchanged parts.
3756 Here we implement this feature in an optimized way
3757 for the case where code conversion is NOT needed.
3758 The following if-statement handles the case of conversion
3759 in a less optimal way.
3761 If the code conversion is "automatic" then we try using this
3762 method and hope for the best.
3763 But if we discover the need for conversion, we give up on this method
3764 and let the following if-statement handle the replace job. */
3767 && !(coding
.common_flags
& CODING_REQUIRE_DECODING_MASK
))
3769 /* same_at_start and same_at_end count bytes,
3770 because file access counts bytes
3771 and BEG and END count bytes. */
3772 int same_at_start
= BEGV_BYTE
;
3773 int same_at_end
= ZV_BYTE
;
3775 /* There is still a possibility we will find the need to do code
3776 conversion. If that happens, we set this variable to 1 to
3777 give up on handling REPLACE in the optimized way. */
3778 int giveup_match_end
= 0;
3780 if (XINT (beg
) != 0)
3782 if (lseek (fd
, XINT (beg
), 0) < 0)
3783 report_file_error ("Setting file position",
3784 Fcons (orig_filename
, Qnil
));
3789 /* Count how many chars at the start of the file
3790 match the text at the beginning of the buffer. */
3795 nread
= emacs_read (fd
, buffer
, sizeof buffer
);
3797 error ("IO error reading %s: %s",
3798 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
3799 else if (nread
== 0)
3802 if (coding
.type
== coding_type_undecided
)
3803 detect_coding (&coding
, buffer
, nread
);
3804 if (coding
.common_flags
& CODING_REQUIRE_DECODING_MASK
)
3805 /* We found that the file should be decoded somehow.
3806 Let's give up here. */
3808 giveup_match_end
= 1;
3812 if (coding
.eol_type
== CODING_EOL_UNDECIDED
)
3813 detect_eol (&coding
, buffer
, nread
);
3814 if (coding
.eol_type
!= CODING_EOL_UNDECIDED
3815 && coding
.eol_type
!= CODING_EOL_LF
)
3816 /* We found that the format of eol should be decoded.
3817 Let's give up here. */
3819 giveup_match_end
= 1;
3824 while (bufpos
< nread
&& same_at_start
< ZV_BYTE
3825 && FETCH_BYTE (same_at_start
) == buffer
[bufpos
])
3826 same_at_start
++, bufpos
++;
3827 /* If we found a discrepancy, stop the scan.
3828 Otherwise loop around and scan the next bufferful. */
3829 if (bufpos
!= nread
)
3833 /* If the file matches the buffer completely,
3834 there's no need to replace anything. */
3835 if (same_at_start
- BEGV_BYTE
== XINT (end
))
3839 /* Truncate the buffer to the size of the file. */
3840 del_range_1 (same_at_start
, same_at_end
, 0, 0);
3845 /* Count how many chars at the end of the file
3846 match the text at the end of the buffer. But, if we have
3847 already found that decoding is necessary, don't waste time. */
3848 while (!giveup_match_end
)
3850 int total_read
, nread
, bufpos
, curpos
, trial
;
3852 /* At what file position are we now scanning? */
3853 curpos
= XINT (end
) - (ZV_BYTE
- same_at_end
);
3854 /* If the entire file matches the buffer tail, stop the scan. */
3857 /* How much can we scan in the next step? */
3858 trial
= min (curpos
, sizeof buffer
);
3859 if (lseek (fd
, curpos
- trial
, 0) < 0)
3860 report_file_error ("Setting file position",
3861 Fcons (orig_filename
, Qnil
));
3864 while (total_read
< trial
)
3866 nread
= emacs_read (fd
, buffer
+ total_read
, trial
- total_read
);
3868 error ("IO error reading %s: %s",
3869 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
3870 else if (nread
== 0)
3872 total_read
+= nread
;
3875 /* Scan this bufferful from the end, comparing with
3876 the Emacs buffer. */
3877 bufpos
= total_read
;
3879 /* Compare with same_at_start to avoid counting some buffer text
3880 as matching both at the file's beginning and at the end. */
3881 while (bufpos
> 0 && same_at_end
> same_at_start
3882 && FETCH_BYTE (same_at_end
- 1) == buffer
[bufpos
- 1])
3883 same_at_end
--, bufpos
--;
3885 /* If we found a discrepancy, stop the scan.
3886 Otherwise loop around and scan the preceding bufferful. */
3889 /* If this discrepancy is because of code conversion,
3890 we cannot use this method; giveup and try the other. */
3891 if (same_at_end
> same_at_start
3892 && FETCH_BYTE (same_at_end
- 1) >= 0200
3893 && ! NILP (current_buffer
->enable_multibyte_characters
)
3894 && (CODING_MAY_REQUIRE_DECODING (&coding
)))
3895 giveup_match_end
= 1;
3901 if (! giveup_match_end
)
3905 /* We win! We can handle REPLACE the optimized way. */
3907 /* Extend the start of non-matching text area to multibyte
3908 character boundary. */
3909 if (! NILP (current_buffer
->enable_multibyte_characters
))
3910 while (same_at_start
> BEGV_BYTE
3911 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3914 /* Extend the end of non-matching text area to multibyte
3915 character boundary. */
3916 if (! NILP (current_buffer
->enable_multibyte_characters
))
3917 while (same_at_end
< ZV_BYTE
3918 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3921 /* Don't try to reuse the same piece of text twice. */
3922 overlap
= (same_at_start
- BEGV_BYTE
3923 - (same_at_end
+ st
.st_size
- ZV
));
3925 same_at_end
+= overlap
;
3927 /* Arrange to read only the nonmatching middle part of the file. */
3928 XSETFASTINT (beg
, XINT (beg
) + (same_at_start
- BEGV_BYTE
));
3929 XSETFASTINT (end
, XINT (end
) - (ZV_BYTE
- same_at_end
));
3931 del_range_byte (same_at_start
, same_at_end
, 0);
3932 /* Insert from the file at the proper position. */
3933 temp
= BYTE_TO_CHAR (same_at_start
);
3934 SET_PT_BOTH (temp
, same_at_start
);
3936 /* If display currently starts at beginning of line,
3937 keep it that way. */
3938 if (XBUFFER (XWINDOW (selected_window
)->buffer
) == current_buffer
)
3939 XWINDOW (selected_window
)->start_at_line_beg
= Fbolp ();
3941 replace_handled
= 1;
3945 /* If requested, replace the accessible part of the buffer
3946 with the file contents. Avoid replacing text at the
3947 beginning or end of the buffer that matches the file contents;
3948 that preserves markers pointing to the unchanged parts.
3950 Here we implement this feature for the case where code conversion
3951 is needed, in a simple way that needs a lot of memory.
3952 The preceding if-statement handles the case of no conversion
3953 in a more optimized way. */
3954 if (!NILP (replace
) && ! replace_handled
&& BEGV
< ZV
)
3956 int same_at_start
= BEGV_BYTE
;
3957 int same_at_end
= ZV_BYTE
;
3960 /* Make sure that the gap is large enough. */
3961 int bufsize
= 2 * st
.st_size
;
3962 unsigned char *conversion_buffer
= (unsigned char *) xmalloc (bufsize
);
3965 /* First read the whole file, performing code conversion into
3966 CONVERSION_BUFFER. */
3968 if (lseek (fd
, XINT (beg
), 0) < 0)
3970 xfree (conversion_buffer
);
3971 report_file_error ("Setting file position",
3972 Fcons (orig_filename
, Qnil
));
3975 total
= st
.st_size
; /* Total bytes in the file. */
3976 how_much
= 0; /* Bytes read from file so far. */
3977 inserted
= 0; /* Bytes put into CONVERSION_BUFFER so far. */
3978 unprocessed
= 0; /* Bytes not processed in previous loop. */
3980 while (how_much
< total
)
3982 /* try is reserved in some compilers (Microsoft C) */
3983 int trytry
= min (total
- how_much
, READ_BUF_SIZE
- unprocessed
);
3984 unsigned char *destination
= read_buf
+ unprocessed
;
3987 /* Allow quitting out of the actual I/O. */
3990 this = emacs_read (fd
, destination
, trytry
);
3993 if (this < 0 || this + unprocessed
== 0)
4001 if (CODING_MAY_REQUIRE_DECODING (&coding
))
4003 int require
, result
;
4005 this += unprocessed
;
4007 /* If we are using more space than estimated,
4008 make CONVERSION_BUFFER bigger. */
4009 require
= decoding_buffer_size (&coding
, this);
4010 if (inserted
+ require
+ 2 * (total
- how_much
) > bufsize
)
4012 bufsize
= inserted
+ require
+ 2 * (total
- how_much
);
4013 conversion_buffer
= (unsigned char *) xrealloc (conversion_buffer
, bufsize
);
4016 /* Convert this batch with results in CONVERSION_BUFFER. */
4017 if (how_much
>= total
) /* This is the last block. */
4018 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4019 result
= decode_coding (&coding
, read_buf
,
4020 conversion_buffer
+ inserted
,
4021 this, bufsize
- inserted
);
4023 /* Save for next iteration whatever we didn't convert. */
4024 unprocessed
= this - coding
.consumed
;
4025 bcopy (read_buf
+ coding
.consumed
, read_buf
, unprocessed
);
4026 if (!NILP (current_buffer
->enable_multibyte_characters
))
4027 this = coding
.produced
;
4029 this = str_as_unibyte (conversion_buffer
+ inserted
,
4036 /* At this point, INSERTED is how many characters (i.e. bytes)
4037 are present in CONVERSION_BUFFER.
4038 HOW_MUCH should equal TOTAL,
4039 or should be <= 0 if we couldn't read the file. */
4043 xfree (conversion_buffer
);
4046 error ("IO error reading %s: %s",
4047 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
4048 else if (how_much
== -2)
4049 error ("maximum buffer size exceeded");
4052 /* Compare the beginning of the converted file
4053 with the buffer text. */
4056 while (bufpos
< inserted
&& same_at_start
< same_at_end
4057 && FETCH_BYTE (same_at_start
) == conversion_buffer
[bufpos
])
4058 same_at_start
++, bufpos
++;
4060 /* If the file matches the buffer completely,
4061 there's no need to replace anything. */
4063 if (bufpos
== inserted
)
4065 xfree (conversion_buffer
);
4068 /* Truncate the buffer to the size of the file. */
4069 del_range_byte (same_at_start
, same_at_end
, 0);
4074 /* Extend the start of non-matching text area to multibyte
4075 character boundary. */
4076 if (! NILP (current_buffer
->enable_multibyte_characters
))
4077 while (same_at_start
> BEGV_BYTE
4078 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
4081 /* Scan this bufferful from the end, comparing with
4082 the Emacs buffer. */
4085 /* Compare with same_at_start to avoid counting some buffer text
4086 as matching both at the file's beginning and at the end. */
4087 while (bufpos
> 0 && same_at_end
> same_at_start
4088 && FETCH_BYTE (same_at_end
- 1) == conversion_buffer
[bufpos
- 1])
4089 same_at_end
--, bufpos
--;
4091 /* Extend the end of non-matching text area to multibyte
4092 character boundary. */
4093 if (! NILP (current_buffer
->enable_multibyte_characters
))
4094 while (same_at_end
< ZV_BYTE
4095 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
4098 /* Don't try to reuse the same piece of text twice. */
4099 overlap
= same_at_start
- BEGV_BYTE
- (same_at_end
+ inserted
- ZV_BYTE
);
4101 same_at_end
+= overlap
;
4103 /* If display currently starts at beginning of line,
4104 keep it that way. */
4105 if (XBUFFER (XWINDOW (selected_window
)->buffer
) == current_buffer
)
4106 XWINDOW (selected_window
)->start_at_line_beg
= Fbolp ();
4108 /* Replace the chars that we need to replace,
4109 and update INSERTED to equal the number of bytes
4110 we are taking from the file. */
4111 inserted
-= (Z_BYTE
- same_at_end
) + (same_at_start
- BEG_BYTE
);
4113 if (same_at_end
!= same_at_start
)
4115 del_range_byte (same_at_start
, same_at_end
, 0);
4117 same_at_start
= GPT_BYTE
;
4121 temp
= BYTE_TO_CHAR (same_at_start
);
4123 /* Insert from the file at the proper position. */
4124 SET_PT_BOTH (temp
, same_at_start
);
4125 insert_1 (conversion_buffer
+ same_at_start
- BEG_BYTE
, inserted
,
4127 /* Set `inserted' to the number of inserted characters. */
4128 inserted
= PT
- temp
;
4130 xfree (conversion_buffer
);
4139 register Lisp_Object temp
;
4141 total
= XINT (end
) - XINT (beg
);
4143 /* Make sure point-max won't overflow after this insertion. */
4144 XSETINT (temp
, total
);
4145 if (total
!= XINT (temp
))
4146 error ("Maximum buffer size exceeded");
4149 /* For a special file, all we can do is guess. */
4150 total
= READ_BUF_SIZE
;
4152 if (NILP (visit
) && total
> 0)
4153 prepare_to_modify_buffer (PT
, PT
, NULL
);
4156 if (GAP_SIZE
< total
)
4157 make_gap (total
- GAP_SIZE
);
4159 if (XINT (beg
) != 0 || !NILP (replace
))
4161 if (lseek (fd
, XINT (beg
), 0) < 0)
4162 report_file_error ("Setting file position",
4163 Fcons (orig_filename
, Qnil
));
4166 /* In the following loop, HOW_MUCH contains the total bytes read so
4167 far for a regular file, and not changed for a special file. But,
4168 before exiting the loop, it is set to a negative value if I/O
4172 /* Total bytes inserted. */
4175 /* Here, we don't do code conversion in the loop. It is done by
4176 code_convert_region after all data are read into the buffer. */
4178 int gap_size
= GAP_SIZE
;
4180 while (how_much
< total
)
4182 /* try is reserved in some compilers (Microsoft C) */
4183 int trytry
= min (total
- how_much
, READ_BUF_SIZE
);
4190 /* Maybe make more room. */
4191 if (gap_size
< trytry
)
4193 make_gap (total
- gap_size
);
4194 gap_size
= GAP_SIZE
;
4197 /* Read from the file, capturing `quit'. When an
4198 error occurs, end the loop, and arrange for a quit
4199 to be signaled after decoding the text we read. */
4200 non_regular_fd
= fd
;
4201 non_regular_inserted
= inserted
;
4202 non_regular_nbytes
= trytry
;
4203 val
= internal_condition_case_1 (read_non_regular
, Qnil
, Qerror
,
4204 read_non_regular_quit
);
4215 /* Allow quitting out of the actual I/O. We don't make text
4216 part of the buffer until all the reading is done, so a C-g
4217 here doesn't do any harm. */
4220 this = emacs_read (fd
, BEG_ADDR
+ PT_BYTE
- 1 + inserted
, trytry
);
4232 /* For a regular file, where TOTAL is the real size,
4233 count HOW_MUCH to compare with it.
4234 For a special file, where TOTAL is just a buffer size,
4235 so don't bother counting in HOW_MUCH.
4236 (INSERTED is where we count the number of characters inserted.) */
4243 /* Make the text read part of the buffer. */
4244 GAP_SIZE
-= inserted
;
4246 GPT_BYTE
+= inserted
;
4248 ZV_BYTE
+= inserted
;
4253 /* Put an anchor to ensure multi-byte form ends at gap. */
4258 /* Discard the unwind protect for closing the file. */
4262 error ("IO error reading %s: %s",
4263 XSTRING (orig_filename
)->data
, emacs_strerror (errno
));
4267 if (! coding_system_decided
)
4269 /* The coding system is not yet decided. Decide it by an
4270 optimized method for handling `coding:' tag.
4272 Note that we can get here only if the buffer was empty
4273 before the insertion. */
4277 if (!NILP (Vcoding_system_for_read
))
4278 val
= Vcoding_system_for_read
;
4281 /* Since we are sure that the current buffer was empty
4282 before the insertion, we can toggle
4283 enable-multibyte-characters directly here without taking
4284 care of marker adjustment and byte combining problem. By
4285 this way, we can run Lisp program safely before decoding
4286 the inserted text. */
4287 Lisp_Object unwind_data
;
4288 int count
= specpdl_ptr
- specpdl
;
4290 unwind_data
= Fcons (current_buffer
->enable_multibyte_characters
,
4291 Fcons (current_buffer
->undo_list
,
4292 Fcurrent_buffer ()));
4293 current_buffer
->enable_multibyte_characters
= Qnil
;
4294 current_buffer
->undo_list
= Qt
;
4295 record_unwind_protect (decide_coding_unwind
, unwind_data
);
4297 if (inserted
> 0 && ! NILP (Vset_auto_coding_function
))
4299 val
= call2 (Vset_auto_coding_function
,
4300 filename
, make_number (inserted
));
4305 /* If the coding system is not yet decided, check
4306 file-coding-system-alist. */
4307 Lisp_Object args
[6], coding_systems
;
4309 args
[0] = Qinsert_file_contents
, args
[1] = orig_filename
;
4310 args
[2] = visit
, args
[3] = beg
, args
[4] = end
, args
[5] = Qnil
;
4311 coding_systems
= Ffind_operation_coding_system (6, args
);
4312 if (CONSP (coding_systems
))
4313 val
= XCAR (coding_systems
);
4316 unbind_to (count
, Qnil
);
4317 inserted
= Z_BYTE
- BEG_BYTE
;
4320 /* The following kludgy code is to avoid some compiler bug.
4322 setup_coding_system (val, &coding);
4325 struct coding_system temp_coding
;
4326 setup_coding_system (val
, &temp_coding
);
4327 bcopy (&temp_coding
, &coding
, sizeof coding
);
4329 /* Ensure we set Vlast_coding_system_used. */
4330 set_coding_system
= 1;
4332 if (NILP (current_buffer
->enable_multibyte_characters
)
4334 /* We must suppress all character code conversion except for
4335 end-of-line conversion. */
4336 setup_raw_text_coding_system (&coding
);
4337 coding
.src_multibyte
= 0;
4338 coding
.dst_multibyte
4339 = !NILP (current_buffer
->enable_multibyte_characters
);
4343 && (coding
.type
== coding_type_no_conversion
4344 || coding
.type
== coding_type_raw_text
))
4346 /* Visiting a file with these coding systems should always make
4347 the buffer unibyte. If we happen to be replacing text in a
4348 multibyte buffer (this happens when reverting an RMAIL
4349 buffer), positions in the buffer, markers etc. may have byte
4350 positions != character positions, so just setting
4351 enable_multibyte_characters to nil doesn't suffice. */
4353 && !NILP (current_buffer
->enable_multibyte_characters
))
4354 Fset_buffer_multibyte (Qnil
);
4356 current_buffer
->enable_multibyte_characters
= Qnil
;
4357 coding
.dst_multibyte
= 0;
4360 if (inserted
> 0 || coding
.type
== coding_type_ccl
)
4362 if (CODING_MAY_REQUIRE_DECODING (&coding
))
4364 code_convert_region (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4366 inserted
= coding
.produced_char
;
4369 adjust_after_insert (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4374 /* Use the conversion type to determine buffer-file-type
4375 (find-buffer-file-type is now used to help determine the
4377 if ((coding
.eol_type
== CODING_EOL_UNDECIDED
4378 || coding
.eol_type
== CODING_EOL_LF
)
4379 && ! CODING_REQUIRE_DECODING (&coding
))
4380 current_buffer
->buffer_file_type
= Qt
;
4382 current_buffer
->buffer_file_type
= Qnil
;
4389 if (!EQ (current_buffer
->undo_list
, Qt
))
4390 current_buffer
->undo_list
= Qnil
;
4392 stat (XSTRING (filename
)->data
, &st
);
4397 current_buffer
->modtime
= st
.st_mtime
;
4398 current_buffer
->filename
= orig_filename
;
4401 SAVE_MODIFF
= MODIFF
;
4402 current_buffer
->auto_save_modified
= MODIFF
;
4403 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
4404 #ifdef CLASH_DETECTION
4407 if (!NILP (current_buffer
->file_truename
))
4408 unlock_file (current_buffer
->file_truename
);
4409 unlock_file (filename
);
4411 #endif /* CLASH_DETECTION */
4413 Fsignal (Qfile_error
,
4414 Fcons (build_string ("not a regular file"),
4415 Fcons (orig_filename
, Qnil
)));
4418 /* Decode file format */
4421 int empty_undo_list_p
= 0;
4423 /* If we're anyway going to discard undo information, don't
4424 record it in the first place. The buffer's undo list at this
4425 point is either nil or t when visiting a file. */
4428 empty_undo_list_p
= NILP (current_buffer
->undo_list
);
4429 current_buffer
->undo_list
= Qt
;
4432 insval
= call3 (Qformat_decode
,
4433 Qnil
, make_number (inserted
), visit
);
4434 CHECK_NUMBER (insval
, 0);
4435 inserted
= XFASTINT (insval
);
4438 current_buffer
->undo_list
= empty_undo_list_p
? Qnil
: Qt
;
4441 if (set_coding_system
)
4442 Vlast_coding_system_used
= coding
.symbol
;
4444 /* Call after-change hooks for the inserted text, aside from the case
4445 of normal visiting (not with REPLACE), which is done in a new buffer
4446 "before" the buffer is changed. */
4447 if (inserted
> 0 && total
> 0
4448 && (NILP (visit
) || !NILP (replace
)))
4450 signal_after_change (PT
, 0, inserted
);
4451 update_compositions (PT
, PT
, CHECK_BORDER
);
4454 p
= Vafter_insert_file_functions
;
4457 insval
= call1 (Fcar (p
), make_number (inserted
));
4460 CHECK_NUMBER (insval
, 0);
4461 inserted
= XFASTINT (insval
);
4468 && current_buffer
->modtime
== -1)
4470 /* If visiting nonexistent file, return nil. */
4471 report_file_error ("Opening input file", Fcons (orig_filename
, Qnil
));
4475 Fsignal (Qquit
, Qnil
);
4477 /* ??? Retval needs to be dealt with in all cases consistently. */
4479 val
= Fcons (orig_filename
,
4480 Fcons (make_number (inserted
),
4483 RETURN_UNGCPRO (unbind_to (count
, val
));
4486 static Lisp_Object build_annotations
P_ ((Lisp_Object
, Lisp_Object
,
4489 /* If build_annotations switched buffers, switch back to BUF.
4490 Kill the temporary buffer that was selected in the meantime.
4492 Since this kill only the last temporary buffer, some buffers remain
4493 not killed if build_annotations switched buffers more than once.
4497 build_annotations_unwind (buf
)
4502 if (XBUFFER (buf
) == current_buffer
)
4504 tembuf
= Fcurrent_buffer ();
4506 Fkill_buffer (tembuf
);
4510 DEFUN ("write-region", Fwrite_region
, Swrite_region
, 3, 7,
4511 "r\nFWrite region to file: \ni\ni\ni\np",
4512 "Write current region into specified file.\n\
4513 When called from a program, takes three arguments:\n\
4514 START, END and FILENAME. START and END are buffer positions.\n\
4515 Optional fourth argument APPEND if non-nil means\n\
4516 append to existing file contents (if any). If it is an integer,\n\
4517 seek to that offset in the file before writing.\n\
4518 Optional fifth argument VISIT if t means\n\
4519 set the last-save-file-modtime of buffer to this file's modtime\n\
4520 and mark buffer not modified.\n\
4521 If VISIT is a string, it is a second file name;\n\
4522 the output goes to FILENAME, but the buffer is marked as visiting VISIT.\n\
4523 VISIT is also the file name to lock and unlock for clash detection.\n\
4524 If VISIT is neither t nor nil nor a string,\n\
4525 that means do not print the \"Wrote file\" message.\n\
4526 The optional sixth arg LOCKNAME, if non-nil, specifies the name to\n\
4527 use for locking and unlocking, overriding FILENAME and VISIT.\n\
4528 The optional seventh arg MUSTBENEW, if non-nil, insists on a check\n\
4529 for an existing file with the same name. If MUSTBENEW is `excl',\n\
4530 that means to get an error if the file already exists; never overwrite.\n\
4531 If MUSTBENEW is neither nil nor `excl', that means ask for\n\
4532 confirmation before overwriting, but do go ahead and overwrite the file\n\
4533 if the user confirms.\n\
4534 Kludgy feature: if START is a string, then that string is written\n\
4535 to the file, instead of any buffer contents, and END is ignored.\n\
4537 This does code conversion according to the value of\n\
4538 `coding-system-for-write', `buffer-file-coding-system', or\n\
4539 `file-coding-system-alist', and sets the variable\n\
4540 `last-coding-system-used' to the coding system actually used.")
4542 (start
, end
, filename
, append
, visit
, lockname
, mustbenew
)
4543 Lisp_Object start
, end
, filename
, append
, visit
, lockname
, mustbenew
;
4551 int count
= specpdl_ptr
- specpdl
;
4554 unsigned char *fname
= 0; /* If non-0, original filename (must rename) */
4556 Lisp_Object handler
;
4557 Lisp_Object visit_file
;
4558 Lisp_Object annotations
;
4559 Lisp_Object encoded_filename
;
4560 int visiting
= (EQ (visit
, Qt
) || STRINGP (visit
));
4561 int quietly
= !NILP (visit
);
4562 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
4563 struct buffer
*given_buffer
;
4565 int buffer_file_type
= O_BINARY
;
4567 struct coding_system coding
;
4569 if (current_buffer
->base_buffer
&& visiting
)
4570 error ("Cannot do file visiting in an indirect buffer");
4572 if (!NILP (start
) && !STRINGP (start
))
4573 validate_region (&start
, &end
);
4575 GCPRO4 (start
, filename
, visit
, lockname
);
4577 /* Decide the coding-system to encode the data with. */
4583 else if (!NILP (Vcoding_system_for_write
))
4584 val
= Vcoding_system_for_write
;
4587 /* If the variable `buffer-file-coding-system' is set locally,
4588 it means that the file was read with some kind of code
4589 conversion or the variable is explicitly set by users. We
4590 had better write it out with the same coding system even if
4591 `enable-multibyte-characters' is nil.
4593 If it is not set locally, we anyway have to convert EOL
4594 format if the default value of `buffer-file-coding-system'
4595 tells that it is not Unix-like (LF only) format. */
4596 int using_default_coding
= 0;
4597 int force_raw_text
= 0;
4599 val
= current_buffer
->buffer_file_coding_system
;
4601 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4604 if (NILP (current_buffer
->enable_multibyte_characters
))
4610 /* Check file-coding-system-alist. */
4611 Lisp_Object args
[7], coding_systems
;
4613 args
[0] = Qwrite_region
; args
[1] = start
; args
[2] = end
;
4614 args
[3] = filename
; args
[4] = append
; args
[5] = visit
;
4616 coding_systems
= Ffind_operation_coding_system (7, args
);
4617 if (CONSP (coding_systems
) && !NILP (XCDR (coding_systems
)))
4618 val
= XCDR (coding_systems
);
4622 && !NILP (current_buffer
->buffer_file_coding_system
))
4624 /* If we still have not decided a coding system, use the
4625 default value of buffer-file-coding-system. */
4626 val
= current_buffer
->buffer_file_coding_system
;
4627 using_default_coding
= 1;
4631 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4632 /* Confirm that VAL can surely encode the current region. */
4633 val
= call3 (Vselect_safe_coding_system_function
, start
, end
, val
);
4635 setup_coding_system (Fcheck_coding_system (val
), &coding
);
4636 if (coding
.eol_type
== CODING_EOL_UNDECIDED
4637 && !using_default_coding
)
4639 if (! EQ (default_buffer_file_coding
.symbol
,
4640 buffer_defaults
.buffer_file_coding_system
))
4641 setup_coding_system (buffer_defaults
.buffer_file_coding_system
,
4642 &default_buffer_file_coding
);
4643 if (default_buffer_file_coding
.eol_type
!= CODING_EOL_UNDECIDED
)
4645 Lisp_Object subsidiaries
;
4647 coding
.eol_type
= default_buffer_file_coding
.eol_type
;
4648 subsidiaries
= Fget (coding
.symbol
, Qeol_type
);
4649 if (VECTORP (subsidiaries
)
4650 && XVECTOR (subsidiaries
)->size
== 3)
4652 = XVECTOR (subsidiaries
)->contents
[coding
.eol_type
];
4657 setup_raw_text_coding_system (&coding
);
4658 goto done_setup_coding
;
4661 setup_coding_system (Fcheck_coding_system (val
), &coding
);
4664 if (!STRINGP (start
) && !NILP (current_buffer
->selective_display
))
4665 coding
.mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
4668 Vlast_coding_system_used
= coding
.symbol
;
4670 filename
= Fexpand_file_name (filename
, Qnil
);
4672 if (! NILP (mustbenew
) && !EQ (mustbenew
, Qexcl
))
4673 barf_or_query_if_file_exists (filename
, "overwrite", 1, 0, 1);
4675 if (STRINGP (visit
))
4676 visit_file
= Fexpand_file_name (visit
, Qnil
);
4678 visit_file
= filename
;
4683 if (NILP (lockname
))
4684 lockname
= visit_file
;
4686 GCPRO5 (start
, filename
, annotations
, visit_file
, lockname
);
4688 /* If the file name has special constructs in it,
4689 call the corresponding file handler. */
4690 handler
= Ffind_file_name_handler (filename
, Qwrite_region
);
4691 /* If FILENAME has no handler, see if VISIT has one. */
4692 if (NILP (handler
) && STRINGP (visit
))
4693 handler
= Ffind_file_name_handler (visit
, Qwrite_region
);
4695 if (!NILP (handler
))
4698 val
= call6 (handler
, Qwrite_region
, start
, end
,
4699 filename
, append
, visit
);
4703 SAVE_MODIFF
= MODIFF
;
4704 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
4705 current_buffer
->filename
= visit_file
;
4711 /* Special kludge to simplify auto-saving. */
4714 XSETFASTINT (start
, BEG
);
4715 XSETFASTINT (end
, Z
);
4718 record_unwind_protect (build_annotations_unwind
, Fcurrent_buffer ());
4719 count1
= specpdl_ptr
- specpdl
;
4721 given_buffer
= current_buffer
;
4722 annotations
= build_annotations (start
, end
, coding
.pre_write_conversion
);
4723 if (current_buffer
!= given_buffer
)
4725 XSETFASTINT (start
, BEGV
);
4726 XSETFASTINT (end
, ZV
);
4729 #ifdef CLASH_DETECTION
4732 #if 0 /* This causes trouble for GNUS. */
4733 /* If we've locked this file for some other buffer,
4734 query before proceeding. */
4735 if (!visiting
&& EQ (Ffile_locked_p (lockname
), Qt
))
4736 call2 (intern ("ask-user-about-lock"), filename
, Vuser_login_name
);
4739 lock_file (lockname
);
4741 #endif /* CLASH_DETECTION */
4743 encoded_filename
= ENCODE_FILE (filename
);
4745 fn
= XSTRING (encoded_filename
)->data
;
4749 desc
= emacs_open (fn
, O_WRONLY
| buffer_file_type
, 0);
4750 #else /* not DOS_NT */
4751 desc
= emacs_open (fn
, O_WRONLY
, 0);
4752 #endif /* not DOS_NT */
4754 if (desc
< 0 && (NILP (append
) || errno
== ENOENT
))
4756 if (auto_saving
) /* Overwrite any previous version of autosave file */
4758 vms_truncate (fn
); /* if fn exists, truncate to zero length */
4759 desc
= emacs_open (fn
, O_RDWR
, 0);
4761 desc
= creat_copy_attrs (STRINGP (current_buffer
->filename
)
4762 ? XSTRING (current_buffer
->filename
)->data
: 0,
4765 else /* Write to temporary name and rename if no errors */
4767 Lisp_Object temp_name
;
4768 temp_name
= Ffile_name_directory (filename
);
4770 if (!NILP (temp_name
))
4772 temp_name
= Fmake_temp_name (concat2 (temp_name
,
4773 build_string ("$$SAVE$$")));
4774 fname
= XSTRING (filename
)->data
;
4775 fn
= XSTRING (temp_name
)->data
;
4776 desc
= creat_copy_attrs (fname
, fn
);
4779 /* If we can't open the temporary file, try creating a new
4780 version of the original file. VMS "creat" creates a
4781 new version rather than truncating an existing file. */
4784 desc
= creat (fn
, 0666);
4785 #if 0 /* This can clobber an existing file and fail to replace it,
4786 if the user runs out of space. */
4789 /* We can't make a new version;
4790 try to truncate and rewrite existing version if any. */
4792 desc
= emacs_open (fn
, O_RDWR
, 0);
4798 desc
= creat (fn
, 0666);
4802 desc
= emacs_open (fn
,
4803 O_WRONLY
| O_CREAT
| buffer_file_type
4804 | (EQ (mustbenew
, Qexcl
) ? O_EXCL
: O_TRUNC
),
4805 S_IREAD
| S_IWRITE
);
4806 #else /* not DOS_NT */
4807 desc
= emacs_open (fn
, O_WRONLY
| O_TRUNC
| O_CREAT
4808 | (EQ (mustbenew
, Qexcl
) ? O_EXCL
: 0),
4809 auto_saving
? auto_save_mode_bits
: 0666);
4810 #endif /* not DOS_NT */
4811 #endif /* not VMS */
4815 #ifdef CLASH_DETECTION
4817 if (!auto_saving
) unlock_file (lockname
);
4819 #endif /* CLASH_DETECTION */
4821 report_file_error ("Opening output file", Fcons (filename
, Qnil
));
4824 record_unwind_protect (close_file_unwind
, make_number (desc
));
4826 if (!NILP (append
) && !NILP (Ffile_regular_p (filename
)))
4830 if (NUMBERP (append
))
4831 ret
= lseek (desc
, XINT (append
), 1);
4833 ret
= lseek (desc
, 0, 2);
4836 #ifdef CLASH_DETECTION
4837 if (!auto_saving
) unlock_file (lockname
);
4838 #endif /* CLASH_DETECTION */
4840 report_file_error ("Lseek error", Fcons (filename
, Qnil
));
4848 * Kludge Warning: The VMS C RTL likes to insert carriage returns
4849 * if we do writes that don't end with a carriage return. Furthermore
4850 * it cannot handle writes of more then 16K. The modified
4851 * version of "sys_write" in SYSDEP.C (see comment there) copes with
4852 * this EXCEPT for the last record (iff it doesn't end with a carriage
4853 * return). This implies that if your buffer doesn't end with a carriage
4854 * return, you get one free... tough. However it also means that if
4855 * we make two calls to sys_write (a la the following code) you can
4856 * get one at the gap as well. The easiest way to fix this (honest)
4857 * is to move the gap to the next newline (or the end of the buffer).
4862 if (GPT
> BEG
&& GPT_ADDR
[-1] != '\n')
4863 move_gap (find_next_newline (GPT
, 1));
4865 /* Whether VMS or not, we must move the gap to the next of newline
4866 when we must put designation sequences at beginning of line. */
4867 if (INTEGERP (start
)
4868 && coding
.type
== coding_type_iso2022
4869 && coding
.flags
& CODING_FLAG_ISO_DESIGNATE_AT_BOL
4870 && GPT
> BEG
&& GPT_ADDR
[-1] != '\n')
4872 int opoint
= PT
, opoint_byte
= PT_BYTE
;
4873 scan_newline (PT
, PT_BYTE
, ZV
, ZV_BYTE
, 1, 0);
4874 move_gap_both (PT
, PT_BYTE
);
4875 SET_PT_BOTH (opoint
, opoint_byte
);
4882 if (STRINGP (start
))
4884 failure
= 0 > a_write (desc
, start
, 0, XSTRING (start
)->size
,
4885 &annotations
, &coding
);
4888 else if (XINT (start
) != XINT (end
))
4890 tem
= CHAR_TO_BYTE (XINT (start
));
4892 if (XINT (start
) < GPT
)
4894 failure
= 0 > a_write (desc
, Qnil
, XINT (start
),
4895 min (GPT
, XINT (end
)) - XINT (start
),
4896 &annotations
, &coding
);
4900 if (XINT (end
) > GPT
&& !failure
)
4902 tem
= max (XINT (start
), GPT
);
4903 failure
= 0 > a_write (desc
, Qnil
, tem
, XINT (end
) - tem
,
4904 &annotations
, &coding
);
4910 /* If file was empty, still need to write the annotations */
4911 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4912 failure
= 0 > a_write (desc
, Qnil
, XINT (end
), 0, &annotations
, &coding
);
4916 if (CODING_REQUIRE_FLUSHING (&coding
)
4917 && !(coding
.mode
& CODING_MODE_LAST_BLOCK
)
4920 /* We have to flush out a data. */
4921 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4922 failure
= 0 > e_write (desc
, Qnil
, 0, 0, &coding
);
4929 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4930 Disk full in NFS may be reported here. */
4931 /* mib says that closing the file will try to write as fast as NFS can do
4932 it, and that means the fsync here is not crucial for autosave files. */
4933 if (!auto_saving
&& fsync (desc
) < 0)
4935 /* If fsync fails with EINTR, don't treat that as serious. */
4937 failure
= 1, save_errno
= errno
;
4941 /* Spurious "file has changed on disk" warnings have been
4942 observed on Suns as well.
4943 It seems that `close' can change the modtime, under nfs.
4945 (This has supposedly been fixed in Sunos 4,
4946 but who knows about all the other machines with NFS?) */
4949 /* On VMS and APOLLO, must do the stat after the close
4950 since closing changes the modtime. */
4953 /* Recall that #if defined does not work on VMS. */
4960 /* NFS can report a write failure now. */
4961 if (emacs_close (desc
) < 0)
4962 failure
= 1, save_errno
= errno
;
4965 /* If we wrote to a temporary name and had no errors, rename to real name. */
4969 failure
= (rename (fn
, fname
) != 0), save_errno
= errno
;
4977 /* Discard the unwind protect for close_file_unwind. */
4978 specpdl_ptr
= specpdl
+ count1
;
4979 /* Restore the original current buffer. */
4980 visit_file
= unbind_to (count
, visit_file
);
4982 #ifdef CLASH_DETECTION
4984 unlock_file (lockname
);
4985 #endif /* CLASH_DETECTION */
4987 /* Do this before reporting IO error
4988 to avoid a "file has changed on disk" warning on
4989 next attempt to save. */
4991 current_buffer
->modtime
= st
.st_mtime
;
4994 error ("IO error writing %s: %s", XSTRING (filename
)->data
,
4995 emacs_strerror (save_errno
));
4999 SAVE_MODIFF
= MODIFF
;
5000 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
5001 current_buffer
->filename
= visit_file
;
5002 update_mode_lines
++;
5008 message_with_string ("Wrote %s", visit_file
, 1);
5013 Lisp_Object
merge ();
5015 DEFUN ("car-less-than-car", Fcar_less_than_car
, Scar_less_than_car
, 2, 2, 0,
5016 "Return t if (car A) is numerically less than (car B).")
5020 return Flss (Fcar (a
), Fcar (b
));
5023 /* Build the complete list of annotations appropriate for writing out
5024 the text between START and END, by calling all the functions in
5025 write-region-annotate-functions and merging the lists they return.
5026 If one of these functions switches to a different buffer, we assume
5027 that buffer contains altered text. Therefore, the caller must
5028 make sure to restore the current buffer in all cases,
5029 as save-excursion would do. */
5032 build_annotations (start
, end
, pre_write_conversion
)
5033 Lisp_Object start
, end
, pre_write_conversion
;
5035 Lisp_Object annotations
;
5037 struct gcpro gcpro1
, gcpro2
;
5038 Lisp_Object original_buffer
;
5041 XSETBUFFER (original_buffer
, current_buffer
);
5044 p
= Vwrite_region_annotate_functions
;
5045 GCPRO2 (annotations
, p
);
5048 struct buffer
*given_buffer
= current_buffer
;
5049 Vwrite_region_annotations_so_far
= annotations
;
5050 res
= call2 (Fcar (p
), start
, end
);
5051 /* If the function makes a different buffer current,
5052 assume that means this buffer contains altered text to be output.
5053 Reset START and END from the buffer bounds
5054 and discard all previous annotations because they should have
5055 been dealt with by this function. */
5056 if (current_buffer
!= given_buffer
)
5058 XSETFASTINT (start
, BEGV
);
5059 XSETFASTINT (end
, ZV
);
5062 Flength (res
); /* Check basic validity of return value */
5063 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5067 /* Now do the same for annotation functions implied by the file-format */
5068 if (auto_saving
&& (!EQ (Vauto_save_file_format
, Qt
)))
5069 p
= Vauto_save_file_format
;
5071 p
= current_buffer
->file_format
;
5072 for (i
= 0; !NILP (p
); p
= Fcdr (p
), ++i
)
5074 struct buffer
*given_buffer
= current_buffer
;
5076 Vwrite_region_annotations_so_far
= annotations
;
5078 /* Value is either a list of annotations or nil if the function
5079 has written annotations to a temporary buffer, which is now
5081 res
= call5 (Qformat_annotate_function
, Fcar (p
), start
, end
,
5082 original_buffer
, make_number (i
));
5083 if (current_buffer
!= given_buffer
)
5085 XSETFASTINT (start
, BEGV
);
5086 XSETFASTINT (end
, ZV
);
5091 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5094 /* At last, do the same for the function PRE_WRITE_CONVERSION
5095 implied by the current coding-system. */
5096 if (!NILP (pre_write_conversion
))
5098 struct buffer
*given_buffer
= current_buffer
;
5099 Vwrite_region_annotations_so_far
= annotations
;
5100 res
= call2 (pre_write_conversion
, start
, end
);
5102 annotations
= (current_buffer
!= given_buffer
5104 : merge (annotations
, res
, Qcar_less_than_car
));
5111 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5112 If STRING is nil, POS is the character position in the current buffer.
5113 Intersperse with them the annotations from *ANNOT
5114 which fall within the range of POS to POS + NCHARS,
5115 each at its appropriate position.
5117 We modify *ANNOT by discarding elements as we use them up.
5119 The return value is negative in case of system call failure. */
5122 a_write (desc
, string
, pos
, nchars
, annot
, coding
)
5125 register int nchars
;
5128 struct coding_system
*coding
;
5132 int lastpos
= pos
+ nchars
;
5134 while (NILP (*annot
) || CONSP (*annot
))
5136 tem
= Fcar_safe (Fcar (*annot
));
5139 nextpos
= XFASTINT (tem
);
5141 /* If there are no more annotations in this range,
5142 output the rest of the range all at once. */
5143 if (! (nextpos
>= pos
&& nextpos
<= lastpos
))
5144 return e_write (desc
, string
, pos
, lastpos
, coding
);
5146 /* Output buffer text up to the next annotation's position. */
5149 if (0 > e_write (desc
, string
, pos
, nextpos
, coding
))
5153 /* Output the annotation. */
5154 tem
= Fcdr (Fcar (*annot
));
5157 if (0 > e_write (desc
, tem
, 0, XSTRING (tem
)->size
, coding
))
5160 *annot
= Fcdr (*annot
);
5165 #ifndef WRITE_BUF_SIZE
5166 #define WRITE_BUF_SIZE (16 * 1024)
5169 /* Write text in the range START and END into descriptor DESC,
5170 encoding them with coding system CODING. If STRING is nil, START
5171 and END are character positions of the current buffer, else they
5172 are indexes to the string STRING. */
5175 e_write (desc
, string
, start
, end
, coding
)
5179 struct coding_system
*coding
;
5181 register char *addr
;
5182 register int nbytes
;
5183 char buf
[WRITE_BUF_SIZE
];
5187 coding
->composing
= COMPOSITION_DISABLED
;
5188 if (coding
->composing
!= COMPOSITION_DISABLED
)
5189 coding_save_composition (coding
, start
, end
, string
);
5191 if (STRINGP (string
))
5193 addr
= XSTRING (string
)->data
;
5194 nbytes
= STRING_BYTES (XSTRING (string
));
5195 coding
->src_multibyte
= STRING_MULTIBYTE (string
);
5197 else if (start
< end
)
5199 /* It is assured that the gap is not in the range START and END-1. */
5200 addr
= CHAR_POS_ADDR (start
);
5201 nbytes
= CHAR_TO_BYTE (end
) - CHAR_TO_BYTE (start
);
5202 coding
->src_multibyte
5203 = !NILP (current_buffer
->enable_multibyte_characters
);
5209 coding
->src_multibyte
= 1;
5212 /* We used to have a code for handling selective display here. But,
5213 now it is handled within encode_coding. */
5218 result
= encode_coding (coding
, addr
, buf
, nbytes
, WRITE_BUF_SIZE
);
5219 if (coding
->produced
> 0)
5221 coding
->produced
-= emacs_write (desc
, buf
, coding
->produced
);
5222 if (coding
->produced
)
5228 nbytes
-= coding
->consumed
;
5229 addr
+= coding
->consumed
;
5230 if (result
== CODING_FINISH_INSUFFICIENT_SRC
5233 /* The source text ends by an incomplete multibyte form.
5234 There's no way other than write it out as is. */
5235 nbytes
-= emacs_write (desc
, addr
, nbytes
);
5244 start
+= coding
->consumed_char
;
5245 if (coding
->cmp_data
)
5246 coding_adjust_composition_offset (coding
, start
);
5249 if (coding
->cmp_data
)
5250 coding_free_composition_data (coding
);
5255 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime
,
5256 Sverify_visited_file_modtime
, 1, 1, 0,
5257 "Return t if last mod time of BUF's visited file matches what BUF records.\n\
5258 This means that the file has not been changed since it was visited or saved.")
5264 Lisp_Object handler
;
5265 Lisp_Object filename
;
5267 CHECK_BUFFER (buf
, 0);
5270 if (!STRINGP (b
->filename
)) return Qt
;
5271 if (b
->modtime
== 0) return Qt
;
5273 /* If the file name has special constructs in it,
5274 call the corresponding file handler. */
5275 handler
= Ffind_file_name_handler (b
->filename
,
5276 Qverify_visited_file_modtime
);
5277 if (!NILP (handler
))
5278 return call2 (handler
, Qverify_visited_file_modtime
, buf
);
5280 filename
= ENCODE_FILE (b
->filename
);
5282 if (stat (XSTRING (filename
)->data
, &st
) < 0)
5284 /* If the file doesn't exist now and didn't exist before,
5285 we say that it isn't modified, provided the error is a tame one. */
5286 if (errno
== ENOENT
|| errno
== EACCES
|| errno
== ENOTDIR
)
5291 if (st
.st_mtime
== b
->modtime
5292 /* If both are positive, accept them if they are off by one second. */
5293 || (st
.st_mtime
> 0 && b
->modtime
> 0
5294 && (st
.st_mtime
== b
->modtime
+ 1
5295 || st
.st_mtime
== b
->modtime
- 1)))
5300 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime
,
5301 Sclear_visited_file_modtime
, 0, 0, 0,
5302 "Clear out records of last mod time of visited file.\n\
5303 Next attempt to save will certainly not complain of a discrepancy.")
5306 current_buffer
->modtime
= 0;
5310 DEFUN ("visited-file-modtime", Fvisited_file_modtime
,
5311 Svisited_file_modtime
, 0, 0, 0,
5312 "Return the current buffer's recorded visited file modification time.\n\
5313 The value is a list of the form (HIGH . LOW), like the time values\n\
5314 that `file-attributes' returns.")
5317 return long_to_cons ((unsigned long) current_buffer
->modtime
);
5320 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime
,
5321 Sset_visited_file_modtime
, 0, 1, 0,
5322 "Update buffer's recorded modification time from the visited file's time.\n\
5323 Useful if the buffer was not read from the file normally\n\
5324 or if the file itself has been changed for some known benign reason.\n\
5325 An argument specifies the modification time value to use\n\
5326 \(instead of that of the visited file), in the form of a list\n\
5327 \(HIGH . LOW) or (HIGH LOW).")
5329 Lisp_Object time_list
;
5331 if (!NILP (time_list
))
5332 current_buffer
->modtime
= cons_to_long (time_list
);
5335 register Lisp_Object filename
;
5337 Lisp_Object handler
;
5339 filename
= Fexpand_file_name (current_buffer
->filename
, Qnil
);
5341 /* If the file name has special constructs in it,
5342 call the corresponding file handler. */
5343 handler
= Ffind_file_name_handler (filename
, Qset_visited_file_modtime
);
5344 if (!NILP (handler
))
5345 /* The handler can find the file name the same way we did. */
5346 return call2 (handler
, Qset_visited_file_modtime
, Qnil
);
5348 filename
= ENCODE_FILE (filename
);
5350 if (stat (XSTRING (filename
)->data
, &st
) >= 0)
5351 current_buffer
->modtime
= st
.st_mtime
;
5358 auto_save_error (error
)
5361 Lisp_Object args
[3], msg
;
5363 struct gcpro gcpro1
;
5367 args
[0] = build_string ("Auto-saving %s: %s");
5368 args
[1] = current_buffer
->name
;
5369 args
[2] = Ferror_message_string (error
);
5370 msg
= Fformat (3, args
);
5372 nbytes
= STRING_BYTES (XSTRING (msg
));
5374 for (i
= 0; i
< 3; ++i
)
5377 message2 (XSTRING (msg
)->data
, nbytes
, STRING_MULTIBYTE (msg
));
5379 message2_nolog (XSTRING (msg
)->data
, nbytes
, STRING_MULTIBYTE (msg
));
5380 Fsleep_for (make_number (1), Qnil
);
5392 /* Get visited file's mode to become the auto save file's mode. */
5393 if (! NILP (current_buffer
->filename
)
5394 && stat (XSTRING (current_buffer
->filename
)->data
, &st
) >= 0)
5395 /* But make sure we can overwrite it later! */
5396 auto_save_mode_bits
= st
.st_mode
| 0600;
5398 auto_save_mode_bits
= 0666;
5401 Fwrite_region (Qnil
, Qnil
,
5402 current_buffer
->auto_save_file_name
,
5403 Qnil
, Qlambda
, Qnil
, Qnil
);
5407 do_auto_save_unwind (stream
) /* used as unwind-protect function */
5412 fclose ((FILE *) (XFASTINT (XCAR (stream
)) << 16
5413 | XFASTINT (XCDR (stream
))));
5419 do_auto_save_unwind_1 (value
) /* used as unwind-protect function */
5422 minibuffer_auto_raise
= XINT (value
);
5426 DEFUN ("do-auto-save", Fdo_auto_save
, Sdo_auto_save
, 0, 2, "",
5427 "Auto-save all buffers that need it.\n\
5428 This is all buffers that have auto-saving enabled\n\
5429 and are changed since last auto-saved.\n\
5430 Auto-saving writes the buffer into a file\n\
5431 so that your editing is not lost if the system crashes.\n\
5432 This file is not the file you visited; that changes only when you save.\n\
5433 Normally we run the normal hook `auto-save-hook' before saving.\n\n\
5434 A non-nil NO-MESSAGE argument means do not print any message if successful.\n\
5435 A non-nil CURRENT-ONLY argument means save only current buffer.")
5436 (no_message
, current_only
)
5437 Lisp_Object no_message
, current_only
;
5439 struct buffer
*old
= current_buffer
, *b
;
5440 Lisp_Object tail
, buf
;
5442 int do_handled_files
;
5445 Lisp_Object lispstream
;
5446 int count
= specpdl_ptr
- specpdl
;
5447 int orig_minibuffer_auto_raise
= minibuffer_auto_raise
;
5448 int message_p
= push_message ();
5450 /* Ordinarily don't quit within this function,
5451 but don't make it impossible to quit (in case we get hung in I/O). */
5455 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5456 point to non-strings reached from Vbuffer_alist. */
5461 if (!NILP (Vrun_hooks
))
5462 call1 (Vrun_hooks
, intern ("auto-save-hook"));
5464 if (STRINGP (Vauto_save_list_file_name
))
5466 Lisp_Object listfile
;
5468 listfile
= Fexpand_file_name (Vauto_save_list_file_name
, Qnil
);
5470 /* Don't try to create the directory when shutting down Emacs,
5471 because creating the directory might signal an error, and
5472 that would leave Emacs in a strange state. */
5473 if (!NILP (Vrun_hooks
))
5476 dir
= Ffile_name_directory (listfile
);
5477 if (NILP (Ffile_directory_p (dir
)))
5478 call2 (Qmake_directory
, dir
, Qt
);
5481 stream
= fopen (XSTRING (listfile
)->data
, "w");
5484 /* Arrange to close that file whether or not we get an error.
5485 Also reset auto_saving to 0. */
5486 lispstream
= Fcons (Qnil
, Qnil
);
5487 XSETFASTINT (XCAR (lispstream
), (EMACS_UINT
)stream
>> 16);
5488 XSETFASTINT (XCDR (lispstream
), (EMACS_UINT
)stream
& 0xffff);
5499 record_unwind_protect (do_auto_save_unwind
, lispstream
);
5500 record_unwind_protect (do_auto_save_unwind_1
,
5501 make_number (minibuffer_auto_raise
));
5502 minibuffer_auto_raise
= 0;
5505 /* First, save all files which don't have handlers. If Emacs is
5506 crashing, the handlers may tweak what is causing Emacs to crash
5507 in the first place, and it would be a shame if Emacs failed to
5508 autosave perfectly ordinary files because it couldn't handle some
5510 for (do_handled_files
= 0; do_handled_files
< 2; do_handled_files
++)
5511 for (tail
= Vbuffer_alist
; GC_CONSP (tail
); tail
= XCDR (tail
))
5513 buf
= XCDR (XCAR (tail
));
5516 /* Record all the buffers that have auto save mode
5517 in the special file that lists them. For each of these buffers,
5518 Record visited name (if any) and auto save name. */
5519 if (STRINGP (b
->auto_save_file_name
)
5520 && stream
!= NULL
&& do_handled_files
== 0)
5522 if (!NILP (b
->filename
))
5524 fwrite (XSTRING (b
->filename
)->data
, 1,
5525 STRING_BYTES (XSTRING (b
->filename
)), stream
);
5527 putc ('\n', stream
);
5528 fwrite (XSTRING (b
->auto_save_file_name
)->data
, 1,
5529 STRING_BYTES (XSTRING (b
->auto_save_file_name
)), stream
);
5530 putc ('\n', stream
);
5533 if (!NILP (current_only
)
5534 && b
!= current_buffer
)
5537 /* Don't auto-save indirect buffers.
5538 The base buffer takes care of it. */
5542 /* Check for auto save enabled
5543 and file changed since last auto save
5544 and file changed since last real save. */
5545 if (STRINGP (b
->auto_save_file_name
)
5546 && BUF_SAVE_MODIFF (b
) < BUF_MODIFF (b
)
5547 && b
->auto_save_modified
< BUF_MODIFF (b
)
5548 /* -1 means we've turned off autosaving for a while--see below. */
5549 && XINT (b
->save_length
) >= 0
5550 && (do_handled_files
5551 || NILP (Ffind_file_name_handler (b
->auto_save_file_name
,
5554 EMACS_TIME before_time
, after_time
;
5556 EMACS_GET_TIME (before_time
);
5558 /* If we had a failure, don't try again for 20 minutes. */
5559 if (b
->auto_save_failure_time
>= 0
5560 && EMACS_SECS (before_time
) - b
->auto_save_failure_time
< 1200)
5563 if ((XFASTINT (b
->save_length
) * 10
5564 > (BUF_Z (b
) - BUF_BEG (b
)) * 13)
5565 /* A short file is likely to change a large fraction;
5566 spare the user annoying messages. */
5567 && XFASTINT (b
->save_length
) > 5000
5568 /* These messages are frequent and annoying for `*mail*'. */
5569 && !EQ (b
->filename
, Qnil
)
5570 && NILP (no_message
))
5572 /* It has shrunk too much; turn off auto-saving here. */
5573 minibuffer_auto_raise
= orig_minibuffer_auto_raise
;
5574 message_with_string ("Buffer %s has shrunk a lot; auto save turned off there",
5576 minibuffer_auto_raise
= 0;
5577 /* Turn off auto-saving until there's a real save,
5578 and prevent any more warnings. */
5579 XSETINT (b
->save_length
, -1);
5580 Fsleep_for (make_number (1), Qnil
);
5583 set_buffer_internal (b
);
5584 if (!auto_saved
&& NILP (no_message
))
5585 message1 ("Auto-saving...");
5586 internal_condition_case (auto_save_1
, Qt
, auto_save_error
);
5588 b
->auto_save_modified
= BUF_MODIFF (b
);
5589 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
5590 set_buffer_internal (old
);
5592 EMACS_GET_TIME (after_time
);
5594 /* If auto-save took more than 60 seconds,
5595 assume it was an NFS failure that got a timeout. */
5596 if (EMACS_SECS (after_time
) - EMACS_SECS (before_time
) > 60)
5597 b
->auto_save_failure_time
= EMACS_SECS (after_time
);
5601 /* Prevent another auto save till enough input events come in. */
5602 record_auto_save ();
5604 if (auto_saved
&& NILP (no_message
))
5608 sit_for (1, 0, 0, 0, 0);
5612 message1 ("Auto-saving...done");
5617 unbind_to (count
, Qnil
);
5621 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved
,
5622 Sset_buffer_auto_saved
, 0, 0, 0,
5623 "Mark current buffer as auto-saved with its current text.\n\
5624 No auto-save file will be written until the buffer changes again.")
5627 current_buffer
->auto_save_modified
= MODIFF
;
5628 XSETFASTINT (current_buffer
->save_length
, Z
- BEG
);
5629 current_buffer
->auto_save_failure_time
= -1;
5633 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure
,
5634 Sclear_buffer_auto_save_failure
, 0, 0, 0,
5635 "Clear any record of a recent auto-save failure in the current buffer.")
5638 current_buffer
->auto_save_failure_time
= -1;
5642 DEFUN ("recent-auto-save-p", Frecent_auto_save_p
, Srecent_auto_save_p
,
5644 "Return t if buffer has been auto-saved since last read in or saved.")
5647 return (SAVE_MODIFF
< current_buffer
->auto_save_modified
) ? Qt
: Qnil
;
5650 /* Reading and completing file names */
5651 extern Lisp_Object
Ffile_name_completion (), Ffile_name_all_completions ();
5653 /* In the string VAL, change each $ to $$ and return the result. */
5656 double_dollars (val
)
5659 register unsigned char *old
, *new;
5663 osize
= STRING_BYTES (XSTRING (val
));
5665 /* Count the number of $ characters. */
5666 for (n
= osize
, count
= 0, old
= XSTRING (val
)->data
; n
> 0; n
--)
5667 if (*old
++ == '$') count
++;
5670 old
= XSTRING (val
)->data
;
5671 val
= make_uninit_multibyte_string (XSTRING (val
)->size
+ count
,
5673 new = XSTRING (val
)->data
;
5674 for (n
= osize
; n
> 0; n
--)
5687 DEFUN ("read-file-name-internal", Fread_file_name_internal
, Sread_file_name_internal
,
5689 "Internal subroutine for read-file-name. Do not call this.")
5690 (string
, dir
, action
)
5691 Lisp_Object string
, dir
, action
;
5692 /* action is nil for complete, t for return list of completions,
5693 lambda for verify final value */
5695 Lisp_Object name
, specdir
, realdir
, val
, orig_string
;
5697 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
5699 CHECK_STRING (string
, 0);
5706 /* No need to protect ACTION--we only compare it with t and nil. */
5707 GCPRO5 (string
, realdir
, name
, specdir
, orig_string
);
5709 if (XSTRING (string
)->size
== 0)
5711 if (EQ (action
, Qlambda
))
5719 orig_string
= string
;
5720 string
= Fsubstitute_in_file_name (string
);
5721 changed
= NILP (Fstring_equal (string
, orig_string
));
5722 name
= Ffile_name_nondirectory (string
);
5723 val
= Ffile_name_directory (string
);
5725 realdir
= Fexpand_file_name (val
, realdir
);
5730 specdir
= Ffile_name_directory (string
);
5731 val
= Ffile_name_completion (name
, realdir
);
5736 return double_dollars (string
);
5740 if (!NILP (specdir
))
5741 val
= concat2 (specdir
, val
);
5743 return double_dollars (val
);
5746 #endif /* not VMS */
5750 if (EQ (action
, Qt
))
5751 return Ffile_name_all_completions (name
, realdir
);
5752 /* Only other case actually used is ACTION = lambda */
5754 /* Supposedly this helps commands such as `cd' that read directory names,
5755 but can someone explain how it helps them? -- RMS */
5756 if (XSTRING (name
)->size
== 0)
5759 return Ffile_exists_p (string
);
5762 DEFUN ("read-file-name", Fread_file_name
, Sread_file_name
, 1, 5, 0,
5763 "Read file name, prompting with PROMPT and completing in directory DIR.\n\
5764 Value is not expanded---you must call `expand-file-name' yourself.\n\
5765 Default name to DEFAULT-FILENAME if user enters a null string.\n\
5766 (If DEFAULT-FILENAME is omitted, the visited file name is used,\n\
5767 except that if INITIAL is specified, that combined with DIR is used.)\n\
5768 Fourth arg MUSTMATCH non-nil means require existing file's name.\n\
5769 Non-nil and non-t means also require confirmation after completion.\n\
5770 Fifth arg INITIAL specifies text to start with.\n\
5771 DIR defaults to current buffer's directory default.\n\
5773 If this command was invoked with the mouse, use a file dialog box if\n\
5774 `use-dialog-box' is non-nil, and the window system or X toolkit in use\n\
5775 provides a file dialog box..")
5776 (prompt
, dir
, default_filename
, mustmatch
, initial
)
5777 Lisp_Object prompt
, dir
, default_filename
, mustmatch
, initial
;
5779 Lisp_Object val
, insdef
, tem
;
5780 struct gcpro gcpro1
, gcpro2
;
5781 register char *homedir
;
5782 int replace_in_history
= 0;
5783 int add_to_history
= 0;
5787 dir
= current_buffer
->directory
;
5788 if (NILP (default_filename
))
5790 if (! NILP (initial
))
5791 default_filename
= Fexpand_file_name (initial
, dir
);
5793 default_filename
= current_buffer
->filename
;
5796 /* If dir starts with user's homedir, change that to ~. */
5797 homedir
= (char *) egetenv ("HOME");
5799 /* homedir can be NULL in temacs, since Vprocess_environment is not
5800 yet set up. We shouldn't crash in that case. */
5803 homedir
= strcpy (alloca (strlen (homedir
) + 1), homedir
);
5804 CORRECT_DIR_SEPS (homedir
);
5809 && !strncmp (homedir
, XSTRING (dir
)->data
, strlen (homedir
))
5810 && IS_DIRECTORY_SEP (XSTRING (dir
)->data
[strlen (homedir
)]))
5812 dir
= make_string (XSTRING (dir
)->data
+ strlen (homedir
) - 1,
5813 STRING_BYTES (XSTRING (dir
)) - strlen (homedir
) + 1);
5814 XSTRING (dir
)->data
[0] = '~';
5816 /* Likewise for default_filename. */
5818 && STRINGP (default_filename
)
5819 && !strncmp (homedir
, XSTRING (default_filename
)->data
, strlen (homedir
))
5820 && IS_DIRECTORY_SEP (XSTRING (default_filename
)->data
[strlen (homedir
)]))
5823 = make_string (XSTRING (default_filename
)->data
+ strlen (homedir
) - 1,
5824 STRING_BYTES (XSTRING (default_filename
)) - strlen (homedir
) + 1);
5825 XSTRING (default_filename
)->data
[0] = '~';
5827 if (!NILP (default_filename
))
5829 CHECK_STRING (default_filename
, 3);
5830 default_filename
= double_dollars (default_filename
);
5833 if (insert_default_directory
&& STRINGP (dir
))
5836 if (!NILP (initial
))
5838 Lisp_Object args
[2], pos
;
5842 insdef
= Fconcat (2, args
);
5843 pos
= make_number (XSTRING (double_dollars (dir
))->size
);
5844 insdef
= Fcons (double_dollars (insdef
), pos
);
5847 insdef
= double_dollars (insdef
);
5849 else if (STRINGP (initial
))
5850 insdef
= Fcons (double_dollars (initial
), make_number (0));
5854 count
= specpdl_ptr
- specpdl
;
5856 specbind (intern ("completion-ignore-case"), Qt
);
5859 specbind (intern ("minibuffer-completing-file-name"), Qt
);
5861 GCPRO2 (insdef
, default_filename
);
5863 #if defined (USE_MOTIF) || defined (HAVE_NTGUI)
5864 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
5868 /* If DIR contains a file name, split it. */
5870 file
= Ffile_name_nondirectory (dir
);
5871 if (XSTRING (file
)->size
&& NILP (default_filename
))
5873 default_filename
= file
;
5874 dir
= Ffile_name_directory (dir
);
5876 if (!NILP(default_filename
))
5877 default_filename
= Fexpand_file_name (default_filename
, dir
);
5878 val
= Fx_file_dialog (prompt
, dir
, default_filename
, mustmatch
);
5883 val
= Fcompleting_read (prompt
, intern ("read-file-name-internal"),
5884 dir
, mustmatch
, insdef
,
5885 Qfile_name_history
, default_filename
, Qnil
);
5887 tem
= Fsymbol_value (Qfile_name_history
);
5888 if (CONSP (tem
) && EQ (XCAR (tem
), val
))
5889 replace_in_history
= 1;
5891 /* If Fcompleting_read returned the inserted default string itself
5892 (rather than a new string with the same contents),
5893 it has to mean that the user typed RET with the minibuffer empty.
5894 In that case, we really want to return ""
5895 so that commands such as set-visited-file-name can distinguish. */
5896 if (EQ (val
, default_filename
))
5898 /* In this case, Fcompleting_read has not added an element
5899 to the history. Maybe we should. */
5900 if (! replace_in_history
)
5903 val
= build_string ("");
5906 unbind_to (count
, Qnil
);
5909 error ("No file name specified");
5911 tem
= Fstring_equal (val
, CONSP (insdef
) ? XCAR (insdef
) : insdef
);
5913 if (!NILP (tem
) && !NILP (default_filename
))
5914 val
= default_filename
;
5915 else if (XSTRING (val
)->size
== 0 && NILP (insdef
))
5917 if (!NILP (default_filename
))
5918 val
= default_filename
;
5920 error ("No default file name");
5922 val
= Fsubstitute_in_file_name (val
);
5924 if (replace_in_history
)
5925 /* Replace what Fcompleting_read added to the history
5926 with what we will actually return. */
5927 XCAR (Fsymbol_value (Qfile_name_history
)) = double_dollars (val
);
5928 else if (add_to_history
)
5930 /* Add the value to the history--but not if it matches
5931 the last value already there. */
5932 Lisp_Object val1
= double_dollars (val
);
5933 tem
= Fsymbol_value (Qfile_name_history
);
5934 if (! CONSP (tem
) || NILP (Fequal (XCAR (tem
), val1
)))
5935 Fset (Qfile_name_history
,
5946 /* Must be set before any path manipulation is performed. */
5947 XSETFASTINT (Vdirectory_sep_char
, '/');
5954 Qexpand_file_name
= intern ("expand-file-name");
5955 Qsubstitute_in_file_name
= intern ("substitute-in-file-name");
5956 Qdirectory_file_name
= intern ("directory-file-name");
5957 Qfile_name_directory
= intern ("file-name-directory");
5958 Qfile_name_nondirectory
= intern ("file-name-nondirectory");
5959 Qunhandled_file_name_directory
= intern ("unhandled-file-name-directory");
5960 Qfile_name_as_directory
= intern ("file-name-as-directory");
5961 Qcopy_file
= intern ("copy-file");
5962 Qmake_directory_internal
= intern ("make-directory-internal");
5963 Qmake_directory
= intern ("make-directory");
5964 Qdelete_directory
= intern ("delete-directory");
5965 Qdelete_file
= intern ("delete-file");
5966 Qrename_file
= intern ("rename-file");
5967 Qadd_name_to_file
= intern ("add-name-to-file");
5968 Qmake_symbolic_link
= intern ("make-symbolic-link");
5969 Qfile_exists_p
= intern ("file-exists-p");
5970 Qfile_executable_p
= intern ("file-executable-p");
5971 Qfile_readable_p
= intern ("file-readable-p");
5972 Qfile_writable_p
= intern ("file-writable-p");
5973 Qfile_symlink_p
= intern ("file-symlink-p");
5974 Qaccess_file
= intern ("access-file");
5975 Qfile_directory_p
= intern ("file-directory-p");
5976 Qfile_regular_p
= intern ("file-regular-p");
5977 Qfile_accessible_directory_p
= intern ("file-accessible-directory-p");
5978 Qfile_modes
= intern ("file-modes");
5979 Qset_file_modes
= intern ("set-file-modes");
5980 Qfile_newer_than_file_p
= intern ("file-newer-than-file-p");
5981 Qinsert_file_contents
= intern ("insert-file-contents");
5982 Qwrite_region
= intern ("write-region");
5983 Qverify_visited_file_modtime
= intern ("verify-visited-file-modtime");
5984 Qset_visited_file_modtime
= intern ("set-visited-file-modtime");
5986 staticpro (&Qexpand_file_name
);
5987 staticpro (&Qsubstitute_in_file_name
);
5988 staticpro (&Qdirectory_file_name
);
5989 staticpro (&Qfile_name_directory
);
5990 staticpro (&Qfile_name_nondirectory
);
5991 staticpro (&Qunhandled_file_name_directory
);
5992 staticpro (&Qfile_name_as_directory
);
5993 staticpro (&Qcopy_file
);
5994 staticpro (&Qmake_directory_internal
);
5995 staticpro (&Qmake_directory
);
5996 staticpro (&Qdelete_directory
);
5997 staticpro (&Qdelete_file
);
5998 staticpro (&Qrename_file
);
5999 staticpro (&Qadd_name_to_file
);
6000 staticpro (&Qmake_symbolic_link
);
6001 staticpro (&Qfile_exists_p
);
6002 staticpro (&Qfile_executable_p
);
6003 staticpro (&Qfile_readable_p
);
6004 staticpro (&Qfile_writable_p
);
6005 staticpro (&Qaccess_file
);
6006 staticpro (&Qfile_symlink_p
);
6007 staticpro (&Qfile_directory_p
);
6008 staticpro (&Qfile_regular_p
);
6009 staticpro (&Qfile_accessible_directory_p
);
6010 staticpro (&Qfile_modes
);
6011 staticpro (&Qset_file_modes
);
6012 staticpro (&Qfile_newer_than_file_p
);
6013 staticpro (&Qinsert_file_contents
);
6014 staticpro (&Qwrite_region
);
6015 staticpro (&Qverify_visited_file_modtime
);
6016 staticpro (&Qset_visited_file_modtime
);
6018 Qfile_name_history
= intern ("file-name-history");
6019 Fset (Qfile_name_history
, Qnil
);
6020 staticpro (&Qfile_name_history
);
6022 Qfile_error
= intern ("file-error");
6023 staticpro (&Qfile_error
);
6024 Qfile_already_exists
= intern ("file-already-exists");
6025 staticpro (&Qfile_already_exists
);
6026 Qfile_date_error
= intern ("file-date-error");
6027 staticpro (&Qfile_date_error
);
6028 Qexcl
= intern ("excl");
6032 Qfind_buffer_file_type
= intern ("find-buffer-file-type");
6033 staticpro (&Qfind_buffer_file_type
);
6036 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system
,
6037 "*Coding system for encoding file names.\n\
6038 If it is nil, default-file-name-coding-system (which see) is used.");
6039 Vfile_name_coding_system
= Qnil
;
6041 DEFVAR_LISP ("default-file-name-coding-system",
6042 &Vdefault_file_name_coding_system
,
6043 "Default coding system for encoding file names.\n\
6044 This variable is used only when file-name-coding-system is nil.\n\
6046 This variable is set/changed by the command set-language-environment.\n\
6047 User should not set this variable manually,\n\
6048 instead use file-name-coding-system to get a constant encoding\n\
6049 of file names regardless of the current language environment.");
6050 Vdefault_file_name_coding_system
= Qnil
;
6052 DEFVAR_LISP ("auto-save-file-format", &Vauto_save_file_format
,
6053 "*Format in which to write auto-save files.\n\
6054 Should be a list of symbols naming formats that are defined in `format-alist'.\n\
6055 If it is t, which is the default, auto-save files are written in the\n\
6056 same format as a regular save would use.");
6057 Vauto_save_file_format
= Qt
;
6059 Qformat_decode
= intern ("format-decode");
6060 staticpro (&Qformat_decode
);
6061 Qformat_annotate_function
= intern ("format-annotate-function");
6062 staticpro (&Qformat_annotate_function
);
6064 Qcar_less_than_car
= intern ("car-less-than-car");
6065 staticpro (&Qcar_less_than_car
);
6067 Fput (Qfile_error
, Qerror_conditions
,
6068 Fcons (Qfile_error
, Fcons (Qerror
, Qnil
)));
6069 Fput (Qfile_error
, Qerror_message
,
6070 build_string ("File error"));
6072 Fput (Qfile_already_exists
, Qerror_conditions
,
6073 Fcons (Qfile_already_exists
,
6074 Fcons (Qfile_error
, Fcons (Qerror
, Qnil
))));
6075 Fput (Qfile_already_exists
, Qerror_message
,
6076 build_string ("File already exists"));
6078 Fput (Qfile_date_error
, Qerror_conditions
,
6079 Fcons (Qfile_date_error
,
6080 Fcons (Qfile_error
, Fcons (Qerror
, Qnil
))));
6081 Fput (Qfile_date_error
, Qerror_message
,
6082 build_string ("Cannot set file date"));
6084 DEFVAR_BOOL ("insert-default-directory", &insert_default_directory
,
6085 "*Non-nil means when reading a filename start with default dir in minibuffer.");
6086 insert_default_directory
= 1;
6088 DEFVAR_BOOL ("vms-stmlf-recfm", &vms_stmlf_recfm
,
6089 "*Non-nil means write new files with record format `stmlf'.\n\
6090 nil means use format `var'. This variable is meaningful only on VMS.");
6091 vms_stmlf_recfm
= 0;
6093 DEFVAR_LISP ("directory-sep-char", &Vdirectory_sep_char
,
6094 "Directory separator character for built-in functions that return file names.\n\
6095 The value should be either ?/ or ?\\ (any other value is treated as ?\\).\n\
6096 This variable affects the built-in functions only on Windows,\n\
6097 on other platforms, it is initialized so that Lisp code can find out\n\
6098 what the normal separator is.\n\
6100 WARNING: This variable is deprecated and will be removed in the near\n\
6101 future. DO NOT USE IT.");
6103 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist
,
6104 "*Alist of elements (REGEXP . HANDLER) for file names handled specially.\n\
6105 If a file name matches REGEXP, then all I/O on that file is done by calling\n\
6108 The first argument given to HANDLER is the name of the I/O primitive\n\
6109 to be handled; the remaining arguments are the arguments that were\n\
6110 passed to that primitive. For example, if you do\n\
6111 (file-exists-p FILENAME)\n\
6112 and FILENAME is handled by HANDLER, then HANDLER is called like this:\n\
6113 (funcall HANDLER 'file-exists-p FILENAME)\n\
6114 The function `find-file-name-handler' checks this list for a handler\n\
6115 for its argument.");
6116 Vfile_name_handler_alist
= Qnil
;
6118 DEFVAR_LISP ("set-auto-coding-function",
6119 &Vset_auto_coding_function
,
6120 "If non-nil, a function to call to decide a coding system of file.\n\
6121 Two arguments are passed to this function: the file name\n\
6122 and the length of a file contents following the point.\n\
6123 This function should return a coding system to decode the file contents.\n\
6124 It should check the file name against `auto-coding-alist'.\n\
6125 If no coding system is decided, it should check a coding system\n\
6126 specified in the heading lines with the format:\n\
6127 -*- ... coding: CODING-SYSTEM; ... -*-\n\
6128 or local variable spec of the tailing lines with `coding:' tag.");
6129 Vset_auto_coding_function
= Qnil
;
6131 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions
,
6132 "A list of functions to be called at the end of `insert-file-contents'.\n\
6133 Each is passed one argument, the number of bytes inserted. It should return\n\
6134 the new byte count, and leave point the same. If `insert-file-contents' is\n\
6135 intercepted by a handler from `file-name-handler-alist', that handler is\n\
6136 responsible for calling the after-insert-file-functions if appropriate.");
6137 Vafter_insert_file_functions
= Qnil
;
6139 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions
,
6140 "A list of functions to be called at the start of `write-region'.\n\
6141 Each is passed two arguments, START and END as for `write-region'.\n\
6142 These are usually two numbers but not always; see the documentation\n\
6143 for `write-region'. The function should return a list of pairs\n\
6144 of the form (POSITION . STRING), consisting of strings to be effectively\n\
6145 inserted at the specified positions of the file being written (1 means to\n\
6146 insert before the first byte written). The POSITIONs must be sorted into\n\
6147 increasing order. If there are several functions in the list, the several\n\
6148 lists are merged destructively.");
6149 Vwrite_region_annotate_functions
= Qnil
;
6151 DEFVAR_LISP ("write-region-annotations-so-far",
6152 &Vwrite_region_annotations_so_far
,
6153 "When an annotation function is called, this holds the previous annotations.\n\
6154 These are the annotations made by other annotation functions\n\
6155 that were already called. See also `write-region-annotate-functions'.");
6156 Vwrite_region_annotations_so_far
= Qnil
;
6158 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers
,
6159 "A list of file name handlers that temporarily should not be used.\n\
6160 This applies only to the operation `inhibit-file-name-operation'.");
6161 Vinhibit_file_name_handlers
= Qnil
;
6163 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation
,
6164 "The operation for which `inhibit-file-name-handlers' is applicable.");
6165 Vinhibit_file_name_operation
= Qnil
;
6167 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name
,
6168 "File name in which we write a list of all auto save file names.\n\
6169 This variable is initialized automatically from `auto-save-list-file-prefix'\n\
6170 shortly after Emacs reads your `.emacs' file, if you have not yet given it\n\
6172 Vauto_save_list_file_name
= Qnil
;
6174 defsubr (&Sfind_file_name_handler
);
6175 defsubr (&Sfile_name_directory
);
6176 defsubr (&Sfile_name_nondirectory
);
6177 defsubr (&Sunhandled_file_name_directory
);
6178 defsubr (&Sfile_name_as_directory
);
6179 defsubr (&Sdirectory_file_name
);
6180 defsubr (&Smake_temp_name
);
6181 defsubr (&Sexpand_file_name
);
6182 defsubr (&Ssubstitute_in_file_name
);
6183 defsubr (&Scopy_file
);
6184 defsubr (&Smake_directory_internal
);
6185 defsubr (&Sdelete_directory
);
6186 defsubr (&Sdelete_file
);
6187 defsubr (&Srename_file
);
6188 defsubr (&Sadd_name_to_file
);
6190 defsubr (&Smake_symbolic_link
);
6191 #endif /* S_IFLNK */
6193 defsubr (&Sdefine_logical_name
);
6196 defsubr (&Ssysnetunam
);
6197 #endif /* HPUX_NET */
6198 defsubr (&Sfile_name_absolute_p
);
6199 defsubr (&Sfile_exists_p
);
6200 defsubr (&Sfile_executable_p
);
6201 defsubr (&Sfile_readable_p
);
6202 defsubr (&Sfile_writable_p
);
6203 defsubr (&Saccess_file
);
6204 defsubr (&Sfile_symlink_p
);
6205 defsubr (&Sfile_directory_p
);
6206 defsubr (&Sfile_accessible_directory_p
);
6207 defsubr (&Sfile_regular_p
);
6208 defsubr (&Sfile_modes
);
6209 defsubr (&Sset_file_modes
);
6210 defsubr (&Sset_default_file_modes
);
6211 defsubr (&Sdefault_file_modes
);
6212 defsubr (&Sfile_newer_than_file_p
);
6213 defsubr (&Sinsert_file_contents
);
6214 defsubr (&Swrite_region
);
6215 defsubr (&Scar_less_than_car
);
6216 defsubr (&Sverify_visited_file_modtime
);
6217 defsubr (&Sclear_visited_file_modtime
);
6218 defsubr (&Svisited_file_modtime
);
6219 defsubr (&Sset_visited_file_modtime
);
6220 defsubr (&Sdo_auto_save
);
6221 defsubr (&Sset_buffer_auto_saved
);
6222 defsubr (&Sclear_buffer_auto_save_failure
);
6223 defsubr (&Srecent_auto_save_p
);
6225 defsubr (&Sread_file_name_internal
);
6226 defsubr (&Sread_file_name
);
6229 defsubr (&Sunix_sync
);