Mention archiving.
[emacs.git] / src / fileio.c
blob255d1a9117ae6e2ea87da197949d0fb755a7f76d
1 /* File IO for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995, 1996,
3 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <limits.h>
24 #ifdef HAVE_FCNTL_H
25 #include <fcntl.h>
26 #endif
28 #include <stdio.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
36 #if !defined (S_ISLNK) && defined (S_IFLNK)
37 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
38 #endif
40 #if !defined (S_ISFIFO) && defined (S_IFIFO)
41 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
42 #endif
44 #if !defined (S_ISREG) && defined (S_IFREG)
45 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
46 #endif
48 #ifdef HAVE_PWD_H
49 #include <pwd.h>
50 #endif
52 #include <ctype.h>
53 #include <errno.h>
55 #ifndef vax11c
56 #ifndef USE_CRT_DLL
57 extern int errno;
58 #endif
59 #endif
61 #include "lisp.h"
62 #include "intervals.h"
63 #include "buffer.h"
64 #include "character.h"
65 #include "coding.h"
66 #include "window.h"
67 #include "blockinput.h"
68 #include "frame.h"
69 #include "dispextern.h"
71 #ifdef WINDOWSNT
72 #define NOMINMAX 1
73 #include <windows.h>
74 #include <stdlib.h>
75 #include <fcntl.h>
76 #endif /* not WINDOWSNT */
78 #ifdef MSDOS
79 #include "msdos.h"
80 #include <sys/param.h>
81 #if __DJGPP__ >= 2
82 #include <fcntl.h>
83 #include <string.h>
84 #endif
85 #endif
87 #ifdef DOS_NT
88 #define CORRECT_DIR_SEPS(s) \
89 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
90 else unixtodos_filename (s); \
91 } while (0)
92 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
93 redirector allows the six letters between 'Z' and 'a' as well. */
94 #ifdef MSDOS
95 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
96 #endif
97 #ifdef WINDOWSNT
98 #define IS_DRIVE(x) isalpha (x)
99 #endif
100 /* Need to lower-case the drive letter, or else expanded
101 filenames will sometimes compare inequal, because
102 `expand-file-name' doesn't always down-case the drive letter. */
103 #define DRIVE_LETTER(x) (tolower (x))
104 #endif
106 #include "systime.h"
108 #ifdef HPUX
109 #include <netio.h>
110 #endif
112 #include "commands.h"
113 extern int use_dialog_box;
114 extern int use_file_dialog;
116 #ifndef O_WRONLY
117 #define O_WRONLY 1
118 #endif
120 #ifndef O_RDONLY
121 #define O_RDONLY 0
122 #endif
124 #ifndef S_ISLNK
125 # define lstat stat
126 #endif
128 #ifndef FILE_SYSTEM_CASE
129 #define FILE_SYSTEM_CASE(filename) (filename)
130 #endif
132 /* Nonzero during writing of auto-save files */
133 int auto_saving;
135 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
136 a new file with the same mode as the original */
137 int auto_save_mode_bits;
139 /* Set by auto_save_1 if an error occurred during the last auto-save. */
140 int auto_save_error_occurred;
142 /* The symbol bound to coding-system-for-read when
143 insert-file-contents is called for recovering a file. This is not
144 an actual coding system name, but just an indicator to tell
145 insert-file-contents to use `emacs-mule' with a special flag for
146 auto saving and recovering a file. */
147 Lisp_Object Qauto_save_coding;
149 /* Coding system for file names, or nil if none. */
150 Lisp_Object Vfile_name_coding_system;
152 /* Coding system for file names used only when
153 Vfile_name_coding_system is nil. */
154 Lisp_Object Vdefault_file_name_coding_system;
156 /* Alist of elements (REGEXP . HANDLER) for file names
157 whose I/O is done with a special handler. */
158 Lisp_Object Vfile_name_handler_alist;
160 /* Property name of a file name handler,
161 which gives a list of operations it handles.. */
162 Lisp_Object Qoperations;
164 /* Lisp functions for translating file formats */
165 Lisp_Object Qformat_decode, Qformat_annotate_function;
167 /* Function to be called to decide a coding system of a reading file. */
168 Lisp_Object Vset_auto_coding_function;
170 /* Functions to be called to process text properties in inserted file. */
171 Lisp_Object Vafter_insert_file_functions;
173 /* Lisp function for setting buffer-file-coding-system and the
174 multibyteness of the current buffer after inserting a file. */
175 Lisp_Object Qafter_insert_file_set_coding;
177 /* Functions to be called to create text property annotations for file. */
178 Lisp_Object Vwrite_region_annotate_functions;
179 Lisp_Object Qwrite_region_annotate_functions;
181 /* During build_annotations, each time an annotation function is called,
182 this holds the annotations made by the previous functions. */
183 Lisp_Object Vwrite_region_annotations_so_far;
185 /* File name in which we write a list of all our auto save files. */
186 Lisp_Object Vauto_save_list_file_name;
188 /* Whether or not files are auto-saved into themselves. */
189 Lisp_Object Vauto_save_visited_file_name;
191 /* On NT, specifies the directory separator character, used (eg.) when
192 expanding file names. This can be bound to / or \. */
193 Lisp_Object Vdirectory_sep_char;
195 #ifdef HAVE_FSYNC
196 /* Nonzero means skip the call to fsync in Fwrite-region. */
197 int write_region_inhibit_fsync;
198 #endif
200 /* Non-zero means call move-file-to-trash in Fdelete_file or
201 Fdelete_directory. */
202 int delete_by_moving_to_trash;
204 Lisp_Object Qdelete_by_moving_to_trash;
206 /* Lisp function for moving files to trash. */
207 Lisp_Object Qmove_file_to_trash;
209 extern Lisp_Object Vuser_login_name;
211 #ifdef WINDOWSNT
212 extern Lisp_Object Vw32_get_true_file_attributes;
213 #endif
215 extern int minibuf_level;
217 extern int minibuffer_auto_raise;
219 extern int history_delete_duplicates;
221 /* These variables describe handlers that have "already" had a chance
222 to handle the current operation.
224 Vinhibit_file_name_handlers is a list of file name handlers.
225 Vinhibit_file_name_operation is the operation being handled.
226 If we try to handle that operation, we ignore those handlers. */
228 static Lisp_Object Vinhibit_file_name_handlers;
229 static Lisp_Object Vinhibit_file_name_operation;
231 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
232 Lisp_Object Qexcl;
233 Lisp_Object Qfile_name_history;
235 Lisp_Object Qcar_less_than_car;
237 static int a_write P_ ((int, Lisp_Object, int, int,
238 Lisp_Object *, struct coding_system *));
239 static int e_write P_ ((int, Lisp_Object, int, int, struct coding_system *));
242 void
243 report_file_error (string, data)
244 const char *string;
245 Lisp_Object data;
247 Lisp_Object errstring;
248 int errorno = errno;
249 char *str;
251 synchronize_system_messages_locale ();
252 str = strerror (errorno);
253 errstring = code_convert_string_norecord (make_unibyte_string (str,
254 strlen (str)),
255 Vlocale_coding_system, 0);
257 while (1)
258 switch (errorno)
260 case EEXIST:
261 xsignal (Qfile_already_exists, Fcons (errstring, data));
262 break;
263 default:
264 /* System error messages are capitalized. Downcase the initial
265 unless it is followed by a slash. (The slash case caters to
266 error messages that begin with "I/O" or, in German, "E/A".) */
267 if (STRING_MULTIBYTE (errstring)
268 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
270 int c;
272 str = (char *) SDATA (errstring);
273 c = STRING_CHAR (str, 0);
274 Faset (errstring, make_number (0), make_number (DOWNCASE (c)));
277 xsignal (Qfile_error,
278 Fcons (build_string (string), Fcons (errstring, data)));
282 Lisp_Object
283 close_file_unwind (fd)
284 Lisp_Object fd;
286 emacs_close (XFASTINT (fd));
287 return Qnil;
290 /* Restore point, having saved it as a marker. */
292 static Lisp_Object
293 restore_point_unwind (location)
294 Lisp_Object location;
296 Fgoto_char (location);
297 Fset_marker (location, Qnil, Qnil);
298 return Qnil;
302 Lisp_Object Qexpand_file_name;
303 Lisp_Object Qsubstitute_in_file_name;
304 Lisp_Object Qdirectory_file_name;
305 Lisp_Object Qfile_name_directory;
306 Lisp_Object Qfile_name_nondirectory;
307 Lisp_Object Qunhandled_file_name_directory;
308 Lisp_Object Qfile_name_as_directory;
309 Lisp_Object Qcopy_file;
310 Lisp_Object Qmake_directory_internal;
311 Lisp_Object Qmake_directory;
312 Lisp_Object Qdelete_directory;
313 Lisp_Object Qdelete_file;
314 Lisp_Object Qrename_file;
315 Lisp_Object Qadd_name_to_file;
316 Lisp_Object Qmake_symbolic_link;
317 Lisp_Object Qfile_exists_p;
318 Lisp_Object Qfile_executable_p;
319 Lisp_Object Qfile_readable_p;
320 Lisp_Object Qfile_writable_p;
321 Lisp_Object Qfile_symlink_p;
322 Lisp_Object Qaccess_file;
323 Lisp_Object Qfile_directory_p;
324 Lisp_Object Qfile_regular_p;
325 Lisp_Object Qfile_accessible_directory_p;
326 Lisp_Object Qfile_modes;
327 Lisp_Object Qset_file_modes;
328 Lisp_Object Qset_file_times;
329 Lisp_Object Qfile_newer_than_file_p;
330 Lisp_Object Qinsert_file_contents;
331 Lisp_Object Qwrite_region;
332 Lisp_Object Qverify_visited_file_modtime;
333 Lisp_Object Qset_visited_file_modtime;
335 DEFUN ("find-file-name-handler", Ffind_file_name_handler, Sfind_file_name_handler, 2, 2, 0,
336 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
337 Otherwise, return nil.
338 A file name is handled if one of the regular expressions in
339 `file-name-handler-alist' matches it.
341 If OPERATION equals `inhibit-file-name-operation', then we ignore
342 any handlers that are members of `inhibit-file-name-handlers',
343 but we still do run any other handlers. This lets handlers
344 use the standard functions without calling themselves recursively. */)
345 (filename, operation)
346 Lisp_Object filename, operation;
348 /* This function must not munge the match data. */
349 Lisp_Object chain, inhibited_handlers, result;
350 int pos = -1;
352 result = Qnil;
353 CHECK_STRING (filename);
355 if (EQ (operation, Vinhibit_file_name_operation))
356 inhibited_handlers = Vinhibit_file_name_handlers;
357 else
358 inhibited_handlers = Qnil;
360 for (chain = Vfile_name_handler_alist; CONSP (chain);
361 chain = XCDR (chain))
363 Lisp_Object elt;
364 elt = XCAR (chain);
365 if (CONSP (elt))
367 Lisp_Object string = XCAR (elt);
368 int match_pos;
369 Lisp_Object handler = XCDR (elt);
370 Lisp_Object operations = Qnil;
372 if (SYMBOLP (handler))
373 operations = Fget (handler, Qoperations);
375 if (STRINGP (string)
376 && (match_pos = fast_string_match (string, filename)) > pos
377 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
379 Lisp_Object tem;
381 handler = XCDR (elt);
382 tem = Fmemq (handler, inhibited_handlers);
383 if (NILP (tem))
385 result = handler;
386 pos = match_pos;
391 QUIT;
393 return result;
396 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
397 1, 1, 0,
398 doc: /* Return the directory component in file name FILENAME.
399 Return nil if FILENAME does not include a directory.
400 Otherwise return a directory name.
401 Given a Unix syntax file name, returns a string ending in slash. */)
402 (filename)
403 Lisp_Object filename;
405 #ifndef DOS_NT
406 register const unsigned char *beg;
407 #else
408 register unsigned char *beg;
409 #endif
410 register const unsigned char *p;
411 Lisp_Object handler;
413 CHECK_STRING (filename);
415 /* If the file name has special constructs in it,
416 call the corresponding file handler. */
417 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
418 if (!NILP (handler))
419 return call2 (handler, Qfile_name_directory, filename);
421 filename = FILE_SYSTEM_CASE (filename);
422 beg = SDATA (filename);
423 #ifdef DOS_NT
424 beg = strcpy (alloca (strlen (beg) + 1), beg);
425 #endif
426 p = beg + SBYTES (filename);
428 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
429 #ifdef DOS_NT
430 /* only recognise drive specifier at the beginning */
431 && !(p[-1] == ':'
432 /* handle the "/:d:foo" and "/:foo" cases correctly */
433 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
434 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
435 #endif
436 ) p--;
438 if (p == beg)
439 return Qnil;
440 #ifdef DOS_NT
441 /* Expansion of "c:" to drive and default directory. */
442 if (p[-1] == ':')
444 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
445 unsigned char *res = alloca (MAXPATHLEN + 1);
446 unsigned char *r = res;
448 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
450 strncpy (res, beg, 2);
451 beg += 2;
452 r += 2;
455 if (getdefdir (toupper (*beg) - 'A' + 1, r))
457 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
458 strcat (res, "/");
459 beg = res;
460 p = beg + strlen (beg);
463 CORRECT_DIR_SEPS (beg);
464 #endif /* DOS_NT */
466 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
469 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
470 Sfile_name_nondirectory, 1, 1, 0,
471 doc: /* Return file name FILENAME sans its directory.
472 For example, in a Unix-syntax file name,
473 this is everything after the last slash,
474 or the entire name if it contains no slash. */)
475 (filename)
476 Lisp_Object filename;
478 register const unsigned char *beg, *p, *end;
479 Lisp_Object handler;
481 CHECK_STRING (filename);
483 /* If the file name has special constructs in it,
484 call the corresponding file handler. */
485 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
486 if (!NILP (handler))
487 return call2 (handler, Qfile_name_nondirectory, filename);
489 beg = SDATA (filename);
490 end = p = beg + SBYTES (filename);
492 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
493 #ifdef DOS_NT
494 /* only recognise drive specifier at beginning */
495 && !(p[-1] == ':'
496 /* handle the "/:d:foo" case correctly */
497 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
498 #endif
500 p--;
502 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
505 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
506 Sunhandled_file_name_directory, 1, 1, 0,
507 doc: /* Return a directly usable directory name somehow associated with FILENAME.
508 A `directly usable' directory name is one that may be used without the
509 intervention of any file handler.
510 If FILENAME is a directly usable file itself, return
511 \(file-name-directory FILENAME).
512 If FILENAME refers to a file which is not accessible from a local process,
513 then this should return nil.
514 The `call-process' and `start-process' functions use this function to
515 get a current directory to run processes in. */)
516 (filename)
517 Lisp_Object filename;
519 Lisp_Object handler;
521 /* If the file name has special constructs in it,
522 call the corresponding file handler. */
523 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
524 if (!NILP (handler))
525 return call2 (handler, Qunhandled_file_name_directory, filename);
527 return Ffile_name_directory (filename);
531 char *
532 file_name_as_directory (out, in)
533 char *out, *in;
535 int size = strlen (in) - 1;
537 strcpy (out, in);
539 if (size < 0)
541 out[0] = '.';
542 out[1] = '/';
543 out[2] = 0;
544 return out;
547 /* For Unix syntax, Append a slash if necessary */
548 if (!IS_DIRECTORY_SEP (out[size]))
550 /* Cannot use DIRECTORY_SEP, which could have any value */
551 out[size + 1] = '/';
552 out[size + 2] = '\0';
554 #ifdef DOS_NT
555 CORRECT_DIR_SEPS (out);
556 #endif
557 return out;
560 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
561 Sfile_name_as_directory, 1, 1, 0,
562 doc: /* Return a string representing the file name FILE interpreted as a directory.
563 This operation exists because a directory is also a file, but its name as
564 a directory is different from its name as a file.
565 The result can be used as the value of `default-directory'
566 or passed as second argument to `expand-file-name'.
567 For a Unix-syntax file name, just appends a slash. */)
568 (file)
569 Lisp_Object file;
571 char *buf;
572 Lisp_Object handler;
574 CHECK_STRING (file);
575 if (NILP (file))
576 return Qnil;
578 /* If the file name has special constructs in it,
579 call the corresponding file handler. */
580 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
581 if (!NILP (handler))
582 return call2 (handler, Qfile_name_as_directory, file);
584 buf = (char *) alloca (SBYTES (file) + 10);
585 file_name_as_directory (buf, SDATA (file));
586 return make_specified_string (buf, -1, strlen (buf),
587 STRING_MULTIBYTE (file));
591 * Convert from directory name to filename.
592 * On UNIX, it's simple: just make sure there isn't a terminating /
594 * Value is nonzero if the string output is different from the input.
598 directory_file_name (src, dst)
599 char *src, *dst;
601 long slen;
603 slen = strlen (src);
605 /* Process as Unix format: just remove any final slash.
606 But leave "/" unchanged; do not change it to "". */
607 strcpy (dst, src);
608 if (slen > 1
609 && IS_DIRECTORY_SEP (dst[slen - 1])
610 #ifdef DOS_NT
611 && !IS_ANY_SEP (dst[slen - 2])
612 #endif
614 dst[slen - 1] = 0;
615 #ifdef DOS_NT
616 CORRECT_DIR_SEPS (dst);
617 #endif
618 return 1;
621 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
622 1, 1, 0,
623 doc: /* Returns the file name of the directory named DIRECTORY.
624 This is the name of the file that holds the data for the directory DIRECTORY.
625 This operation exists because a directory is also a file, but its name as
626 a directory is different from its name as a file.
627 In Unix-syntax, this function just removes the final slash. */)
628 (directory)
629 Lisp_Object directory;
631 char *buf;
632 Lisp_Object handler;
634 CHECK_STRING (directory);
636 if (NILP (directory))
637 return Qnil;
639 /* If the file name has special constructs in it,
640 call the corresponding file handler. */
641 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
642 if (!NILP (handler))
643 return call2 (handler, Qdirectory_file_name, directory);
645 buf = (char *) alloca (SBYTES (directory) + 20);
646 directory_file_name (SDATA (directory), buf);
647 return make_specified_string (buf, -1, strlen (buf),
648 STRING_MULTIBYTE (directory));
651 static char make_temp_name_tbl[64] =
653 'A','B','C','D','E','F','G','H',
654 'I','J','K','L','M','N','O','P',
655 'Q','R','S','T','U','V','W','X',
656 'Y','Z','a','b','c','d','e','f',
657 'g','h','i','j','k','l','m','n',
658 'o','p','q','r','s','t','u','v',
659 'w','x','y','z','0','1','2','3',
660 '4','5','6','7','8','9','-','_'
663 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
665 /* Value is a temporary file name starting with PREFIX, a string.
667 The Emacs process number forms part of the result, so there is
668 no danger of generating a name being used by another process.
669 In addition, this function makes an attempt to choose a name
670 which has no existing file. To make this work, PREFIX should be
671 an absolute file name.
673 BASE64_P non-zero means add the pid as 3 characters in base64
674 encoding. In this case, 6 characters will be added to PREFIX to
675 form the file name. Otherwise, if Emacs is running on a system
676 with long file names, add the pid as a decimal number.
678 This function signals an error if no unique file name could be
679 generated. */
681 Lisp_Object
682 make_temp_name (prefix, base64_p)
683 Lisp_Object prefix;
684 int base64_p;
686 Lisp_Object val;
687 int len, clen;
688 int pid;
689 unsigned char *p, *data;
690 char pidbuf[20];
691 int pidlen;
693 CHECK_STRING (prefix);
695 /* VAL is created by adding 6 characters to PREFIX. The first
696 three are the PID of this process, in base 64, and the second
697 three are incremented if the file already exists. This ensures
698 262144 unique file names per PID per PREFIX. */
700 pid = (int) getpid ();
702 if (base64_p)
704 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
705 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
706 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
707 pidlen = 3;
709 else
711 #ifdef HAVE_LONG_FILE_NAMES
712 sprintf (pidbuf, "%d", pid);
713 pidlen = strlen (pidbuf);
714 #else
715 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
716 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
717 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
718 pidlen = 3;
719 #endif
722 len = SBYTES (prefix); clen = SCHARS (prefix);
723 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
724 if (!STRING_MULTIBYTE (prefix))
725 STRING_SET_UNIBYTE (val);
726 data = SDATA (val);
727 bcopy(SDATA (prefix), data, len);
728 p = data + len;
730 bcopy (pidbuf, p, pidlen);
731 p += pidlen;
733 /* Here we try to minimize useless stat'ing when this function is
734 invoked many times successively with the same PREFIX. We achieve
735 this by initializing count to a random value, and incrementing it
736 afterwards.
738 We don't want make-temp-name to be called while dumping,
739 because then make_temp_name_count_initialized_p would get set
740 and then make_temp_name_count would not be set when Emacs starts. */
742 if (!make_temp_name_count_initialized_p)
744 make_temp_name_count = (unsigned) time (NULL);
745 make_temp_name_count_initialized_p = 1;
748 while (1)
750 struct stat ignored;
751 unsigned num = make_temp_name_count;
753 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
754 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
755 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
757 /* Poor man's congruential RN generator. Replace with
758 ++make_temp_name_count for debugging. */
759 make_temp_name_count += 25229;
760 make_temp_name_count %= 225307;
762 if (stat (data, &ignored) < 0)
764 /* We want to return only if errno is ENOENT. */
765 if (errno == ENOENT)
766 return val;
767 else
768 /* The error here is dubious, but there is little else we
769 can do. The alternatives are to return nil, which is
770 as bad as (and in many cases worse than) throwing the
771 error, or to ignore the error, which will likely result
772 in looping through 225307 stat's, which is not only
773 dog-slow, but also useless since it will fallback to
774 the errow below, anyway. */
775 report_file_error ("Cannot create temporary name for prefix",
776 Fcons (prefix, Qnil));
777 /* not reached */
781 error ("Cannot create temporary name for prefix `%s'",
782 SDATA (prefix));
783 return Qnil;
787 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
788 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
789 The Emacs process number forms part of the result,
790 so there is no danger of generating a name being used by another process.
792 In addition, this function makes an attempt to choose a name
793 which has no existing file. To make this work,
794 PREFIX should be an absolute file name.
796 There is a race condition between calling `make-temp-name' and creating the
797 file which opens all kinds of security holes. For that reason, you should
798 probably use `make-temp-file' instead, except in three circumstances:
800 * If you are creating the file in the user's home directory.
801 * If you are creating a directory rather than an ordinary file.
802 * If you are taking special precautions as `make-temp-file' does. */)
803 (prefix)
804 Lisp_Object prefix;
806 return make_temp_name (prefix, 0);
811 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
812 doc: /* Convert filename NAME to absolute, and canonicalize it.
813 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
814 \(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
815 the current buffer's value of `default-directory' is used.
816 File name components that are `.' are removed, and
817 so are file name components followed by `..', along with the `..' itself;
818 note that these simplifications are done without checking the resulting
819 file names in the file system.
820 An initial `~/' expands to your home directory.
821 An initial `~USER/' expands to USER's home directory.
822 See also the function `substitute-in-file-name'.
824 For technical reasons, this function can return correct but
825 non-intuitive results for the root directory; for instance,
826 \(expand-file-name ".." "/") returns "/..". For this reason, use
827 (directory-file-name (file-name-directory dirname)) to traverse a
828 filesystem tree, not (expand-file-name ".." dirname). */)
829 (name, default_directory)
830 Lisp_Object name, default_directory;
832 /* These point to SDATA and need to be careful with string-relocation
833 during GC (via DECODE_FILE). */
834 unsigned char *nm, *newdir;
835 /* This should only point to alloca'd data. */
836 unsigned char *target;
838 int tlen;
839 struct passwd *pw;
840 #ifdef DOS_NT
841 int drive = 0;
842 int collapse_newdir = 1;
843 int is_escaped = 0;
844 #endif /* DOS_NT */
845 int length;
846 Lisp_Object handler, result;
847 int multibyte;
848 Lisp_Object hdir;
850 CHECK_STRING (name);
852 /* If the file name has special constructs in it,
853 call the corresponding file handler. */
854 handler = Ffind_file_name_handler (name, Qexpand_file_name);
855 if (!NILP (handler))
856 return call3 (handler, Qexpand_file_name, name, default_directory);
858 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
859 if (NILP (default_directory))
860 default_directory = current_buffer->directory;
861 if (! STRINGP (default_directory))
863 #ifdef DOS_NT
864 /* "/" is not considered a root directory on DOS_NT, so using "/"
865 here causes an infinite recursion in, e.g., the following:
867 (let (default-directory)
868 (expand-file-name "a"))
870 To avoid this, we set default_directory to the root of the
871 current drive. */
872 extern char *emacs_root_dir (void);
874 default_directory = build_string (emacs_root_dir ());
875 #else
876 default_directory = build_string ("/");
877 #endif
880 if (!NILP (default_directory))
882 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
883 if (!NILP (handler))
884 return call3 (handler, Qexpand_file_name, name, default_directory);
888 unsigned char *o = SDATA (default_directory);
890 /* Make sure DEFAULT_DIRECTORY is properly expanded.
891 It would be better to do this down below where we actually use
892 default_directory. Unfortunately, calling Fexpand_file_name recursively
893 could invoke GC, and the strings might be relocated. This would
894 be annoying because we have pointers into strings lying around
895 that would need adjusting, and people would add new pointers to
896 the code and forget to adjust them, resulting in intermittent bugs.
897 Putting this call here avoids all that crud.
899 The EQ test avoids infinite recursion. */
900 if (! NILP (default_directory) && !EQ (default_directory, name)
901 /* Save time in some common cases - as long as default_directory
902 is not relative, it can be canonicalized with name below (if it
903 is needed at all) without requiring it to be expanded now. */
904 #ifdef DOS_NT
905 /* Detect MSDOS file names with drive specifiers. */
906 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
907 && IS_DIRECTORY_SEP (o[2]))
908 #ifdef WINDOWSNT
909 /* Detect Windows file names in UNC format. */
910 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
911 #endif
912 #else /* not DOS_NT */
913 /* Detect Unix absolute file names (/... alone is not absolute on
914 DOS or Windows). */
915 && ! (IS_DIRECTORY_SEP (o[0]))
916 #endif /* not DOS_NT */
919 struct gcpro gcpro1;
921 GCPRO1 (name);
922 default_directory = Fexpand_file_name (default_directory, Qnil);
923 UNGCPRO;
926 name = FILE_SYSTEM_CASE (name);
927 multibyte = STRING_MULTIBYTE (name);
928 if (multibyte != STRING_MULTIBYTE (default_directory))
930 if (multibyte)
931 default_directory = string_to_multibyte (default_directory);
932 else
934 name = string_to_multibyte (name);
935 multibyte = 1;
939 nm = SDATA (name);
941 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
942 nm = strcpy (alloca (strlen (nm) + 1), nm);
944 #ifdef DOS_NT
945 /* Note if special escape prefix is present, but remove for now. */
946 if (nm[0] == '/' && nm[1] == ':')
948 is_escaped = 1;
949 nm += 2;
952 /* Find and remove drive specifier if present; this makes nm absolute
953 even if the rest of the name appears to be relative. Only look for
954 drive specifier at the beginning. */
955 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
957 drive = nm[0];
958 nm += 2;
961 #ifdef WINDOWSNT
962 /* If we see "c://somedir", we want to strip the first slash after the
963 colon when stripping the drive letter. Otherwise, this expands to
964 "//somedir". */
965 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
966 nm++;
968 /* Discard any previous drive specifier if nm is now in UNC format. */
969 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
971 drive = 0;
973 #endif /* WINDOWSNT */
974 #endif /* DOS_NT */
976 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
977 none are found, we can probably return right away. We will avoid
978 allocating a new string if name is already fully expanded. */
979 if (
980 IS_DIRECTORY_SEP (nm[0])
981 #ifdef MSDOS
982 && drive && !is_escaped
983 #endif
984 #ifdef WINDOWSNT
985 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
986 #endif
989 /* If it turns out that the filename we want to return is just a
990 suffix of FILENAME, we don't need to go through and edit
991 things; we just need to construct a new string using data
992 starting at the middle of FILENAME. If we set lose to a
993 non-zero value, that means we've discovered that we can't do
994 that cool trick. */
995 int lose = 0;
996 unsigned char *p = nm;
998 while (*p)
1000 /* Since we know the name is absolute, we can assume that each
1001 element starts with a "/". */
1003 /* "." and ".." are hairy. */
1004 if (IS_DIRECTORY_SEP (p[0])
1005 && p[1] == '.'
1006 && (IS_DIRECTORY_SEP (p[2])
1007 || p[2] == 0
1008 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1009 || p[3] == 0))))
1010 lose = 1;
1011 /* We want to replace multiple `/' in a row with a single
1012 slash. */
1013 else if (p > nm
1014 && IS_DIRECTORY_SEP (p[0])
1015 && IS_DIRECTORY_SEP (p[1]))
1016 lose = 1;
1017 p++;
1019 if (!lose)
1021 #ifdef DOS_NT
1022 /* Make sure directories are all separated with / or \ as
1023 desired, but avoid allocation of a new string when not
1024 required. */
1025 CORRECT_DIR_SEPS (nm);
1026 #ifdef WINDOWSNT
1027 if (IS_DIRECTORY_SEP (nm[1]))
1029 if (strcmp (nm, SDATA (name)) != 0)
1030 name = make_specified_string (nm, -1, strlen (nm), multibyte);
1032 else
1033 #endif
1034 /* drive must be set, so this is okay */
1035 if (strcmp (nm - 2, SDATA (name)) != 0)
1037 char temp[] = " :";
1039 name = make_specified_string (nm, -1, p - nm, multibyte);
1040 temp[0] = DRIVE_LETTER (drive);
1041 name = concat2 (build_string (temp), name);
1043 return name;
1044 #else /* not DOS_NT */
1045 if (strcmp (nm, SDATA (name)) == 0)
1046 return name;
1047 return make_specified_string (nm, -1, strlen (nm), multibyte);
1048 #endif /* not DOS_NT */
1052 /* At this point, nm might or might not be an absolute file name. We
1053 need to expand ~ or ~user if present, otherwise prefix nm with
1054 default_directory if nm is not absolute, and finally collapse /./
1055 and /foo/../ sequences.
1057 We set newdir to be the appropriate prefix if one is needed:
1058 - the relevant user directory if nm starts with ~ or ~user
1059 - the specified drive's working dir (DOS/NT only) if nm does not
1060 start with /
1061 - the value of default_directory.
1063 Note that these prefixes are not guaranteed to be absolute (except
1064 for the working dir of a drive). Therefore, to ensure we always
1065 return an absolute name, if the final prefix is not absolute we
1066 append it to the current working directory. */
1068 newdir = 0;
1070 if (nm[0] == '~') /* prefix ~ */
1072 if (IS_DIRECTORY_SEP (nm[1])
1073 || nm[1] == 0) /* ~ by itself */
1075 Lisp_Object tem;
1077 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1078 newdir = (unsigned char *) "";
1079 nm++;
1080 /* egetenv may return a unibyte string, which will bite us since
1081 we expect the directory to be multibyte. */
1082 tem = build_string (newdir);
1083 if (!STRING_MULTIBYTE (tem))
1085 hdir = DECODE_FILE (tem);
1086 newdir = SDATA (hdir);
1088 #ifdef DOS_NT
1089 collapse_newdir = 0;
1090 #endif
1092 else /* ~user/filename */
1094 unsigned char *o, *p;
1095 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
1096 o = alloca (p - nm + 1);
1097 bcopy ((char *) nm, o, p - nm);
1098 o [p - nm] = 0;
1100 BLOCK_INPUT;
1101 pw = (struct passwd *) getpwnam (o + 1);
1102 UNBLOCK_INPUT;
1103 if (pw)
1105 newdir = (unsigned char *) pw -> pw_dir;
1106 nm = p;
1107 #ifdef DOS_NT
1108 collapse_newdir = 0;
1109 #endif
1112 /* If we don't find a user of that name, leave the name
1113 unchanged; don't move nm forward to p. */
1117 #ifdef DOS_NT
1118 /* On DOS and Windows, nm is absolute if a drive name was specified;
1119 use the drive's current directory as the prefix if needed. */
1120 if (!newdir && drive)
1122 /* Get default directory if needed to make nm absolute. */
1123 if (!IS_DIRECTORY_SEP (nm[0]))
1125 newdir = alloca (MAXPATHLEN + 1);
1126 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1127 newdir = NULL;
1129 if (!newdir)
1131 /* Either nm starts with /, or drive isn't mounted. */
1132 newdir = alloca (4);
1133 newdir[0] = DRIVE_LETTER (drive);
1134 newdir[1] = ':';
1135 newdir[2] = '/';
1136 newdir[3] = 0;
1139 #endif /* DOS_NT */
1141 /* Finally, if no prefix has been specified and nm is not absolute,
1142 then it must be expanded relative to default_directory. */
1144 if (1
1145 #ifndef DOS_NT
1146 /* /... alone is not absolute on DOS and Windows. */
1147 && !IS_DIRECTORY_SEP (nm[0])
1148 #endif
1149 #ifdef WINDOWSNT
1150 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1151 #endif
1152 && !newdir)
1154 newdir = SDATA (default_directory);
1155 #ifdef DOS_NT
1156 /* Note if special escape prefix is present, but remove for now. */
1157 if (newdir[0] == '/' && newdir[1] == ':')
1159 is_escaped = 1;
1160 newdir += 2;
1162 #endif
1165 #ifdef DOS_NT
1166 if (newdir)
1168 /* First ensure newdir is an absolute name. */
1169 if (
1170 /* Detect MSDOS file names with drive specifiers. */
1171 ! (IS_DRIVE (newdir[0])
1172 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1173 #ifdef WINDOWSNT
1174 /* Detect Windows file names in UNC format. */
1175 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1176 #endif
1179 /* Effectively, let newdir be (expand-file-name newdir cwd).
1180 Because of the admonition against calling expand-file-name
1181 when we have pointers into lisp strings, we accomplish this
1182 indirectly by prepending newdir to nm if necessary, and using
1183 cwd (or the wd of newdir's drive) as the new newdir. */
1185 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1187 drive = newdir[0];
1188 newdir += 2;
1190 if (!IS_DIRECTORY_SEP (nm[0]))
1192 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1193 file_name_as_directory (tmp, newdir);
1194 strcat (tmp, nm);
1195 nm = tmp;
1197 newdir = alloca (MAXPATHLEN + 1);
1198 if (drive)
1200 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1201 newdir = "/";
1203 else
1204 getwd (newdir);
1207 /* Strip off drive name from prefix, if present. */
1208 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1210 drive = newdir[0];
1211 newdir += 2;
1214 /* Keep only a prefix from newdir if nm starts with slash
1215 (//server/share for UNC, nothing otherwise). */
1216 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1218 #ifdef WINDOWSNT
1219 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1221 unsigned char *p;
1222 newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
1223 p = newdir + 2;
1224 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1225 p++;
1226 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1227 *p = 0;
1229 else
1230 #endif
1231 newdir = "";
1234 #endif /* DOS_NT */
1236 if (newdir)
1238 /* Get rid of any slash at the end of newdir, unless newdir is
1239 just / or // (an incomplete UNC name). */
1240 length = strlen (newdir);
1241 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1242 #ifdef WINDOWSNT
1243 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1244 #endif
1247 unsigned char *temp = (unsigned char *) alloca (length);
1248 bcopy (newdir, temp, length - 1);
1249 temp[length - 1] = 0;
1250 newdir = temp;
1252 tlen = length + 1;
1254 else
1255 tlen = 0;
1257 /* Now concatenate the directory and name to new space in the stack frame */
1258 tlen += strlen (nm) + 1;
1259 #ifdef DOS_NT
1260 /* Reserve space for drive specifier and escape prefix, since either
1261 or both may need to be inserted. (The Microsoft x86 compiler
1262 produces incorrect code if the following two lines are combined.) */
1263 target = (unsigned char *) alloca (tlen + 4);
1264 target += 4;
1265 #else /* not DOS_NT */
1266 target = (unsigned char *) alloca (tlen);
1267 #endif /* not DOS_NT */
1268 *target = 0;
1270 if (newdir)
1272 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1274 #ifdef DOS_NT
1275 /* If newdir is effectively "C:/", then the drive letter will have
1276 been stripped and newdir will be "/". Concatenating with an
1277 absolute directory in nm produces "//", which will then be
1278 incorrectly treated as a network share. Ignore newdir in
1279 this case (keeping the drive letter). */
1280 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1281 && newdir[1] == '\0'))
1282 #endif
1283 strcpy (target, newdir);
1285 else
1286 file_name_as_directory (target, newdir);
1289 strcat (target, nm);
1291 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1292 appear. */
1294 unsigned char *p = target;
1295 unsigned char *o = target;
1297 while (*p)
1299 if (!IS_DIRECTORY_SEP (*p))
1301 *o++ = *p++;
1303 else if (p[1] == '.'
1304 && (IS_DIRECTORY_SEP (p[2])
1305 || p[2] == 0))
1307 /* If "/." is the entire filename, keep the "/". Otherwise,
1308 just delete the whole "/.". */
1309 if (o == target && p[2] == '\0')
1310 *o++ = *p;
1311 p += 2;
1313 else if (p[1] == '.' && p[2] == '.'
1314 /* `/../' is the "superroot" on certain file systems.
1315 Turned off on DOS_NT systems because they have no
1316 "superroot" and because this causes us to produce
1317 file names like "d:/../foo" which fail file-related
1318 functions of the underlying OS. (To reproduce, try a
1319 long series of "../../" in default_directory, longer
1320 than the number of levels from the root.) */
1321 #ifndef DOS_NT
1322 && o != target
1323 #endif
1324 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1326 #ifdef WINDOWSNT
1327 unsigned char *prev_o = o;
1328 #endif
1329 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1331 #ifdef WINDOWSNT
1332 /* Don't go below server level in UNC filenames. */
1333 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1334 && IS_DIRECTORY_SEP (*target))
1335 o = prev_o;
1336 else
1337 #endif
1338 /* Keep initial / only if this is the whole name. */
1339 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1340 ++o;
1341 p += 3;
1343 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1344 /* Collapse multiple `/' in a row. */
1345 p++;
1346 else
1348 *o++ = *p++;
1352 #ifdef DOS_NT
1353 /* At last, set drive name. */
1354 #ifdef WINDOWSNT
1355 /* Except for network file name. */
1356 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1357 #endif /* WINDOWSNT */
1359 if (!drive) abort ();
1360 target -= 2;
1361 target[0] = DRIVE_LETTER (drive);
1362 target[1] = ':';
1364 /* Reinsert the escape prefix if required. */
1365 if (is_escaped)
1367 target -= 2;
1368 target[0] = '/';
1369 target[1] = ':';
1371 CORRECT_DIR_SEPS (target);
1372 #endif /* DOS_NT */
1374 result = make_specified_string (target, -1, o - target, multibyte);
1377 /* Again look to see if the file name has special constructs in it
1378 and perhaps call the corresponding file handler. This is needed
1379 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1380 the ".." component gives us "/user@host:/bar/../baz" which needs
1381 to be expanded again. */
1382 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1383 if (!NILP (handler))
1384 return call3 (handler, Qexpand_file_name, result, default_directory);
1386 return result;
1389 #if 0
1390 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1391 This is the old version of expand-file-name, before it was thoroughly
1392 rewritten for Emacs 10.31. We leave this version here commented-out,
1393 because the code is very complex and likely to have subtle bugs. If
1394 bugs _are_ found, it might be of interest to look at the old code and
1395 see what did it do in the relevant situation.
1397 Don't remove this code: it's true that it will be accessible via CVS,
1398 but a few years from deletion, people will forget it is there. */
1400 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1401 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1402 "Convert FILENAME to absolute, and canonicalize it.\n\
1403 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1404 \(does not start with slash); if DEFAULT is nil or missing,\n\
1405 the current buffer's value of default-directory is used.\n\
1406 Filenames containing `.' or `..' as components are simplified;\n\
1407 initial `~/' expands to your home directory.\n\
1408 See also the function `substitute-in-file-name'.")
1409 (name, defalt)
1410 Lisp_Object name, defalt;
1412 unsigned char *nm;
1414 register unsigned char *newdir, *p, *o;
1415 int tlen;
1416 unsigned char *target;
1417 struct passwd *pw;
1418 int lose;
1420 CHECK_STRING (name);
1421 nm = SDATA (name);
1423 /* If nm is absolute, flush ...// and detect /./ and /../.
1424 If no /./ or /../ we can return right away. */
1425 if (nm[0] == '/')
1427 p = nm;
1428 lose = 0;
1429 while (*p)
1431 if (p[0] == '/' && p[1] == '/'
1433 nm = p + 1;
1434 if (p[0] == '/' && p[1] == '~')
1435 nm = p + 1, lose = 1;
1436 if (p[0] == '/' && p[1] == '.'
1437 && (p[2] == '/' || p[2] == 0
1438 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1439 lose = 1;
1440 p++;
1442 if (!lose)
1444 if (nm == SDATA (name))
1445 return name;
1446 return build_string (nm);
1450 /* Now determine directory to start with and put it in NEWDIR */
1452 newdir = 0;
1454 if (nm[0] == '~') /* prefix ~ */
1455 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1457 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1458 newdir = (unsigned char *) "";
1459 nm++;
1461 else /* ~user/filename */
1463 /* Get past ~ to user */
1464 unsigned char *user = nm + 1;
1465 /* Find end of name. */
1466 unsigned char *ptr = (unsigned char *) index (user, '/');
1467 int len = ptr ? ptr - user : strlen (user);
1468 /* Copy the user name into temp storage. */
1469 o = (unsigned char *) alloca (len + 1);
1470 bcopy ((char *) user, o, len);
1471 o[len] = 0;
1473 /* Look up the user name. */
1474 BLOCK_INPUT;
1475 pw = (struct passwd *) getpwnam (o + 1);
1476 UNBLOCK_INPUT;
1477 if (!pw)
1478 error ("\"%s\" isn't a registered user", o + 1);
1480 newdir = (unsigned char *) pw->pw_dir;
1482 /* Discard the user name from NM. */
1483 nm += len;
1486 if (nm[0] != '/' && !newdir)
1488 if (NILP (defalt))
1489 defalt = current_buffer->directory;
1490 CHECK_STRING (defalt);
1491 newdir = SDATA (defalt);
1494 /* Now concatenate the directory and name to new space in the stack frame */
1496 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1497 target = (unsigned char *) alloca (tlen);
1498 *target = 0;
1500 if (newdir)
1502 if (nm[0] == 0 || nm[0] == '/')
1503 strcpy (target, newdir);
1504 else
1505 file_name_as_directory (target, newdir);
1508 strcat (target, nm);
1510 /* Now canonicalize by removing /. and /foo/.. if they appear */
1512 p = target;
1513 o = target;
1515 while (*p)
1517 if (*p != '/')
1519 *o++ = *p++;
1521 else if (!strncmp (p, "//", 2)
1524 o = target;
1525 p++;
1527 else if (p[0] == '/' && p[1] == '.'
1528 && (p[2] == '/' || p[2] == 0))
1529 p += 2;
1530 else if (!strncmp (p, "/..", 3)
1531 /* `/../' is the "superroot" on certain file systems. */
1532 && o != target
1533 && (p[3] == '/' || p[3] == 0))
1535 while (o != target && *--o != '/')
1537 if (o == target && *o == '/')
1538 ++o;
1539 p += 3;
1541 else
1543 *o++ = *p++;
1547 return make_string (target, o - target);
1549 #endif
1551 /* If /~ or // appears, discard everything through first slash. */
1552 static int
1553 file_name_absolute_p (filename)
1554 const unsigned char *filename;
1556 return
1557 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1558 #ifdef DOS_NT
1559 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1560 && IS_DIRECTORY_SEP (filename[2]))
1561 #endif
1565 static unsigned char *
1566 search_embedded_absfilename (nm, endp)
1567 unsigned char *nm, *endp;
1569 unsigned char *p, *s;
1571 for (p = nm + 1; p < endp; p++)
1573 if ((0
1574 || IS_DIRECTORY_SEP (p[-1]))
1575 && file_name_absolute_p (p)
1576 #if defined (WINDOWSNT) || defined(CYGWIN)
1577 /* // at start of file name is meaningful in Apollo,
1578 WindowsNT and Cygwin systems. */
1579 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1580 #endif /* not (WINDOWSNT || CYGWIN) */
1583 for (s = p; *s && (!IS_DIRECTORY_SEP (*s)); s++);
1584 if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
1586 unsigned char *o = alloca (s - p + 1);
1587 struct passwd *pw;
1588 bcopy (p, o, s - p);
1589 o [s - p] = 0;
1591 /* If we have ~user and `user' exists, discard
1592 everything up to ~. But if `user' does not exist, leave
1593 ~user alone, it might be a literal file name. */
1594 BLOCK_INPUT;
1595 pw = getpwnam (o + 1);
1596 UNBLOCK_INPUT;
1597 if (pw)
1598 return p;
1600 else
1601 return p;
1604 return NULL;
1607 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1608 Ssubstitute_in_file_name, 1, 1, 0,
1609 doc: /* Substitute environment variables referred to in FILENAME.
1610 `$FOO' where FOO is an environment variable name means to substitute
1611 the value of that variable. The variable name should be terminated
1612 with a character not a letter, digit or underscore; otherwise, enclose
1613 the entire variable name in braces.
1614 If `/~' appears, all of FILENAME through that `/' is discarded. */)
1615 (filename)
1616 Lisp_Object filename;
1618 unsigned char *nm;
1620 register unsigned char *s, *p, *o, *x, *endp;
1621 unsigned char *target = NULL;
1622 int total = 0;
1623 int substituted = 0;
1624 unsigned char *xnm;
1625 Lisp_Object handler;
1627 CHECK_STRING (filename);
1629 /* If the file name has special constructs in it,
1630 call the corresponding file handler. */
1631 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1632 if (!NILP (handler))
1633 return call2 (handler, Qsubstitute_in_file_name, filename);
1635 nm = SDATA (filename);
1636 #ifdef DOS_NT
1637 nm = strcpy (alloca (strlen (nm) + 1), nm);
1638 CORRECT_DIR_SEPS (nm);
1639 substituted = (strcmp (nm, SDATA (filename)) != 0);
1640 #endif
1641 endp = nm + SBYTES (filename);
1643 /* If /~ or // appears, discard everything through first slash. */
1644 p = search_embedded_absfilename (nm, endp);
1645 if (p)
1646 /* Start over with the new string, so we check the file-name-handler
1647 again. Important with filenames like "/home/foo//:/hello///there"
1648 which whould substitute to "/:/hello///there" rather than "/there". */
1649 return Fsubstitute_in_file_name
1650 (make_specified_string (p, -1, endp - p,
1651 STRING_MULTIBYTE (filename)));
1654 /* See if any variables are substituted into the string
1655 and find the total length of their values in `total' */
1657 for (p = nm; p != endp;)
1658 if (*p != '$')
1659 p++;
1660 else
1662 p++;
1663 if (p == endp)
1664 goto badsubst;
1665 else if (*p == '$')
1667 /* "$$" means a single "$" */
1668 p++;
1669 total -= 1;
1670 substituted = 1;
1671 continue;
1673 else if (*p == '{')
1675 o = ++p;
1676 while (p != endp && *p != '}') p++;
1677 if (*p != '}') goto missingclose;
1678 s = p;
1680 else
1682 o = p;
1683 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1684 s = p;
1687 /* Copy out the variable name */
1688 target = (unsigned char *) alloca (s - o + 1);
1689 strncpy (target, o, s - o);
1690 target[s - o] = 0;
1691 #ifdef DOS_NT
1692 strupr (target); /* $home == $HOME etc. */
1693 #endif /* DOS_NT */
1695 /* Get variable value */
1696 o = (unsigned char *) egetenv (target);
1697 if (o)
1698 { /* Eight-bit chars occupy upto 2 bytes in multibyte. */
1699 total += strlen (o) * (STRING_MULTIBYTE (filename) ? 2 : 1);
1700 substituted = 1;
1702 else if (*p == '}')
1703 goto badvar;
1706 if (!substituted)
1707 return filename;
1709 /* If substitution required, recopy the string and do it */
1710 /* Make space in stack frame for the new copy */
1711 xnm = (unsigned char *) alloca (SBYTES (filename) + total + 1);
1712 x = xnm;
1714 /* Copy the rest of the name through, replacing $ constructs with values */
1715 for (p = nm; *p;)
1716 if (*p != '$')
1717 *x++ = *p++;
1718 else
1720 p++;
1721 if (p == endp)
1722 goto badsubst;
1723 else if (*p == '$')
1725 *x++ = *p++;
1726 continue;
1728 else if (*p == '{')
1730 o = ++p;
1731 while (p != endp && *p != '}') p++;
1732 if (*p != '}') goto missingclose;
1733 s = p++;
1735 else
1737 o = p;
1738 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1739 s = p;
1742 /* Copy out the variable name */
1743 target = (unsigned char *) alloca (s - o + 1);
1744 strncpy (target, o, s - o);
1745 target[s - o] = 0;
1746 #ifdef DOS_NT
1747 strupr (target); /* $home == $HOME etc. */
1748 #endif /* DOS_NT */
1750 /* Get variable value */
1751 o = (unsigned char *) egetenv (target);
1752 if (!o)
1754 *x++ = '$';
1755 strcpy (x, target); x+= strlen (target);
1757 else if (STRING_MULTIBYTE (filename))
1759 /* If the original string is multibyte,
1760 convert what we substitute into multibyte. */
1761 while (*o)
1763 int c = *o++;
1764 c = unibyte_char_to_multibyte (c);
1765 x += CHAR_STRING (c, x);
1768 else
1770 strcpy (x, o);
1771 x += strlen (o);
1775 *x = 0;
1777 /* If /~ or // appears, discard everything through first slash. */
1778 while ((p = search_embedded_absfilename (xnm, x)))
1779 /* This time we do not start over because we've already expanded envvars
1780 and replaced $$ with $. Maybe we should start over as well, but we'd
1781 need to quote some $ to $$ first. */
1782 xnm = p;
1784 return make_specified_string (xnm, -1, x - xnm, STRING_MULTIBYTE (filename));
1786 badsubst:
1787 error ("Bad format environment-variable substitution");
1788 missingclose:
1789 error ("Missing \"}\" in environment-variable substitution");
1790 badvar:
1791 error ("Substituting nonexistent environment variable \"%s\"", target);
1793 /* NOTREACHED */
1794 return Qnil;
1797 /* A slightly faster and more convenient way to get
1798 (directory-file-name (expand-file-name FOO)). */
1800 Lisp_Object
1801 expand_and_dir_to_file (filename, defdir)
1802 Lisp_Object filename, defdir;
1804 register Lisp_Object absname;
1806 absname = Fexpand_file_name (filename, defdir);
1808 /* Remove final slash, if any (unless this is the root dir).
1809 stat behaves differently depending! */
1810 if (SCHARS (absname) > 1
1811 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1812 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
1813 /* We cannot take shortcuts; they might be wrong for magic file names. */
1814 absname = Fdirectory_file_name (absname);
1815 return absname;
1818 /* Signal an error if the file ABSNAME already exists.
1819 If INTERACTIVE is nonzero, ask the user whether to proceed,
1820 and bypass the error if the user says to go ahead.
1821 QUERYSTRING is a name for the action that is being considered
1822 to alter the file.
1824 *STATPTR is used to store the stat information if the file exists.
1825 If the file does not exist, STATPTR->st_mode is set to 0.
1826 If STATPTR is null, we don't store into it.
1828 If QUICK is nonzero, we ask for y or n, not yes or no. */
1830 void
1831 barf_or_query_if_file_exists (absname, querystring, interactive, statptr, quick)
1832 Lisp_Object absname;
1833 unsigned char *querystring;
1834 int interactive;
1835 struct stat *statptr;
1836 int quick;
1838 register Lisp_Object tem, encoded_filename;
1839 struct stat statbuf;
1840 struct gcpro gcpro1;
1842 encoded_filename = ENCODE_FILE (absname);
1844 /* stat is a good way to tell whether the file exists,
1845 regardless of what access permissions it has. */
1846 if (lstat (SDATA (encoded_filename), &statbuf) >= 0)
1848 if (! interactive)
1849 xsignal2 (Qfile_already_exists,
1850 build_string ("File already exists"), absname);
1851 GCPRO1 (absname);
1852 tem = format2 ("File %s already exists; %s anyway? ",
1853 absname, build_string (querystring));
1854 if (quick)
1855 tem = Fy_or_n_p (tem);
1856 else
1857 tem = do_yes_or_no_p (tem);
1858 UNGCPRO;
1859 if (NILP (tem))
1860 xsignal2 (Qfile_already_exists,
1861 build_string ("File already exists"), absname);
1862 if (statptr)
1863 *statptr = statbuf;
1865 else
1867 if (statptr)
1868 statptr->st_mode = 0;
1870 return;
1873 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 5,
1874 "fCopy file: \nGCopy %s to file: \np\nP",
1875 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1876 If NEWNAME names a directory, copy FILE there.
1878 This function always sets the file modes of the output file to match
1879 the input file.
1881 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1882 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1883 signal a `file-already-exists' error without overwriting. If
1884 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1885 about overwriting; this is what happens in interactive use with M-x.
1886 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1887 existing file.
1889 Fourth arg KEEP-TIME non-nil means give the output file the same
1890 last-modified time as the old one. (This works on only some systems.)
1892 A prefix arg makes KEEP-TIME non-nil.
1894 If PRESERVE-UID-GID is non-nil, we try to transfer the
1895 uid and gid of FILE to NEWNAME. */)
1896 (file, newname, ok_if_already_exists, keep_time, preserve_uid_gid)
1897 Lisp_Object file, newname, ok_if_already_exists, keep_time;
1898 Lisp_Object preserve_uid_gid;
1900 int ifd, ofd, n;
1901 char buf[16 * 1024];
1902 struct stat st, out_st;
1903 Lisp_Object handler;
1904 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1905 int count = SPECPDL_INDEX ();
1906 int input_file_statable_p;
1907 Lisp_Object encoded_file, encoded_newname;
1909 encoded_file = encoded_newname = Qnil;
1910 GCPRO4 (file, newname, encoded_file, encoded_newname);
1911 CHECK_STRING (file);
1912 CHECK_STRING (newname);
1914 if (!NILP (Ffile_directory_p (newname)))
1915 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1916 else
1917 newname = Fexpand_file_name (newname, Qnil);
1919 file = Fexpand_file_name (file, Qnil);
1921 /* If the input file name has special constructs in it,
1922 call the corresponding file handler. */
1923 handler = Ffind_file_name_handler (file, Qcopy_file);
1924 /* Likewise for output file name. */
1925 if (NILP (handler))
1926 handler = Ffind_file_name_handler (newname, Qcopy_file);
1927 if (!NILP (handler))
1928 RETURN_UNGCPRO (call6 (handler, Qcopy_file, file, newname,
1929 ok_if_already_exists, keep_time, preserve_uid_gid));
1931 encoded_file = ENCODE_FILE (file);
1932 encoded_newname = ENCODE_FILE (newname);
1934 if (NILP (ok_if_already_exists)
1935 || INTEGERP (ok_if_already_exists))
1936 barf_or_query_if_file_exists (newname, "copy to it",
1937 INTEGERP (ok_if_already_exists), &out_st, 0);
1938 else if (stat (SDATA (encoded_newname), &out_st) < 0)
1939 out_st.st_mode = 0;
1941 #ifdef WINDOWSNT
1942 if (!CopyFile (SDATA (encoded_file),
1943 SDATA (encoded_newname),
1944 FALSE))
1945 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
1946 /* CopyFile retains the timestamp by default. */
1947 else if (NILP (keep_time))
1949 EMACS_TIME now;
1950 DWORD attributes;
1951 char * filename;
1953 EMACS_GET_TIME (now);
1954 filename = SDATA (encoded_newname);
1956 /* Ensure file is writable while its modified time is set. */
1957 attributes = GetFileAttributes (filename);
1958 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
1959 if (set_file_times (filename, now, now))
1961 /* Restore original attributes. */
1962 SetFileAttributes (filename, attributes);
1963 xsignal2 (Qfile_date_error,
1964 build_string ("Cannot set file date"), newname);
1966 /* Restore original attributes. */
1967 SetFileAttributes (filename, attributes);
1969 #else /* not WINDOWSNT */
1970 immediate_quit = 1;
1971 ifd = emacs_open (SDATA (encoded_file), O_RDONLY, 0);
1972 immediate_quit = 0;
1974 if (ifd < 0)
1975 report_file_error ("Opening input file", Fcons (file, Qnil));
1977 record_unwind_protect (close_file_unwind, make_number (ifd));
1979 /* We can only copy regular files and symbolic links. Other files are not
1980 copyable by us. */
1981 input_file_statable_p = (fstat (ifd, &st) >= 0);
1983 #if !defined (MSDOS) || __DJGPP__ > 1
1984 if (out_st.st_mode != 0
1985 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1987 errno = 0;
1988 report_file_error ("Input and output files are the same",
1989 Fcons (file, Fcons (newname, Qnil)));
1991 #endif
1993 #if defined (S_ISREG) && defined (S_ISLNK)
1994 if (input_file_statable_p)
1996 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
1998 #if defined (EISDIR)
1999 /* Get a better looking error message. */
2000 errno = EISDIR;
2001 #endif /* EISDIR */
2002 report_file_error ("Non-regular file", Fcons (file, Qnil));
2005 #endif /* S_ISREG && S_ISLNK */
2007 #ifdef MSDOS
2008 /* System's default file type was set to binary by _fmode in emacs.c. */
2009 ofd = emacs_open (SDATA (encoded_newname),
2010 O_WRONLY | O_TRUNC | O_CREAT
2011 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2012 S_IREAD | S_IWRITE);
2013 #else /* not MSDOS */
2014 ofd = emacs_open (SDATA (encoded_newname),
2015 O_WRONLY | O_TRUNC | O_CREAT
2016 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2017 0666);
2018 #endif /* not MSDOS */
2019 if (ofd < 0)
2020 report_file_error ("Opening output file", Fcons (newname, Qnil));
2022 record_unwind_protect (close_file_unwind, make_number (ofd));
2024 immediate_quit = 1;
2025 QUIT;
2026 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2027 if (emacs_write (ofd, buf, n) != n)
2028 report_file_error ("I/O error", Fcons (newname, Qnil));
2029 immediate_quit = 0;
2031 #ifndef MSDOS
2032 /* Preserve the original file modes, and if requested, also its
2033 owner and group. */
2034 if (input_file_statable_p)
2036 if (! NILP (preserve_uid_gid))
2037 fchown (ofd, st.st_uid, st.st_gid);
2038 fchmod (ofd, st.st_mode & 07777);
2040 #endif /* not MSDOS */
2042 /* Closing the output clobbers the file times on some systems. */
2043 if (emacs_close (ofd) < 0)
2044 report_file_error ("I/O error", Fcons (newname, Qnil));
2046 if (input_file_statable_p)
2048 if (!NILP (keep_time))
2050 EMACS_TIME atime, mtime;
2051 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2052 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2053 if (set_file_times (SDATA (encoded_newname),
2054 atime, mtime))
2055 xsignal2 (Qfile_date_error,
2056 build_string ("Cannot set file date"), newname);
2060 emacs_close (ifd);
2062 #if defined (__DJGPP__) && __DJGPP__ > 1
2063 if (input_file_statable_p)
2065 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2066 and if it can't, it tells so. Otherwise, under MSDOS we usually
2067 get only the READ bit, which will make the copied file read-only,
2068 so it's better not to chmod at all. */
2069 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2070 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2072 #endif /* DJGPP version 2 or newer */
2073 #endif /* not WINDOWSNT */
2075 /* Discard the unwind protects. */
2076 specpdl_ptr = specpdl + count;
2078 UNGCPRO;
2079 return Qnil;
2082 DEFUN ("make-directory-internal", Fmake_directory_internal,
2083 Smake_directory_internal, 1, 1, 0,
2084 doc: /* Create a new directory named DIRECTORY. */)
2085 (directory)
2086 Lisp_Object directory;
2088 const unsigned char *dir;
2089 Lisp_Object handler;
2090 Lisp_Object encoded_dir;
2092 CHECK_STRING (directory);
2093 directory = Fexpand_file_name (directory, Qnil);
2095 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2096 if (!NILP (handler))
2097 return call2 (handler, Qmake_directory_internal, directory);
2099 encoded_dir = ENCODE_FILE (directory);
2101 dir = SDATA (encoded_dir);
2103 #ifdef WINDOWSNT
2104 if (mkdir (dir) != 0)
2105 #else
2106 if (mkdir (dir, 0777) != 0)
2107 #endif
2108 report_file_error ("Creating directory", list1 (directory));
2110 return Qnil;
2113 DEFUN ("delete-directory", Fdelete_directory, Sdelete_directory, 1, 1, "FDelete directory: ",
2114 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2115 (directory)
2116 Lisp_Object directory;
2118 const unsigned char *dir;
2119 Lisp_Object handler;
2120 Lisp_Object encoded_dir;
2122 CHECK_STRING (directory);
2123 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2125 handler = Ffind_file_name_handler (directory, Qdelete_directory);
2126 if (!NILP (handler))
2127 return call2 (handler, Qdelete_directory, directory);
2129 if (delete_by_moving_to_trash)
2130 return call1 (Qmove_file_to_trash, directory);
2132 encoded_dir = ENCODE_FILE (directory);
2134 dir = SDATA (encoded_dir);
2136 if (rmdir (dir) != 0)
2137 report_file_error ("Removing directory", list1 (directory));
2139 return Qnil;
2142 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 1, "fDelete file: ",
2143 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2144 If file has multiple names, it continues to exist with the other names. */)
2145 (filename)
2146 Lisp_Object filename;
2148 Lisp_Object handler;
2149 Lisp_Object encoded_file;
2150 struct gcpro gcpro1;
2152 GCPRO1 (filename);
2153 if (!NILP (Ffile_directory_p (filename))
2154 && NILP (Ffile_symlink_p (filename)))
2155 xsignal2 (Qfile_error,
2156 build_string ("Removing old name: is a directory"),
2157 filename);
2158 UNGCPRO;
2159 filename = Fexpand_file_name (filename, Qnil);
2161 handler = Ffind_file_name_handler (filename, Qdelete_file);
2162 if (!NILP (handler))
2163 return call2 (handler, Qdelete_file, filename);
2165 if (delete_by_moving_to_trash)
2166 return call1 (Qmove_file_to_trash, filename);
2168 encoded_file = ENCODE_FILE (filename);
2170 if (0 > unlink (SDATA (encoded_file)))
2171 report_file_error ("Removing old name", list1 (filename));
2172 return Qnil;
2175 static Lisp_Object
2176 internal_delete_file_1 (ignore)
2177 Lisp_Object ignore;
2179 return Qt;
2182 /* Delete file FILENAME, returning 1 if successful and 0 if failed. */
2185 internal_delete_file (filename)
2186 Lisp_Object filename;
2188 Lisp_Object tem;
2189 tem = internal_condition_case_1 (Fdelete_file, filename,
2190 Qt, internal_delete_file_1);
2191 return NILP (tem);
2194 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2195 "fRename file: \nGRename %s to file: \np",
2196 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2197 If file has names other than FILE, it continues to have those names.
2198 Signals a `file-already-exists' error if a file NEWNAME already exists
2199 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2200 A number as third arg means request confirmation if NEWNAME already exists.
2201 This is what happens in interactive use with M-x. */)
2202 (file, newname, ok_if_already_exists)
2203 Lisp_Object file, newname, ok_if_already_exists;
2205 Lisp_Object handler;
2206 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2207 Lisp_Object encoded_file, encoded_newname, symlink_target;
2209 symlink_target = encoded_file = encoded_newname = Qnil;
2210 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2211 CHECK_STRING (file);
2212 CHECK_STRING (newname);
2213 file = Fexpand_file_name (file, Qnil);
2215 if ((!NILP (Ffile_directory_p (newname)))
2216 #ifdef DOS_NT
2217 /* If the file names are identical but for the case,
2218 don't attempt to move directory to itself. */
2219 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2220 #endif
2222 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2223 else
2224 newname = Fexpand_file_name (newname, Qnil);
2226 /* If the file name has special constructs in it,
2227 call the corresponding file handler. */
2228 handler = Ffind_file_name_handler (file, Qrename_file);
2229 if (NILP (handler))
2230 handler = Ffind_file_name_handler (newname, Qrename_file);
2231 if (!NILP (handler))
2232 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2233 file, newname, ok_if_already_exists));
2235 encoded_file = ENCODE_FILE (file);
2236 encoded_newname = ENCODE_FILE (newname);
2238 #ifdef DOS_NT
2239 /* If the file names are identical but for the case, don't ask for
2240 confirmation: they simply want to change the letter-case of the
2241 file name. */
2242 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2243 #endif
2244 if (NILP (ok_if_already_exists)
2245 || INTEGERP (ok_if_already_exists))
2246 barf_or_query_if_file_exists (newname, "rename to it",
2247 INTEGERP (ok_if_already_exists), 0, 0);
2248 if (0 > rename (SDATA (encoded_file), SDATA (encoded_newname)))
2250 if (errno == EXDEV)
2252 int count;
2253 #ifdef S_IFLNK
2254 symlink_target = Ffile_symlink_p (file);
2255 if (! NILP (symlink_target))
2256 Fmake_symbolic_link (symlink_target, newname,
2257 NILP (ok_if_already_exists) ? Qnil : Qt);
2258 else
2259 #endif
2260 Fcopy_file (file, newname,
2261 /* We have already prompted if it was an integer,
2262 so don't have copy-file prompt again. */
2263 NILP (ok_if_already_exists) ? Qnil : Qt,
2264 Qt, Qt);
2266 count = SPECPDL_INDEX ();
2267 specbind (Qdelete_by_moving_to_trash, Qnil);
2268 Fdelete_file (file);
2269 unbind_to (count, Qnil);
2271 else
2272 report_file_error ("Renaming", list2 (file, newname));
2274 UNGCPRO;
2275 return Qnil;
2278 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2279 "fAdd name to file: \nGName to add to %s: \np",
2280 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2281 Signals a `file-already-exists' error if a file NEWNAME already exists
2282 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2283 A number as third arg means request confirmation if NEWNAME already exists.
2284 This is what happens in interactive use with M-x. */)
2285 (file, newname, ok_if_already_exists)
2286 Lisp_Object file, newname, ok_if_already_exists;
2288 Lisp_Object handler;
2289 Lisp_Object encoded_file, encoded_newname;
2290 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2292 GCPRO4 (file, newname, encoded_file, encoded_newname);
2293 encoded_file = encoded_newname = Qnil;
2294 CHECK_STRING (file);
2295 CHECK_STRING (newname);
2296 file = Fexpand_file_name (file, Qnil);
2298 if (!NILP (Ffile_directory_p (newname)))
2299 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2300 else
2301 newname = Fexpand_file_name (newname, Qnil);
2303 /* If the file name has special constructs in it,
2304 call the corresponding file handler. */
2305 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2306 if (!NILP (handler))
2307 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2308 newname, ok_if_already_exists));
2310 /* If the new name has special constructs in it,
2311 call the corresponding file handler. */
2312 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2313 if (!NILP (handler))
2314 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2315 newname, ok_if_already_exists));
2317 encoded_file = ENCODE_FILE (file);
2318 encoded_newname = ENCODE_FILE (newname);
2320 if (NILP (ok_if_already_exists)
2321 || INTEGERP (ok_if_already_exists))
2322 barf_or_query_if_file_exists (newname, "make it a new name",
2323 INTEGERP (ok_if_already_exists), 0, 0);
2325 unlink (SDATA (newname));
2326 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname)))
2327 report_file_error ("Adding new name", list2 (file, newname));
2329 UNGCPRO;
2330 return Qnil;
2333 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2334 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2335 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2336 Both args must be strings.
2337 Signals a `file-already-exists' error if a file LINKNAME already exists
2338 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2339 A number as third arg means request confirmation if LINKNAME already exists.
2340 This happens for interactive use with M-x. */)
2341 (filename, linkname, ok_if_already_exists)
2342 Lisp_Object filename, linkname, ok_if_already_exists;
2344 Lisp_Object handler;
2345 Lisp_Object encoded_filename, encoded_linkname;
2346 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2348 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2349 encoded_filename = encoded_linkname = Qnil;
2350 CHECK_STRING (filename);
2351 CHECK_STRING (linkname);
2352 /* If the link target has a ~, we must expand it to get
2353 a truly valid file name. Otherwise, do not expand;
2354 we want to permit links to relative file names. */
2355 if (SREF (filename, 0) == '~')
2356 filename = Fexpand_file_name (filename, Qnil);
2358 if (!NILP (Ffile_directory_p (linkname)))
2359 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2360 else
2361 linkname = Fexpand_file_name (linkname, Qnil);
2363 /* If the file name has special constructs in it,
2364 call the corresponding file handler. */
2365 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2366 if (!NILP (handler))
2367 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2368 linkname, ok_if_already_exists));
2370 /* If the new link name has special constructs in it,
2371 call the corresponding file handler. */
2372 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2373 if (!NILP (handler))
2374 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2375 linkname, ok_if_already_exists));
2377 #ifdef S_IFLNK
2378 encoded_filename = ENCODE_FILE (filename);
2379 encoded_linkname = ENCODE_FILE (linkname);
2381 if (NILP (ok_if_already_exists)
2382 || INTEGERP (ok_if_already_exists))
2383 barf_or_query_if_file_exists (linkname, "make it a link",
2384 INTEGERP (ok_if_already_exists), 0, 0);
2385 if (0 > symlink (SDATA (encoded_filename),
2386 SDATA (encoded_linkname)))
2388 /* If we didn't complain already, silently delete existing file. */
2389 if (errno == EEXIST)
2391 unlink (SDATA (encoded_linkname));
2392 if (0 <= symlink (SDATA (encoded_filename),
2393 SDATA (encoded_linkname)))
2395 UNGCPRO;
2396 return Qnil;
2400 report_file_error ("Making symbolic link", list2 (filename, linkname));
2402 UNGCPRO;
2403 return Qnil;
2405 #else
2406 UNGCPRO;
2407 xsignal1 (Qfile_error, build_string ("Symbolic links are not supported"));
2409 #endif /* S_IFLNK */
2413 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2414 1, 1, 0,
2415 doc: /* Return t if file FILENAME specifies an absolute file name.
2416 On Unix, this is a name starting with a `/' or a `~'. */)
2417 (filename)
2418 Lisp_Object filename;
2420 CHECK_STRING (filename);
2421 return file_name_absolute_p (SDATA (filename)) ? Qt : Qnil;
2424 /* Return nonzero if file FILENAME exists and can be executed. */
2426 static int
2427 check_executable (filename)
2428 char *filename;
2430 #ifdef DOS_NT
2431 int len = strlen (filename);
2432 char *suffix;
2433 struct stat st;
2434 if (stat (filename, &st) < 0)
2435 return 0;
2436 #if defined (WINDOWSNT) || (defined (MSDOS) && __DJGPP__ > 1)
2437 return ((st.st_mode & S_IEXEC) != 0);
2438 #else
2439 return (S_ISREG (st.st_mode)
2440 && len >= 5
2441 && (xstrcasecmp ((suffix = filename + len-4), ".com") == 0
2442 || xstrcasecmp (suffix, ".exe") == 0
2443 || xstrcasecmp (suffix, ".bat") == 0)
2444 || (st.st_mode & S_IFMT) == S_IFDIR);
2445 #endif /* not WINDOWSNT */
2446 #else /* not DOS_NT */
2447 #ifdef HAVE_EUIDACCESS
2448 return (euidaccess (filename, 1) >= 0);
2449 #else
2450 /* Access isn't quite right because it uses the real uid
2451 and we really want to test with the effective uid.
2452 But Unix doesn't give us a right way to do it. */
2453 return (access (filename, 1) >= 0);
2454 #endif
2455 #endif /* not DOS_NT */
2458 /* Return nonzero if file FILENAME exists and can be written. */
2460 static int
2461 check_writable (filename)
2462 char *filename;
2464 #ifdef MSDOS
2465 struct stat st;
2466 if (stat (filename, &st) < 0)
2467 return 0;
2468 return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
2469 #else /* not MSDOS */
2470 #ifdef HAVE_EUIDACCESS
2471 return (euidaccess (filename, 2) >= 0);
2472 #else
2473 /* Access isn't quite right because it uses the real uid
2474 and we really want to test with the effective uid.
2475 But Unix doesn't give us a right way to do it.
2476 Opening with O_WRONLY could work for an ordinary file,
2477 but would lose for directories. */
2478 return (access (filename, 2) >= 0);
2479 #endif
2480 #endif /* not MSDOS */
2483 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2484 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2485 See also `file-readable-p' and `file-attributes'.
2486 This returns nil for a symlink to a nonexistent file.
2487 Use `file-symlink-p' to test for such links. */)
2488 (filename)
2489 Lisp_Object filename;
2491 Lisp_Object absname;
2492 Lisp_Object handler;
2493 struct stat statbuf;
2495 CHECK_STRING (filename);
2496 absname = Fexpand_file_name (filename, Qnil);
2498 /* If the file name has special constructs in it,
2499 call the corresponding file handler. */
2500 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2501 if (!NILP (handler))
2502 return call2 (handler, Qfile_exists_p, absname);
2504 absname = ENCODE_FILE (absname);
2506 return (stat (SDATA (absname), &statbuf) >= 0) ? Qt : Qnil;
2509 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2510 doc: /* Return t if FILENAME can be executed by you.
2511 For a directory, this means you can access files in that directory. */)
2512 (filename)
2513 Lisp_Object filename;
2515 Lisp_Object absname;
2516 Lisp_Object handler;
2518 CHECK_STRING (filename);
2519 absname = Fexpand_file_name (filename, Qnil);
2521 /* If the file name has special constructs in it,
2522 call the corresponding file handler. */
2523 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2524 if (!NILP (handler))
2525 return call2 (handler, Qfile_executable_p, absname);
2527 absname = ENCODE_FILE (absname);
2529 return (check_executable (SDATA (absname)) ? Qt : Qnil);
2532 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2533 doc: /* Return t if file FILENAME exists and you can read it.
2534 See also `file-exists-p' and `file-attributes'. */)
2535 (filename)
2536 Lisp_Object filename;
2538 Lisp_Object absname;
2539 Lisp_Object handler;
2540 int desc;
2541 int flags;
2542 struct stat statbuf;
2544 CHECK_STRING (filename);
2545 absname = Fexpand_file_name (filename, Qnil);
2547 /* If the file name has special constructs in it,
2548 call the corresponding file handler. */
2549 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2550 if (!NILP (handler))
2551 return call2 (handler, Qfile_readable_p, absname);
2553 absname = ENCODE_FILE (absname);
2555 #if defined(DOS_NT) || defined(macintosh)
2556 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2557 directories. */
2558 if (access (SDATA (absname), 0) == 0)
2559 return Qt;
2560 return Qnil;
2561 #else /* not DOS_NT and not macintosh */
2562 flags = O_RDONLY;
2563 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
2564 /* Opening a fifo without O_NONBLOCK can wait.
2565 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2566 except in the case of a fifo, on a system which handles it. */
2567 desc = stat (SDATA (absname), &statbuf);
2568 if (desc < 0)
2569 return Qnil;
2570 if (S_ISFIFO (statbuf.st_mode))
2571 flags |= O_NONBLOCK;
2572 #endif
2573 desc = emacs_open (SDATA (absname), flags, 0);
2574 if (desc < 0)
2575 return Qnil;
2576 emacs_close (desc);
2577 return Qt;
2578 #endif /* not DOS_NT and not macintosh */
2581 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2582 on the RT/PC. */
2583 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2584 doc: /* Return t if file FILENAME can be written or created by you. */)
2585 (filename)
2586 Lisp_Object filename;
2588 Lisp_Object absname, dir, encoded;
2589 Lisp_Object handler;
2590 struct stat statbuf;
2592 CHECK_STRING (filename);
2593 absname = Fexpand_file_name (filename, Qnil);
2595 /* If the file name has special constructs in it,
2596 call the corresponding file handler. */
2597 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2598 if (!NILP (handler))
2599 return call2 (handler, Qfile_writable_p, absname);
2601 encoded = ENCODE_FILE (absname);
2602 if (stat (SDATA (encoded), &statbuf) >= 0)
2603 return (check_writable (SDATA (encoded))
2604 ? Qt : Qnil);
2606 dir = Ffile_name_directory (absname);
2607 #ifdef MSDOS
2608 if (!NILP (dir))
2609 dir = Fdirectory_file_name (dir);
2610 #endif /* MSDOS */
2612 dir = ENCODE_FILE (dir);
2613 #ifdef WINDOWSNT
2614 /* The read-only attribute of the parent directory doesn't affect
2615 whether a file or directory can be created within it. Some day we
2616 should check ACLs though, which do affect this. */
2617 if (stat (SDATA (dir), &statbuf) < 0)
2618 return Qnil;
2619 return (statbuf.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2620 #else
2621 return (check_writable (!NILP (dir) ? (char *) SDATA (dir) : "")
2622 ? Qt : Qnil);
2623 #endif
2626 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2627 doc: /* Access file FILENAME, and get an error if that does not work.
2628 The second argument STRING is used in the error message.
2629 If there is no error, returns nil. */)
2630 (filename, string)
2631 Lisp_Object filename, string;
2633 Lisp_Object handler, encoded_filename, absname;
2634 int fd;
2636 CHECK_STRING (filename);
2637 absname = Fexpand_file_name (filename, Qnil);
2639 CHECK_STRING (string);
2641 /* If the file name has special constructs in it,
2642 call the corresponding file handler. */
2643 handler = Ffind_file_name_handler (absname, Qaccess_file);
2644 if (!NILP (handler))
2645 return call3 (handler, Qaccess_file, absname, string);
2647 encoded_filename = ENCODE_FILE (absname);
2649 fd = emacs_open (SDATA (encoded_filename), O_RDONLY, 0);
2650 if (fd < 0)
2651 report_file_error (SDATA (string), Fcons (filename, Qnil));
2652 emacs_close (fd);
2654 return Qnil;
2657 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2658 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2659 The value is the link target, as a string.
2660 Otherwise it returns nil.
2662 This function returns t when given the name of a symlink that
2663 points to a nonexistent file. */)
2664 (filename)
2665 Lisp_Object filename;
2667 Lisp_Object handler;
2669 CHECK_STRING (filename);
2670 filename = Fexpand_file_name (filename, Qnil);
2672 /* If the file name has special constructs in it,
2673 call the corresponding file handler. */
2674 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2675 if (!NILP (handler))
2676 return call2 (handler, Qfile_symlink_p, filename);
2678 #ifdef S_IFLNK
2680 char *buf;
2681 int bufsize;
2682 int valsize;
2683 Lisp_Object val;
2685 filename = ENCODE_FILE (filename);
2687 bufsize = 50;
2688 buf = NULL;
2691 bufsize *= 2;
2692 buf = (char *) xrealloc (buf, bufsize);
2693 bzero (buf, bufsize);
2695 errno = 0;
2696 valsize = readlink (SDATA (filename), buf, bufsize);
2697 if (valsize == -1)
2699 #ifdef ERANGE
2700 /* HP-UX reports ERANGE if buffer is too small. */
2701 if (errno == ERANGE)
2702 valsize = bufsize;
2703 else
2704 #endif
2706 xfree (buf);
2707 return Qnil;
2711 while (valsize >= bufsize);
2713 val = make_string (buf, valsize);
2714 if (buf[0] == '/' && index (buf, ':'))
2715 val = concat2 (build_string ("/:"), val);
2716 xfree (buf);
2717 val = DECODE_FILE (val);
2718 return val;
2720 #else /* not S_IFLNK */
2721 return Qnil;
2722 #endif /* not S_IFLNK */
2725 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2726 doc: /* Return t if FILENAME names an existing directory.
2727 Symbolic links to directories count as directories.
2728 See `file-symlink-p' to distinguish symlinks. */)
2729 (filename)
2730 Lisp_Object filename;
2732 register Lisp_Object absname;
2733 struct stat st;
2734 Lisp_Object handler;
2736 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2738 /* If the file name has special constructs in it,
2739 call the corresponding file handler. */
2740 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2741 if (!NILP (handler))
2742 return call2 (handler, Qfile_directory_p, absname);
2744 absname = ENCODE_FILE (absname);
2746 if (stat (SDATA (absname), &st) < 0)
2747 return Qnil;
2748 return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2751 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
2752 doc: /* Return t if file FILENAME names a directory you can open.
2753 For the value to be t, FILENAME must specify the name of a directory as a file,
2754 and the directory must allow you to open files in it. In order to use a
2755 directory as a buffer's current directory, this predicate must return true.
2756 A directory name spec may be given instead; then the value is t
2757 if the directory so specified exists and really is a readable and
2758 searchable directory. */)
2759 (filename)
2760 Lisp_Object filename;
2762 Lisp_Object handler;
2763 int tem;
2764 struct gcpro gcpro1;
2766 /* If the file name has special constructs in it,
2767 call the corresponding file handler. */
2768 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
2769 if (!NILP (handler))
2770 return call2 (handler, Qfile_accessible_directory_p, filename);
2772 GCPRO1 (filename);
2773 tem = (NILP (Ffile_directory_p (filename))
2774 || NILP (Ffile_executable_p (filename)));
2775 UNGCPRO;
2776 return tem ? Qnil : Qt;
2779 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2780 doc: /* Return t if FILENAME names a regular file.
2781 This is the sort of file that holds an ordinary stream of data bytes.
2782 Symbolic links to regular files count as regular files.
2783 See `file-symlink-p' to distinguish symlinks. */)
2784 (filename)
2785 Lisp_Object filename;
2787 register Lisp_Object absname;
2788 struct stat st;
2789 Lisp_Object handler;
2791 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2793 /* If the file name has special constructs in it,
2794 call the corresponding file handler. */
2795 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2796 if (!NILP (handler))
2797 return call2 (handler, Qfile_regular_p, absname);
2799 absname = ENCODE_FILE (absname);
2801 #ifdef WINDOWSNT
2803 int result;
2804 Lisp_Object tem = Vw32_get_true_file_attributes;
2806 /* Tell stat to use expensive method to get accurate info. */
2807 Vw32_get_true_file_attributes = Qt;
2808 result = stat (SDATA (absname), &st);
2809 Vw32_get_true_file_attributes = tem;
2811 if (result < 0)
2812 return Qnil;
2813 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2815 #else
2816 if (stat (SDATA (absname), &st) < 0)
2817 return Qnil;
2818 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2819 #endif
2822 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
2823 doc: /* Return mode bits of file named FILENAME, as an integer.
2824 Return nil, if file does not exist or is not accessible. */)
2825 (filename)
2826 Lisp_Object filename;
2828 Lisp_Object absname;
2829 struct stat st;
2830 Lisp_Object handler;
2832 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2834 /* If the file name has special constructs in it,
2835 call the corresponding file handler. */
2836 handler = Ffind_file_name_handler (absname, Qfile_modes);
2837 if (!NILP (handler))
2838 return call2 (handler, Qfile_modes, absname);
2840 absname = ENCODE_FILE (absname);
2842 if (stat (SDATA (absname), &st) < 0)
2843 return Qnil;
2844 #if defined (MSDOS) && __DJGPP__ < 2
2845 if (check_executable (SDATA (absname)))
2846 st.st_mode |= S_IEXEC;
2847 #endif /* MSDOS && __DJGPP__ < 2 */
2849 return make_number (st.st_mode & 07777);
2852 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
2853 "(let ((file (read-file-name \"File: \"))) \
2854 (list file (read-file-modes nil file)))",
2855 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
2856 Only the 12 low bits of MODE are used.
2858 Interactively, mode bits are read by `read-file-modes', which accepts
2859 symbolic notation, like the `chmod' command from GNU Coreutils. */)
2860 (filename, mode)
2861 Lisp_Object filename, mode;
2863 Lisp_Object absname, encoded_absname;
2864 Lisp_Object handler;
2866 absname = Fexpand_file_name (filename, current_buffer->directory);
2867 CHECK_NUMBER (mode);
2869 /* If the file name has special constructs in it,
2870 call the corresponding file handler. */
2871 handler = Ffind_file_name_handler (absname, Qset_file_modes);
2872 if (!NILP (handler))
2873 return call3 (handler, Qset_file_modes, absname, mode);
2875 encoded_absname = ENCODE_FILE (absname);
2877 if (chmod (SDATA (encoded_absname), XINT (mode)) < 0)
2878 report_file_error ("Doing chmod", Fcons (absname, Qnil));
2880 return Qnil;
2883 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
2884 doc: /* Set the file permission bits for newly created files.
2885 The argument MODE should be an integer; only the low 9 bits are used.
2886 This setting is inherited by subprocesses. */)
2887 (mode)
2888 Lisp_Object mode;
2890 CHECK_NUMBER (mode);
2892 umask ((~ XINT (mode)) & 0777);
2894 return Qnil;
2897 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
2898 doc: /* Return the default file protection for created files.
2899 The value is an integer. */)
2902 int realmask;
2903 Lisp_Object value;
2905 realmask = umask (0);
2906 umask (realmask);
2908 XSETINT (value, (~ realmask) & 0777);
2909 return value;
2912 extern int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
2914 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
2915 doc: /* Set times of file FILENAME to TIME.
2916 Set both access and modification times.
2917 Return t on success, else nil.
2918 Use the current time if TIME is nil. TIME is in the format of
2919 `current-time'. */)
2920 (filename, time)
2921 Lisp_Object filename, time;
2923 Lisp_Object absname, encoded_absname;
2924 Lisp_Object handler;
2925 time_t sec;
2926 int usec;
2928 if (! lisp_time_argument (time, &sec, &usec))
2929 error ("Invalid time specification");
2931 absname = Fexpand_file_name (filename, current_buffer->directory);
2933 /* If the file name has special constructs in it,
2934 call the corresponding file handler. */
2935 handler = Ffind_file_name_handler (absname, Qset_file_times);
2936 if (!NILP (handler))
2937 return call3 (handler, Qset_file_times, absname, time);
2939 encoded_absname = ENCODE_FILE (absname);
2942 EMACS_TIME t;
2944 EMACS_SET_SECS (t, sec);
2945 EMACS_SET_USECS (t, usec);
2947 if (set_file_times (SDATA (encoded_absname), t, t))
2949 #ifdef DOS_NT
2950 struct stat st;
2952 /* Setting times on a directory always fails. */
2953 if (stat (SDATA (encoded_absname), &st) == 0
2954 && (st.st_mode & S_IFMT) == S_IFDIR)
2955 return Qnil;
2956 #endif
2957 report_file_error ("Setting file times", Fcons (absname, Qnil));
2958 return Qnil;
2962 return Qt;
2965 #ifdef HAVE_SYNC
2966 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
2967 doc: /* Tell Unix to finish all pending disk updates. */)
2970 sync ();
2971 return Qnil;
2974 #endif /* HAVE_SYNC */
2976 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
2977 doc: /* Return t if file FILE1 is newer than file FILE2.
2978 If FILE1 does not exist, the answer is nil;
2979 otherwise, if FILE2 does not exist, the answer is t. */)
2980 (file1, file2)
2981 Lisp_Object file1, file2;
2983 Lisp_Object absname1, absname2;
2984 struct stat st;
2985 int mtime1;
2986 Lisp_Object handler;
2987 struct gcpro gcpro1, gcpro2;
2989 CHECK_STRING (file1);
2990 CHECK_STRING (file2);
2992 absname1 = Qnil;
2993 GCPRO2 (absname1, file2);
2994 absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
2995 absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
2996 UNGCPRO;
2998 /* If the file name has special constructs in it,
2999 call the corresponding file handler. */
3000 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3001 if (NILP (handler))
3002 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3003 if (!NILP (handler))
3004 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3006 GCPRO2 (absname1, absname2);
3007 absname1 = ENCODE_FILE (absname1);
3008 absname2 = ENCODE_FILE (absname2);
3009 UNGCPRO;
3011 if (stat (SDATA (absname1), &st) < 0)
3012 return Qnil;
3014 mtime1 = st.st_mtime;
3016 if (stat (SDATA (absname2), &st) < 0)
3017 return Qt;
3019 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3022 #ifdef DOS_NT
3023 Lisp_Object Qfind_buffer_file_type;
3024 #endif /* DOS_NT */
3026 #ifndef READ_BUF_SIZE
3027 #define READ_BUF_SIZE (64 << 10)
3028 #endif
3030 extern void adjust_markers_for_delete P_ ((int, int, int, int));
3032 /* This function is called after Lisp functions to decide a coding
3033 system are called, or when they cause an error. Before they are
3034 called, the current buffer is set unibyte and it contains only a
3035 newly inserted text (thus the buffer was empty before the
3036 insertion).
3038 The functions may set markers, overlays, text properties, or even
3039 alter the buffer contents, change the current buffer.
3041 Here, we reset all those changes by:
3042 o set back the current buffer.
3043 o move all markers and overlays to BEG.
3044 o remove all text properties.
3045 o set back the buffer multibyteness. */
3047 static Lisp_Object
3048 decide_coding_unwind (unwind_data)
3049 Lisp_Object unwind_data;
3051 Lisp_Object multibyte, undo_list, buffer;
3053 multibyte = XCAR (unwind_data);
3054 unwind_data = XCDR (unwind_data);
3055 undo_list = XCAR (unwind_data);
3056 buffer = XCDR (unwind_data);
3058 if (current_buffer != XBUFFER (buffer))
3059 set_buffer_internal (XBUFFER (buffer));
3060 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3061 adjust_overlays_for_delete (BEG, Z - BEG);
3062 BUF_INTERVALS (current_buffer) = 0;
3063 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3065 /* Now we are safe to change the buffer's multibyteness directly. */
3066 current_buffer->enable_multibyte_characters = multibyte;
3067 current_buffer->undo_list = undo_list;
3069 return Qnil;
3073 /* Used to pass values from insert-file-contents to read_non_regular. */
3075 static int non_regular_fd;
3076 static int non_regular_inserted;
3077 static int non_regular_nbytes;
3080 /* Read from a non-regular file.
3081 Read non_regular_trytry bytes max from non_regular_fd.
3082 Non_regular_inserted specifies where to put the read bytes.
3083 Value is the number of bytes read. */
3085 static Lisp_Object
3086 read_non_regular ()
3088 int nbytes;
3090 immediate_quit = 1;
3091 QUIT;
3092 nbytes = emacs_read (non_regular_fd,
3093 BEG_ADDR + PT_BYTE - BEG_BYTE + non_regular_inserted,
3094 non_regular_nbytes);
3095 immediate_quit = 0;
3096 return make_number (nbytes);
3100 /* Condition-case handler used when reading from non-regular files
3101 in insert-file-contents. */
3103 static Lisp_Object
3104 read_non_regular_quit ()
3106 return Qnil;
3110 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3111 1, 5, 0,
3112 doc: /* Insert contents of file FILENAME after point.
3113 Returns list of absolute file name and number of characters inserted.
3114 If second argument VISIT is non-nil, the buffer's visited filename and
3115 last save file modtime are set, and it is marked unmodified. If
3116 visiting and the file does not exist, visiting is completed before the
3117 error is signaled.
3119 The optional third and fourth arguments BEG and END specify what portion
3120 of the file to insert. These arguments count bytes in the file, not
3121 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3123 If optional fifth argument REPLACE is non-nil, replace the current
3124 buffer contents (in the accessible portion) with the file contents.
3125 This is better than simply deleting and inserting the whole thing
3126 because (1) it preserves some marker positions and (2) it puts less data
3127 in the undo list. When REPLACE is non-nil, the second return value is
3128 the number of characters that replace previous buffer contents.
3130 This function does code conversion according to the value of
3131 `coding-system-for-read' or `file-coding-system-alist', and sets the
3132 variable `last-coding-system-used' to the coding system actually used. */)
3133 (filename, visit, beg, end, replace)
3134 Lisp_Object filename, visit, beg, end, replace;
3136 struct stat st;
3137 register int fd;
3138 int inserted = 0;
3139 int nochange = 0;
3140 register int how_much;
3141 register int unprocessed;
3142 int count = SPECPDL_INDEX ();
3143 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3144 Lisp_Object handler, val, insval, orig_filename, old_undo;
3145 Lisp_Object p;
3146 int total = 0;
3147 int not_regular = 0;
3148 unsigned char read_buf[READ_BUF_SIZE];
3149 struct coding_system coding;
3150 unsigned char buffer[1 << 14];
3151 int replace_handled = 0;
3152 int set_coding_system = 0;
3153 Lisp_Object coding_system;
3154 int read_quit = 0;
3155 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3156 int we_locked_file = 0;
3157 int deferred_remove_unwind_protect = 0;
3159 if (current_buffer->base_buffer && ! NILP (visit))
3160 error ("Cannot do file visiting in an indirect buffer");
3162 if (!NILP (current_buffer->read_only))
3163 Fbarf_if_buffer_read_only ();
3165 val = Qnil;
3166 p = Qnil;
3167 orig_filename = Qnil;
3168 old_undo = Qnil;
3170 GCPRO5 (filename, val, p, orig_filename, old_undo);
3172 CHECK_STRING (filename);
3173 filename = Fexpand_file_name (filename, Qnil);
3175 /* The value Qnil means that the coding system is not yet
3176 decided. */
3177 coding_system = Qnil;
3179 /* If the file name has special constructs in it,
3180 call the corresponding file handler. */
3181 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3182 if (!NILP (handler))
3184 val = call6 (handler, Qinsert_file_contents, filename,
3185 visit, beg, end, replace);
3186 if (CONSP (val) && CONSP (XCDR (val)))
3187 inserted = XINT (XCAR (XCDR (val)));
3188 goto handled;
3191 orig_filename = filename;
3192 filename = ENCODE_FILE (filename);
3194 fd = -1;
3196 #ifdef WINDOWSNT
3198 Lisp_Object tem = Vw32_get_true_file_attributes;
3200 /* Tell stat to use expensive method to get accurate info. */
3201 Vw32_get_true_file_attributes = Qt;
3202 total = stat (SDATA (filename), &st);
3203 Vw32_get_true_file_attributes = tem;
3205 if (total < 0)
3206 #else
3207 if (stat (SDATA (filename), &st) < 0)
3208 #endif /* WINDOWSNT */
3210 if (fd >= 0) emacs_close (fd);
3211 badopen:
3212 if (NILP (visit))
3213 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3214 st.st_mtime = -1;
3215 how_much = 0;
3216 if (!NILP (Vcoding_system_for_read))
3217 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3218 goto notfound;
3221 #ifdef S_IFREG
3222 /* This code will need to be changed in order to work on named
3223 pipes, and it's probably just not worth it. So we should at
3224 least signal an error. */
3225 if (!S_ISREG (st.st_mode))
3227 not_regular = 1;
3229 if (! NILP (visit))
3230 goto notfound;
3232 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3233 xsignal2 (Qfile_error,
3234 build_string ("not a regular file"), orig_filename);
3236 #endif
3238 if (fd < 0)
3239 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0)
3240 goto badopen;
3242 /* Replacement should preserve point as it preserves markers. */
3243 if (!NILP (replace))
3244 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3246 record_unwind_protect (close_file_unwind, make_number (fd));
3248 /* Can happen on any platform that uses long as type of off_t, but allows
3249 file sizes to exceed 2Gb, so give a suitable message. */
3250 if (! not_regular && st.st_size < 0)
3251 error ("Maximum buffer size exceeded");
3253 /* Prevent redisplay optimizations. */
3254 current_buffer->clip_changed = 1;
3256 if (!NILP (visit))
3258 if (!NILP (beg) || !NILP (end))
3259 error ("Attempt to visit less than an entire file");
3260 if (BEG < Z && NILP (replace))
3261 error ("Cannot do file visiting in a non-empty buffer");
3264 if (!NILP (beg))
3265 CHECK_NUMBER (beg);
3266 else
3267 XSETFASTINT (beg, 0);
3269 if (!NILP (end))
3270 CHECK_NUMBER (end);
3271 else
3273 if (! not_regular)
3275 XSETINT (end, st.st_size);
3277 /* Arithmetic overflow can occur if an Emacs integer cannot
3278 represent the file size, or if the calculations below
3279 overflow. The calculations below double the file size
3280 twice, so check that it can be multiplied by 4 safely. */
3281 if (XINT (end) != st.st_size
3282 || st.st_size > INT_MAX / 4)
3283 error ("Maximum buffer size exceeded");
3285 /* The file size returned from stat may be zero, but data
3286 may be readable nonetheless, for example when this is a
3287 file in the /proc filesystem. */
3288 if (st.st_size == 0)
3289 XSETINT (end, READ_BUF_SIZE);
3293 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3295 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3296 setup_coding_system (coding_system, &coding);
3297 /* Ensure we set Vlast_coding_system_used. */
3298 set_coding_system = 1;
3300 else if (BEG < Z)
3302 /* Decide the coding system to use for reading the file now
3303 because we can't use an optimized method for handling
3304 `coding:' tag if the current buffer is not empty. */
3305 if (!NILP (Vcoding_system_for_read))
3306 coding_system = Vcoding_system_for_read;
3307 else
3309 /* Don't try looking inside a file for a coding system
3310 specification if it is not seekable. */
3311 if (! not_regular && ! NILP (Vset_auto_coding_function))
3313 /* Find a coding system specified in the heading two
3314 lines or in the tailing several lines of the file.
3315 We assume that the 1K-byte and 3K-byte for heading
3316 and tailing respectively are sufficient for this
3317 purpose. */
3318 int nread;
3320 if (st.st_size <= (1024 * 4))
3321 nread = emacs_read (fd, read_buf, 1024 * 4);
3322 else
3324 nread = emacs_read (fd, read_buf, 1024);
3325 if (nread >= 0)
3327 if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
3328 report_file_error ("Setting file position",
3329 Fcons (orig_filename, Qnil));
3330 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3334 if (nread < 0)
3335 error ("IO error reading %s: %s",
3336 SDATA (orig_filename), emacs_strerror (errno));
3337 else if (nread > 0)
3339 struct buffer *prev = current_buffer;
3340 Lisp_Object buffer;
3341 struct buffer *buf;
3343 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3345 buffer = Fget_buffer_create (build_string (" *code-converting-work*"));
3346 buf = XBUFFER (buffer);
3348 delete_all_overlays (buf);
3349 buf->directory = current_buffer->directory;
3350 buf->read_only = Qnil;
3351 buf->filename = Qnil;
3352 buf->undo_list = Qt;
3353 eassert (buf->overlays_before == NULL);
3354 eassert (buf->overlays_after == NULL);
3356 set_buffer_internal (buf);
3357 Ferase_buffer ();
3358 buf->enable_multibyte_characters = Qnil;
3360 insert_1_both (read_buf, nread, nread, 0, 0, 0);
3361 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3362 coding_system = call2 (Vset_auto_coding_function,
3363 filename, make_number (nread));
3364 set_buffer_internal (prev);
3366 /* Discard the unwind protect for recovering the
3367 current buffer. */
3368 specpdl_ptr--;
3370 /* Rewind the file for the actual read done later. */
3371 if (lseek (fd, 0, 0) < 0)
3372 report_file_error ("Setting file position",
3373 Fcons (orig_filename, Qnil));
3377 if (NILP (coding_system))
3379 /* If we have not yet decided a coding system, check
3380 file-coding-system-alist. */
3381 Lisp_Object args[6];
3383 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3384 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3385 coding_system = Ffind_operation_coding_system (6, args);
3386 if (CONSP (coding_system))
3387 coding_system = XCAR (coding_system);
3391 if (NILP (coding_system))
3392 coding_system = Qundecided;
3393 else
3394 CHECK_CODING_SYSTEM (coding_system);
3396 if (NILP (current_buffer->enable_multibyte_characters))
3397 /* We must suppress all character code conversion except for
3398 end-of-line conversion. */
3399 coding_system = raw_text_coding_system (coding_system);
3401 setup_coding_system (coding_system, &coding);
3402 /* Ensure we set Vlast_coding_system_used. */
3403 set_coding_system = 1;
3406 /* If requested, replace the accessible part of the buffer
3407 with the file contents. Avoid replacing text at the
3408 beginning or end of the buffer that matches the file contents;
3409 that preserves markers pointing to the unchanged parts.
3411 Here we implement this feature in an optimized way
3412 for the case where code conversion is NOT needed.
3413 The following if-statement handles the case of conversion
3414 in a less optimal way.
3416 If the code conversion is "automatic" then we try using this
3417 method and hope for the best.
3418 But if we discover the need for conversion, we give up on this method
3419 and let the following if-statement handle the replace job. */
3420 if (!NILP (replace)
3421 && BEGV < ZV
3422 && (NILP (coding_system)
3423 || ! CODING_REQUIRE_DECODING (&coding)))
3425 /* same_at_start and same_at_end count bytes,
3426 because file access counts bytes
3427 and BEG and END count bytes. */
3428 int same_at_start = BEGV_BYTE;
3429 int same_at_end = ZV_BYTE;
3430 int overlap;
3431 /* There is still a possibility we will find the need to do code
3432 conversion. If that happens, we set this variable to 1 to
3433 give up on handling REPLACE in the optimized way. */
3434 int giveup_match_end = 0;
3436 if (XINT (beg) != 0)
3438 if (lseek (fd, XINT (beg), 0) < 0)
3439 report_file_error ("Setting file position",
3440 Fcons (orig_filename, Qnil));
3443 immediate_quit = 1;
3444 QUIT;
3445 /* Count how many chars at the start of the file
3446 match the text at the beginning of the buffer. */
3447 while (1)
3449 int nread, bufpos;
3451 nread = emacs_read (fd, buffer, sizeof buffer);
3452 if (nread < 0)
3453 error ("IO error reading %s: %s",
3454 SDATA (orig_filename), emacs_strerror (errno));
3455 else if (nread == 0)
3456 break;
3458 if (CODING_REQUIRE_DETECTION (&coding))
3460 coding_system = detect_coding_system (buffer, nread, nread, 1, 0,
3461 coding_system);
3462 setup_coding_system (coding_system, &coding);
3465 if (CODING_REQUIRE_DECODING (&coding))
3466 /* We found that the file should be decoded somehow.
3467 Let's give up here. */
3469 giveup_match_end = 1;
3470 break;
3473 bufpos = 0;
3474 while (bufpos < nread && same_at_start < ZV_BYTE
3475 && FETCH_BYTE (same_at_start) == buffer[bufpos])
3476 same_at_start++, bufpos++;
3477 /* If we found a discrepancy, stop the scan.
3478 Otherwise loop around and scan the next bufferful. */
3479 if (bufpos != nread)
3480 break;
3482 immediate_quit = 0;
3483 /* If the file matches the buffer completely,
3484 there's no need to replace anything. */
3485 if (same_at_start - BEGV_BYTE == XINT (end))
3487 emacs_close (fd);
3488 specpdl_ptr--;
3489 /* Truncate the buffer to the size of the file. */
3490 del_range_1 (same_at_start, same_at_end, 0, 0);
3491 goto handled;
3493 immediate_quit = 1;
3494 QUIT;
3495 /* Count how many chars at the end of the file
3496 match the text at the end of the buffer. But, if we have
3497 already found that decoding is necessary, don't waste time. */
3498 while (!giveup_match_end)
3500 int total_read, nread, bufpos, curpos, trial;
3502 /* At what file position are we now scanning? */
3503 curpos = XINT (end) - (ZV_BYTE - same_at_end);
3504 /* If the entire file matches the buffer tail, stop the scan. */
3505 if (curpos == 0)
3506 break;
3507 /* How much can we scan in the next step? */
3508 trial = min (curpos, sizeof buffer);
3509 if (lseek (fd, curpos - trial, 0) < 0)
3510 report_file_error ("Setting file position",
3511 Fcons (orig_filename, Qnil));
3513 total_read = nread = 0;
3514 while (total_read < trial)
3516 nread = emacs_read (fd, buffer + total_read, trial - total_read);
3517 if (nread < 0)
3518 error ("IO error reading %s: %s",
3519 SDATA (orig_filename), emacs_strerror (errno));
3520 else if (nread == 0)
3521 break;
3522 total_read += nread;
3525 /* Scan this bufferful from the end, comparing with
3526 the Emacs buffer. */
3527 bufpos = total_read;
3529 /* Compare with same_at_start to avoid counting some buffer text
3530 as matching both at the file's beginning and at the end. */
3531 while (bufpos > 0 && same_at_end > same_at_start
3532 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
3533 same_at_end--, bufpos--;
3535 /* If we found a discrepancy, stop the scan.
3536 Otherwise loop around and scan the preceding bufferful. */
3537 if (bufpos != 0)
3539 /* If this discrepancy is because of code conversion,
3540 we cannot use this method; giveup and try the other. */
3541 if (same_at_end > same_at_start
3542 && FETCH_BYTE (same_at_end - 1) >= 0200
3543 && ! NILP (current_buffer->enable_multibyte_characters)
3544 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3545 giveup_match_end = 1;
3546 break;
3549 if (nread == 0)
3550 break;
3552 immediate_quit = 0;
3554 if (! giveup_match_end)
3556 int temp;
3558 /* We win! We can handle REPLACE the optimized way. */
3560 /* Extend the start of non-matching text area to multibyte
3561 character boundary. */
3562 if (! NILP (current_buffer->enable_multibyte_characters))
3563 while (same_at_start > BEGV_BYTE
3564 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3565 same_at_start--;
3567 /* Extend the end of non-matching text area to multibyte
3568 character boundary. */
3569 if (! NILP (current_buffer->enable_multibyte_characters))
3570 while (same_at_end < ZV_BYTE
3571 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3572 same_at_end++;
3574 /* Don't try to reuse the same piece of text twice. */
3575 overlap = (same_at_start - BEGV_BYTE
3576 - (same_at_end + st.st_size - ZV));
3577 if (overlap > 0)
3578 same_at_end += overlap;
3580 /* Arrange to read only the nonmatching middle part of the file. */
3581 XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV_BYTE));
3582 XSETFASTINT (end, XINT (end) - (ZV_BYTE - same_at_end));
3584 del_range_byte (same_at_start, same_at_end, 0);
3585 /* Insert from the file at the proper position. */
3586 temp = BYTE_TO_CHAR (same_at_start);
3587 SET_PT_BOTH (temp, same_at_start);
3589 /* If display currently starts at beginning of line,
3590 keep it that way. */
3591 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3592 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3594 replace_handled = 1;
3598 /* If requested, replace the accessible part of the buffer
3599 with the file contents. Avoid replacing text at the
3600 beginning or end of the buffer that matches the file contents;
3601 that preserves markers pointing to the unchanged parts.
3603 Here we implement this feature for the case where code conversion
3604 is needed, in a simple way that needs a lot of memory.
3605 The preceding if-statement handles the case of no conversion
3606 in a more optimized way. */
3607 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3609 EMACS_INT same_at_start = BEGV_BYTE;
3610 EMACS_INT same_at_end = ZV_BYTE;
3611 EMACS_INT same_at_start_charpos;
3612 EMACS_INT inserted_chars;
3613 EMACS_INT overlap;
3614 EMACS_INT bufpos;
3615 unsigned char *decoded;
3616 int temp;
3617 int this_count = SPECPDL_INDEX ();
3618 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
3619 Lisp_Object conversion_buffer;
3621 conversion_buffer = code_conversion_save (1, multibyte);
3623 /* First read the whole file, performing code conversion into
3624 CONVERSION_BUFFER. */
3626 if (lseek (fd, XINT (beg), 0) < 0)
3627 report_file_error ("Setting file position",
3628 Fcons (orig_filename, Qnil));
3630 total = st.st_size; /* Total bytes in the file. */
3631 how_much = 0; /* Bytes read from file so far. */
3632 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3633 unprocessed = 0; /* Bytes not processed in previous loop. */
3635 GCPRO1 (conversion_buffer);
3636 while (how_much < total)
3638 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
3639 quitting while reading a huge while. */
3640 /* try is reserved in some compilers (Microsoft C) */
3641 int trytry = min (total - how_much, READ_BUF_SIZE - unprocessed);
3642 int this;
3644 /* Allow quitting out of the actual I/O. */
3645 immediate_quit = 1;
3646 QUIT;
3647 this = emacs_read (fd, read_buf + unprocessed, trytry);
3648 immediate_quit = 0;
3650 if (this <= 0)
3652 if (this < 0)
3653 how_much = this;
3654 break;
3657 how_much += this;
3659 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3660 BUF_Z (XBUFFER (conversion_buffer)));
3661 decode_coding_c_string (&coding, read_buf, unprocessed + this,
3662 conversion_buffer);
3663 unprocessed = coding.carryover_bytes;
3664 if (coding.carryover_bytes > 0)
3665 bcopy (coding.carryover, read_buf, unprocessed);
3667 UNGCPRO;
3668 emacs_close (fd);
3670 /* We should remove the unwind_protect calling
3671 close_file_unwind, but other stuff has been added the stack,
3672 so defer the removal till we reach the `handled' label. */
3673 deferred_remove_unwind_protect = 1;
3675 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
3676 if we couldn't read the file. */
3678 if (how_much < 0)
3679 error ("IO error reading %s: %s",
3680 SDATA (orig_filename), emacs_strerror (errno));
3682 if (unprocessed > 0)
3684 coding.mode |= CODING_MODE_LAST_BLOCK;
3685 decode_coding_c_string (&coding, read_buf, unprocessed,
3686 conversion_buffer);
3687 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3690 coding_system = CODING_ID_NAME (coding.id);
3691 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3692 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3693 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3695 /* Compare the beginning of the converted string with the buffer
3696 text. */
3698 bufpos = 0;
3699 while (bufpos < inserted && same_at_start < same_at_end
3700 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3701 same_at_start++, bufpos++;
3703 /* If the file matches the head of buffer completely,
3704 there's no need to replace anything. */
3706 if (bufpos == inserted)
3708 /* Truncate the buffer to the size of the file. */
3709 if (same_at_start == same_at_end)
3710 nochange = 1;
3711 else
3712 del_range_byte (same_at_start, same_at_end, 0);
3713 inserted = 0;
3715 unbind_to (this_count, Qnil);
3716 goto handled;
3719 /* Extend the start of non-matching text area to the previous
3720 multibyte character boundary. */
3721 if (! NILP (current_buffer->enable_multibyte_characters))
3722 while (same_at_start > BEGV_BYTE
3723 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3724 same_at_start--;
3726 /* Scan this bufferful from the end, comparing with
3727 the Emacs buffer. */
3728 bufpos = inserted;
3730 /* Compare with same_at_start to avoid counting some buffer text
3731 as matching both at the file's beginning and at the end. */
3732 while (bufpos > 0 && same_at_end > same_at_start
3733 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3734 same_at_end--, bufpos--;
3736 /* Extend the end of non-matching text area to the next
3737 multibyte character boundary. */
3738 if (! NILP (current_buffer->enable_multibyte_characters))
3739 while (same_at_end < ZV_BYTE
3740 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3741 same_at_end++;
3743 /* Don't try to reuse the same piece of text twice. */
3744 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3745 if (overlap > 0)
3746 same_at_end += overlap;
3748 /* If display currently starts at beginning of line,
3749 keep it that way. */
3750 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3751 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3753 /* Replace the chars that we need to replace,
3754 and update INSERTED to equal the number of bytes
3755 we are taking from the decoded string. */
3756 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3758 if (same_at_end != same_at_start)
3760 del_range_byte (same_at_start, same_at_end, 0);
3761 temp = GPT;
3762 same_at_start = GPT_BYTE;
3764 else
3766 temp = BYTE_TO_CHAR (same_at_start);
3768 /* Insert from the file at the proper position. */
3769 SET_PT_BOTH (temp, same_at_start);
3770 same_at_start_charpos
3771 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3772 same_at_start - BEGV_BYTE
3773 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3774 inserted_chars
3775 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3776 same_at_start + inserted - BEGV_BYTE
3777 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
3778 - same_at_start_charpos);
3779 /* This binding is to avoid ask-user-about-supersession-threat
3780 being called in insert_from_buffer (via in
3781 prepare_to_modify_buffer). */
3782 specbind (intern ("buffer-file-name"), Qnil);
3783 insert_from_buffer (XBUFFER (conversion_buffer),
3784 same_at_start_charpos, inserted_chars, 0);
3785 /* Set `inserted' to the number of inserted characters. */
3786 inserted = PT - temp;
3787 /* Set point before the inserted characters. */
3788 SET_PT_BOTH (temp, same_at_start);
3790 unbind_to (this_count, Qnil);
3792 goto handled;
3795 if (! not_regular)
3797 register Lisp_Object temp;
3799 total = XINT (end) - XINT (beg);
3801 /* Make sure point-max won't overflow after this insertion. */
3802 XSETINT (temp, total);
3803 if (total != XINT (temp))
3804 error ("Maximum buffer size exceeded");
3806 else
3807 /* For a special file, all we can do is guess. */
3808 total = READ_BUF_SIZE;
3810 if (NILP (visit) && inserted > 0)
3812 #ifdef CLASH_DETECTION
3813 if (!NILP (current_buffer->file_truename)
3814 /* Make binding buffer-file-name to nil effective. */
3815 && !NILP (current_buffer->filename)
3816 && SAVE_MODIFF >= MODIFF)
3817 we_locked_file = 1;
3818 #endif /* CLASH_DETECTION */
3819 prepare_to_modify_buffer (GPT, GPT, NULL);
3822 move_gap (PT);
3823 if (GAP_SIZE < total)
3824 make_gap (total - GAP_SIZE);
3826 if (XINT (beg) != 0 || !NILP (replace))
3828 if (lseek (fd, XINT (beg), 0) < 0)
3829 report_file_error ("Setting file position",
3830 Fcons (orig_filename, Qnil));
3833 /* In the following loop, HOW_MUCH contains the total bytes read so
3834 far for a regular file, and not changed for a special file. But,
3835 before exiting the loop, it is set to a negative value if I/O
3836 error occurs. */
3837 how_much = 0;
3839 /* Total bytes inserted. */
3840 inserted = 0;
3842 /* Here, we don't do code conversion in the loop. It is done by
3843 decode_coding_gap after all data are read into the buffer. */
3845 int gap_size = GAP_SIZE;
3847 while (how_much < total)
3849 /* try is reserved in some compilers (Microsoft C) */
3850 int trytry = min (total - how_much, READ_BUF_SIZE);
3851 int this;
3853 if (not_regular)
3855 Lisp_Object val;
3857 /* Maybe make more room. */
3858 if (gap_size < trytry)
3860 make_gap (total - gap_size);
3861 gap_size = GAP_SIZE;
3864 /* Read from the file, capturing `quit'. When an
3865 error occurs, end the loop, and arrange for a quit
3866 to be signaled after decoding the text we read. */
3867 non_regular_fd = fd;
3868 non_regular_inserted = inserted;
3869 non_regular_nbytes = trytry;
3870 val = internal_condition_case_1 (read_non_regular, Qnil, Qerror,
3871 read_non_regular_quit);
3872 if (NILP (val))
3874 read_quit = 1;
3875 break;
3878 this = XINT (val);
3880 else
3882 /* Allow quitting out of the actual I/O. We don't make text
3883 part of the buffer until all the reading is done, so a C-g
3884 here doesn't do any harm. */
3885 immediate_quit = 1;
3886 QUIT;
3887 this = emacs_read (fd, BEG_ADDR + PT_BYTE - BEG_BYTE + inserted, trytry);
3888 immediate_quit = 0;
3891 if (this <= 0)
3893 how_much = this;
3894 break;
3897 gap_size -= this;
3899 /* For a regular file, where TOTAL is the real size,
3900 count HOW_MUCH to compare with it.
3901 For a special file, where TOTAL is just a buffer size,
3902 so don't bother counting in HOW_MUCH.
3903 (INSERTED is where we count the number of characters inserted.) */
3904 if (! not_regular)
3905 how_much += this;
3906 inserted += this;
3910 /* Now we have read all the file data into the gap.
3911 If it was empty, undo marking the buffer modified. */
3913 if (inserted == 0)
3915 #ifdef CLASH_DETECTION
3916 if (we_locked_file)
3917 unlock_file (current_buffer->file_truename);
3918 #endif
3919 Vdeactivate_mark = old_Vdeactivate_mark;
3921 else
3922 Vdeactivate_mark = Qt;
3924 /* Make the text read part of the buffer. */
3925 GAP_SIZE -= inserted;
3926 GPT += inserted;
3927 GPT_BYTE += inserted;
3928 ZV += inserted;
3929 ZV_BYTE += inserted;
3930 Z += inserted;
3931 Z_BYTE += inserted;
3933 if (GAP_SIZE > 0)
3934 /* Put an anchor to ensure multi-byte form ends at gap. */
3935 *GPT_ADDR = 0;
3937 emacs_close (fd);
3939 /* Discard the unwind protect for closing the file. */
3940 specpdl_ptr--;
3942 if (how_much < 0)
3943 error ("IO error reading %s: %s",
3944 SDATA (orig_filename), emacs_strerror (errno));
3946 notfound:
3948 if (NILP (coding_system))
3950 /* The coding system is not yet decided. Decide it by an
3951 optimized method for handling `coding:' tag.
3953 Note that we can get here only if the buffer was empty
3954 before the insertion. */
3956 if (!NILP (Vcoding_system_for_read))
3957 coding_system = Vcoding_system_for_read;
3958 else
3960 /* Since we are sure that the current buffer was empty
3961 before the insertion, we can toggle
3962 enable-multibyte-characters directly here without taking
3963 care of marker adjustment. By this way, we can run Lisp
3964 program safely before decoding the inserted text. */
3965 Lisp_Object unwind_data;
3966 int count = SPECPDL_INDEX ();
3968 unwind_data = Fcons (current_buffer->enable_multibyte_characters,
3969 Fcons (current_buffer->undo_list,
3970 Fcurrent_buffer ()));
3971 current_buffer->enable_multibyte_characters = Qnil;
3972 current_buffer->undo_list = Qt;
3973 record_unwind_protect (decide_coding_unwind, unwind_data);
3975 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
3977 coding_system = call2 (Vset_auto_coding_function,
3978 filename, make_number (inserted));
3981 if (NILP (coding_system))
3983 /* If the coding system is not yet decided, check
3984 file-coding-system-alist. */
3985 Lisp_Object args[6];
3987 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3988 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
3989 coding_system = Ffind_operation_coding_system (6, args);
3990 if (CONSP (coding_system))
3991 coding_system = XCAR (coding_system);
3993 unbind_to (count, Qnil);
3994 inserted = Z_BYTE - BEG_BYTE;
3997 if (NILP (coding_system))
3998 coding_system = Qundecided;
3999 else
4000 CHECK_CODING_SYSTEM (coding_system);
4002 if (NILP (current_buffer->enable_multibyte_characters))
4003 /* We must suppress all character code conversion except for
4004 end-of-line conversion. */
4005 coding_system = raw_text_coding_system (coding_system);
4006 setup_coding_system (coding_system, &coding);
4007 /* Ensure we set Vlast_coding_system_used. */
4008 set_coding_system = 1;
4011 if (!NILP (visit))
4013 /* When we visit a file by raw-text, we change the buffer to
4014 unibyte. */
4015 if (CODING_FOR_UNIBYTE (&coding)
4016 /* Can't do this if part of the buffer might be preserved. */
4017 && NILP (replace))
4018 /* Visiting a file with these coding system makes the buffer
4019 unibyte. */
4020 current_buffer->enable_multibyte_characters = Qnil;
4023 coding.dst_multibyte = ! NILP (current_buffer->enable_multibyte_characters);
4024 if (CODING_MAY_REQUIRE_DECODING (&coding)
4025 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4027 move_gap_both (PT, PT_BYTE);
4028 GAP_SIZE += inserted;
4029 ZV_BYTE -= inserted;
4030 Z_BYTE -= inserted;
4031 ZV -= inserted;
4032 Z -= inserted;
4033 decode_coding_gap (&coding, inserted, inserted);
4034 inserted = coding.produced_char;
4035 coding_system = CODING_ID_NAME (coding.id);
4037 else if (inserted > 0)
4038 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4039 inserted);
4041 /* Now INSERTED is measured in characters. */
4043 #ifdef DOS_NT
4044 /* Use the conversion type to determine buffer-file-type
4045 (find-buffer-file-type is now used to help determine the
4046 conversion). */
4047 if ((VECTORP (CODING_ID_EOL_TYPE (coding.id))
4048 || EQ (CODING_ID_EOL_TYPE (coding.id), Qunix))
4049 && ! CODING_REQUIRE_DECODING (&coding))
4050 current_buffer->buffer_file_type = Qt;
4051 else
4052 current_buffer->buffer_file_type = Qnil;
4053 #endif
4055 handled:
4057 if (deferred_remove_unwind_protect)
4058 /* If requested above, discard the unwind protect for closing the
4059 file. */
4060 specpdl_ptr--;
4062 if (!NILP (visit))
4064 if (!EQ (current_buffer->undo_list, Qt) && !nochange)
4065 current_buffer->undo_list = Qnil;
4067 if (NILP (handler))
4069 current_buffer->modtime = st.st_mtime;
4070 current_buffer->filename = orig_filename;
4073 SAVE_MODIFF = MODIFF;
4074 current_buffer->auto_save_modified = MODIFF;
4075 XSETFASTINT (current_buffer->save_length, Z - BEG);
4076 #ifdef CLASH_DETECTION
4077 if (NILP (handler))
4079 if (!NILP (current_buffer->file_truename))
4080 unlock_file (current_buffer->file_truename);
4081 unlock_file (filename);
4083 #endif /* CLASH_DETECTION */
4084 if (not_regular)
4085 xsignal2 (Qfile_error,
4086 build_string ("not a regular file"), orig_filename);
4089 if (set_coding_system)
4090 Vlast_coding_system_used = coding_system;
4092 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4094 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4095 visit);
4096 if (! NILP (insval))
4098 CHECK_NUMBER (insval);
4099 inserted = XFASTINT (insval);
4103 /* Decode file format. */
4104 if (inserted > 0)
4106 /* Don't run point motion or modification hooks when decoding. */
4107 int count = SPECPDL_INDEX ();
4108 int old_inserted = inserted;
4109 specbind (Qinhibit_point_motion_hooks, Qt);
4110 specbind (Qinhibit_modification_hooks, Qt);
4112 /* Save old undo list and don't record undo for decoding. */
4113 old_undo = current_buffer->undo_list;
4114 current_buffer->undo_list = Qt;
4116 if (NILP (replace))
4118 insval = call3 (Qformat_decode,
4119 Qnil, make_number (inserted), visit);
4120 CHECK_NUMBER (insval);
4121 inserted = XFASTINT (insval);
4123 else
4125 /* If REPLACE is non-nil and we succeeded in not replacing the
4126 beginning or end of the buffer text with the file's contents,
4127 call format-decode with `point' positioned at the beginning
4128 of the buffer and `inserted' equalling the number of
4129 characters in the buffer. Otherwise, format-decode might
4130 fail to correctly analyze the beginning or end of the buffer.
4131 Hence we temporarily save `point' and `inserted' here and
4132 restore `point' iff format-decode did not insert or delete
4133 any text. Otherwise we leave `point' at point-min. */
4134 int opoint = PT;
4135 int opoint_byte = PT_BYTE;
4136 int oinserted = ZV - BEGV;
4137 int ochars_modiff = CHARS_MODIFF;
4139 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4140 insval = call3 (Qformat_decode,
4141 Qnil, make_number (oinserted), visit);
4142 CHECK_NUMBER (insval);
4143 if (ochars_modiff == CHARS_MODIFF)
4144 /* format_decode didn't modify buffer's characters => move
4145 point back to position before inserted text and leave
4146 value of inserted alone. */
4147 SET_PT_BOTH (opoint, opoint_byte);
4148 else
4149 /* format_decode modified buffer's characters => consider
4150 entire buffer changed and leave point at point-min. */
4151 inserted = XFASTINT (insval);
4154 /* For consistency with format-decode call these now iff inserted > 0
4155 (martin 2007-06-28). */
4156 p = Vafter_insert_file_functions;
4157 while (CONSP (p))
4159 if (NILP (replace))
4161 insval = call1 (XCAR (p), make_number (inserted));
4162 if (!NILP (insval))
4164 CHECK_NUMBER (insval);
4165 inserted = XFASTINT (insval);
4168 else
4170 /* For the rationale of this see the comment on
4171 format-decode above. */
4172 int opoint = PT;
4173 int opoint_byte = PT_BYTE;
4174 int oinserted = ZV - BEGV;
4175 int ochars_modiff = CHARS_MODIFF;
4177 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4178 insval = call1 (XCAR (p), make_number (oinserted));
4179 if (!NILP (insval))
4181 CHECK_NUMBER (insval);
4182 if (ochars_modiff == CHARS_MODIFF)
4183 /* after_insert_file_functions didn't modify
4184 buffer's characters => move point back to
4185 position before inserted text and leave value of
4186 inserted alone. */
4187 SET_PT_BOTH (opoint, opoint_byte);
4188 else
4189 /* after_insert_file_functions did modify buffer's
4190 characters => consider entire buffer changed and
4191 leave point at point-min. */
4192 inserted = XFASTINT (insval);
4196 QUIT;
4197 p = XCDR (p);
4200 if (NILP (visit))
4202 current_buffer->undo_list = old_undo;
4203 if (CONSP (old_undo) && inserted != old_inserted)
4205 /* Adjust the last undo record for the size change during
4206 the format conversion. */
4207 Lisp_Object tem = XCAR (old_undo);
4208 if (CONSP (tem) && INTEGERP (XCAR (tem))
4209 && INTEGERP (XCDR (tem))
4210 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4211 XSETCDR (tem, make_number (PT + inserted));
4214 else
4215 /* If undo_list was Qt before, keep it that way.
4216 Otherwise start with an empty undo_list. */
4217 current_buffer->undo_list = EQ (old_undo, Qt) ? Qt : Qnil;
4219 unbind_to (count, Qnil);
4222 /* Call after-change hooks for the inserted text, aside from the case
4223 of normal visiting (not with REPLACE), which is done in a new buffer
4224 "before" the buffer is changed. */
4225 if (inserted > 0 && total > 0
4226 && (NILP (visit) || !NILP (replace)))
4228 signal_after_change (PT, 0, inserted);
4229 update_compositions (PT, PT, CHECK_BORDER);
4232 if (!NILP (visit)
4233 && current_buffer->modtime == -1)
4235 /* If visiting nonexistent file, return nil. */
4236 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4239 if (read_quit)
4240 Fsignal (Qquit, Qnil);
4242 /* ??? Retval needs to be dealt with in all cases consistently. */
4243 if (NILP (val))
4244 val = Fcons (orig_filename,
4245 Fcons (make_number (inserted),
4246 Qnil));
4248 RETURN_UNGCPRO (unbind_to (count, val));
4251 static Lisp_Object build_annotations P_ ((Lisp_Object, Lisp_Object));
4253 /* If build_annotations switched buffers, switch back to BUF.
4254 Kill the temporary buffer that was selected in the meantime.
4256 Since this kill only the last temporary buffer, some buffers remain
4257 not killed if build_annotations switched buffers more than once.
4258 -- K.Handa */
4260 static Lisp_Object
4261 build_annotations_unwind (buf)
4262 Lisp_Object buf;
4264 Lisp_Object tembuf;
4266 if (XBUFFER (buf) == current_buffer)
4267 return Qnil;
4268 tembuf = Fcurrent_buffer ();
4269 Fset_buffer (buf);
4270 Fkill_buffer (tembuf);
4271 return Qnil;
4274 /* Decide the coding-system to encode the data with. */
4276 static Lisp_Object
4277 choose_write_coding_system (start, end, filename,
4278 append, visit, lockname, coding)
4279 Lisp_Object start, end, filename, append, visit, lockname;
4280 struct coding_system *coding;
4282 Lisp_Object val;
4283 Lisp_Object eol_parent = Qnil;
4285 if (auto_saving
4286 && NILP (Fstring_equal (current_buffer->filename,
4287 current_buffer->auto_save_file_name)))
4289 val = Qutf_8_emacs;
4290 eol_parent = Qunix;
4292 else if (!NILP (Vcoding_system_for_write))
4294 val = Vcoding_system_for_write;
4295 if (coding_system_require_warning
4296 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4297 /* Confirm that VAL can surely encode the current region. */
4298 val = call5 (Vselect_safe_coding_system_function,
4299 start, end, Fcons (Qt, Fcons (val, Qnil)),
4300 Qnil, filename);
4302 else
4304 /* If the variable `buffer-file-coding-system' is set locally,
4305 it means that the file was read with some kind of code
4306 conversion or the variable is explicitly set by users. We
4307 had better write it out with the same coding system even if
4308 `enable-multibyte-characters' is nil.
4310 If it is not set locally, we anyway have to convert EOL
4311 format if the default value of `buffer-file-coding-system'
4312 tells that it is not Unix-like (LF only) format. */
4313 int using_default_coding = 0;
4314 int force_raw_text = 0;
4316 val = current_buffer->buffer_file_coding_system;
4317 if (NILP (val)
4318 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4320 val = Qnil;
4321 if (NILP (current_buffer->enable_multibyte_characters))
4322 force_raw_text = 1;
4325 if (NILP (val))
4327 /* Check file-coding-system-alist. */
4328 Lisp_Object args[7], coding_systems;
4330 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4331 args[3] = filename; args[4] = append; args[5] = visit;
4332 args[6] = lockname;
4333 coding_systems = Ffind_operation_coding_system (7, args);
4334 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4335 val = XCDR (coding_systems);
4338 if (NILP (val))
4340 /* If we still have not decided a coding system, use the
4341 default value of buffer-file-coding-system. */
4342 val = current_buffer->buffer_file_coding_system;
4343 using_default_coding = 1;
4346 if (! NILP (val) && ! force_raw_text)
4348 Lisp_Object spec, attrs;
4350 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4351 attrs = AREF (spec, 0);
4352 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4353 force_raw_text = 1;
4356 if (!force_raw_text
4357 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4358 /* Confirm that VAL can surely encode the current region. */
4359 val = call5 (Vselect_safe_coding_system_function,
4360 start, end, val, Qnil, filename);
4362 /* If the decided coding-system doesn't specify end-of-line
4363 format, we use that of
4364 `default-buffer-file-coding-system'. */
4365 if (! using_default_coding
4366 && ! NILP (buffer_defaults.buffer_file_coding_system))
4367 val = (coding_inherit_eol_type
4368 (val, buffer_defaults.buffer_file_coding_system));
4370 /* If we decide not to encode text, use `raw-text' or one of its
4371 subsidiaries. */
4372 if (force_raw_text)
4373 val = raw_text_coding_system (val);
4376 val = coding_inherit_eol_type (val, eol_parent);
4377 setup_coding_system (val, coding);
4379 if (!STRINGP (start) && !NILP (current_buffer->selective_display))
4380 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4381 return val;
4384 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4385 "r\nFWrite region to file: \ni\ni\ni\np",
4386 doc: /* Write current region into specified file.
4387 When called from a program, requires three arguments:
4388 START, END and FILENAME. START and END are normally buffer positions
4389 specifying the part of the buffer to write.
4390 If START is nil, that means to use the entire buffer contents.
4391 If START is a string, then output that string to the file
4392 instead of any buffer contents; END is ignored.
4394 Optional fourth argument APPEND if non-nil means
4395 append to existing file contents (if any). If it is an integer,
4396 seek to that offset in the file before writing.
4397 Optional fifth argument VISIT, if t or a string, means
4398 set the last-save-file-modtime of buffer to this file's modtime
4399 and mark buffer not modified.
4400 If VISIT is a string, it is a second file name;
4401 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4402 VISIT is also the file name to lock and unlock for clash detection.
4403 If VISIT is neither t nor nil nor a string,
4404 that means do not display the \"Wrote file\" message.
4405 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4406 use for locking and unlocking, overriding FILENAME and VISIT.
4407 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4408 for an existing file with the same name. If MUSTBENEW is `excl',
4409 that means to get an error if the file already exists; never overwrite.
4410 If MUSTBENEW is neither nil nor `excl', that means ask for
4411 confirmation before overwriting, but do go ahead and overwrite the file
4412 if the user confirms.
4414 This does code conversion according to the value of
4415 `coding-system-for-write', `buffer-file-coding-system', or
4416 `file-coding-system-alist', and sets the variable
4417 `last-coding-system-used' to the coding system actually used. */)
4418 (start, end, filename, append, visit, lockname, mustbenew)
4419 Lisp_Object start, end, filename, append, visit, lockname, mustbenew;
4421 register int desc;
4422 int failure;
4423 int save_errno = 0;
4424 const unsigned char *fn;
4425 struct stat st;
4426 int count = SPECPDL_INDEX ();
4427 int count1;
4428 Lisp_Object handler;
4429 Lisp_Object visit_file;
4430 Lisp_Object annotations;
4431 Lisp_Object encoded_filename;
4432 int visiting = (EQ (visit, Qt) || STRINGP (visit));
4433 int quietly = !NILP (visit);
4434 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4435 struct buffer *given_buffer;
4436 #ifdef DOS_NT
4437 int buffer_file_type = O_BINARY;
4438 #endif /* DOS_NT */
4439 struct coding_system coding;
4441 if (current_buffer->base_buffer && visiting)
4442 error ("Cannot do file visiting in an indirect buffer");
4444 if (!NILP (start) && !STRINGP (start))
4445 validate_region (&start, &end);
4447 visit_file = Qnil;
4448 GCPRO5 (start, filename, visit, visit_file, lockname);
4450 filename = Fexpand_file_name (filename, Qnil);
4452 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4453 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4455 if (STRINGP (visit))
4456 visit_file = Fexpand_file_name (visit, Qnil);
4457 else
4458 visit_file = filename;
4460 if (NILP (lockname))
4461 lockname = visit_file;
4463 annotations = Qnil;
4465 /* If the file name has special constructs in it,
4466 call the corresponding file handler. */
4467 handler = Ffind_file_name_handler (filename, Qwrite_region);
4468 /* If FILENAME has no handler, see if VISIT has one. */
4469 if (NILP (handler) && STRINGP (visit))
4470 handler = Ffind_file_name_handler (visit, Qwrite_region);
4472 if (!NILP (handler))
4474 Lisp_Object val;
4475 val = call6 (handler, Qwrite_region, start, end,
4476 filename, append, visit);
4478 if (visiting)
4480 SAVE_MODIFF = MODIFF;
4481 XSETFASTINT (current_buffer->save_length, Z - BEG);
4482 current_buffer->filename = visit_file;
4484 UNGCPRO;
4485 return val;
4488 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4490 /* Special kludge to simplify auto-saving. */
4491 if (NILP (start))
4493 /* Do it later, so write-region-annotate-function can work differently
4494 if we save "the buffer" vs "a region".
4495 This is useful in tar-mode. --Stef
4496 XSETFASTINT (start, BEG);
4497 XSETFASTINT (end, Z); */
4498 Fwiden ();
4501 record_unwind_protect (build_annotations_unwind, Fcurrent_buffer ());
4502 count1 = SPECPDL_INDEX ();
4504 given_buffer = current_buffer;
4506 if (!STRINGP (start))
4508 annotations = build_annotations (start, end);
4510 if (current_buffer != given_buffer)
4512 XSETFASTINT (start, BEGV);
4513 XSETFASTINT (end, ZV);
4517 if (NILP (start))
4519 XSETFASTINT (start, BEGV);
4520 XSETFASTINT (end, ZV);
4523 UNGCPRO;
4525 GCPRO5 (start, filename, annotations, visit_file, lockname);
4527 /* Decide the coding-system to encode the data with.
4528 We used to make this choice before calling build_annotations, but that
4529 leads to problems when a write-annotate-function takes care of
4530 unsavable chars (as was the case with X-Symbol). */
4531 Vlast_coding_system_used
4532 = choose_write_coding_system (start, end, filename,
4533 append, visit, lockname, &coding);
4535 #ifdef CLASH_DETECTION
4536 if (!auto_saving)
4538 #if 0 /* This causes trouble for GNUS. */
4539 /* If we've locked this file for some other buffer,
4540 query before proceeding. */
4541 if (!visiting && EQ (Ffile_locked_p (lockname), Qt))
4542 call2 (intern ("ask-user-about-lock"), filename, Vuser_login_name);
4543 #endif
4545 lock_file (lockname);
4547 #endif /* CLASH_DETECTION */
4549 encoded_filename = ENCODE_FILE (filename);
4551 fn = SDATA (encoded_filename);
4552 desc = -1;
4553 if (!NILP (append))
4554 #ifdef DOS_NT
4555 desc = emacs_open (fn, O_WRONLY | buffer_file_type, 0);
4556 #else /* not DOS_NT */
4557 desc = emacs_open (fn, O_WRONLY, 0);
4558 #endif /* not DOS_NT */
4560 if (desc < 0 && (NILP (append) || errno == ENOENT))
4561 #ifdef DOS_NT
4562 desc = emacs_open (fn,
4563 O_WRONLY | O_CREAT | buffer_file_type
4564 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
4565 S_IREAD | S_IWRITE);
4566 #else /* not DOS_NT */
4567 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
4568 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
4569 auto_saving ? auto_save_mode_bits : 0666);
4570 #endif /* not DOS_NT */
4572 if (desc < 0)
4574 #ifdef CLASH_DETECTION
4575 save_errno = errno;
4576 if (!auto_saving) unlock_file (lockname);
4577 errno = save_errno;
4578 #endif /* CLASH_DETECTION */
4579 UNGCPRO;
4580 report_file_error ("Opening output file", Fcons (filename, Qnil));
4583 record_unwind_protect (close_file_unwind, make_number (desc));
4585 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
4587 long ret;
4589 if (NUMBERP (append))
4590 ret = lseek (desc, XINT (append), 1);
4591 else
4592 ret = lseek (desc, 0, 2);
4593 if (ret < 0)
4595 #ifdef CLASH_DETECTION
4596 if (!auto_saving) unlock_file (lockname);
4597 #endif /* CLASH_DETECTION */
4598 UNGCPRO;
4599 report_file_error ("Lseek error", Fcons (filename, Qnil));
4603 UNGCPRO;
4605 #if 0
4606 /* The new encoding routine doesn't require the following. */
4608 /* Whether VMS or not, we must move the gap to the next of newline
4609 when we must put designation sequences at beginning of line. */
4610 if (INTEGERP (start)
4611 && coding.type == coding_type_iso2022
4612 && coding.flags & CODING_FLAG_ISO_DESIGNATE_AT_BOL
4613 && GPT > BEG && GPT_ADDR[-1] != '\n')
4615 int opoint = PT, opoint_byte = PT_BYTE;
4616 scan_newline (PT, PT_BYTE, ZV, ZV_BYTE, 1, 0);
4617 move_gap_both (PT, PT_BYTE);
4618 SET_PT_BOTH (opoint, opoint_byte);
4620 #endif
4622 failure = 0;
4623 immediate_quit = 1;
4625 if (STRINGP (start))
4627 failure = 0 > a_write (desc, start, 0, SCHARS (start),
4628 &annotations, &coding);
4629 save_errno = errno;
4631 else if (XINT (start) != XINT (end))
4633 failure = 0 > a_write (desc, Qnil,
4634 XINT (start), XINT (end) - XINT (start),
4635 &annotations, &coding);
4636 save_errno = errno;
4638 else
4640 /* If file was empty, still need to write the annotations */
4641 coding.mode |= CODING_MODE_LAST_BLOCK;
4642 failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4643 save_errno = errno;
4646 if (CODING_REQUIRE_FLUSHING (&coding)
4647 && !(coding.mode & CODING_MODE_LAST_BLOCK)
4648 && ! failure)
4650 /* We have to flush out a data. */
4651 coding.mode |= CODING_MODE_LAST_BLOCK;
4652 failure = 0 > e_write (desc, Qnil, 1, 1, &coding);
4653 save_errno = errno;
4656 immediate_quit = 0;
4658 #ifdef HAVE_FSYNC
4659 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4660 Disk full in NFS may be reported here. */
4661 /* mib says that closing the file will try to write as fast as NFS can do
4662 it, and that means the fsync here is not crucial for autosave files. */
4663 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
4665 /* If fsync fails with EINTR, don't treat that as serious. Also
4666 ignore EINVAL which happens when fsync is not supported on this
4667 file. */
4668 if (errno != EINTR && errno != EINVAL)
4669 failure = 1, save_errno = errno;
4671 #endif
4673 /* Spurious "file has changed on disk" warnings have been
4674 observed on Suns as well.
4675 It seems that `close' can change the modtime, under nfs.
4677 (This has supposedly been fixed in Sunos 4,
4678 but who knows about all the other machines with NFS?) */
4679 #if 0
4681 #define FOO
4682 fstat (desc, &st);
4683 #endif
4685 /* NFS can report a write failure now. */
4686 if (emacs_close (desc) < 0)
4687 failure = 1, save_errno = errno;
4689 #ifndef FOO
4690 stat (fn, &st);
4691 #endif
4692 /* Discard the unwind protect for close_file_unwind. */
4693 specpdl_ptr = specpdl + count1;
4694 /* Restore the original current buffer. */
4695 visit_file = unbind_to (count, visit_file);
4697 #ifdef CLASH_DETECTION
4698 if (!auto_saving)
4699 unlock_file (lockname);
4700 #endif /* CLASH_DETECTION */
4702 /* Do this before reporting IO error
4703 to avoid a "file has changed on disk" warning on
4704 next attempt to save. */
4705 if (visiting)
4706 current_buffer->modtime = st.st_mtime;
4708 if (failure)
4709 error ("IO error writing %s: %s", SDATA (filename),
4710 emacs_strerror (save_errno));
4712 if (visiting)
4714 SAVE_MODIFF = MODIFF;
4715 XSETFASTINT (current_buffer->save_length, Z - BEG);
4716 current_buffer->filename = visit_file;
4717 update_mode_lines++;
4719 else if (quietly)
4721 if (auto_saving
4722 && ! NILP (Fstring_equal (current_buffer->filename,
4723 current_buffer->auto_save_file_name)))
4724 SAVE_MODIFF = MODIFF;
4726 return Qnil;
4729 if (!auto_saving)
4730 message_with_string ((INTEGERP (append)
4731 ? "Updated %s"
4732 : ! NILP (append)
4733 ? "Added to %s"
4734 : "Wrote %s"),
4735 visit_file, 1);
4737 return Qnil;
4740 Lisp_Object merge ();
4742 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4743 doc: /* Return t if (car A) is numerically less than (car B). */)
4744 (a, b)
4745 Lisp_Object a, b;
4747 return Flss (Fcar (a), Fcar (b));
4750 /* Build the complete list of annotations appropriate for writing out
4751 the text between START and END, by calling all the functions in
4752 write-region-annotate-functions and merging the lists they return.
4753 If one of these functions switches to a different buffer, we assume
4754 that buffer contains altered text. Therefore, the caller must
4755 make sure to restore the current buffer in all cases,
4756 as save-excursion would do. */
4758 static Lisp_Object
4759 build_annotations (start, end)
4760 Lisp_Object start, end;
4762 Lisp_Object annotations;
4763 Lisp_Object p, res;
4764 struct gcpro gcpro1, gcpro2;
4765 Lisp_Object original_buffer;
4766 int i, used_global = 0;
4768 XSETBUFFER (original_buffer, current_buffer);
4770 annotations = Qnil;
4771 p = Vwrite_region_annotate_functions;
4772 GCPRO2 (annotations, p);
4773 while (CONSP (p))
4775 struct buffer *given_buffer = current_buffer;
4776 if (EQ (Qt, XCAR (p)) && !used_global)
4777 { /* Use the global value of the hook. */
4778 Lisp_Object arg[2];
4779 used_global = 1;
4780 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
4781 arg[1] = XCDR (p);
4782 p = Fappend (2, arg);
4783 continue;
4785 Vwrite_region_annotations_so_far = annotations;
4786 res = call2 (XCAR (p), start, end);
4787 /* If the function makes a different buffer current,
4788 assume that means this buffer contains altered text to be output.
4789 Reset START and END from the buffer bounds
4790 and discard all previous annotations because they should have
4791 been dealt with by this function. */
4792 if (current_buffer != given_buffer)
4794 XSETFASTINT (start, BEGV);
4795 XSETFASTINT (end, ZV);
4796 annotations = Qnil;
4798 Flength (res); /* Check basic validity of return value */
4799 annotations = merge (annotations, res, Qcar_less_than_car);
4800 p = XCDR (p);
4803 /* Now do the same for annotation functions implied by the file-format */
4804 if (auto_saving && (!EQ (current_buffer->auto_save_file_format, Qt)))
4805 p = current_buffer->auto_save_file_format;
4806 else
4807 p = current_buffer->file_format;
4808 for (i = 0; CONSP (p); p = XCDR (p), ++i)
4810 struct buffer *given_buffer = current_buffer;
4812 Vwrite_region_annotations_so_far = annotations;
4814 /* Value is either a list of annotations or nil if the function
4815 has written annotations to a temporary buffer, which is now
4816 current. */
4817 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
4818 original_buffer, make_number (i));
4819 if (current_buffer != given_buffer)
4821 XSETFASTINT (start, BEGV);
4822 XSETFASTINT (end, ZV);
4823 annotations = Qnil;
4826 if (CONSP (res))
4827 annotations = merge (annotations, res, Qcar_less_than_car);
4830 UNGCPRO;
4831 return annotations;
4835 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
4836 If STRING is nil, POS is the character position in the current buffer.
4837 Intersperse with them the annotations from *ANNOT
4838 which fall within the range of POS to POS + NCHARS,
4839 each at its appropriate position.
4841 We modify *ANNOT by discarding elements as we use them up.
4843 The return value is negative in case of system call failure. */
4845 static int
4846 a_write (desc, string, pos, nchars, annot, coding)
4847 int desc;
4848 Lisp_Object string;
4849 register int nchars;
4850 int pos;
4851 Lisp_Object *annot;
4852 struct coding_system *coding;
4854 Lisp_Object tem;
4855 int nextpos;
4856 int lastpos = pos + nchars;
4858 while (NILP (*annot) || CONSP (*annot))
4860 tem = Fcar_safe (Fcar (*annot));
4861 nextpos = pos - 1;
4862 if (INTEGERP (tem))
4863 nextpos = XFASTINT (tem);
4865 /* If there are no more annotations in this range,
4866 output the rest of the range all at once. */
4867 if (! (nextpos >= pos && nextpos <= lastpos))
4868 return e_write (desc, string, pos, lastpos, coding);
4870 /* Output buffer text up to the next annotation's position. */
4871 if (nextpos > pos)
4873 if (0 > e_write (desc, string, pos, nextpos, coding))
4874 return -1;
4875 pos = nextpos;
4877 /* Output the annotation. */
4878 tem = Fcdr (Fcar (*annot));
4879 if (STRINGP (tem))
4881 if (0 > e_write (desc, tem, 0, SCHARS (tem), coding))
4882 return -1;
4884 *annot = Fcdr (*annot);
4886 return 0;
4890 /* Write text in the range START and END into descriptor DESC,
4891 encoding them with coding system CODING. If STRING is nil, START
4892 and END are character positions of the current buffer, else they
4893 are indexes to the string STRING. */
4895 static int
4896 e_write (desc, string, start, end, coding)
4897 int desc;
4898 Lisp_Object string;
4899 int start, end;
4900 struct coding_system *coding;
4902 if (STRINGP (string))
4904 start = 0;
4905 end = SCHARS (string);
4908 /* We used to have a code for handling selective display here. But,
4909 now it is handled within encode_coding. */
4911 while (start < end)
4913 if (STRINGP (string))
4915 coding->src_multibyte = SCHARS (string) < SBYTES (string);
4916 if (CODING_REQUIRE_ENCODING (coding))
4918 encode_coding_object (coding, string,
4919 start, string_char_to_byte (string, start),
4920 end, string_char_to_byte (string, end), Qt);
4922 else
4924 coding->dst_object = string;
4925 coding->consumed_char = SCHARS (string);
4926 coding->produced = SBYTES (string);
4929 else
4931 int start_byte = CHAR_TO_BYTE (start);
4932 int end_byte = CHAR_TO_BYTE (end);
4934 coding->src_multibyte = (end - start) < (end_byte - start_byte);
4935 if (CODING_REQUIRE_ENCODING (coding))
4937 encode_coding_object (coding, Fcurrent_buffer (),
4938 start, start_byte, end, end_byte, Qt);
4940 else
4942 coding->dst_object = Qnil;
4943 coding->dst_pos_byte = start_byte;
4944 if (start >= GPT || end <= GPT)
4946 coding->consumed_char = end - start;
4947 coding->produced = end_byte - start_byte;
4949 else
4951 coding->consumed_char = GPT - start;
4952 coding->produced = GPT_BYTE - start_byte;
4957 if (coding->produced > 0)
4959 coding->produced -=
4960 emacs_write (desc,
4961 STRINGP (coding->dst_object)
4962 ? SDATA (coding->dst_object)
4963 : BYTE_POS_ADDR (coding->dst_pos_byte),
4964 coding->produced);
4966 if (coding->produced)
4967 return -1;
4969 start += coding->consumed_char;
4972 return 0;
4975 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
4976 Sverify_visited_file_modtime, 1, 1, 0,
4977 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
4978 This means that the file has not been changed since it was visited or saved.
4979 See Info node `(elisp)Modification Time' for more details. */)
4980 (buf)
4981 Lisp_Object buf;
4983 struct buffer *b;
4984 struct stat st;
4985 Lisp_Object handler;
4986 Lisp_Object filename;
4988 CHECK_BUFFER (buf);
4989 b = XBUFFER (buf);
4991 if (!STRINGP (b->filename)) return Qt;
4992 if (b->modtime == 0) return Qt;
4994 /* If the file name has special constructs in it,
4995 call the corresponding file handler. */
4996 handler = Ffind_file_name_handler (b->filename,
4997 Qverify_visited_file_modtime);
4998 if (!NILP (handler))
4999 return call2 (handler, Qverify_visited_file_modtime, buf);
5001 filename = ENCODE_FILE (b->filename);
5003 if (stat (SDATA (filename), &st) < 0)
5005 /* If the file doesn't exist now and didn't exist before,
5006 we say that it isn't modified, provided the error is a tame one. */
5007 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
5008 st.st_mtime = -1;
5009 else
5010 st.st_mtime = 0;
5012 if (st.st_mtime == b->modtime
5013 /* If both are positive, accept them if they are off by one second. */
5014 || (st.st_mtime > 0 && b->modtime > 0
5015 && (st.st_mtime == b->modtime + 1
5016 || st.st_mtime == b->modtime - 1)))
5017 return Qt;
5018 return Qnil;
5021 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5022 Sclear_visited_file_modtime, 0, 0, 0,
5023 doc: /* Clear out records of last mod time of visited file.
5024 Next attempt to save will certainly not complain of a discrepancy. */)
5027 current_buffer->modtime = 0;
5028 return Qnil;
5031 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5032 Svisited_file_modtime, 0, 0, 0,
5033 doc: /* Return the current buffer's recorded visited file modification time.
5034 The value is a list of the form (HIGH LOW), like the time values
5035 that `file-attributes' returns. If the current buffer has no recorded
5036 file modification time, this function returns 0.
5037 See Info node `(elisp)Modification Time' for more details. */)
5040 if (! current_buffer->modtime)
5041 return make_number (0);
5042 return make_time ((time_t) current_buffer->modtime);
5045 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5046 Sset_visited_file_modtime, 0, 1, 0,
5047 doc: /* Update buffer's recorded modification time from the visited file's time.
5048 Useful if the buffer was not read from the file normally
5049 or if the file itself has been changed for some known benign reason.
5050 An argument specifies the modification time value to use
5051 \(instead of that of the visited file), in the form of a list
5052 \(HIGH . LOW) or (HIGH LOW). */)
5053 (time_list)
5054 Lisp_Object time_list;
5056 if (!NILP (time_list))
5057 current_buffer->modtime = cons_to_long (time_list);
5058 else
5060 register Lisp_Object filename;
5061 struct stat st;
5062 Lisp_Object handler;
5064 filename = Fexpand_file_name (current_buffer->filename, Qnil);
5066 /* If the file name has special constructs in it,
5067 call the corresponding file handler. */
5068 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5069 if (!NILP (handler))
5070 /* The handler can find the file name the same way we did. */
5071 return call2 (handler, Qset_visited_file_modtime, Qnil);
5073 filename = ENCODE_FILE (filename);
5075 if (stat (SDATA (filename), &st) >= 0)
5076 current_buffer->modtime = st.st_mtime;
5079 return Qnil;
5082 Lisp_Object
5083 auto_save_error (error)
5084 Lisp_Object error;
5086 Lisp_Object args[3], msg;
5087 int i, nbytes;
5088 struct gcpro gcpro1;
5089 char *msgbuf;
5090 USE_SAFE_ALLOCA;
5092 auto_save_error_occurred = 1;
5094 ring_bell (XFRAME (selected_frame));
5096 args[0] = build_string ("Auto-saving %s: %s");
5097 args[1] = current_buffer->name;
5098 args[2] = Ferror_message_string (error);
5099 msg = Fformat (3, args);
5100 GCPRO1 (msg);
5101 nbytes = SBYTES (msg);
5102 SAFE_ALLOCA (msgbuf, char *, nbytes);
5103 bcopy (SDATA (msg), msgbuf, nbytes);
5105 for (i = 0; i < 3; ++i)
5107 if (i == 0)
5108 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5109 else
5110 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5111 Fsleep_for (make_number (1), Qnil);
5114 SAFE_FREE ();
5115 UNGCPRO;
5116 return Qnil;
5119 Lisp_Object
5120 auto_save_1 ()
5122 struct stat st;
5123 Lisp_Object modes;
5125 auto_save_mode_bits = 0666;
5127 /* Get visited file's mode to become the auto save file's mode. */
5128 if (! NILP (current_buffer->filename))
5130 if (stat (SDATA (current_buffer->filename), &st) >= 0)
5131 /* But make sure we can overwrite it later! */
5132 auto_save_mode_bits = st.st_mode | 0600;
5133 else if ((modes = Ffile_modes (current_buffer->filename),
5134 INTEGERP (modes)))
5135 /* Remote files don't cooperate with stat. */
5136 auto_save_mode_bits = XINT (modes) | 0600;
5139 return
5140 Fwrite_region (Qnil, Qnil, current_buffer->auto_save_file_name, Qnil,
5141 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5142 Qnil, Qnil);
5145 static Lisp_Object
5146 do_auto_save_unwind (arg) /* used as unwind-protect function */
5147 Lisp_Object arg;
5149 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5150 auto_saving = 0;
5151 if (stream != NULL)
5153 BLOCK_INPUT;
5154 fclose (stream);
5155 UNBLOCK_INPUT;
5157 return Qnil;
5160 static Lisp_Object
5161 do_auto_save_unwind_1 (value) /* used as unwind-protect function */
5162 Lisp_Object value;
5164 minibuffer_auto_raise = XINT (value);
5165 return Qnil;
5168 static Lisp_Object
5169 do_auto_save_make_dir (dir)
5170 Lisp_Object dir;
5172 Lisp_Object mode;
5174 call2 (Qmake_directory, dir, Qt);
5175 XSETFASTINT (mode, 0700);
5176 return Fset_file_modes (dir, mode);
5179 static Lisp_Object
5180 do_auto_save_eh (ignore)
5181 Lisp_Object ignore;
5183 return Qnil;
5186 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5187 doc: /* Auto-save all buffers that need it.
5188 This is all buffers that have auto-saving enabled
5189 and are changed since last auto-saved.
5190 Auto-saving writes the buffer into a file
5191 so that your editing is not lost if the system crashes.
5192 This file is not the file you visited; that changes only when you save.
5193 Normally we run the normal hook `auto-save-hook' before saving.
5195 A non-nil NO-MESSAGE argument means do not print any message if successful.
5196 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5197 (no_message, current_only)
5198 Lisp_Object no_message, current_only;
5200 struct buffer *old = current_buffer, *b;
5201 Lisp_Object tail, buf;
5202 int auto_saved = 0;
5203 int do_handled_files;
5204 Lisp_Object oquit;
5205 FILE *stream = NULL;
5206 int count = SPECPDL_INDEX ();
5207 int orig_minibuffer_auto_raise = minibuffer_auto_raise;
5208 int old_message_p = 0;
5209 struct gcpro gcpro1, gcpro2;
5211 if (max_specpdl_size < specpdl_size + 40)
5212 max_specpdl_size = specpdl_size + 40;
5214 if (minibuf_level)
5215 no_message = Qt;
5217 if (NILP (no_message))
5219 old_message_p = push_message ();
5220 record_unwind_protect (pop_message_unwind, Qnil);
5223 /* Ordinarily don't quit within this function,
5224 but don't make it impossible to quit (in case we get hung in I/O). */
5225 oquit = Vquit_flag;
5226 Vquit_flag = Qnil;
5228 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5229 point to non-strings reached from Vbuffer_alist. */
5231 if (!NILP (Vrun_hooks))
5232 call1 (Vrun_hooks, intern ("auto-save-hook"));
5234 if (STRINGP (Vauto_save_list_file_name))
5236 Lisp_Object listfile;
5238 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5240 /* Don't try to create the directory when shutting down Emacs,
5241 because creating the directory might signal an error, and
5242 that would leave Emacs in a strange state. */
5243 if (!NILP (Vrun_hooks))
5245 Lisp_Object dir;
5246 dir = Qnil;
5247 GCPRO2 (dir, listfile);
5248 dir = Ffile_name_directory (listfile);
5249 if (NILP (Ffile_directory_p (dir)))
5250 internal_condition_case_1 (do_auto_save_make_dir,
5251 dir, Fcons (Fcons (Qfile_error, Qnil), Qnil),
5252 do_auto_save_eh);
5253 UNGCPRO;
5256 stream = fopen (SDATA (listfile), "w");
5259 record_unwind_protect (do_auto_save_unwind,
5260 make_save_value (stream, 0));
5261 record_unwind_protect (do_auto_save_unwind_1,
5262 make_number (minibuffer_auto_raise));
5263 minibuffer_auto_raise = 0;
5264 auto_saving = 1;
5265 auto_save_error_occurred = 0;
5267 /* On first pass, save all files that don't have handlers.
5268 On second pass, save all files that do have handlers.
5270 If Emacs is crashing, the handlers may tweak what is causing
5271 Emacs to crash in the first place, and it would be a shame if
5272 Emacs failed to autosave perfectly ordinary files because it
5273 couldn't handle some ange-ftp'd file. */
5275 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5276 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5278 buf = XCDR (XCAR (tail));
5279 b = XBUFFER (buf);
5281 /* Record all the buffers that have auto save mode
5282 in the special file that lists them. For each of these buffers,
5283 Record visited name (if any) and auto save name. */
5284 if (STRINGP (b->auto_save_file_name)
5285 && stream != NULL && do_handled_files == 0)
5287 BLOCK_INPUT;
5288 if (!NILP (b->filename))
5290 fwrite (SDATA (b->filename), 1,
5291 SBYTES (b->filename), stream);
5293 putc ('\n', stream);
5294 fwrite (SDATA (b->auto_save_file_name), 1,
5295 SBYTES (b->auto_save_file_name), stream);
5296 putc ('\n', stream);
5297 UNBLOCK_INPUT;
5300 if (!NILP (current_only)
5301 && b != current_buffer)
5302 continue;
5304 /* Don't auto-save indirect buffers.
5305 The base buffer takes care of it. */
5306 if (b->base_buffer)
5307 continue;
5309 /* Check for auto save enabled
5310 and file changed since last auto save
5311 and file changed since last real save. */
5312 if (STRINGP (b->auto_save_file_name)
5313 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5314 && b->auto_save_modified < BUF_MODIFF (b)
5315 /* -1 means we've turned off autosaving for a while--see below. */
5316 && XINT (b->save_length) >= 0
5317 && (do_handled_files
5318 || NILP (Ffind_file_name_handler (b->auto_save_file_name,
5319 Qwrite_region))))
5321 EMACS_TIME before_time, after_time;
5323 EMACS_GET_TIME (before_time);
5325 /* If we had a failure, don't try again for 20 minutes. */
5326 if (b->auto_save_failure_time >= 0
5327 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5328 continue;
5330 if ((XFASTINT (b->save_length) * 10
5331 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5332 /* A short file is likely to change a large fraction;
5333 spare the user annoying messages. */
5334 && XFASTINT (b->save_length) > 5000
5335 /* These messages are frequent and annoying for `*mail*'. */
5336 && !EQ (b->filename, Qnil)
5337 && NILP (no_message))
5339 /* It has shrunk too much; turn off auto-saving here. */
5340 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5341 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5342 b->name, 1);
5343 minibuffer_auto_raise = 0;
5344 /* Turn off auto-saving until there's a real save,
5345 and prevent any more warnings. */
5346 XSETINT (b->save_length, -1);
5347 Fsleep_for (make_number (1), Qnil);
5348 continue;
5350 set_buffer_internal (b);
5351 if (!auto_saved && NILP (no_message))
5352 message1 ("Auto-saving...");
5353 internal_condition_case (auto_save_1, Qt, auto_save_error);
5354 auto_saved++;
5355 b->auto_save_modified = BUF_MODIFF (b);
5356 XSETFASTINT (current_buffer->save_length, Z - BEG);
5357 set_buffer_internal (old);
5359 EMACS_GET_TIME (after_time);
5361 /* If auto-save took more than 60 seconds,
5362 assume it was an NFS failure that got a timeout. */
5363 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5364 b->auto_save_failure_time = EMACS_SECS (after_time);
5368 /* Prevent another auto save till enough input events come in. */
5369 record_auto_save ();
5371 if (auto_saved && NILP (no_message))
5373 if (old_message_p)
5375 /* If we are going to restore an old message,
5376 give time to read ours. */
5377 sit_for (make_number (1), 0, 0);
5378 restore_message ();
5380 else if (!auto_save_error_occurred)
5381 /* Don't overwrite the error message if an error occurred.
5382 If we displayed a message and then restored a state
5383 with no message, leave a "done" message on the screen. */
5384 message1 ("Auto-saving...done");
5387 Vquit_flag = oquit;
5389 /* This restores the message-stack status. */
5390 unbind_to (count, Qnil);
5391 return Qnil;
5394 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5395 Sset_buffer_auto_saved, 0, 0, 0,
5396 doc: /* Mark current buffer as auto-saved with its current text.
5397 No auto-save file will be written until the buffer changes again. */)
5400 current_buffer->auto_save_modified = MODIFF;
5401 XSETFASTINT (current_buffer->save_length, Z - BEG);
5402 current_buffer->auto_save_failure_time = -1;
5403 return Qnil;
5406 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5407 Sclear_buffer_auto_save_failure, 0, 0, 0,
5408 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5411 current_buffer->auto_save_failure_time = -1;
5412 return Qnil;
5415 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5416 0, 0, 0,
5417 doc: /* Return t if current buffer has been auto-saved recently.
5418 More precisely, if it has been auto-saved since last read from or saved
5419 in the visited file. If the buffer has no visited file,
5420 then any auto-save counts as "recent". */)
5423 return (SAVE_MODIFF < current_buffer->auto_save_modified) ? Qt : Qnil;
5426 /* Reading and completing file names */
5428 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5429 Snext_read_file_uses_dialog_p, 0, 0, 0,
5430 doc: /* Return t if a call to `read-file-name' will use a dialog.
5431 The return value is only relevant for a call to `read-file-name' that happens
5432 before any other event (mouse or keypress) is handeled. */)
5435 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK)
5436 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5437 && use_dialog_box
5438 && use_file_dialog
5439 && have_menus_p ())
5440 return Qt;
5441 #endif
5442 return Qnil;
5445 Lisp_Object
5446 Fread_file_name (prompt, dir, default_filename, mustmatch, initial, predicate)
5447 Lisp_Object prompt, dir, default_filename, mustmatch, initial, predicate;
5449 struct gcpro gcpro1, gcpro2;
5450 Lisp_Object args[7];
5452 GCPRO1 (default_filename);
5453 args[0] = intern ("read-file-name");
5454 args[1] = prompt;
5455 args[2] = dir;
5456 args[3] = default_filename;
5457 args[4] = mustmatch;
5458 args[5] = initial;
5459 args[6] = predicate;
5460 RETURN_UNGCPRO (Ffuncall (7, args));
5464 void
5465 init_fileio_once ()
5467 /* Must be set before any path manipulation is performed. */
5468 XSETFASTINT (Vdirectory_sep_char, '/');
5472 void
5473 syms_of_fileio ()
5475 Qoperations = intern ("operations");
5476 Qexpand_file_name = intern ("expand-file-name");
5477 Qsubstitute_in_file_name = intern ("substitute-in-file-name");
5478 Qdirectory_file_name = intern ("directory-file-name");
5479 Qfile_name_directory = intern ("file-name-directory");
5480 Qfile_name_nondirectory = intern ("file-name-nondirectory");
5481 Qunhandled_file_name_directory = intern ("unhandled-file-name-directory");
5482 Qfile_name_as_directory = intern ("file-name-as-directory");
5483 Qcopy_file = intern ("copy-file");
5484 Qmake_directory_internal = intern ("make-directory-internal");
5485 Qmake_directory = intern ("make-directory");
5486 Qdelete_directory = intern ("delete-directory");
5487 Qdelete_file = intern ("delete-file");
5488 Qrename_file = intern ("rename-file");
5489 Qadd_name_to_file = intern ("add-name-to-file");
5490 Qmake_symbolic_link = intern ("make-symbolic-link");
5491 Qfile_exists_p = intern ("file-exists-p");
5492 Qfile_executable_p = intern ("file-executable-p");
5493 Qfile_readable_p = intern ("file-readable-p");
5494 Qfile_writable_p = intern ("file-writable-p");
5495 Qfile_symlink_p = intern ("file-symlink-p");
5496 Qaccess_file = intern ("access-file");
5497 Qfile_directory_p = intern ("file-directory-p");
5498 Qfile_regular_p = intern ("file-regular-p");
5499 Qfile_accessible_directory_p = intern ("file-accessible-directory-p");
5500 Qfile_modes = intern ("file-modes");
5501 Qset_file_modes = intern ("set-file-modes");
5502 Qset_file_times = intern ("set-file-times");
5503 Qfile_newer_than_file_p = intern ("file-newer-than-file-p");
5504 Qinsert_file_contents = intern ("insert-file-contents");
5505 Qwrite_region = intern ("write-region");
5506 Qverify_visited_file_modtime = intern ("verify-visited-file-modtime");
5507 Qset_visited_file_modtime = intern ("set-visited-file-modtime");
5508 Qauto_save_coding = intern ("auto-save-coding");
5510 staticpro (&Qoperations);
5511 staticpro (&Qexpand_file_name);
5512 staticpro (&Qsubstitute_in_file_name);
5513 staticpro (&Qdirectory_file_name);
5514 staticpro (&Qfile_name_directory);
5515 staticpro (&Qfile_name_nondirectory);
5516 staticpro (&Qunhandled_file_name_directory);
5517 staticpro (&Qfile_name_as_directory);
5518 staticpro (&Qcopy_file);
5519 staticpro (&Qmake_directory_internal);
5520 staticpro (&Qmake_directory);
5521 staticpro (&Qdelete_directory);
5522 staticpro (&Qdelete_file);
5523 staticpro (&Qrename_file);
5524 staticpro (&Qadd_name_to_file);
5525 staticpro (&Qmake_symbolic_link);
5526 staticpro (&Qfile_exists_p);
5527 staticpro (&Qfile_executable_p);
5528 staticpro (&Qfile_readable_p);
5529 staticpro (&Qfile_writable_p);
5530 staticpro (&Qaccess_file);
5531 staticpro (&Qfile_symlink_p);
5532 staticpro (&Qfile_directory_p);
5533 staticpro (&Qfile_regular_p);
5534 staticpro (&Qfile_accessible_directory_p);
5535 staticpro (&Qfile_modes);
5536 staticpro (&Qset_file_modes);
5537 staticpro (&Qset_file_times);
5538 staticpro (&Qfile_newer_than_file_p);
5539 staticpro (&Qinsert_file_contents);
5540 staticpro (&Qwrite_region);
5541 staticpro (&Qverify_visited_file_modtime);
5542 staticpro (&Qset_visited_file_modtime);
5543 staticpro (&Qauto_save_coding);
5545 Qfile_name_history = intern ("file-name-history");
5546 Fset (Qfile_name_history, Qnil);
5547 staticpro (&Qfile_name_history);
5549 Qfile_error = intern ("file-error");
5550 staticpro (&Qfile_error);
5551 Qfile_already_exists = intern ("file-already-exists");
5552 staticpro (&Qfile_already_exists);
5553 Qfile_date_error = intern ("file-date-error");
5554 staticpro (&Qfile_date_error);
5555 Qexcl = intern ("excl");
5556 staticpro (&Qexcl);
5558 #ifdef DOS_NT
5559 Qfind_buffer_file_type = intern ("find-buffer-file-type");
5560 staticpro (&Qfind_buffer_file_type);
5561 #endif /* DOS_NT */
5563 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system,
5564 doc: /* *Coding system for encoding file names.
5565 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5566 Vfile_name_coding_system = Qnil;
5568 DEFVAR_LISP ("default-file-name-coding-system",
5569 &Vdefault_file_name_coding_system,
5570 doc: /* Default coding system for encoding file names.
5571 This variable is used only when `file-name-coding-system' is nil.
5573 This variable is set/changed by the command `set-language-environment'.
5574 User should not set this variable manually,
5575 instead use `file-name-coding-system' to get a constant encoding
5576 of file names regardless of the current language environment. */);
5577 Vdefault_file_name_coding_system = Qnil;
5579 Qformat_decode = intern ("format-decode");
5580 staticpro (&Qformat_decode);
5581 Qformat_annotate_function = intern ("format-annotate-function");
5582 staticpro (&Qformat_annotate_function);
5583 Qafter_insert_file_set_coding = intern ("after-insert-file-set-coding");
5584 staticpro (&Qafter_insert_file_set_coding);
5586 Qcar_less_than_car = intern ("car-less-than-car");
5587 staticpro (&Qcar_less_than_car);
5589 Fput (Qfile_error, Qerror_conditions,
5590 list2 (Qfile_error, Qerror));
5591 Fput (Qfile_error, Qerror_message,
5592 build_string ("File error"));
5594 Fput (Qfile_already_exists, Qerror_conditions,
5595 list3 (Qfile_already_exists, Qfile_error, Qerror));
5596 Fput (Qfile_already_exists, Qerror_message,
5597 build_string ("File already exists"));
5599 Fput (Qfile_date_error, Qerror_conditions,
5600 list3 (Qfile_date_error, Qfile_error, Qerror));
5601 Fput (Qfile_date_error, Qerror_message,
5602 build_string ("Cannot set file date"));
5604 DEFVAR_LISP ("directory-sep-char", &Vdirectory_sep_char,
5605 doc: /* Directory separator character for built-in functions that return file names.
5606 The value is always ?/. Don't use this variable, just use `/'. */);
5608 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
5609 doc: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
5610 If a file name matches REGEXP, then all I/O on that file is done by calling
5611 HANDLER.
5613 The first argument given to HANDLER is the name of the I/O primitive
5614 to be handled; the remaining arguments are the arguments that were
5615 passed to that primitive. For example, if you do
5616 (file-exists-p FILENAME)
5617 and FILENAME is handled by HANDLER, then HANDLER is called like this:
5618 (funcall HANDLER 'file-exists-p FILENAME)
5619 The function `find-file-name-handler' checks this list for a handler
5620 for its argument. */);
5621 Vfile_name_handler_alist = Qnil;
5623 DEFVAR_LISP ("set-auto-coding-function",
5624 &Vset_auto_coding_function,
5625 doc: /* If non-nil, a function to call to decide a coding system of file.
5626 Two arguments are passed to this function: the file name
5627 and the length of a file contents following the point.
5628 This function should return a coding system to decode the file contents.
5629 It should check the file name against `auto-coding-alist'.
5630 If no coding system is decided, it should check a coding system
5631 specified in the heading lines with the format:
5632 -*- ... coding: CODING-SYSTEM; ... -*-
5633 or local variable spec of the tailing lines with `coding:' tag. */);
5634 Vset_auto_coding_function = Qnil;
5636 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
5637 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5638 Each is passed one argument, the number of characters inserted,
5639 with point at the start of the inserted text. Each function
5640 should leave point the same, and return the new character count.
5641 If `insert-file-contents' is intercepted by a handler from
5642 `file-name-handler-alist', that handler is responsible for calling the
5643 functions in `after-insert-file-functions' if appropriate. */);
5644 Vafter_insert_file_functions = Qnil;
5646 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
5647 doc: /* A list of functions to be called at the start of `write-region'.
5648 Each is passed two arguments, START and END as for `write-region'.
5649 These are usually two numbers but not always; see the documentation
5650 for `write-region'. The function should return a list of pairs
5651 of the form (POSITION . STRING), consisting of strings to be effectively
5652 inserted at the specified positions of the file being written (1 means to
5653 insert before the first byte written). The POSITIONs must be sorted into
5654 increasing order. If there are several functions in the list, the several
5655 lists are merged destructively. Alternatively, the function can return
5656 with a different buffer current; in that case it should pay attention
5657 to the annotations returned by previous functions and listed in
5658 `write-region-annotations-so-far'.*/);
5659 Vwrite_region_annotate_functions = Qnil;
5660 staticpro (&Qwrite_region_annotate_functions);
5661 Qwrite_region_annotate_functions
5662 = intern ("write-region-annotate-functions");
5664 DEFVAR_LISP ("write-region-annotations-so-far",
5665 &Vwrite_region_annotations_so_far,
5666 doc: /* When an annotation function is called, this holds the previous annotations.
5667 These are the annotations made by other annotation functions
5668 that were already called. See also `write-region-annotate-functions'. */);
5669 Vwrite_region_annotations_so_far = Qnil;
5671 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
5672 doc: /* A list of file name handlers that temporarily should not be used.
5673 This applies only to the operation `inhibit-file-name-operation'. */);
5674 Vinhibit_file_name_handlers = Qnil;
5676 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
5677 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5678 Vinhibit_file_name_operation = Qnil;
5680 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
5681 doc: /* File name in which we write a list of all auto save file names.
5682 This variable is initialized automatically from `auto-save-list-file-prefix'
5683 shortly after Emacs reads your `.emacs' file, if you have not yet given it
5684 a non-nil value. */);
5685 Vauto_save_list_file_name = Qnil;
5687 DEFVAR_LISP ("auto-save-visited-file-name", &Vauto_save_visited_file_name,
5688 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5689 Normally auto-save files are written under other names. */);
5690 Vauto_save_visited_file_name = Qnil;
5692 #ifdef HAVE_FSYNC
5693 DEFVAR_BOOL ("write-region-inhibit-fsync", &write_region_inhibit_fsync,
5694 doc: /* *Non-nil means don't call fsync in `write-region'.
5695 This variable affects calls to `write-region' as well as save commands.
5696 A non-nil value may result in data loss! */);
5697 write_region_inhibit_fsync = 0;
5698 #endif
5700 DEFVAR_BOOL ("delete-by-moving-to-trash", &delete_by_moving_to_trash,
5701 doc: /* Specifies whether to use the system's trash can.
5702 When non-nil, the function `move-file-to-trash' will be used by
5703 `delete-file' and `delete-directory'. */);
5704 delete_by_moving_to_trash = 0;
5705 Qdelete_by_moving_to_trash = intern ("delete-by-moving-to-trash");
5706 Qmove_file_to_trash = intern ("move-file-to-trash");
5707 staticpro (&Qmove_file_to_trash);
5709 defsubr (&Sfind_file_name_handler);
5710 defsubr (&Sfile_name_directory);
5711 defsubr (&Sfile_name_nondirectory);
5712 defsubr (&Sunhandled_file_name_directory);
5713 defsubr (&Sfile_name_as_directory);
5714 defsubr (&Sdirectory_file_name);
5715 defsubr (&Smake_temp_name);
5716 defsubr (&Sexpand_file_name);
5717 defsubr (&Ssubstitute_in_file_name);
5718 defsubr (&Scopy_file);
5719 defsubr (&Smake_directory_internal);
5720 defsubr (&Sdelete_directory);
5721 defsubr (&Sdelete_file);
5722 defsubr (&Srename_file);
5723 defsubr (&Sadd_name_to_file);
5724 defsubr (&Smake_symbolic_link);
5725 defsubr (&Sfile_name_absolute_p);
5726 defsubr (&Sfile_exists_p);
5727 defsubr (&Sfile_executable_p);
5728 defsubr (&Sfile_readable_p);
5729 defsubr (&Sfile_writable_p);
5730 defsubr (&Saccess_file);
5731 defsubr (&Sfile_symlink_p);
5732 defsubr (&Sfile_directory_p);
5733 defsubr (&Sfile_accessible_directory_p);
5734 defsubr (&Sfile_regular_p);
5735 defsubr (&Sfile_modes);
5736 defsubr (&Sset_file_modes);
5737 defsubr (&Sset_file_times);
5738 defsubr (&Sset_default_file_modes);
5739 defsubr (&Sdefault_file_modes);
5740 defsubr (&Sfile_newer_than_file_p);
5741 defsubr (&Sinsert_file_contents);
5742 defsubr (&Swrite_region);
5743 defsubr (&Scar_less_than_car);
5744 defsubr (&Sverify_visited_file_modtime);
5745 defsubr (&Sclear_visited_file_modtime);
5746 defsubr (&Svisited_file_modtime);
5747 defsubr (&Sset_visited_file_modtime);
5748 defsubr (&Sdo_auto_save);
5749 defsubr (&Sset_buffer_auto_saved);
5750 defsubr (&Sclear_buffer_auto_save_failure);
5751 defsubr (&Srecent_auto_save_p);
5753 defsubr (&Snext_read_file_uses_dialog_p);
5755 #ifdef HAVE_SYNC
5756 defsubr (&Sunix_sync);
5757 #endif
5760 /* arch-tag: 64ba3fd7-f844-4fb2-ba4b-427eb928786c
5761 (do not change this comment) */