* customize.texi (Composite Types): Move alist/plist from Simple Types (Bug#7545).
[emacs.git] / src / fileio.c
blob89c18d32c1543e50329aaa94ba77a1e852219386
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, 2010, 2011 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>
31 #include <setjmp.h>
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
37 #if !defined (S_ISLNK) && defined (S_IFLNK)
38 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
39 #endif
41 #if !defined (S_ISFIFO) && defined (S_IFIFO)
42 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
43 #endif
45 #if !defined (S_ISREG) && defined (S_IFREG)
46 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
47 #endif
49 #ifdef HAVE_PWD_H
50 #include <pwd.h>
51 #endif
53 #include <ctype.h>
54 #include <errno.h>
56 #ifndef vax11c
57 #ifndef USE_CRT_DLL
58 extern int errno;
59 #endif
60 #endif
62 #include "lisp.h"
63 #include "intervals.h"
64 #include "buffer.h"
65 #include "character.h"
66 #include "coding.h"
67 #include "window.h"
68 #include "blockinput.h"
69 #include "frame.h"
70 #include "dispextern.h"
72 #ifdef WINDOWSNT
73 #define NOMINMAX 1
74 #include <windows.h>
75 #include <stdlib.h>
76 #include <fcntl.h>
77 #endif /* not WINDOWSNT */
79 #ifdef MSDOS
80 #include "msdos.h"
81 #include <sys/param.h>
82 #if __DJGPP__ >= 2
83 #include <fcntl.h>
84 #include <string.h>
85 #endif
86 #endif
88 #ifdef DOS_NT
89 #define CORRECT_DIR_SEPS(s) \
90 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
91 else unixtodos_filename (s); \
92 } while (0)
93 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
94 redirector allows the six letters between 'Z' and 'a' as well. */
95 #ifdef MSDOS
96 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
97 #endif
98 #ifdef WINDOWSNT
99 #define IS_DRIVE(x) isalpha (x)
100 #endif
101 /* Need to lower-case the drive letter, or else expanded
102 filenames will sometimes compare inequal, because
103 `expand-file-name' doesn't always down-case the drive letter. */
104 #define DRIVE_LETTER(x) (tolower (x))
105 #endif
107 #include "systime.h"
109 #ifdef HPUX
110 #include <netio.h>
111 #endif
113 #include "commands.h"
114 extern int use_dialog_box;
115 extern int use_file_dialog;
117 #ifndef O_WRONLY
118 #define O_WRONLY 1
119 #endif
121 #ifndef O_RDONLY
122 #define O_RDONLY 0
123 #endif
125 #ifndef S_ISLNK
126 # define lstat stat
127 #endif
129 #ifndef FILE_SYSTEM_CASE
130 #define FILE_SYSTEM_CASE(filename) (filename)
131 #endif
133 /* Nonzero during writing of auto-save files */
134 int auto_saving;
136 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
137 a new file with the same mode as the original */
138 int auto_save_mode_bits;
140 /* Set by auto_save_1 if an error occurred during the last auto-save. */
141 int auto_save_error_occurred;
143 /* The symbol bound to coding-system-for-read when
144 insert-file-contents is called for recovering a file. This is not
145 an actual coding system name, but just an indicator to tell
146 insert-file-contents to use `emacs-mule' with a special flag for
147 auto saving and recovering a file. */
148 Lisp_Object Qauto_save_coding;
150 /* Coding system for file names, or nil if none. */
151 Lisp_Object Vfile_name_coding_system;
153 /* Coding system for file names used only when
154 Vfile_name_coding_system is nil. */
155 Lisp_Object Vdefault_file_name_coding_system;
157 /* Alist of elements (REGEXP . HANDLER) for file names
158 whose I/O is done with a special handler. */
159 Lisp_Object Vfile_name_handler_alist;
161 /* Property name of a file name handler,
162 which gives a list of operations it handles.. */
163 Lisp_Object Qoperations;
165 /* Lisp functions for translating file formats */
166 Lisp_Object Qformat_decode, Qformat_annotate_function;
168 /* Function to be called to decide a coding system of a reading file. */
169 Lisp_Object Vset_auto_coding_function;
171 /* Functions to be called to process text properties in inserted file. */
172 Lisp_Object Vafter_insert_file_functions;
174 /* Lisp function for setting buffer-file-coding-system and the
175 multibyteness of the current buffer after inserting a file. */
176 Lisp_Object Qafter_insert_file_set_coding;
178 /* Functions to be called to create text property annotations for file. */
179 Lisp_Object Vwrite_region_annotate_functions;
180 Lisp_Object Qwrite_region_annotate_functions;
181 Lisp_Object Vwrite_region_post_annotation_function;
183 /* During build_annotations, each time an annotation function is called,
184 this holds the annotations made by the previous functions. */
185 Lisp_Object Vwrite_region_annotations_so_far;
187 /* Each time an annotation function changes the buffer, the new buffer
188 is added here. */
189 Lisp_Object Vwrite_region_annotation_buffers;
191 /* File name in which we write a list of all our auto save files. */
192 Lisp_Object Vauto_save_list_file_name;
194 /* Whether or not files are auto-saved into themselves. */
195 Lisp_Object Vauto_save_visited_file_name;
197 /* Whether or not to continue auto-saving after a large deletion. */
198 Lisp_Object Vauto_save_include_big_deletions;
200 /* On NT, specifies the directory separator character, used (eg.) when
201 expanding file names. This can be bound to / or \. */
202 Lisp_Object Vdirectory_sep_char;
204 #ifdef HAVE_FSYNC
205 /* Nonzero means skip the call to fsync in Fwrite-region. */
206 int write_region_inhibit_fsync;
207 #endif
209 /* Non-zero means call move-file-to-trash in Fdelete_file or
210 Fdelete_directory_internal. */
211 int delete_by_moving_to_trash;
213 Lisp_Object Qdelete_by_moving_to_trash;
215 /* Lisp function for moving files to trash. */
216 Lisp_Object Qmove_file_to_trash;
218 /* Lisp function for recursively copying directories. */
219 Lisp_Object Qcopy_directory;
221 /* Lisp function for recursively deleting directories. */
222 Lisp_Object Qdelete_directory;
224 extern Lisp_Object Vuser_login_name;
226 #ifdef WINDOWSNT
227 extern Lisp_Object Vw32_get_true_file_attributes;
228 #endif
230 extern int minibuf_level;
232 extern int minibuffer_auto_raise;
234 /* These variables describe handlers that have "already" had a chance
235 to handle the current operation.
237 Vinhibit_file_name_handlers is a list of file name handlers.
238 Vinhibit_file_name_operation is the operation being handled.
239 If we try to handle that operation, we ignore those handlers. */
241 static Lisp_Object Vinhibit_file_name_handlers;
242 static Lisp_Object Vinhibit_file_name_operation;
244 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
245 Lisp_Object Qexcl;
246 Lisp_Object Qfile_name_history;
248 Lisp_Object Qcar_less_than_car;
250 static int a_write P_ ((int, Lisp_Object, int, int,
251 Lisp_Object *, struct coding_system *));
252 static int e_write P_ ((int, Lisp_Object, int, int, struct coding_system *));
255 void
256 report_file_error (string, data)
257 const char *string;
258 Lisp_Object data;
260 Lisp_Object errstring;
261 int errorno = errno;
262 char *str;
264 synchronize_system_messages_locale ();
265 str = strerror (errorno);
266 errstring = code_convert_string_norecord (make_unibyte_string (str,
267 strlen (str)),
268 Vlocale_coding_system, 0);
270 while (1)
271 switch (errorno)
273 case EEXIST:
274 xsignal (Qfile_already_exists, Fcons (errstring, data));
275 break;
276 default:
277 /* System error messages are capitalized. Downcase the initial
278 unless it is followed by a slash. (The slash case caters to
279 error messages that begin with "I/O" or, in German, "E/A".) */
280 if (STRING_MULTIBYTE (errstring)
281 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
283 int c;
285 str = (char *) SDATA (errstring);
286 c = STRING_CHAR (str);
287 Faset (errstring, make_number (0), make_number (DOWNCASE (c)));
290 xsignal (Qfile_error,
291 Fcons (build_string (string), Fcons (errstring, data)));
295 Lisp_Object
296 close_file_unwind (fd)
297 Lisp_Object fd;
299 emacs_close (XFASTINT (fd));
300 return Qnil;
303 /* Restore point, having saved it as a marker. */
305 Lisp_Object
306 restore_point_unwind (location)
307 Lisp_Object location;
309 Fgoto_char (location);
310 Fset_marker (location, Qnil, Qnil);
311 return Qnil;
315 Lisp_Object Qexpand_file_name;
316 Lisp_Object Qsubstitute_in_file_name;
317 Lisp_Object Qdirectory_file_name;
318 Lisp_Object Qfile_name_directory;
319 Lisp_Object Qfile_name_nondirectory;
320 Lisp_Object Qunhandled_file_name_directory;
321 Lisp_Object Qfile_name_as_directory;
322 Lisp_Object Qcopy_file;
323 Lisp_Object Qmake_directory_internal;
324 Lisp_Object Qmake_directory;
325 Lisp_Object Qdelete_directory_internal;
326 Lisp_Object Qdelete_file;
327 Lisp_Object Qrename_file;
328 Lisp_Object Qadd_name_to_file;
329 Lisp_Object Qmake_symbolic_link;
330 Lisp_Object Qfile_exists_p;
331 Lisp_Object Qfile_executable_p;
332 Lisp_Object Qfile_readable_p;
333 Lisp_Object Qfile_writable_p;
334 Lisp_Object Qfile_symlink_p;
335 Lisp_Object Qaccess_file;
336 Lisp_Object Qfile_directory_p;
337 Lisp_Object Qfile_regular_p;
338 Lisp_Object Qfile_accessible_directory_p;
339 Lisp_Object Qfile_modes;
340 Lisp_Object Qset_file_modes;
341 Lisp_Object Qset_file_times;
342 Lisp_Object Qfile_newer_than_file_p;
343 Lisp_Object Qinsert_file_contents;
344 Lisp_Object Qwrite_region;
345 Lisp_Object Qverify_visited_file_modtime;
346 Lisp_Object Qset_visited_file_modtime;
348 DEFUN ("find-file-name-handler", Ffind_file_name_handler, Sfind_file_name_handler, 2, 2, 0,
349 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
350 Otherwise, return nil.
351 A file name is handled if one of the regular expressions in
352 `file-name-handler-alist' matches it.
354 If OPERATION equals `inhibit-file-name-operation', then we ignore
355 any handlers that are members of `inhibit-file-name-handlers',
356 but we still do run any other handlers. This lets handlers
357 use the standard functions without calling themselves recursively. */)
358 (filename, operation)
359 Lisp_Object filename, operation;
361 /* This function must not munge the match data. */
362 Lisp_Object chain, inhibited_handlers, result;
363 int pos = -1;
365 result = Qnil;
366 CHECK_STRING (filename);
368 if (EQ (operation, Vinhibit_file_name_operation))
369 inhibited_handlers = Vinhibit_file_name_handlers;
370 else
371 inhibited_handlers = Qnil;
373 for (chain = Vfile_name_handler_alist; CONSP (chain);
374 chain = XCDR (chain))
376 Lisp_Object elt;
377 elt = XCAR (chain);
378 if (CONSP (elt))
380 Lisp_Object string = XCAR (elt);
381 int match_pos;
382 Lisp_Object handler = XCDR (elt);
383 Lisp_Object operations = Qnil;
385 if (SYMBOLP (handler))
386 operations = Fget (handler, Qoperations);
388 if (STRINGP (string)
389 && (match_pos = fast_string_match (string, filename)) > pos
390 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
392 Lisp_Object tem;
394 handler = XCDR (elt);
395 tem = Fmemq (handler, inhibited_handlers);
396 if (NILP (tem))
398 result = handler;
399 pos = match_pos;
404 QUIT;
406 return result;
409 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
410 1, 1, 0,
411 doc: /* Return the directory component in file name FILENAME.
412 Return nil if FILENAME does not include a directory.
413 Otherwise return a directory name.
414 Given a Unix syntax file name, returns a string ending in slash. */)
415 (filename)
416 Lisp_Object filename;
418 #ifndef DOS_NT
419 register const unsigned char *beg;
420 #else
421 register unsigned char *beg;
422 #endif
423 register const unsigned char *p;
424 Lisp_Object handler;
426 CHECK_STRING (filename);
428 /* If the file name has special constructs in it,
429 call the corresponding file handler. */
430 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
431 if (!NILP (handler))
432 return call2 (handler, Qfile_name_directory, filename);
434 filename = FILE_SYSTEM_CASE (filename);
435 #ifdef DOS_NT
436 beg = (unsigned char *) alloca (SBYTES (filename) + 1);
437 bcopy (SDATA (filename), beg, SBYTES (filename) + 1);
438 #else
439 beg = SDATA (filename);
440 #endif
441 p = beg + SBYTES (filename);
443 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
444 #ifdef DOS_NT
445 /* only recognise drive specifier at the beginning */
446 && !(p[-1] == ':'
447 /* handle the "/:d:foo" and "/:foo" cases correctly */
448 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
449 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
450 #endif
451 ) p--;
453 if (p == beg)
454 return Qnil;
455 #ifdef DOS_NT
456 /* Expansion of "c:" to drive and default directory. */
457 if (p[-1] == ':')
459 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
460 unsigned char *res = alloca (MAXPATHLEN + 1);
461 unsigned char *r = res;
463 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
465 strncpy (res, beg, 2);
466 beg += 2;
467 r += 2;
470 if (getdefdir (toupper (*beg) - 'A' + 1, r))
472 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
473 strcat (res, "/");
474 beg = res;
475 p = beg + strlen (beg);
478 CORRECT_DIR_SEPS (beg);
479 #endif /* DOS_NT */
481 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
484 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
485 Sfile_name_nondirectory, 1, 1, 0,
486 doc: /* Return file name FILENAME sans its directory.
487 For example, in a Unix-syntax file name,
488 this is everything after the last slash,
489 or the entire name if it contains no slash. */)
490 (filename)
491 Lisp_Object filename;
493 register const unsigned char *beg, *p, *end;
494 Lisp_Object handler;
496 CHECK_STRING (filename);
498 /* If the file name has special constructs in it,
499 call the corresponding file handler. */
500 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
501 if (!NILP (handler))
502 return call2 (handler, Qfile_name_nondirectory, filename);
504 beg = SDATA (filename);
505 end = p = beg + SBYTES (filename);
507 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
508 #ifdef DOS_NT
509 /* only recognise drive specifier at beginning */
510 && !(p[-1] == ':'
511 /* handle the "/:d:foo" case correctly */
512 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
513 #endif
515 p--;
517 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
520 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
521 Sunhandled_file_name_directory, 1, 1, 0,
522 doc: /* Return a directly usable directory name somehow associated with FILENAME.
523 A `directly usable' directory name is one that may be used without the
524 intervention of any file handler.
525 If FILENAME is a directly usable file itself, return
526 \(file-name-directory FILENAME).
527 If FILENAME refers to a file which is not accessible from a local process,
528 then this should return nil.
529 The `call-process' and `start-process' functions use this function to
530 get a current directory to run processes in. */)
531 (filename)
532 Lisp_Object filename;
534 Lisp_Object handler;
536 /* If the file name has special constructs in it,
537 call the corresponding file handler. */
538 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
539 if (!NILP (handler))
540 return call2 (handler, Qunhandled_file_name_directory, filename);
542 return Ffile_name_directory (filename);
546 char *
547 file_name_as_directory (out, in)
548 char *out, *in;
550 int size = strlen (in) - 1;
552 strcpy (out, in);
554 if (size < 0)
556 out[0] = '.';
557 out[1] = '/';
558 out[2] = 0;
559 return out;
562 /* For Unix syntax, Append a slash if necessary */
563 if (!IS_DIRECTORY_SEP (out[size]))
565 /* Cannot use DIRECTORY_SEP, which could have any value */
566 out[size + 1] = '/';
567 out[size + 2] = '\0';
569 #ifdef DOS_NT
570 CORRECT_DIR_SEPS (out);
571 #endif
572 return out;
575 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
576 Sfile_name_as_directory, 1, 1, 0,
577 doc: /* Return a string representing the file name FILE interpreted as a directory.
578 This operation exists because a directory is also a file, but its name as
579 a directory is different from its name as a file.
580 The result can be used as the value of `default-directory'
581 or passed as second argument to `expand-file-name'.
582 For a Unix-syntax file name, just appends a slash. */)
583 (file)
584 Lisp_Object file;
586 char *buf;
587 Lisp_Object handler;
589 CHECK_STRING (file);
590 if (NILP (file))
591 return Qnil;
593 /* If the file name has special constructs in it,
594 call the corresponding file handler. */
595 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
596 if (!NILP (handler))
597 return call2 (handler, Qfile_name_as_directory, file);
599 buf = (char *) alloca (SBYTES (file) + 10);
600 file_name_as_directory (buf, SDATA (file));
601 return make_specified_string (buf, -1, strlen (buf),
602 STRING_MULTIBYTE (file));
606 * Convert from directory name to filename.
607 * On UNIX, it's simple: just make sure there isn't a terminating /
609 * Value is nonzero if the string output is different from the input.
613 directory_file_name (src, dst)
614 char *src, *dst;
616 long slen;
618 slen = strlen (src);
620 /* Process as Unix format: just remove any final slash.
621 But leave "/" unchanged; do not change it to "". */
622 strcpy (dst, src);
623 if (slen > 1
624 && IS_DIRECTORY_SEP (dst[slen - 1])
625 #ifdef DOS_NT
626 && !IS_ANY_SEP (dst[slen - 2])
627 #endif
629 dst[slen - 1] = 0;
630 #ifdef DOS_NT
631 CORRECT_DIR_SEPS (dst);
632 #endif
633 return 1;
636 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
637 1, 1, 0,
638 doc: /* Returns the file name of the directory named DIRECTORY.
639 This is the name of the file that holds the data for the directory DIRECTORY.
640 This operation exists because a directory is also a file, but its name as
641 a directory is different from its name as a file.
642 In Unix-syntax, this function just removes the final slash. */)
643 (directory)
644 Lisp_Object directory;
646 char *buf;
647 Lisp_Object handler;
649 CHECK_STRING (directory);
651 if (NILP (directory))
652 return Qnil;
654 /* If the file name has special constructs in it,
655 call the corresponding file handler. */
656 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
657 if (!NILP (handler))
658 return call2 (handler, Qdirectory_file_name, directory);
660 buf = (char *) alloca (SBYTES (directory) + 20);
661 directory_file_name (SDATA (directory), buf);
662 return make_specified_string (buf, -1, strlen (buf),
663 STRING_MULTIBYTE (directory));
666 static const char make_temp_name_tbl[64] =
668 'A','B','C','D','E','F','G','H',
669 'I','J','K','L','M','N','O','P',
670 'Q','R','S','T','U','V','W','X',
671 'Y','Z','a','b','c','d','e','f',
672 'g','h','i','j','k','l','m','n',
673 'o','p','q','r','s','t','u','v',
674 'w','x','y','z','0','1','2','3',
675 '4','5','6','7','8','9','-','_'
678 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
680 /* Value is a temporary file name starting with PREFIX, a string.
682 The Emacs process number forms part of the result, so there is
683 no danger of generating a name being used by another process.
684 In addition, this function makes an attempt to choose a name
685 which has no existing file. To make this work, PREFIX should be
686 an absolute file name.
688 BASE64_P non-zero means add the pid as 3 characters in base64
689 encoding. In this case, 6 characters will be added to PREFIX to
690 form the file name. Otherwise, if Emacs is running on a system
691 with long file names, add the pid as a decimal number.
693 This function signals an error if no unique file name could be
694 generated. */
696 Lisp_Object
697 make_temp_name (prefix, base64_p)
698 Lisp_Object prefix;
699 int base64_p;
701 Lisp_Object val;
702 int len, clen;
703 int pid;
704 unsigned char *p, *data;
705 char pidbuf[20];
706 int pidlen;
708 CHECK_STRING (prefix);
710 /* VAL is created by adding 6 characters to PREFIX. The first
711 three are the PID of this process, in base 64, and the second
712 three are incremented if the file already exists. This ensures
713 262144 unique file names per PID per PREFIX. */
715 pid = (int) getpid ();
717 if (base64_p)
719 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
720 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
721 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
722 pidlen = 3;
724 else
726 #ifdef HAVE_LONG_FILE_NAMES
727 sprintf (pidbuf, "%d", pid);
728 pidlen = strlen (pidbuf);
729 #else
730 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
731 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
732 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
733 pidlen = 3;
734 #endif
737 len = SBYTES (prefix); clen = SCHARS (prefix);
738 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
739 if (!STRING_MULTIBYTE (prefix))
740 STRING_SET_UNIBYTE (val);
741 data = SDATA (val);
742 bcopy(SDATA (prefix), data, len);
743 p = data + len;
745 bcopy (pidbuf, p, pidlen);
746 p += pidlen;
748 /* Here we try to minimize useless stat'ing when this function is
749 invoked many times successively with the same PREFIX. We achieve
750 this by initializing count to a random value, and incrementing it
751 afterwards.
753 We don't want make-temp-name to be called while dumping,
754 because then make_temp_name_count_initialized_p would get set
755 and then make_temp_name_count would not be set when Emacs starts. */
757 if (!make_temp_name_count_initialized_p)
759 make_temp_name_count = (unsigned) time (NULL);
760 make_temp_name_count_initialized_p = 1;
763 while (1)
765 struct stat ignored;
766 unsigned num = make_temp_name_count;
768 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
769 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
770 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
772 /* Poor man's congruential RN generator. Replace with
773 ++make_temp_name_count for debugging. */
774 make_temp_name_count += 25229;
775 make_temp_name_count %= 225307;
777 if (stat (data, &ignored) < 0)
779 /* We want to return only if errno is ENOENT. */
780 if (errno == ENOENT)
781 return val;
782 else
783 /* The error here is dubious, but there is little else we
784 can do. The alternatives are to return nil, which is
785 as bad as (and in many cases worse than) throwing the
786 error, or to ignore the error, which will likely result
787 in looping through 225307 stat's, which is not only
788 dog-slow, but also useless since it will fallback to
789 the errow below, anyway. */
790 report_file_error ("Cannot create temporary name for prefix",
791 Fcons (prefix, Qnil));
792 /* not reached */
796 error ("Cannot create temporary name for prefix `%s'",
797 SDATA (prefix));
798 return Qnil;
802 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
803 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
804 The Emacs process number forms part of the result,
805 so there is no danger of generating a name being used by another process.
807 In addition, this function makes an attempt to choose a name
808 which has no existing file. To make this work,
809 PREFIX should be an absolute file name.
811 There is a race condition between calling `make-temp-name' and creating the
812 file which opens all kinds of security holes. For that reason, you should
813 probably use `make-temp-file' instead, except in three circumstances:
815 * If you are creating the file in the user's home directory.
816 * If you are creating a directory rather than an ordinary file.
817 * If you are taking special precautions as `make-temp-file' does. */)
818 (prefix)
819 Lisp_Object prefix;
821 return make_temp_name (prefix, 0);
826 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
827 doc: /* Convert filename NAME to absolute, and canonicalize it.
828 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
829 \(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
830 the current buffer's value of `default-directory' is used.
831 NAME should be a string that is a valid file name for the underlying
832 filesystem.
833 File name components that are `.' are removed, and
834 so are file name components followed by `..', along with the `..' itself;
835 note that these simplifications are done without checking the resulting
836 file names in the file system.
837 Multiple consecutive slashes are collapsed into a single slash,
838 except at the beginning of the file name when they are significant (e.g.,
839 UNC file names on MS-Windows.)
840 An initial `~/' expands to your home directory.
841 An initial `~USER/' expands to USER's home directory.
842 See also the function `substitute-in-file-name'.
844 For technical reasons, this function can return correct but
845 non-intuitive results for the root directory; for instance,
846 \(expand-file-name ".." "/") returns "/..". For this reason, use
847 \(directory-file-name (file-name-directory dirname)) to traverse a
848 filesystem tree, not (expand-file-name ".." dirname). */)
849 (name, default_directory)
850 Lisp_Object name, default_directory;
852 /* These point to SDATA and need to be careful with string-relocation
853 during GC (via DECODE_FILE). */
854 unsigned char *nm, *newdir;
855 /* This should only point to alloca'd data. */
856 unsigned char *target;
858 int tlen;
859 struct passwd *pw;
860 #ifdef DOS_NT
861 int drive = 0;
862 int collapse_newdir = 1;
863 int is_escaped = 0;
864 #endif /* DOS_NT */
865 int length;
866 Lisp_Object handler, result;
867 int multibyte;
868 Lisp_Object hdir;
870 CHECK_STRING (name);
872 /* If the file name has special constructs in it,
873 call the corresponding file handler. */
874 handler = Ffind_file_name_handler (name, Qexpand_file_name);
875 if (!NILP (handler))
876 return call3 (handler, Qexpand_file_name, name, default_directory);
878 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
879 if (NILP (default_directory))
880 default_directory = current_buffer->directory;
881 if (! STRINGP (default_directory))
883 #ifdef DOS_NT
884 /* "/" is not considered a root directory on DOS_NT, so using "/"
885 here causes an infinite recursion in, e.g., the following:
887 (let (default-directory)
888 (expand-file-name "a"))
890 To avoid this, we set default_directory to the root of the
891 current drive. */
892 extern char *emacs_root_dir (void);
894 default_directory = build_string (emacs_root_dir ());
895 #else
896 default_directory = build_string ("/");
897 #endif
900 if (!NILP (default_directory))
902 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
903 if (!NILP (handler))
904 return call3 (handler, Qexpand_file_name, name, default_directory);
908 unsigned char *o = SDATA (default_directory);
910 /* Make sure DEFAULT_DIRECTORY is properly expanded.
911 It would be better to do this down below where we actually use
912 default_directory. Unfortunately, calling Fexpand_file_name recursively
913 could invoke GC, and the strings might be relocated. This would
914 be annoying because we have pointers into strings lying around
915 that would need adjusting, and people would add new pointers to
916 the code and forget to adjust them, resulting in intermittent bugs.
917 Putting this call here avoids all that crud.
919 The EQ test avoids infinite recursion. */
920 if (! NILP (default_directory) && !EQ (default_directory, name)
921 /* Save time in some common cases - as long as default_directory
922 is not relative, it can be canonicalized with name below (if it
923 is needed at all) without requiring it to be expanded now. */
924 #ifdef DOS_NT
925 /* Detect MSDOS file names with drive specifiers. */
926 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
927 && IS_DIRECTORY_SEP (o[2]))
928 #ifdef WINDOWSNT
929 /* Detect Windows file names in UNC format. */
930 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
931 #endif
932 #else /* not DOS_NT */
933 /* Detect Unix absolute file names (/... alone is not absolute on
934 DOS or Windows). */
935 && ! (IS_DIRECTORY_SEP (o[0]))
936 #endif /* not DOS_NT */
939 struct gcpro gcpro1;
941 GCPRO1 (name);
942 default_directory = Fexpand_file_name (default_directory, Qnil);
943 UNGCPRO;
946 name = FILE_SYSTEM_CASE (name);
947 multibyte = STRING_MULTIBYTE (name);
948 if (multibyte != STRING_MULTIBYTE (default_directory))
950 if (multibyte)
951 default_directory = string_to_multibyte (default_directory);
952 else
954 name = string_to_multibyte (name);
955 multibyte = 1;
959 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
960 nm = (unsigned char *) alloca (SBYTES (name) + 1);
961 bcopy (SDATA (name), nm, SBYTES (name) + 1);
963 #ifdef DOS_NT
964 /* Note if special escape prefix is present, but remove for now. */
965 if (nm[0] == '/' && nm[1] == ':')
967 is_escaped = 1;
968 nm += 2;
971 /* Find and remove drive specifier if present; this makes nm absolute
972 even if the rest of the name appears to be relative. Only look for
973 drive specifier at the beginning. */
974 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
976 drive = nm[0];
977 nm += 2;
980 #ifdef WINDOWSNT
981 /* If we see "c://somedir", we want to strip the first slash after the
982 colon when stripping the drive letter. Otherwise, this expands to
983 "//somedir". */
984 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
985 nm++;
987 /* Discard any previous drive specifier if nm is now in UNC format. */
988 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
990 drive = 0;
992 #endif /* WINDOWSNT */
993 #endif /* DOS_NT */
995 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
996 none are found, we can probably return right away. We will avoid
997 allocating a new string if name is already fully expanded. */
998 if (
999 IS_DIRECTORY_SEP (nm[0])
1000 #ifdef MSDOS
1001 && drive && !is_escaped
1002 #endif
1003 #ifdef WINDOWSNT
1004 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
1005 #endif
1008 /* If it turns out that the filename we want to return is just a
1009 suffix of FILENAME, we don't need to go through and edit
1010 things; we just need to construct a new string using data
1011 starting at the middle of FILENAME. If we set lose to a
1012 non-zero value, that means we've discovered that we can't do
1013 that cool trick. */
1014 int lose = 0;
1015 unsigned char *p = nm;
1017 while (*p)
1019 /* Since we know the name is absolute, we can assume that each
1020 element starts with a "/". */
1022 /* "." and ".." are hairy. */
1023 if (IS_DIRECTORY_SEP (p[0])
1024 && p[1] == '.'
1025 && (IS_DIRECTORY_SEP (p[2])
1026 || p[2] == 0
1027 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1028 || p[3] == 0))))
1029 lose = 1;
1030 /* We want to replace multiple `/' in a row with a single
1031 slash. */
1032 else if (p > nm
1033 && IS_DIRECTORY_SEP (p[0])
1034 && IS_DIRECTORY_SEP (p[1]))
1035 lose = 1;
1036 p++;
1038 if (!lose)
1040 #ifdef DOS_NT
1041 /* Make sure directories are all separated with / or \ as
1042 desired, but avoid allocation of a new string when not
1043 required. */
1044 CORRECT_DIR_SEPS (nm);
1045 #ifdef WINDOWSNT
1046 if (IS_DIRECTORY_SEP (nm[1]))
1048 if (strcmp (nm, SDATA (name)) != 0)
1049 name = make_specified_string (nm, -1, strlen (nm), multibyte);
1051 else
1052 #endif
1053 /* drive must be set, so this is okay */
1054 if (strcmp (nm - 2, SDATA (name)) != 0)
1056 char temp[] = " :";
1058 name = make_specified_string (nm, -1, p - nm, multibyte);
1059 temp[0] = DRIVE_LETTER (drive);
1060 name = concat2 (build_string (temp), name);
1062 return name;
1063 #else /* not DOS_NT */
1064 if (strcmp (nm, SDATA (name)) == 0)
1065 return name;
1066 return make_specified_string (nm, -1, strlen (nm), multibyte);
1067 #endif /* not DOS_NT */
1071 /* At this point, nm might or might not be an absolute file name. We
1072 need to expand ~ or ~user if present, otherwise prefix nm with
1073 default_directory if nm is not absolute, and finally collapse /./
1074 and /foo/../ sequences.
1076 We set newdir to be the appropriate prefix if one is needed:
1077 - the relevant user directory if nm starts with ~ or ~user
1078 - the specified drive's working dir (DOS/NT only) if nm does not
1079 start with /
1080 - the value of default_directory.
1082 Note that these prefixes are not guaranteed to be absolute (except
1083 for the working dir of a drive). Therefore, to ensure we always
1084 return an absolute name, if the final prefix is not absolute we
1085 append it to the current working directory. */
1087 newdir = 0;
1089 if (nm[0] == '~') /* prefix ~ */
1091 if (IS_DIRECTORY_SEP (nm[1])
1092 || nm[1] == 0) /* ~ by itself */
1094 Lisp_Object tem;
1096 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1097 newdir = (unsigned char *) "";
1098 nm++;
1099 /* egetenv may return a unibyte string, which will bite us since
1100 we expect the directory to be multibyte. */
1101 tem = build_string (newdir);
1102 if (!STRING_MULTIBYTE (tem))
1104 hdir = DECODE_FILE (tem);
1105 newdir = SDATA (hdir);
1107 #ifdef DOS_NT
1108 collapse_newdir = 0;
1109 #endif
1111 else /* ~user/filename */
1113 unsigned char *o, *p;
1114 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
1115 o = alloca (p - nm + 1);
1116 bcopy ((char *) nm, o, p - nm);
1117 o [p - nm] = 0;
1119 BLOCK_INPUT;
1120 pw = (struct passwd *) getpwnam (o + 1);
1121 UNBLOCK_INPUT;
1122 if (pw)
1124 newdir = (unsigned char *) pw -> pw_dir;
1125 nm = p;
1126 #ifdef DOS_NT
1127 collapse_newdir = 0;
1128 #endif
1131 /* If we don't find a user of that name, leave the name
1132 unchanged; don't move nm forward to p. */
1136 #ifdef DOS_NT
1137 /* On DOS and Windows, nm is absolute if a drive name was specified;
1138 use the drive's current directory as the prefix if needed. */
1139 if (!newdir && drive)
1141 /* Get default directory if needed to make nm absolute. */
1142 if (!IS_DIRECTORY_SEP (nm[0]))
1144 newdir = alloca (MAXPATHLEN + 1);
1145 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1146 newdir = NULL;
1148 if (!newdir)
1150 /* Either nm starts with /, or drive isn't mounted. */
1151 newdir = alloca (4);
1152 newdir[0] = DRIVE_LETTER (drive);
1153 newdir[1] = ':';
1154 newdir[2] = '/';
1155 newdir[3] = 0;
1158 #endif /* DOS_NT */
1160 /* Finally, if no prefix has been specified and nm is not absolute,
1161 then it must be expanded relative to default_directory. */
1163 if (1
1164 #ifndef DOS_NT
1165 /* /... alone is not absolute on DOS and Windows. */
1166 && !IS_DIRECTORY_SEP (nm[0])
1167 #endif
1168 #ifdef WINDOWSNT
1169 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1170 #endif
1171 && !newdir)
1173 newdir = SDATA (default_directory);
1174 #ifdef DOS_NT
1175 /* Note if special escape prefix is present, but remove for now. */
1176 if (newdir[0] == '/' && newdir[1] == ':')
1178 is_escaped = 1;
1179 newdir += 2;
1181 #endif
1184 #ifdef DOS_NT
1185 if (newdir)
1187 /* First ensure newdir is an absolute name. */
1188 if (
1189 /* Detect MSDOS file names with drive specifiers. */
1190 ! (IS_DRIVE (newdir[0])
1191 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1192 #ifdef WINDOWSNT
1193 /* Detect Windows file names in UNC format. */
1194 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1195 #endif
1198 /* Effectively, let newdir be (expand-file-name newdir cwd).
1199 Because of the admonition against calling expand-file-name
1200 when we have pointers into lisp strings, we accomplish this
1201 indirectly by prepending newdir to nm if necessary, and using
1202 cwd (or the wd of newdir's drive) as the new newdir. */
1204 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1206 drive = newdir[0];
1207 newdir += 2;
1209 if (!IS_DIRECTORY_SEP (nm[0]))
1211 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1212 file_name_as_directory (tmp, newdir);
1213 strcat (tmp, nm);
1214 nm = tmp;
1216 newdir = alloca (MAXPATHLEN + 1);
1217 if (drive)
1219 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1220 newdir = "/";
1222 else
1223 getwd (newdir);
1226 /* Strip off drive name from prefix, if present. */
1227 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1229 drive = newdir[0];
1230 newdir += 2;
1233 /* Keep only a prefix from newdir if nm starts with slash
1234 (//server/share for UNC, nothing otherwise). */
1235 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1237 #ifdef WINDOWSNT
1238 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1240 unsigned char *p;
1241 newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
1242 p = newdir + 2;
1243 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1244 p++;
1245 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1246 *p = 0;
1248 else
1249 #endif
1250 newdir = "";
1253 #endif /* DOS_NT */
1255 if (newdir)
1257 /* Get rid of any slash at the end of newdir, unless newdir is
1258 just / or // (an incomplete UNC name). */
1259 length = strlen (newdir);
1260 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1261 #ifdef WINDOWSNT
1262 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1263 #endif
1266 unsigned char *temp = (unsigned char *) alloca (length);
1267 bcopy (newdir, temp, length - 1);
1268 temp[length - 1] = 0;
1269 newdir = temp;
1271 tlen = length + 1;
1273 else
1274 tlen = 0;
1276 /* Now concatenate the directory and name to new space in the stack frame */
1277 tlen += strlen (nm) + 1;
1278 #ifdef DOS_NT
1279 /* Reserve space for drive specifier and escape prefix, since either
1280 or both may need to be inserted. (The Microsoft x86 compiler
1281 produces incorrect code if the following two lines are combined.) */
1282 target = (unsigned char *) alloca (tlen + 4);
1283 target += 4;
1284 #else /* not DOS_NT */
1285 target = (unsigned char *) alloca (tlen);
1286 #endif /* not DOS_NT */
1287 *target = 0;
1289 if (newdir)
1291 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1293 #ifdef DOS_NT
1294 /* If newdir is effectively "C:/", then the drive letter will have
1295 been stripped and newdir will be "/". Concatenating with an
1296 absolute directory in nm produces "//", which will then be
1297 incorrectly treated as a network share. Ignore newdir in
1298 this case (keeping the drive letter). */
1299 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1300 && newdir[1] == '\0'))
1301 #endif
1302 strcpy (target, newdir);
1304 else
1305 file_name_as_directory (target, newdir);
1308 strcat (target, nm);
1310 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1311 appear. */
1313 unsigned char *p = target;
1314 unsigned char *o = target;
1316 while (*p)
1318 if (!IS_DIRECTORY_SEP (*p))
1320 *o++ = *p++;
1322 else if (p[1] == '.'
1323 && (IS_DIRECTORY_SEP (p[2])
1324 || p[2] == 0))
1326 /* If "/." is the entire filename, keep the "/". Otherwise,
1327 just delete the whole "/.". */
1328 if (o == target && p[2] == '\0')
1329 *o++ = *p;
1330 p += 2;
1332 else if (p[1] == '.' && p[2] == '.'
1333 /* `/../' is the "superroot" on certain file systems.
1334 Turned off on DOS_NT systems because they have no
1335 "superroot" and because this causes us to produce
1336 file names like "d:/../foo" which fail file-related
1337 functions of the underlying OS. (To reproduce, try a
1338 long series of "../../" in default_directory, longer
1339 than the number of levels from the root.) */
1340 #ifndef DOS_NT
1341 && o != target
1342 #endif
1343 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1345 #ifdef WINDOWSNT
1346 unsigned char *prev_o = o;
1347 #endif
1348 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1350 #ifdef WINDOWSNT
1351 /* Don't go below server level in UNC filenames. */
1352 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1353 && IS_DIRECTORY_SEP (*target))
1354 o = prev_o;
1355 else
1356 #endif
1357 /* Keep initial / only if this is the whole name. */
1358 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1359 ++o;
1360 p += 3;
1362 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1363 /* Collapse multiple `/' in a row. */
1364 p++;
1365 else
1367 *o++ = *p++;
1371 #ifdef DOS_NT
1372 /* At last, set drive name. */
1373 #ifdef WINDOWSNT
1374 /* Except for network file name. */
1375 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1376 #endif /* WINDOWSNT */
1378 if (!drive) abort ();
1379 target -= 2;
1380 target[0] = DRIVE_LETTER (drive);
1381 target[1] = ':';
1383 /* Reinsert the escape prefix if required. */
1384 if (is_escaped)
1386 target -= 2;
1387 target[0] = '/';
1388 target[1] = ':';
1390 CORRECT_DIR_SEPS (target);
1391 #endif /* DOS_NT */
1393 result = make_specified_string (target, -1, o - target, multibyte);
1396 /* Again look to see if the file name has special constructs in it
1397 and perhaps call the corresponding file handler. This is needed
1398 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1399 the ".." component gives us "/user@host:/bar/../baz" which needs
1400 to be expanded again. */
1401 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1402 if (!NILP (handler))
1403 return call3 (handler, Qexpand_file_name, result, default_directory);
1405 return result;
1408 #if 0
1409 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1410 This is the old version of expand-file-name, before it was thoroughly
1411 rewritten for Emacs 10.31. We leave this version here commented-out,
1412 because the code is very complex and likely to have subtle bugs. If
1413 bugs _are_ found, it might be of interest to look at the old code and
1414 see what did it do in the relevant situation.
1416 Don't remove this code: it's true that it will be accessible
1417 from the repository, but a few years from deletion, people will
1418 forget it is there. */
1420 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1421 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1422 "Convert FILENAME to absolute, and canonicalize it.\n\
1423 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1424 \(does not start with slash); if DEFAULT is nil or missing,\n\
1425 the current buffer's value of default-directory is used.\n\
1426 Filenames containing `.' or `..' as components are simplified;\n\
1427 initial `~/' expands to your home directory.\n\
1428 See also the function `substitute-in-file-name'.")
1429 (name, defalt)
1430 Lisp_Object name, defalt;
1432 unsigned char *nm;
1434 register unsigned char *newdir, *p, *o;
1435 int tlen;
1436 unsigned char *target;
1437 struct passwd *pw;
1438 int lose;
1440 CHECK_STRING (name);
1441 nm = SDATA (name);
1443 /* If nm is absolute, flush ...// and detect /./ and /../.
1444 If no /./ or /../ we can return right away. */
1445 if (nm[0] == '/')
1447 p = nm;
1448 lose = 0;
1449 while (*p)
1451 if (p[0] == '/' && p[1] == '/'
1453 nm = p + 1;
1454 if (p[0] == '/' && p[1] == '~')
1455 nm = p + 1, lose = 1;
1456 if (p[0] == '/' && p[1] == '.'
1457 && (p[2] == '/' || p[2] == 0
1458 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1459 lose = 1;
1460 p++;
1462 if (!lose)
1464 if (nm == SDATA (name))
1465 return name;
1466 return build_string (nm);
1470 /* Now determine directory to start with and put it in NEWDIR */
1472 newdir = 0;
1474 if (nm[0] == '~') /* prefix ~ */
1475 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1477 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1478 newdir = (unsigned char *) "";
1479 nm++;
1481 else /* ~user/filename */
1483 /* Get past ~ to user */
1484 unsigned char *user = nm + 1;
1485 /* Find end of name. */
1486 unsigned char *ptr = (unsigned char *) index (user, '/');
1487 int len = ptr ? ptr - user : strlen (user);
1488 /* Copy the user name into temp storage. */
1489 o = (unsigned char *) alloca (len + 1);
1490 bcopy ((char *) user, o, len);
1491 o[len] = 0;
1493 /* Look up the user name. */
1494 BLOCK_INPUT;
1495 pw = (struct passwd *) getpwnam (o + 1);
1496 UNBLOCK_INPUT;
1497 if (!pw)
1498 error ("\"%s\" isn't a registered user", o + 1);
1500 newdir = (unsigned char *) pw->pw_dir;
1502 /* Discard the user name from NM. */
1503 nm += len;
1506 if (nm[0] != '/' && !newdir)
1508 if (NILP (defalt))
1509 defalt = current_buffer->directory;
1510 CHECK_STRING (defalt);
1511 newdir = SDATA (defalt);
1514 /* Now concatenate the directory and name to new space in the stack frame */
1516 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1517 target = (unsigned char *) alloca (tlen);
1518 *target = 0;
1520 if (newdir)
1522 if (nm[0] == 0 || nm[0] == '/')
1523 strcpy (target, newdir);
1524 else
1525 file_name_as_directory (target, newdir);
1528 strcat (target, nm);
1530 /* Now canonicalize by removing /. and /foo/.. if they appear */
1532 p = target;
1533 o = target;
1535 while (*p)
1537 if (*p != '/')
1539 *o++ = *p++;
1541 else if (!strncmp (p, "//", 2)
1544 o = target;
1545 p++;
1547 else if (p[0] == '/' && p[1] == '.'
1548 && (p[2] == '/' || p[2] == 0))
1549 p += 2;
1550 else if (!strncmp (p, "/..", 3)
1551 /* `/../' is the "superroot" on certain file systems. */
1552 && o != target
1553 && (p[3] == '/' || p[3] == 0))
1555 while (o != target && *--o != '/')
1557 if (o == target && *o == '/')
1558 ++o;
1559 p += 3;
1561 else
1563 *o++ = *p++;
1567 return make_string (target, o - target);
1569 #endif
1571 /* If /~ or // appears, discard everything through first slash. */
1572 static int
1573 file_name_absolute_p (filename)
1574 const unsigned char *filename;
1576 return
1577 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1578 #ifdef DOS_NT
1579 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1580 && IS_DIRECTORY_SEP (filename[2]))
1581 #endif
1585 static unsigned char *
1586 search_embedded_absfilename (nm, endp)
1587 unsigned char *nm, *endp;
1589 unsigned char *p, *s;
1591 for (p = nm + 1; p < endp; p++)
1593 if ((0
1594 || IS_DIRECTORY_SEP (p[-1]))
1595 && file_name_absolute_p (p)
1596 #if defined (WINDOWSNT) || defined(CYGWIN)
1597 /* // at start of file name is meaningful in Apollo,
1598 WindowsNT and Cygwin systems. */
1599 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1600 #endif /* not (WINDOWSNT || CYGWIN) */
1603 for (s = p; *s && (!IS_DIRECTORY_SEP (*s)); s++);
1604 if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
1606 unsigned char *o = alloca (s - p + 1);
1607 struct passwd *pw;
1608 bcopy (p, o, s - p);
1609 o [s - p] = 0;
1611 /* If we have ~user and `user' exists, discard
1612 everything up to ~. But if `user' does not exist, leave
1613 ~user alone, it might be a literal file name. */
1614 BLOCK_INPUT;
1615 pw = getpwnam (o + 1);
1616 UNBLOCK_INPUT;
1617 if (pw)
1618 return p;
1620 else
1621 return p;
1624 return NULL;
1627 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1628 Ssubstitute_in_file_name, 1, 1, 0,
1629 doc: /* Substitute environment variables referred to in FILENAME.
1630 `$FOO' where FOO is an environment variable name means to substitute
1631 the value of that variable. The variable name should be terminated
1632 with a character not a letter, digit or underscore; otherwise, enclose
1633 the entire variable name in braces.
1635 If `/~' appears, all of FILENAME through that `/' is discarded.
1636 If `//' appears, everything up to and including the first of
1637 those `/' is discarded. */)
1638 (filename)
1639 Lisp_Object filename;
1641 unsigned char *nm;
1643 register unsigned char *s, *p, *o, *x, *endp;
1644 unsigned char *target = NULL;
1645 int total = 0;
1646 int substituted = 0;
1647 int multibyte;
1648 unsigned char *xnm;
1649 Lisp_Object handler;
1651 CHECK_STRING (filename);
1653 multibyte = STRING_MULTIBYTE (filename);
1655 /* If the file name has special constructs in it,
1656 call the corresponding file handler. */
1657 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1658 if (!NILP (handler))
1659 return call2 (handler, Qsubstitute_in_file_name, filename);
1661 /* Always work on a copy of the string, in case GC happens during
1662 decode of environment variables, causing the original Lisp_String
1663 data to be relocated. */
1664 nm = (unsigned char *) alloca (SBYTES (filename) + 1);
1665 bcopy (SDATA (filename), nm, SBYTES (filename) + 1);
1667 #ifdef DOS_NT
1668 CORRECT_DIR_SEPS (nm);
1669 substituted = (strcmp (nm, SDATA (filename)) != 0);
1670 #endif
1671 endp = nm + SBYTES (filename);
1673 /* If /~ or // appears, discard everything through first slash. */
1674 p = search_embedded_absfilename (nm, endp);
1675 if (p)
1676 /* Start over with the new string, so we check the file-name-handler
1677 again. Important with filenames like "/home/foo//:/hello///there"
1678 which whould substitute to "/:/hello///there" rather than "/there". */
1679 return Fsubstitute_in_file_name
1680 (make_specified_string (p, -1, endp - p, multibyte));
1682 /* See if any variables are substituted into the string
1683 and find the total length of their values in `total' */
1685 for (p = nm; p != endp;)
1686 if (*p != '$')
1687 p++;
1688 else
1690 p++;
1691 if (p == endp)
1692 goto badsubst;
1693 else if (*p == '$')
1695 /* "$$" means a single "$" */
1696 p++;
1697 total -= 1;
1698 substituted = 1;
1699 continue;
1701 else if (*p == '{')
1703 o = ++p;
1704 while (p != endp && *p != '}') p++;
1705 if (*p != '}') goto missingclose;
1706 s = p;
1708 else
1710 o = p;
1711 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1712 s = p;
1715 /* Copy out the variable name */
1716 target = (unsigned char *) alloca (s - o + 1);
1717 strncpy (target, o, s - o);
1718 target[s - o] = 0;
1719 #ifdef DOS_NT
1720 strupr (target); /* $home == $HOME etc. */
1721 #endif /* DOS_NT */
1723 /* Get variable value */
1724 o = (unsigned char *) egetenv (target);
1725 if (o)
1727 /* Don't try to guess a maximum length - UTF8 can use up to
1728 four bytes per character. This code is unlikely to run
1729 in a situation that requires performance, so decoding the
1730 env variables twice should be acceptable. Note that
1731 decoding may cause a garbage collect. */
1732 Lisp_Object orig, decoded;
1733 orig = make_unibyte_string (o, strlen (o));
1734 decoded = DECODE_FILE (orig);
1735 total += SBYTES (decoded);
1736 substituted = 1;
1738 else if (*p == '}')
1739 goto badvar;
1742 if (!substituted)
1743 return filename;
1745 /* If substitution required, recopy the string and do it */
1746 /* Make space in stack frame for the new copy */
1747 xnm = (unsigned char *) alloca (SBYTES (filename) + total + 1);
1748 x = xnm;
1750 /* Copy the rest of the name through, replacing $ constructs with values */
1751 for (p = nm; *p;)
1752 if (*p != '$')
1753 *x++ = *p++;
1754 else
1756 p++;
1757 if (p == endp)
1758 goto badsubst;
1759 else if (*p == '$')
1761 *x++ = *p++;
1762 continue;
1764 else if (*p == '{')
1766 o = ++p;
1767 while (p != endp && *p != '}') p++;
1768 if (*p != '}') goto missingclose;
1769 s = p++;
1771 else
1773 o = p;
1774 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1775 s = p;
1778 /* Copy out the variable name */
1779 target = (unsigned char *) alloca (s - o + 1);
1780 strncpy (target, o, s - o);
1781 target[s - o] = 0;
1782 #ifdef DOS_NT
1783 strupr (target); /* $home == $HOME etc. */
1784 #endif /* DOS_NT */
1786 /* Get variable value */
1787 o = (unsigned char *) egetenv (target);
1788 if (!o)
1790 *x++ = '$';
1791 strcpy (x, target); x+= strlen (target);
1793 else
1795 Lisp_Object orig, decoded;
1796 int orig_length, decoded_length;
1797 orig_length = strlen (o);
1798 orig = make_unibyte_string (o, orig_length);
1799 decoded = DECODE_FILE (orig);
1800 decoded_length = SBYTES (decoded);
1801 strncpy (x, SDATA (decoded), decoded_length);
1802 x += decoded_length;
1804 /* If environment variable needed decoding, return value
1805 needs to be multibyte. */
1806 if (decoded_length != orig_length
1807 || strncmp (SDATA (decoded), o, orig_length))
1808 multibyte = 1;
1812 *x = 0;
1814 /* If /~ or // appears, discard everything through first slash. */
1815 while ((p = search_embedded_absfilename (xnm, x)))
1816 /* This time we do not start over because we've already expanded envvars
1817 and replaced $$ with $. Maybe we should start over as well, but we'd
1818 need to quote some $ to $$ first. */
1819 xnm = p;
1821 return make_specified_string (xnm, -1, x - xnm, multibyte);
1823 badsubst:
1824 error ("Bad format environment-variable substitution");
1825 missingclose:
1826 error ("Missing \"}\" in environment-variable substitution");
1827 badvar:
1828 error ("Substituting nonexistent environment variable \"%s\"", target);
1830 /* NOTREACHED */
1831 return Qnil;
1834 /* A slightly faster and more convenient way to get
1835 (directory-file-name (expand-file-name FOO)). */
1837 Lisp_Object
1838 expand_and_dir_to_file (filename, defdir)
1839 Lisp_Object filename, defdir;
1841 register Lisp_Object absname;
1843 absname = Fexpand_file_name (filename, defdir);
1845 /* Remove final slash, if any (unless this is the root dir).
1846 stat behaves differently depending! */
1847 if (SCHARS (absname) > 1
1848 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1849 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
1850 /* We cannot take shortcuts; they might be wrong for magic file names. */
1851 absname = Fdirectory_file_name (absname);
1852 return absname;
1855 /* Signal an error if the file ABSNAME already exists.
1856 If INTERACTIVE is nonzero, ask the user whether to proceed,
1857 and bypass the error if the user says to go ahead.
1858 QUERYSTRING is a name for the action that is being considered
1859 to alter the file.
1861 *STATPTR is used to store the stat information if the file exists.
1862 If the file does not exist, STATPTR->st_mode is set to 0.
1863 If STATPTR is null, we don't store into it.
1865 If QUICK is nonzero, we ask for y or n, not yes or no. */
1867 void
1868 barf_or_query_if_file_exists (absname, querystring, interactive, statptr, quick)
1869 Lisp_Object absname;
1870 unsigned char *querystring;
1871 int interactive;
1872 struct stat *statptr;
1873 int quick;
1875 register Lisp_Object tem, encoded_filename;
1876 struct stat statbuf;
1877 struct gcpro gcpro1;
1879 encoded_filename = ENCODE_FILE (absname);
1881 /* stat is a good way to tell whether the file exists,
1882 regardless of what access permissions it has. */
1883 if (lstat (SDATA (encoded_filename), &statbuf) >= 0)
1885 if (! interactive)
1886 xsignal2 (Qfile_already_exists,
1887 build_string ("File already exists"), absname);
1888 GCPRO1 (absname);
1889 tem = format2 ("File %s already exists; %s anyway? ",
1890 absname, build_string (querystring));
1891 if (quick)
1892 tem = Fy_or_n_p (tem);
1893 else
1894 tem = do_yes_or_no_p (tem);
1895 UNGCPRO;
1896 if (NILP (tem))
1897 xsignal2 (Qfile_already_exists,
1898 build_string ("File already exists"), absname);
1899 if (statptr)
1900 *statptr = statbuf;
1902 else
1904 if (statptr)
1905 statptr->st_mode = 0;
1907 return;
1910 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 5,
1911 "fCopy file: \nGCopy %s to file: \np\nP",
1912 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1913 If NEWNAME names a directory, copy FILE there.
1915 This function always sets the file modes of the output file to match
1916 the input file.
1918 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1919 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1920 signal a `file-already-exists' error without overwriting. If
1921 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1922 about overwriting; this is what happens in interactive use with M-x.
1923 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1924 existing file.
1926 Fourth arg KEEP-TIME non-nil means give the output file the same
1927 last-modified time as the old one. (This works on only some systems.)
1929 A prefix arg makes KEEP-TIME non-nil.
1931 If PRESERVE-UID-GID is non-nil, we try to transfer the
1932 uid and gid of FILE to NEWNAME. */)
1933 (file, newname, ok_if_already_exists, keep_time, preserve_uid_gid)
1934 Lisp_Object file, newname, ok_if_already_exists, keep_time;
1935 Lisp_Object preserve_uid_gid;
1937 int ifd, ofd, n;
1938 char buf[16 * 1024];
1939 struct stat st, out_st;
1940 Lisp_Object handler;
1941 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1942 int count = SPECPDL_INDEX ();
1943 int input_file_statable_p;
1944 Lisp_Object encoded_file, encoded_newname;
1946 encoded_file = encoded_newname = Qnil;
1947 GCPRO4 (file, newname, encoded_file, encoded_newname);
1948 CHECK_STRING (file);
1949 CHECK_STRING (newname);
1951 if (!NILP (Ffile_directory_p (newname)))
1952 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1953 else
1954 newname = Fexpand_file_name (newname, Qnil);
1956 file = Fexpand_file_name (file, Qnil);
1958 /* If the input file name has special constructs in it,
1959 call the corresponding file handler. */
1960 handler = Ffind_file_name_handler (file, Qcopy_file);
1961 /* Likewise for output file name. */
1962 if (NILP (handler))
1963 handler = Ffind_file_name_handler (newname, Qcopy_file);
1964 if (!NILP (handler))
1965 RETURN_UNGCPRO (call6 (handler, Qcopy_file, file, newname,
1966 ok_if_already_exists, keep_time, preserve_uid_gid));
1968 encoded_file = ENCODE_FILE (file);
1969 encoded_newname = ENCODE_FILE (newname);
1971 if (NILP (ok_if_already_exists)
1972 || INTEGERP (ok_if_already_exists))
1973 barf_or_query_if_file_exists (newname, "copy to it",
1974 INTEGERP (ok_if_already_exists), &out_st, 0);
1975 else if (stat (SDATA (encoded_newname), &out_st) < 0)
1976 out_st.st_mode = 0;
1978 #ifdef WINDOWSNT
1979 if (!CopyFile (SDATA (encoded_file),
1980 SDATA (encoded_newname),
1981 FALSE))
1982 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
1983 /* CopyFile retains the timestamp by default. */
1984 else if (NILP (keep_time))
1986 EMACS_TIME now;
1987 DWORD attributes;
1988 char * filename;
1990 EMACS_GET_TIME (now);
1991 filename = SDATA (encoded_newname);
1993 /* Ensure file is writable while its modified time is set. */
1994 attributes = GetFileAttributes (filename);
1995 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
1996 if (set_file_times (filename, now, now))
1998 /* Restore original attributes. */
1999 SetFileAttributes (filename, attributes);
2000 xsignal2 (Qfile_date_error,
2001 build_string ("Cannot set file date"), newname);
2003 /* Restore original attributes. */
2004 SetFileAttributes (filename, attributes);
2006 #else /* not WINDOWSNT */
2007 immediate_quit = 1;
2008 ifd = emacs_open (SDATA (encoded_file), O_RDONLY, 0);
2009 immediate_quit = 0;
2011 if (ifd < 0)
2012 report_file_error ("Opening input file", Fcons (file, Qnil));
2014 record_unwind_protect (close_file_unwind, make_number (ifd));
2016 /* We can only copy regular files and symbolic links. Other files are not
2017 copyable by us. */
2018 input_file_statable_p = (fstat (ifd, &st) >= 0);
2020 #if !defined (MSDOS) || __DJGPP__ > 1
2021 if (out_st.st_mode != 0
2022 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2024 errno = 0;
2025 report_file_error ("Input and output files are the same",
2026 Fcons (file, Fcons (newname, Qnil)));
2028 #endif
2030 #if defined (S_ISREG) && defined (S_ISLNK)
2031 if (input_file_statable_p)
2033 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
2035 #if defined (EISDIR)
2036 /* Get a better looking error message. */
2037 errno = EISDIR;
2038 #endif /* EISDIR */
2039 report_file_error ("Non-regular file", Fcons (file, Qnil));
2042 #endif /* S_ISREG && S_ISLNK */
2044 #ifdef MSDOS
2045 /* System's default file type was set to binary by _fmode in emacs.c. */
2046 ofd = emacs_open (SDATA (encoded_newname),
2047 O_WRONLY | O_TRUNC | O_CREAT
2048 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2049 S_IREAD | S_IWRITE);
2050 #else /* not MSDOS */
2051 ofd = emacs_open (SDATA (encoded_newname),
2052 O_WRONLY | O_TRUNC | O_CREAT
2053 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2054 0666);
2055 #endif /* not MSDOS */
2056 if (ofd < 0)
2057 report_file_error ("Opening output file", Fcons (newname, Qnil));
2059 record_unwind_protect (close_file_unwind, make_number (ofd));
2061 immediate_quit = 1;
2062 QUIT;
2063 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2064 if (emacs_write (ofd, buf, n) != n)
2065 report_file_error ("I/O error", Fcons (newname, Qnil));
2066 immediate_quit = 0;
2068 #ifndef MSDOS
2069 /* Preserve the original file modes, and if requested, also its
2070 owner and group. */
2071 if (input_file_statable_p)
2073 if (! NILP (preserve_uid_gid))
2074 fchown (ofd, st.st_uid, st.st_gid);
2075 fchmod (ofd, st.st_mode & 07777);
2077 #endif /* not MSDOS */
2079 /* Closing the output clobbers the file times on some systems. */
2080 if (emacs_close (ofd) < 0)
2081 report_file_error ("I/O error", Fcons (newname, Qnil));
2083 if (input_file_statable_p)
2085 if (!NILP (keep_time))
2087 EMACS_TIME atime, mtime;
2088 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2089 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2090 if (set_file_times (SDATA (encoded_newname),
2091 atime, mtime))
2092 xsignal2 (Qfile_date_error,
2093 build_string ("Cannot set file date"), newname);
2097 emacs_close (ifd);
2099 #if defined (__DJGPP__) && __DJGPP__ > 1
2100 if (input_file_statable_p)
2102 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2103 and if it can't, it tells so. Otherwise, under MSDOS we usually
2104 get only the READ bit, which will make the copied file read-only,
2105 so it's better not to chmod at all. */
2106 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2107 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2109 #endif /* DJGPP version 2 or newer */
2110 #endif /* not WINDOWSNT */
2112 /* Discard the unwind protects. */
2113 specpdl_ptr = specpdl + count;
2115 UNGCPRO;
2116 return Qnil;
2119 DEFUN ("make-directory-internal", Fmake_directory_internal,
2120 Smake_directory_internal, 1, 1, 0,
2121 doc: /* Create a new directory named DIRECTORY. */)
2122 (directory)
2123 Lisp_Object directory;
2125 const unsigned char *dir;
2126 Lisp_Object handler;
2127 Lisp_Object encoded_dir;
2129 CHECK_STRING (directory);
2130 directory = Fexpand_file_name (directory, Qnil);
2132 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2133 if (!NILP (handler))
2134 return call2 (handler, Qmake_directory_internal, directory);
2136 encoded_dir = ENCODE_FILE (directory);
2138 dir = SDATA (encoded_dir);
2140 #ifdef WINDOWSNT
2141 if (mkdir (dir) != 0)
2142 #else
2143 if (mkdir (dir, 0777) != 0)
2144 #endif
2145 report_file_error ("Creating directory", list1 (directory));
2147 return Qnil;
2150 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2151 Sdelete_directory_internal, 1, 1, 0,
2152 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2153 (directory)
2154 Lisp_Object directory;
2156 const unsigned char *dir;
2157 Lisp_Object handler;
2158 Lisp_Object encoded_dir;
2160 CHECK_STRING (directory);
2161 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2163 if (delete_by_moving_to_trash)
2164 return call1 (Qmove_file_to_trash, directory);
2166 encoded_dir = ENCODE_FILE (directory);
2168 dir = SDATA (encoded_dir);
2170 if (rmdir (dir) != 0)
2171 report_file_error ("Removing directory", list1 (directory));
2173 return Qnil;
2176 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 1, "fDelete file: ",
2177 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2178 If file has multiple names, it continues to exist with the other names. */)
2179 (filename)
2180 Lisp_Object filename;
2182 Lisp_Object handler;
2183 Lisp_Object encoded_file;
2184 struct gcpro gcpro1;
2186 GCPRO1 (filename);
2187 if (!NILP (Ffile_directory_p (filename))
2188 && NILP (Ffile_symlink_p (filename)))
2189 xsignal2 (Qfile_error,
2190 build_string ("Removing old name: is a directory"),
2191 filename);
2192 UNGCPRO;
2193 filename = Fexpand_file_name (filename, Qnil);
2195 handler = Ffind_file_name_handler (filename, Qdelete_file);
2196 if (!NILP (handler))
2197 return call2 (handler, Qdelete_file, filename);
2199 if (delete_by_moving_to_trash)
2200 return call1 (Qmove_file_to_trash, filename);
2202 encoded_file = ENCODE_FILE (filename);
2204 if (0 > unlink (SDATA (encoded_file)))
2205 report_file_error ("Removing old name", list1 (filename));
2206 return Qnil;
2209 static Lisp_Object
2210 internal_delete_file_1 (ignore)
2211 Lisp_Object ignore;
2213 return Qt;
2216 /* Delete file FILENAME, returning 1 if successful and 0 if failed. */
2219 internal_delete_file (filename)
2220 Lisp_Object filename;
2222 Lisp_Object tem;
2223 tem = internal_condition_case_1 (Fdelete_file, filename,
2224 Qt, internal_delete_file_1);
2225 return NILP (tem);
2228 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2229 "fRename file: \nGRename %s to file: \np",
2230 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2231 If file has names other than FILE, it continues to have those names.
2232 Signals a `file-already-exists' error if a file NEWNAME already exists
2233 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2234 A number as third arg means request confirmation if NEWNAME already exists.
2235 This is what happens in interactive use with M-x. */)
2236 (file, newname, ok_if_already_exists)
2237 Lisp_Object file, newname, ok_if_already_exists;
2239 Lisp_Object handler;
2240 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2241 Lisp_Object encoded_file, encoded_newname, symlink_target;
2243 symlink_target = encoded_file = encoded_newname = Qnil;
2244 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2245 CHECK_STRING (file);
2246 CHECK_STRING (newname);
2247 file = Fexpand_file_name (file, Qnil);
2249 if ((!NILP (Ffile_directory_p (newname)))
2250 #ifdef DOS_NT
2251 /* If the file names are identical but for the case,
2252 don't attempt to move directory to itself. */
2253 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2254 #endif
2257 Lisp_Object fname = NILP (Ffile_directory_p (file))
2258 ? file : Fdirectory_file_name (file);
2259 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2261 else
2262 newname = Fexpand_file_name (newname, Qnil);
2264 /* If the file name has special constructs in it,
2265 call the corresponding file handler. */
2266 handler = Ffind_file_name_handler (file, Qrename_file);
2267 if (NILP (handler))
2268 handler = Ffind_file_name_handler (newname, Qrename_file);
2269 if (!NILP (handler))
2270 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2271 file, newname, ok_if_already_exists));
2273 encoded_file = ENCODE_FILE (file);
2274 encoded_newname = ENCODE_FILE (newname);
2276 #ifdef DOS_NT
2277 /* If the file names are identical but for the case, don't ask for
2278 confirmation: they simply want to change the letter-case of the
2279 file name. */
2280 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2281 #endif
2282 if (NILP (ok_if_already_exists)
2283 || INTEGERP (ok_if_already_exists))
2284 barf_or_query_if_file_exists (newname, "rename to it",
2285 INTEGERP (ok_if_already_exists), 0, 0);
2286 if (0 > rename (SDATA (encoded_file), SDATA (encoded_newname)))
2288 if (errno == EXDEV)
2290 int count;
2291 #ifdef S_IFLNK
2292 symlink_target = Ffile_symlink_p (file);
2293 if (! NILP (symlink_target))
2294 Fmake_symbolic_link (symlink_target, newname,
2295 NILP (ok_if_already_exists) ? Qnil : Qt);
2296 else
2297 #endif
2298 if (!NILP (Ffile_directory_p (file)))
2299 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2300 else
2301 /* We have already prompted if it was an integer, so don't
2302 have copy-file prompt again. */
2303 Fcopy_file (file, newname,
2304 NILP (ok_if_already_exists) ? Qnil : Qt,
2305 Qt, Qt);
2307 count = SPECPDL_INDEX ();
2308 specbind (Qdelete_by_moving_to_trash, Qnil);
2310 if (!NILP (Ffile_directory_p (file))
2311 #ifdef S_IFLNK
2312 && NILP (symlink_target)
2313 #endif
2315 call2 (Qdelete_directory, file, Qt);
2316 else
2317 Fdelete_file (file);
2318 unbind_to (count, Qnil);
2320 else
2321 report_file_error ("Renaming", list2 (file, newname));
2323 UNGCPRO;
2324 return Qnil;
2327 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2328 "fAdd name to file: \nGName to add to %s: \np",
2329 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2330 Signals a `file-already-exists' error if a file NEWNAME already exists
2331 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2332 A number as third arg means request confirmation if NEWNAME already exists.
2333 This is what happens in interactive use with M-x. */)
2334 (file, newname, ok_if_already_exists)
2335 Lisp_Object file, newname, ok_if_already_exists;
2337 Lisp_Object handler;
2338 Lisp_Object encoded_file, encoded_newname;
2339 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2341 GCPRO4 (file, newname, encoded_file, encoded_newname);
2342 encoded_file = encoded_newname = Qnil;
2343 CHECK_STRING (file);
2344 CHECK_STRING (newname);
2345 file = Fexpand_file_name (file, Qnil);
2347 if (!NILP (Ffile_directory_p (newname)))
2348 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2349 else
2350 newname = Fexpand_file_name (newname, Qnil);
2352 /* If the file name has special constructs in it,
2353 call the corresponding file handler. */
2354 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2355 if (!NILP (handler))
2356 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2357 newname, ok_if_already_exists));
2359 /* If the new name has special constructs in it,
2360 call the corresponding file handler. */
2361 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2362 if (!NILP (handler))
2363 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2364 newname, ok_if_already_exists));
2366 encoded_file = ENCODE_FILE (file);
2367 encoded_newname = ENCODE_FILE (newname);
2369 if (NILP (ok_if_already_exists)
2370 || INTEGERP (ok_if_already_exists))
2371 barf_or_query_if_file_exists (newname, "make it a new name",
2372 INTEGERP (ok_if_already_exists), 0, 0);
2374 unlink (SDATA (newname));
2375 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname)))
2376 report_file_error ("Adding new name", list2 (file, newname));
2378 UNGCPRO;
2379 return Qnil;
2382 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2383 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2384 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2385 Both args must be strings.
2386 Signals a `file-already-exists' error if a file LINKNAME already exists
2387 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2388 A number as third arg means request confirmation if LINKNAME already exists.
2389 This happens for interactive use with M-x. */)
2390 (filename, linkname, ok_if_already_exists)
2391 Lisp_Object filename, linkname, ok_if_already_exists;
2393 Lisp_Object handler;
2394 Lisp_Object encoded_filename, encoded_linkname;
2395 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2397 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2398 encoded_filename = encoded_linkname = Qnil;
2399 CHECK_STRING (filename);
2400 CHECK_STRING (linkname);
2401 /* If the link target has a ~, we must expand it to get
2402 a truly valid file name. Otherwise, do not expand;
2403 we want to permit links to relative file names. */
2404 if (SREF (filename, 0) == '~')
2405 filename = Fexpand_file_name (filename, Qnil);
2407 if (!NILP (Ffile_directory_p (linkname)))
2408 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2409 else
2410 linkname = Fexpand_file_name (linkname, Qnil);
2412 /* If the file name has special constructs in it,
2413 call the corresponding file handler. */
2414 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2415 if (!NILP (handler))
2416 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2417 linkname, ok_if_already_exists));
2419 /* If the new link name has special constructs in it,
2420 call the corresponding file handler. */
2421 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2422 if (!NILP (handler))
2423 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2424 linkname, ok_if_already_exists));
2426 #ifdef S_IFLNK
2427 encoded_filename = ENCODE_FILE (filename);
2428 encoded_linkname = ENCODE_FILE (linkname);
2430 if (NILP (ok_if_already_exists)
2431 || INTEGERP (ok_if_already_exists))
2432 barf_or_query_if_file_exists (linkname, "make it a link",
2433 INTEGERP (ok_if_already_exists), 0, 0);
2434 if (0 > symlink (SDATA (encoded_filename),
2435 SDATA (encoded_linkname)))
2437 /* If we didn't complain already, silently delete existing file. */
2438 if (errno == EEXIST)
2440 unlink (SDATA (encoded_linkname));
2441 if (0 <= symlink (SDATA (encoded_filename),
2442 SDATA (encoded_linkname)))
2444 UNGCPRO;
2445 return Qnil;
2449 report_file_error ("Making symbolic link", list2 (filename, linkname));
2451 UNGCPRO;
2452 return Qnil;
2454 #else
2455 UNGCPRO;
2456 xsignal1 (Qfile_error, build_string ("Symbolic links are not supported"));
2458 #endif /* S_IFLNK */
2462 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2463 1, 1, 0,
2464 doc: /* Return t if file FILENAME specifies an absolute file name.
2465 On Unix, this is a name starting with a `/' or a `~'. */)
2466 (filename)
2467 Lisp_Object filename;
2469 CHECK_STRING (filename);
2470 return file_name_absolute_p (SDATA (filename)) ? Qt : Qnil;
2473 /* Return nonzero if file FILENAME exists and can be executed. */
2475 static int
2476 check_executable (filename)
2477 char *filename;
2479 #ifdef DOS_NT
2480 int len = strlen (filename);
2481 char *suffix;
2482 struct stat st;
2483 if (stat (filename, &st) < 0)
2484 return 0;
2485 #if defined (WINDOWSNT) || (defined (MSDOS) && __DJGPP__ > 1)
2486 return ((st.st_mode & S_IEXEC) != 0);
2487 #else
2488 return (S_ISREG (st.st_mode)
2489 && len >= 5
2490 && (xstrcasecmp ((suffix = filename + len-4), ".com") == 0
2491 || xstrcasecmp (suffix, ".exe") == 0
2492 || xstrcasecmp (suffix, ".bat") == 0)
2493 || (st.st_mode & S_IFMT) == S_IFDIR);
2494 #endif /* not WINDOWSNT */
2495 #else /* not DOS_NT */
2496 #ifdef HAVE_EUIDACCESS
2497 return (euidaccess (filename, 1) >= 0);
2498 #else
2499 /* Access isn't quite right because it uses the real uid
2500 and we really want to test with the effective uid.
2501 But Unix doesn't give us a right way to do it. */
2502 return (access (filename, 1) >= 0);
2503 #endif
2504 #endif /* not DOS_NT */
2507 /* Return nonzero if file FILENAME exists and can be written. */
2509 static int
2510 check_writable (filename)
2511 char *filename;
2513 #ifdef MSDOS
2514 struct stat st;
2515 if (stat (filename, &st) < 0)
2516 return 0;
2517 return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
2518 #else /* not MSDOS */
2519 #ifdef HAVE_EUIDACCESS
2520 return (euidaccess (filename, 2) >= 0);
2521 #else
2522 /* Access isn't quite right because it uses the real uid
2523 and we really want to test with the effective uid.
2524 But Unix doesn't give us a right way to do it.
2525 Opening with O_WRONLY could work for an ordinary file,
2526 but would lose for directories. */
2527 return (access (filename, 2) >= 0);
2528 #endif
2529 #endif /* not MSDOS */
2532 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2533 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2534 See also `file-readable-p' and `file-attributes'.
2535 This returns nil for a symlink to a nonexistent file.
2536 Use `file-symlink-p' to test for such links. */)
2537 (filename)
2538 Lisp_Object filename;
2540 Lisp_Object absname;
2541 Lisp_Object handler;
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_exists_p);
2550 if (!NILP (handler))
2551 return call2 (handler, Qfile_exists_p, absname);
2553 absname = ENCODE_FILE (absname);
2555 return (stat (SDATA (absname), &statbuf) >= 0) ? Qt : Qnil;
2558 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2559 doc: /* Return t if FILENAME can be executed by you.
2560 For a directory, this means you can access files in that directory. */)
2561 (filename)
2562 Lisp_Object filename;
2564 Lisp_Object absname;
2565 Lisp_Object handler;
2567 CHECK_STRING (filename);
2568 absname = Fexpand_file_name (filename, Qnil);
2570 /* If the file name has special constructs in it,
2571 call the corresponding file handler. */
2572 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2573 if (!NILP (handler))
2574 return call2 (handler, Qfile_executable_p, absname);
2576 absname = ENCODE_FILE (absname);
2578 return (check_executable (SDATA (absname)) ? Qt : Qnil);
2581 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2582 doc: /* Return t if file FILENAME exists and you can read it.
2583 See also `file-exists-p' and `file-attributes'. */)
2584 (filename)
2585 Lisp_Object filename;
2587 Lisp_Object absname;
2588 Lisp_Object handler;
2589 int desc;
2590 int flags;
2591 struct stat statbuf;
2593 CHECK_STRING (filename);
2594 absname = Fexpand_file_name (filename, Qnil);
2596 /* If the file name has special constructs in it,
2597 call the corresponding file handler. */
2598 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2599 if (!NILP (handler))
2600 return call2 (handler, Qfile_readable_p, absname);
2602 absname = ENCODE_FILE (absname);
2604 #if defined(DOS_NT) || defined(macintosh)
2605 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2606 directories. */
2607 if (access (SDATA (absname), 0) == 0)
2608 return Qt;
2609 return Qnil;
2610 #else /* not DOS_NT and not macintosh */
2611 flags = O_RDONLY;
2612 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
2613 /* Opening a fifo without O_NONBLOCK can wait.
2614 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2615 except in the case of a fifo, on a system which handles it. */
2616 desc = stat (SDATA (absname), &statbuf);
2617 if (desc < 0)
2618 return Qnil;
2619 if (S_ISFIFO (statbuf.st_mode))
2620 flags |= O_NONBLOCK;
2621 #endif
2622 desc = emacs_open (SDATA (absname), flags, 0);
2623 if (desc < 0)
2624 return Qnil;
2625 emacs_close (desc);
2626 return Qt;
2627 #endif /* not DOS_NT and not macintosh */
2630 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2631 on the RT/PC. */
2632 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2633 doc: /* Return t if file FILENAME can be written or created by you. */)
2634 (filename)
2635 Lisp_Object filename;
2637 Lisp_Object absname, dir, encoded;
2638 Lisp_Object handler;
2639 struct stat statbuf;
2641 CHECK_STRING (filename);
2642 absname = Fexpand_file_name (filename, Qnil);
2644 /* If the file name has special constructs in it,
2645 call the corresponding file handler. */
2646 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2647 if (!NILP (handler))
2648 return call2 (handler, Qfile_writable_p, absname);
2650 encoded = ENCODE_FILE (absname);
2651 if (stat (SDATA (encoded), &statbuf) >= 0)
2652 return (check_writable (SDATA (encoded))
2653 ? Qt : Qnil);
2655 dir = Ffile_name_directory (absname);
2656 #ifdef MSDOS
2657 if (!NILP (dir))
2658 dir = Fdirectory_file_name (dir);
2659 #endif /* MSDOS */
2661 dir = ENCODE_FILE (dir);
2662 #ifdef WINDOWSNT
2663 /* The read-only attribute of the parent directory doesn't affect
2664 whether a file or directory can be created within it. Some day we
2665 should check ACLs though, which do affect this. */
2666 if (stat (SDATA (dir), &statbuf) < 0)
2667 return Qnil;
2668 return (statbuf.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2669 #else
2670 return (check_writable (!NILP (dir) ? (char *) SDATA (dir) : "")
2671 ? Qt : Qnil);
2672 #endif
2675 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2676 doc: /* Access file FILENAME, and get an error if that does not work.
2677 The second argument STRING is used in the error message.
2678 If there is no error, returns nil. */)
2679 (filename, string)
2680 Lisp_Object filename, string;
2682 Lisp_Object handler, encoded_filename, absname;
2683 int fd;
2685 CHECK_STRING (filename);
2686 absname = Fexpand_file_name (filename, Qnil);
2688 CHECK_STRING (string);
2690 /* If the file name has special constructs in it,
2691 call the corresponding file handler. */
2692 handler = Ffind_file_name_handler (absname, Qaccess_file);
2693 if (!NILP (handler))
2694 return call3 (handler, Qaccess_file, absname, string);
2696 encoded_filename = ENCODE_FILE (absname);
2698 fd = emacs_open (SDATA (encoded_filename), O_RDONLY, 0);
2699 if (fd < 0)
2700 report_file_error (SDATA (string), Fcons (filename, Qnil));
2701 emacs_close (fd);
2703 return Qnil;
2706 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2707 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2708 The value is the link target, as a string.
2709 Otherwise it returns nil.
2711 This function returns t when given the name of a symlink that
2712 points to a nonexistent file. */)
2713 (filename)
2714 Lisp_Object filename;
2716 Lisp_Object handler;
2718 CHECK_STRING (filename);
2719 filename = Fexpand_file_name (filename, Qnil);
2721 /* If the file name has special constructs in it,
2722 call the corresponding file handler. */
2723 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2724 if (!NILP (handler))
2725 return call2 (handler, Qfile_symlink_p, filename);
2727 #ifdef S_IFLNK
2729 char *buf;
2730 int bufsize;
2731 int valsize;
2732 Lisp_Object val;
2734 filename = ENCODE_FILE (filename);
2736 bufsize = 50;
2737 buf = NULL;
2740 bufsize *= 2;
2741 buf = (char *) xrealloc (buf, bufsize);
2742 bzero (buf, bufsize);
2744 errno = 0;
2745 valsize = readlink (SDATA (filename), buf, bufsize);
2746 if (valsize == -1)
2748 #ifdef ERANGE
2749 /* HP-UX reports ERANGE if buffer is too small. */
2750 if (errno == ERANGE)
2751 valsize = bufsize;
2752 else
2753 #endif
2755 xfree (buf);
2756 return Qnil;
2760 while (valsize >= bufsize);
2762 val = make_string (buf, valsize);
2763 if (buf[0] == '/' && index (buf, ':'))
2764 val = concat2 (build_string ("/:"), val);
2765 xfree (buf);
2766 val = DECODE_FILE (val);
2767 return val;
2769 #else /* not S_IFLNK */
2770 return Qnil;
2771 #endif /* not S_IFLNK */
2774 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2775 doc: /* Return t if FILENAME names an existing directory.
2776 Symbolic links to directories count as directories.
2777 See `file-symlink-p' to distinguish symlinks. */)
2778 (filename)
2779 Lisp_Object filename;
2781 register Lisp_Object absname;
2782 struct stat st;
2783 Lisp_Object handler;
2785 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2787 /* If the file name has special constructs in it,
2788 call the corresponding file handler. */
2789 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2790 if (!NILP (handler))
2791 return call2 (handler, Qfile_directory_p, absname);
2793 absname = ENCODE_FILE (absname);
2795 if (stat (SDATA (absname), &st) < 0)
2796 return Qnil;
2797 return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2800 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
2801 doc: /* Return t if file FILENAME names a directory you can open.
2802 For the value to be t, FILENAME must specify the name of a directory as a file,
2803 and the directory must allow you to open files in it. In order to use a
2804 directory as a buffer's current directory, this predicate must return true.
2805 A directory name spec may be given instead; then the value is t
2806 if the directory so specified exists and really is a readable and
2807 searchable directory. */)
2808 (filename)
2809 Lisp_Object filename;
2811 Lisp_Object handler;
2812 int tem;
2813 struct gcpro gcpro1;
2815 /* If the file name has special constructs in it,
2816 call the corresponding file handler. */
2817 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
2818 if (!NILP (handler))
2819 return call2 (handler, Qfile_accessible_directory_p, filename);
2821 GCPRO1 (filename);
2822 tem = (NILP (Ffile_directory_p (filename))
2823 || NILP (Ffile_executable_p (filename)));
2824 UNGCPRO;
2825 return tem ? Qnil : Qt;
2828 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2829 doc: /* Return t if FILENAME names a regular file.
2830 This is the sort of file that holds an ordinary stream of data bytes.
2831 Symbolic links to regular files count as regular files.
2832 See `file-symlink-p' to distinguish symlinks. */)
2833 (filename)
2834 Lisp_Object filename;
2836 register Lisp_Object absname;
2837 struct stat st;
2838 Lisp_Object handler;
2840 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2842 /* If the file name has special constructs in it,
2843 call the corresponding file handler. */
2844 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2845 if (!NILP (handler))
2846 return call2 (handler, Qfile_regular_p, absname);
2848 absname = ENCODE_FILE (absname);
2850 #ifdef WINDOWSNT
2852 int result;
2853 Lisp_Object tem = Vw32_get_true_file_attributes;
2855 /* Tell stat to use expensive method to get accurate info. */
2856 Vw32_get_true_file_attributes = Qt;
2857 result = stat (SDATA (absname), &st);
2858 Vw32_get_true_file_attributes = tem;
2860 if (result < 0)
2861 return Qnil;
2862 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2864 #else
2865 if (stat (SDATA (absname), &st) < 0)
2866 return Qnil;
2867 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2868 #endif
2871 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
2872 doc: /* Return mode bits of file named FILENAME, as an integer.
2873 Return nil, if file does not exist or is not accessible. */)
2874 (filename)
2875 Lisp_Object filename;
2877 Lisp_Object absname;
2878 struct stat st;
2879 Lisp_Object handler;
2881 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2883 /* If the file name has special constructs in it,
2884 call the corresponding file handler. */
2885 handler = Ffind_file_name_handler (absname, Qfile_modes);
2886 if (!NILP (handler))
2887 return call2 (handler, Qfile_modes, absname);
2889 absname = ENCODE_FILE (absname);
2891 if (stat (SDATA (absname), &st) < 0)
2892 return Qnil;
2893 #if defined (MSDOS) && __DJGPP__ < 2
2894 if (check_executable (SDATA (absname)))
2895 st.st_mode |= S_IEXEC;
2896 #endif /* MSDOS && __DJGPP__ < 2 */
2898 return make_number (st.st_mode & 07777);
2901 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
2902 "(let ((file (read-file-name \"File: \"))) \
2903 (list file (read-file-modes nil file)))",
2904 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
2905 Only the 12 low bits of MODE are used.
2907 Interactively, mode bits are read by `read-file-modes', which accepts
2908 symbolic notation, like the `chmod' command from GNU Coreutils. */)
2909 (filename, mode)
2910 Lisp_Object filename, mode;
2912 Lisp_Object absname, encoded_absname;
2913 Lisp_Object handler;
2915 absname = Fexpand_file_name (filename, current_buffer->directory);
2916 CHECK_NUMBER (mode);
2918 /* If the file name has special constructs in it,
2919 call the corresponding file handler. */
2920 handler = Ffind_file_name_handler (absname, Qset_file_modes);
2921 if (!NILP (handler))
2922 return call3 (handler, Qset_file_modes, absname, mode);
2924 encoded_absname = ENCODE_FILE (absname);
2926 if (chmod (SDATA (encoded_absname), XINT (mode)) < 0)
2927 report_file_error ("Doing chmod", Fcons (absname, Qnil));
2929 return Qnil;
2932 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
2933 doc: /* Set the file permission bits for newly created files.
2934 The argument MODE should be an integer; only the low 9 bits are used.
2935 This setting is inherited by subprocesses. */)
2936 (mode)
2937 Lisp_Object mode;
2939 CHECK_NUMBER (mode);
2941 umask ((~ XINT (mode)) & 0777);
2943 return Qnil;
2946 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
2947 doc: /* Return the default file protection for created files.
2948 The value is an integer. */)
2951 int realmask;
2952 Lisp_Object value;
2954 realmask = umask (0);
2955 umask (realmask);
2957 XSETINT (value, (~ realmask) & 0777);
2958 return value;
2961 extern int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
2963 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
2964 doc: /* Set times of file FILENAME to TIME.
2965 Set both access and modification times.
2966 Return t on success, else nil.
2967 Use the current time if TIME is nil. TIME is in the format of
2968 `current-time'. */)
2969 (filename, time)
2970 Lisp_Object filename, time;
2972 Lisp_Object absname, encoded_absname;
2973 Lisp_Object handler;
2974 time_t sec;
2975 int usec;
2977 if (! lisp_time_argument (time, &sec, &usec))
2978 error ("Invalid time specification");
2980 absname = Fexpand_file_name (filename, current_buffer->directory);
2982 /* If the file name has special constructs in it,
2983 call the corresponding file handler. */
2984 handler = Ffind_file_name_handler (absname, Qset_file_times);
2985 if (!NILP (handler))
2986 return call3 (handler, Qset_file_times, absname, time);
2988 encoded_absname = ENCODE_FILE (absname);
2991 EMACS_TIME t;
2993 EMACS_SET_SECS (t, sec);
2994 EMACS_SET_USECS (t, usec);
2996 if (set_file_times (SDATA (encoded_absname), t, t))
2998 #ifdef DOS_NT
2999 struct stat st;
3001 /* Setting times on a directory always fails. */
3002 if (stat (SDATA (encoded_absname), &st) == 0
3003 && (st.st_mode & S_IFMT) == S_IFDIR)
3004 return Qnil;
3005 #endif
3006 report_file_error ("Setting file times", Fcons (absname, Qnil));
3007 return Qnil;
3011 return Qt;
3014 #ifdef HAVE_SYNC
3015 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3016 doc: /* Tell Unix to finish all pending disk updates. */)
3019 sync ();
3020 return Qnil;
3023 #endif /* HAVE_SYNC */
3025 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3026 doc: /* Return t if file FILE1 is newer than file FILE2.
3027 If FILE1 does not exist, the answer is nil;
3028 otherwise, if FILE2 does not exist, the answer is t. */)
3029 (file1, file2)
3030 Lisp_Object file1, file2;
3032 Lisp_Object absname1, absname2;
3033 struct stat st;
3034 int mtime1;
3035 Lisp_Object handler;
3036 struct gcpro gcpro1, gcpro2;
3038 CHECK_STRING (file1);
3039 CHECK_STRING (file2);
3041 absname1 = Qnil;
3042 GCPRO2 (absname1, file2);
3043 absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
3044 absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
3045 UNGCPRO;
3047 /* If the file name has special constructs in it,
3048 call the corresponding file handler. */
3049 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3050 if (NILP (handler))
3051 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3052 if (!NILP (handler))
3053 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3055 GCPRO2 (absname1, absname2);
3056 absname1 = ENCODE_FILE (absname1);
3057 absname2 = ENCODE_FILE (absname2);
3058 UNGCPRO;
3060 if (stat (SDATA (absname1), &st) < 0)
3061 return Qnil;
3063 mtime1 = st.st_mtime;
3065 if (stat (SDATA (absname2), &st) < 0)
3066 return Qt;
3068 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3071 #ifdef DOS_NT
3072 Lisp_Object Qfind_buffer_file_type;
3073 #endif /* DOS_NT */
3075 #ifndef READ_BUF_SIZE
3076 #define READ_BUF_SIZE (64 << 10)
3077 #endif
3079 /* This function is called after Lisp functions to decide a coding
3080 system are called, or when they cause an error. Before they are
3081 called, the current buffer is set unibyte and it contains only a
3082 newly inserted text (thus the buffer was empty before the
3083 insertion).
3085 The functions may set markers, overlays, text properties, or even
3086 alter the buffer contents, change the current buffer.
3088 Here, we reset all those changes by:
3089 o set back the current buffer.
3090 o move all markers and overlays to BEG.
3091 o remove all text properties.
3092 o set back the buffer multibyteness. */
3094 static Lisp_Object
3095 decide_coding_unwind (unwind_data)
3096 Lisp_Object unwind_data;
3098 Lisp_Object multibyte, undo_list, buffer;
3100 multibyte = XCAR (unwind_data);
3101 unwind_data = XCDR (unwind_data);
3102 undo_list = XCAR (unwind_data);
3103 buffer = XCDR (unwind_data);
3105 if (current_buffer != XBUFFER (buffer))
3106 set_buffer_internal (XBUFFER (buffer));
3107 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3108 adjust_overlays_for_delete (BEG, Z - BEG);
3109 BUF_INTERVALS (current_buffer) = 0;
3110 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3112 /* Now we are safe to change the buffer's multibyteness directly. */
3113 current_buffer->enable_multibyte_characters = multibyte;
3114 current_buffer->undo_list = undo_list;
3116 return Qnil;
3120 /* Used to pass values from insert-file-contents to read_non_regular. */
3122 static int non_regular_fd;
3123 static EMACS_INT non_regular_inserted;
3124 static EMACS_INT non_regular_nbytes;
3127 /* Read from a non-regular file.
3128 Read non_regular_trytry bytes max from non_regular_fd.
3129 Non_regular_inserted specifies where to put the read bytes.
3130 Value is the number of bytes read. */
3132 static Lisp_Object
3133 read_non_regular ()
3135 EMACS_INT nbytes;
3137 immediate_quit = 1;
3138 QUIT;
3139 nbytes = emacs_read (non_regular_fd,
3140 BEG_ADDR + PT_BYTE - BEG_BYTE + non_regular_inserted,
3141 non_regular_nbytes);
3142 immediate_quit = 0;
3143 return make_number (nbytes);
3147 /* Condition-case handler used when reading from non-regular files
3148 in insert-file-contents. */
3150 static Lisp_Object
3151 read_non_regular_quit ()
3153 return Qnil;
3157 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3158 1, 5, 0,
3159 doc: /* Insert contents of file FILENAME after point.
3160 Returns list of absolute file name and number of characters inserted.
3161 If second argument VISIT is non-nil, the buffer's visited filename and
3162 last save file modtime are set, and it is marked unmodified. If
3163 visiting and the file does not exist, visiting is completed before the
3164 error is signaled.
3166 The optional third and fourth arguments BEG and END specify what portion
3167 of the file to insert. These arguments count bytes in the file, not
3168 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3170 If optional fifth argument REPLACE is non-nil, replace the current
3171 buffer contents (in the accessible portion) with the file contents.
3172 This is better than simply deleting and inserting the whole thing
3173 because (1) it preserves some marker positions and (2) it puts less data
3174 in the undo list. When REPLACE is non-nil, the second return value is
3175 the number of characters that replace previous buffer contents.
3177 This function does code conversion according to the value of
3178 `coding-system-for-read' or `file-coding-system-alist', and sets the
3179 variable `last-coding-system-used' to the coding system actually used. */)
3180 (filename, visit, beg, end, replace)
3181 Lisp_Object filename, visit, beg, end, replace;
3183 struct stat st;
3184 register int fd;
3185 EMACS_INT inserted = 0;
3186 int nochange = 0;
3187 register EMACS_INT how_much;
3188 register EMACS_INT unprocessed;
3189 int count = SPECPDL_INDEX ();
3190 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3191 Lisp_Object handler, val, insval, orig_filename, old_undo;
3192 Lisp_Object p;
3193 EMACS_INT total = 0;
3194 int not_regular = 0;
3195 unsigned char read_buf[READ_BUF_SIZE];
3196 struct coding_system coding;
3197 unsigned char buffer[1 << 14];
3198 int replace_handled = 0;
3199 int set_coding_system = 0;
3200 Lisp_Object coding_system;
3201 int read_quit = 0;
3202 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3203 int we_locked_file = 0;
3204 int deferred_remove_unwind_protect = 0;
3206 if (current_buffer->base_buffer && ! NILP (visit))
3207 error ("Cannot do file visiting in an indirect buffer");
3209 if (!NILP (current_buffer->read_only))
3210 Fbarf_if_buffer_read_only ();
3212 val = Qnil;
3213 p = Qnil;
3214 orig_filename = Qnil;
3215 old_undo = Qnil;
3217 GCPRO5 (filename, val, p, orig_filename, old_undo);
3219 CHECK_STRING (filename);
3220 filename = Fexpand_file_name (filename, Qnil);
3222 /* The value Qnil means that the coding system is not yet
3223 decided. */
3224 coding_system = Qnil;
3226 /* If the file name has special constructs in it,
3227 call the corresponding file handler. */
3228 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3229 if (!NILP (handler))
3231 val = call6 (handler, Qinsert_file_contents, filename,
3232 visit, beg, end, replace);
3233 if (CONSP (val) && CONSP (XCDR (val)))
3234 inserted = XINT (XCAR (XCDR (val)));
3235 goto handled;
3238 orig_filename = filename;
3239 filename = ENCODE_FILE (filename);
3241 fd = -1;
3243 #ifdef WINDOWSNT
3245 Lisp_Object tem = Vw32_get_true_file_attributes;
3247 /* Tell stat to use expensive method to get accurate info. */
3248 Vw32_get_true_file_attributes = Qt;
3249 total = stat (SDATA (filename), &st);
3250 Vw32_get_true_file_attributes = tem;
3252 if (total < 0)
3253 #else
3254 if (stat (SDATA (filename), &st) < 0)
3255 #endif /* WINDOWSNT */
3257 if (fd >= 0) emacs_close (fd);
3258 badopen:
3259 if (NILP (visit))
3260 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3261 st.st_mtime = -1;
3262 how_much = 0;
3263 if (!NILP (Vcoding_system_for_read))
3264 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3265 goto notfound;
3268 #ifdef S_IFREG
3269 /* This code will need to be changed in order to work on named
3270 pipes, and it's probably just not worth it. So we should at
3271 least signal an error. */
3272 if (!S_ISREG (st.st_mode))
3274 not_regular = 1;
3276 if (! NILP (visit))
3277 goto notfound;
3279 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3280 xsignal2 (Qfile_error,
3281 build_string ("not a regular file"), orig_filename);
3283 #endif
3285 if (fd < 0)
3286 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0)
3287 goto badopen;
3289 /* Replacement should preserve point as it preserves markers. */
3290 if (!NILP (replace))
3291 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3293 record_unwind_protect (close_file_unwind, make_number (fd));
3295 /* Can happen on any platform that uses long as type of off_t, but allows
3296 file sizes to exceed 2Gb, so give a suitable message. */
3297 if (! not_regular && st.st_size < 0)
3298 error ("Maximum buffer size exceeded");
3300 /* Prevent redisplay optimizations. */
3301 current_buffer->clip_changed = 1;
3303 if (!NILP (visit))
3305 if (!NILP (beg) || !NILP (end))
3306 error ("Attempt to visit less than an entire file");
3307 if (BEG < Z && NILP (replace))
3308 error ("Cannot do file visiting in a non-empty buffer");
3311 if (!NILP (beg))
3312 CHECK_NUMBER (beg);
3313 else
3314 XSETFASTINT (beg, 0);
3316 if (!NILP (end))
3317 CHECK_NUMBER (end);
3318 else
3320 if (! not_regular)
3322 XSETINT (end, st.st_size);
3324 /* Arithmetic overflow can occur if an Emacs integer cannot
3325 represent the file size, or if the calculations below
3326 overflow. The calculations below double the file size
3327 twice, so check that it can be multiplied by 4 safely. */
3328 if (XINT (end) != st.st_size
3329 /* Actually, it should test either INT_MAX or LONG_MAX
3330 depending on which one is used for EMACS_INT. But in
3331 any case, in practice, this test is redundant with the
3332 one above.
3333 || st.st_size > INT_MAX / 4 */)
3334 error ("Maximum buffer size exceeded");
3336 /* The file size returned from stat may be zero, but data
3337 may be readable nonetheless, for example when this is a
3338 file in the /proc filesystem. */
3339 if (st.st_size == 0)
3340 XSETINT (end, READ_BUF_SIZE);
3344 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3346 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3347 setup_coding_system (coding_system, &coding);
3348 /* Ensure we set Vlast_coding_system_used. */
3349 set_coding_system = 1;
3351 else if (BEG < Z)
3353 /* Decide the coding system to use for reading the file now
3354 because we can't use an optimized method for handling
3355 `coding:' tag if the current buffer is not empty. */
3356 if (!NILP (Vcoding_system_for_read))
3357 coding_system = Vcoding_system_for_read;
3358 else
3360 /* Don't try looking inside a file for a coding system
3361 specification if it is not seekable. */
3362 if (! not_regular && ! NILP (Vset_auto_coding_function))
3364 /* Find a coding system specified in the heading two
3365 lines or in the tailing several lines of the file.
3366 We assume that the 1K-byte and 3K-byte for heading
3367 and tailing respectively are sufficient for this
3368 purpose. */
3369 EMACS_INT nread;
3371 if (st.st_size <= (1024 * 4))
3372 nread = emacs_read (fd, read_buf, 1024 * 4);
3373 else
3375 nread = emacs_read (fd, read_buf, 1024);
3376 if (nread >= 0)
3378 if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
3379 report_file_error ("Setting file position",
3380 Fcons (orig_filename, Qnil));
3381 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3385 if (nread < 0)
3386 error ("IO error reading %s: %s",
3387 SDATA (orig_filename), emacs_strerror (errno));
3388 else if (nread > 0)
3390 struct buffer *prev = current_buffer;
3391 Lisp_Object buffer;
3392 struct buffer *buf;
3394 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3396 buffer = Fget_buffer_create (build_string (" *code-converting-work*"));
3397 buf = XBUFFER (buffer);
3399 delete_all_overlays (buf);
3400 buf->directory = current_buffer->directory;
3401 buf->read_only = Qnil;
3402 buf->filename = Qnil;
3403 buf->undo_list = Qt;
3404 eassert (buf->overlays_before == NULL);
3405 eassert (buf->overlays_after == NULL);
3407 set_buffer_internal (buf);
3408 Ferase_buffer ();
3409 buf->enable_multibyte_characters = Qnil;
3411 insert_1_both (read_buf, nread, nread, 0, 0, 0);
3412 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3413 coding_system = call2 (Vset_auto_coding_function,
3414 filename, make_number (nread));
3415 set_buffer_internal (prev);
3417 /* Discard the unwind protect for recovering the
3418 current buffer. */
3419 specpdl_ptr--;
3421 /* Rewind the file for the actual read done later. */
3422 if (lseek (fd, 0, 0) < 0)
3423 report_file_error ("Setting file position",
3424 Fcons (orig_filename, Qnil));
3428 if (NILP (coding_system))
3430 /* If we have not yet decided a coding system, check
3431 file-coding-system-alist. */
3432 Lisp_Object args[6];
3434 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3435 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3436 coding_system = Ffind_operation_coding_system (6, args);
3437 if (CONSP (coding_system))
3438 coding_system = XCAR (coding_system);
3442 if (NILP (coding_system))
3443 coding_system = Qundecided;
3444 else
3445 CHECK_CODING_SYSTEM (coding_system);
3447 if (NILP (current_buffer->enable_multibyte_characters))
3448 /* We must suppress all character code conversion except for
3449 end-of-line conversion. */
3450 coding_system = raw_text_coding_system (coding_system);
3452 setup_coding_system (coding_system, &coding);
3453 /* Ensure we set Vlast_coding_system_used. */
3454 set_coding_system = 1;
3457 /* If requested, replace the accessible part of the buffer
3458 with the file contents. Avoid replacing text at the
3459 beginning or end of the buffer that matches the file contents;
3460 that preserves markers pointing to the unchanged parts.
3462 Here we implement this feature in an optimized way
3463 for the case where code conversion is NOT needed.
3464 The following if-statement handles the case of conversion
3465 in a less optimal way.
3467 If the code conversion is "automatic" then we try using this
3468 method and hope for the best.
3469 But if we discover the need for conversion, we give up on this method
3470 and let the following if-statement handle the replace job. */
3471 if (!NILP (replace)
3472 && BEGV < ZV
3473 && (NILP (coding_system)
3474 || ! CODING_REQUIRE_DECODING (&coding)))
3476 /* same_at_start and same_at_end count bytes,
3477 because file access counts bytes
3478 and BEG and END count bytes. */
3479 EMACS_INT same_at_start = BEGV_BYTE;
3480 EMACS_INT same_at_end = ZV_BYTE;
3481 EMACS_INT overlap;
3482 /* There is still a possibility we will find the need to do code
3483 conversion. If that happens, we set this variable to 1 to
3484 give up on handling REPLACE in the optimized way. */
3485 int giveup_match_end = 0;
3487 if (XINT (beg) != 0)
3489 if (lseek (fd, XINT (beg), 0) < 0)
3490 report_file_error ("Setting file position",
3491 Fcons (orig_filename, Qnil));
3494 immediate_quit = 1;
3495 QUIT;
3496 /* Count how many chars at the start of the file
3497 match the text at the beginning of the buffer. */
3498 while (1)
3500 EMACS_INT nread, bufpos;
3502 nread = emacs_read (fd, buffer, sizeof buffer);
3503 if (nread < 0)
3504 error ("IO error reading %s: %s",
3505 SDATA (orig_filename), emacs_strerror (errno));
3506 else if (nread == 0)
3507 break;
3509 if (CODING_REQUIRE_DETECTION (&coding))
3511 coding_system = detect_coding_system (buffer, nread, nread, 1, 0,
3512 coding_system);
3513 setup_coding_system (coding_system, &coding);
3516 if (CODING_REQUIRE_DECODING (&coding))
3517 /* We found that the file should be decoded somehow.
3518 Let's give up here. */
3520 giveup_match_end = 1;
3521 break;
3524 bufpos = 0;
3525 while (bufpos < nread && same_at_start < ZV_BYTE
3526 && FETCH_BYTE (same_at_start) == buffer[bufpos])
3527 same_at_start++, bufpos++;
3528 /* If we found a discrepancy, stop the scan.
3529 Otherwise loop around and scan the next bufferful. */
3530 if (bufpos != nread)
3531 break;
3533 immediate_quit = 0;
3534 /* If the file matches the buffer completely,
3535 there's no need to replace anything. */
3536 if (same_at_start - BEGV_BYTE == XINT (end))
3538 emacs_close (fd);
3539 specpdl_ptr--;
3540 /* Truncate the buffer to the size of the file. */
3541 del_range_1 (same_at_start, same_at_end, 0, 0);
3542 goto handled;
3544 immediate_quit = 1;
3545 QUIT;
3546 /* Count how many chars at the end of the file
3547 match the text at the end of the buffer. But, if we have
3548 already found that decoding is necessary, don't waste time. */
3549 while (!giveup_match_end)
3551 EMACS_INT total_read, nread, bufpos, curpos, trial;
3553 /* At what file position are we now scanning? */
3554 curpos = XINT (end) - (ZV_BYTE - same_at_end);
3555 /* If the entire file matches the buffer tail, stop the scan. */
3556 if (curpos == 0)
3557 break;
3558 /* How much can we scan in the next step? */
3559 trial = min (curpos, sizeof buffer);
3560 if (lseek (fd, curpos - trial, 0) < 0)
3561 report_file_error ("Setting file position",
3562 Fcons (orig_filename, Qnil));
3564 total_read = nread = 0;
3565 while (total_read < trial)
3567 nread = emacs_read (fd, buffer + total_read, trial - total_read);
3568 if (nread < 0)
3569 error ("IO error reading %s: %s",
3570 SDATA (orig_filename), emacs_strerror (errno));
3571 else if (nread == 0)
3572 break;
3573 total_read += nread;
3576 /* Scan this bufferful from the end, comparing with
3577 the Emacs buffer. */
3578 bufpos = total_read;
3580 /* Compare with same_at_start to avoid counting some buffer text
3581 as matching both at the file's beginning and at the end. */
3582 while (bufpos > 0 && same_at_end > same_at_start
3583 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
3584 same_at_end--, bufpos--;
3586 /* If we found a discrepancy, stop the scan.
3587 Otherwise loop around and scan the preceding bufferful. */
3588 if (bufpos != 0)
3590 /* If this discrepancy is because of code conversion,
3591 we cannot use this method; giveup and try the other. */
3592 if (same_at_end > same_at_start
3593 && FETCH_BYTE (same_at_end - 1) >= 0200
3594 && ! NILP (current_buffer->enable_multibyte_characters)
3595 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3596 giveup_match_end = 1;
3597 break;
3600 if (nread == 0)
3601 break;
3603 immediate_quit = 0;
3605 if (! giveup_match_end)
3607 EMACS_INT temp;
3609 /* We win! We can handle REPLACE the optimized way. */
3611 /* Extend the start of non-matching text area to multibyte
3612 character boundary. */
3613 if (! NILP (current_buffer->enable_multibyte_characters))
3614 while (same_at_start > BEGV_BYTE
3615 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3616 same_at_start--;
3618 /* Extend the end of non-matching text area to multibyte
3619 character boundary. */
3620 if (! NILP (current_buffer->enable_multibyte_characters))
3621 while (same_at_end < ZV_BYTE
3622 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3623 same_at_end++;
3625 /* Don't try to reuse the same piece of text twice. */
3626 overlap = (same_at_start - BEGV_BYTE
3627 - (same_at_end + st.st_size - ZV));
3628 if (overlap > 0)
3629 same_at_end += overlap;
3631 /* Arrange to read only the nonmatching middle part of the file. */
3632 XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV_BYTE));
3633 XSETFASTINT (end, XINT (end) - (ZV_BYTE - same_at_end));
3635 del_range_byte (same_at_start, same_at_end, 0);
3636 /* Insert from the file at the proper position. */
3637 temp = BYTE_TO_CHAR (same_at_start);
3638 SET_PT_BOTH (temp, same_at_start);
3640 /* If display currently starts at beginning of line,
3641 keep it that way. */
3642 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3643 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3645 replace_handled = 1;
3649 /* If requested, replace the accessible part of the buffer
3650 with the file contents. Avoid replacing text at the
3651 beginning or end of the buffer that matches the file contents;
3652 that preserves markers pointing to the unchanged parts.
3654 Here we implement this feature for the case where code conversion
3655 is needed, in a simple way that needs a lot of memory.
3656 The preceding if-statement handles the case of no conversion
3657 in a more optimized way. */
3658 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3660 EMACS_INT same_at_start = BEGV_BYTE;
3661 EMACS_INT same_at_end = ZV_BYTE;
3662 EMACS_INT same_at_start_charpos;
3663 EMACS_INT inserted_chars;
3664 EMACS_INT overlap;
3665 EMACS_INT bufpos;
3666 unsigned char *decoded;
3667 EMACS_INT temp;
3668 int this_count = SPECPDL_INDEX ();
3669 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
3670 Lisp_Object conversion_buffer;
3672 conversion_buffer = code_conversion_save (1, multibyte);
3674 /* First read the whole file, performing code conversion into
3675 CONVERSION_BUFFER. */
3677 if (lseek (fd, XINT (beg), 0) < 0)
3678 report_file_error ("Setting file position",
3679 Fcons (orig_filename, Qnil));
3681 total = st.st_size; /* Total bytes in the file. */
3682 how_much = 0; /* Bytes read from file so far. */
3683 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3684 unprocessed = 0; /* Bytes not processed in previous loop. */
3686 GCPRO1 (conversion_buffer);
3687 while (how_much < total)
3689 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
3690 quitting while reading a huge while. */
3691 /* try is reserved in some compilers (Microsoft C) */
3692 EMACS_INT trytry = min (total - how_much,
3693 READ_BUF_SIZE - unprocessed);
3694 EMACS_INT this;
3696 /* Allow quitting out of the actual I/O. */
3697 immediate_quit = 1;
3698 QUIT;
3699 this = emacs_read (fd, read_buf + unprocessed, trytry);
3700 immediate_quit = 0;
3702 if (this <= 0)
3704 if (this < 0)
3705 how_much = this;
3706 break;
3709 how_much += this;
3711 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3712 BUF_Z (XBUFFER (conversion_buffer)));
3713 decode_coding_c_string (&coding, read_buf, unprocessed + this,
3714 conversion_buffer);
3715 unprocessed = coding.carryover_bytes;
3716 if (coding.carryover_bytes > 0)
3717 bcopy (coding.carryover, read_buf, unprocessed);
3719 UNGCPRO;
3720 emacs_close (fd);
3722 /* We should remove the unwind_protect calling
3723 close_file_unwind, but other stuff has been added the stack,
3724 so defer the removal till we reach the `handled' label. */
3725 deferred_remove_unwind_protect = 1;
3727 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
3728 if we couldn't read the file. */
3730 if (how_much < 0)
3731 error ("IO error reading %s: %s",
3732 SDATA (orig_filename), emacs_strerror (errno));
3734 if (unprocessed > 0)
3736 coding.mode |= CODING_MODE_LAST_BLOCK;
3737 decode_coding_c_string (&coding, read_buf, unprocessed,
3738 conversion_buffer);
3739 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3742 coding_system = CODING_ID_NAME (coding.id);
3743 set_coding_system = 1;
3744 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3745 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3746 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3748 /* Compare the beginning of the converted string with the buffer
3749 text. */
3751 bufpos = 0;
3752 while (bufpos < inserted && same_at_start < same_at_end
3753 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3754 same_at_start++, bufpos++;
3756 /* If the file matches the head of buffer completely,
3757 there's no need to replace anything. */
3759 if (bufpos == inserted)
3761 /* Truncate the buffer to the size of the file. */
3762 if (same_at_start == same_at_end)
3763 nochange = 1;
3764 else
3765 del_range_byte (same_at_start, same_at_end, 0);
3766 inserted = 0;
3768 unbind_to (this_count, Qnil);
3769 goto handled;
3772 /* Extend the start of non-matching text area to the previous
3773 multibyte character boundary. */
3774 if (! NILP (current_buffer->enable_multibyte_characters))
3775 while (same_at_start > BEGV_BYTE
3776 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3777 same_at_start--;
3779 /* Scan this bufferful from the end, comparing with
3780 the Emacs buffer. */
3781 bufpos = inserted;
3783 /* Compare with same_at_start to avoid counting some buffer text
3784 as matching both at the file's beginning and at the end. */
3785 while (bufpos > 0 && same_at_end > same_at_start
3786 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3787 same_at_end--, bufpos--;
3789 /* Extend the end of non-matching text area to the next
3790 multibyte character boundary. */
3791 if (! NILP (current_buffer->enable_multibyte_characters))
3792 while (same_at_end < ZV_BYTE
3793 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3794 same_at_end++;
3796 /* Don't try to reuse the same piece of text twice. */
3797 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3798 if (overlap > 0)
3799 same_at_end += overlap;
3801 /* If display currently starts at beginning of line,
3802 keep it that way. */
3803 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3804 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3806 /* Replace the chars that we need to replace,
3807 and update INSERTED to equal the number of bytes
3808 we are taking from the decoded string. */
3809 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3811 if (same_at_end != same_at_start)
3813 del_range_byte (same_at_start, same_at_end, 0);
3814 temp = GPT;
3815 same_at_start = GPT_BYTE;
3817 else
3819 temp = BYTE_TO_CHAR (same_at_start);
3821 /* Insert from the file at the proper position. */
3822 SET_PT_BOTH (temp, same_at_start);
3823 same_at_start_charpos
3824 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3825 same_at_start - BEGV_BYTE
3826 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3827 inserted_chars
3828 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3829 same_at_start + inserted - BEGV_BYTE
3830 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
3831 - same_at_start_charpos);
3832 /* This binding is to avoid ask-user-about-supersession-threat
3833 being called in insert_from_buffer (via in
3834 prepare_to_modify_buffer). */
3835 specbind (intern ("buffer-file-name"), Qnil);
3836 insert_from_buffer (XBUFFER (conversion_buffer),
3837 same_at_start_charpos, inserted_chars, 0);
3838 /* Set `inserted' to the number of inserted characters. */
3839 inserted = PT - temp;
3840 /* Set point before the inserted characters. */
3841 SET_PT_BOTH (temp, same_at_start);
3843 unbind_to (this_count, Qnil);
3845 goto handled;
3848 if (! not_regular)
3850 register Lisp_Object temp;
3852 total = XINT (end) - XINT (beg);
3854 /* Make sure point-max won't overflow after this insertion. */
3855 XSETINT (temp, total);
3856 if (total != XINT (temp))
3857 error ("Maximum buffer size exceeded");
3859 else
3860 /* For a special file, all we can do is guess. */
3861 total = READ_BUF_SIZE;
3863 if (NILP (visit) && inserted > 0)
3865 #ifdef CLASH_DETECTION
3866 if (!NILP (current_buffer->file_truename)
3867 /* Make binding buffer-file-name to nil effective. */
3868 && !NILP (current_buffer->filename)
3869 && SAVE_MODIFF >= MODIFF)
3870 we_locked_file = 1;
3871 #endif /* CLASH_DETECTION */
3872 prepare_to_modify_buffer (GPT, GPT, NULL);
3875 move_gap (PT);
3876 if (GAP_SIZE < total)
3877 make_gap (total - GAP_SIZE);
3879 if (XINT (beg) != 0 || !NILP (replace))
3881 if (lseek (fd, XINT (beg), 0) < 0)
3882 report_file_error ("Setting file position",
3883 Fcons (orig_filename, Qnil));
3886 /* In the following loop, HOW_MUCH contains the total bytes read so
3887 far for a regular file, and not changed for a special file. But,
3888 before exiting the loop, it is set to a negative value if I/O
3889 error occurs. */
3890 how_much = 0;
3892 /* Total bytes inserted. */
3893 inserted = 0;
3895 /* Here, we don't do code conversion in the loop. It is done by
3896 decode_coding_gap after all data are read into the buffer. */
3898 EMACS_INT gap_size = GAP_SIZE;
3900 while (how_much < total)
3902 /* try is reserved in some compilers (Microsoft C) */
3903 EMACS_INT trytry = min (total - how_much, READ_BUF_SIZE);
3904 EMACS_INT this;
3906 if (not_regular)
3908 Lisp_Object val;
3910 /* Maybe make more room. */
3911 if (gap_size < trytry)
3913 make_gap (total - gap_size);
3914 gap_size = GAP_SIZE;
3917 /* Read from the file, capturing `quit'. When an
3918 error occurs, end the loop, and arrange for a quit
3919 to be signaled after decoding the text we read. */
3920 non_regular_fd = fd;
3921 non_regular_inserted = inserted;
3922 non_regular_nbytes = trytry;
3923 val = internal_condition_case_1 (read_non_regular, Qnil, Qerror,
3924 read_non_regular_quit);
3925 if (NILP (val))
3927 read_quit = 1;
3928 break;
3931 this = XINT (val);
3933 else
3935 /* Allow quitting out of the actual I/O. We don't make text
3936 part of the buffer until all the reading is done, so a C-g
3937 here doesn't do any harm. */
3938 immediate_quit = 1;
3939 QUIT;
3940 this = emacs_read (fd, BEG_ADDR + PT_BYTE - BEG_BYTE + inserted, trytry);
3941 immediate_quit = 0;
3944 if (this <= 0)
3946 how_much = this;
3947 break;
3950 gap_size -= this;
3952 /* For a regular file, where TOTAL is the real size,
3953 count HOW_MUCH to compare with it.
3954 For a special file, where TOTAL is just a buffer size,
3955 so don't bother counting in HOW_MUCH.
3956 (INSERTED is where we count the number of characters inserted.) */
3957 if (! not_regular)
3958 how_much += this;
3959 inserted += this;
3963 /* Now we have read all the file data into the gap.
3964 If it was empty, undo marking the buffer modified. */
3966 if (inserted == 0)
3968 #ifdef CLASH_DETECTION
3969 if (we_locked_file)
3970 unlock_file (current_buffer->file_truename);
3971 #endif
3972 Vdeactivate_mark = old_Vdeactivate_mark;
3974 else
3975 Vdeactivate_mark = Qt;
3977 /* Make the text read part of the buffer. */
3978 GAP_SIZE -= inserted;
3979 GPT += inserted;
3980 GPT_BYTE += inserted;
3981 ZV += inserted;
3982 ZV_BYTE += inserted;
3983 Z += inserted;
3984 Z_BYTE += inserted;
3986 if (GAP_SIZE > 0)
3987 /* Put an anchor to ensure multi-byte form ends at gap. */
3988 *GPT_ADDR = 0;
3990 emacs_close (fd);
3992 /* Discard the unwind protect for closing the file. */
3993 specpdl_ptr--;
3995 if (how_much < 0)
3996 error ("IO error reading %s: %s",
3997 SDATA (orig_filename), emacs_strerror (errno));
3999 notfound:
4001 if (NILP (coding_system))
4003 /* The coding system is not yet decided. Decide it by an
4004 optimized method for handling `coding:' tag.
4006 Note that we can get here only if the buffer was empty
4007 before the insertion. */
4009 if (!NILP (Vcoding_system_for_read))
4010 coding_system = Vcoding_system_for_read;
4011 else
4013 /* Since we are sure that the current buffer was empty
4014 before the insertion, we can toggle
4015 enable-multibyte-characters directly here without taking
4016 care of marker adjustment. By this way, we can run Lisp
4017 program safely before decoding the inserted text. */
4018 Lisp_Object unwind_data;
4019 int count = SPECPDL_INDEX ();
4021 unwind_data = Fcons (current_buffer->enable_multibyte_characters,
4022 Fcons (current_buffer->undo_list,
4023 Fcurrent_buffer ()));
4024 current_buffer->enable_multibyte_characters = Qnil;
4025 current_buffer->undo_list = Qt;
4026 record_unwind_protect (decide_coding_unwind, unwind_data);
4028 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4030 coding_system = call2 (Vset_auto_coding_function,
4031 filename, make_number (inserted));
4034 if (NILP (coding_system))
4036 /* If the coding system is not yet decided, check
4037 file-coding-system-alist. */
4038 Lisp_Object args[6];
4040 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4041 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4042 coding_system = Ffind_operation_coding_system (6, args);
4043 if (CONSP (coding_system))
4044 coding_system = XCAR (coding_system);
4046 unbind_to (count, Qnil);
4047 inserted = Z_BYTE - BEG_BYTE;
4050 if (NILP (coding_system))
4051 coding_system = Qundecided;
4052 else
4053 CHECK_CODING_SYSTEM (coding_system);
4055 if (NILP (current_buffer->enable_multibyte_characters))
4056 /* We must suppress all character code conversion except for
4057 end-of-line conversion. */
4058 coding_system = raw_text_coding_system (coding_system);
4059 setup_coding_system (coding_system, &coding);
4060 /* Ensure we set Vlast_coding_system_used. */
4061 set_coding_system = 1;
4064 if (!NILP (visit))
4066 /* When we visit a file by raw-text, we change the buffer to
4067 unibyte. */
4068 if (CODING_FOR_UNIBYTE (&coding)
4069 /* Can't do this if part of the buffer might be preserved. */
4070 && NILP (replace))
4071 /* Visiting a file with these coding system makes the buffer
4072 unibyte. */
4073 current_buffer->enable_multibyte_characters = Qnil;
4076 coding.dst_multibyte = ! NILP (current_buffer->enable_multibyte_characters);
4077 if (CODING_MAY_REQUIRE_DECODING (&coding)
4078 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4080 move_gap_both (PT, PT_BYTE);
4081 GAP_SIZE += inserted;
4082 ZV_BYTE -= inserted;
4083 Z_BYTE -= inserted;
4084 ZV -= inserted;
4085 Z -= inserted;
4086 decode_coding_gap (&coding, inserted, inserted);
4087 inserted = coding.produced_char;
4088 coding_system = CODING_ID_NAME (coding.id);
4090 else if (inserted > 0)
4091 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4092 inserted);
4094 /* Now INSERTED is measured in characters. */
4096 #ifdef DOS_NT
4097 /* Use the conversion type to determine buffer-file-type
4098 (find-buffer-file-type is now used to help determine the
4099 conversion). */
4100 if ((VECTORP (CODING_ID_EOL_TYPE (coding.id))
4101 || EQ (CODING_ID_EOL_TYPE (coding.id), Qunix))
4102 && ! CODING_REQUIRE_DECODING (&coding))
4103 current_buffer->buffer_file_type = Qt;
4104 else
4105 current_buffer->buffer_file_type = Qnil;
4106 #endif
4108 handled:
4110 if (deferred_remove_unwind_protect)
4111 /* If requested above, discard the unwind protect for closing the
4112 file. */
4113 specpdl_ptr--;
4115 if (!NILP (visit))
4117 if (!EQ (current_buffer->undo_list, Qt) && !nochange)
4118 current_buffer->undo_list = Qnil;
4120 if (NILP (handler))
4122 current_buffer->modtime = st.st_mtime;
4123 current_buffer->filename = orig_filename;
4126 SAVE_MODIFF = MODIFF;
4127 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4128 XSETFASTINT (current_buffer->save_length, Z - BEG);
4129 #ifdef CLASH_DETECTION
4130 if (NILP (handler))
4132 if (!NILP (current_buffer->file_truename))
4133 unlock_file (current_buffer->file_truename);
4134 unlock_file (filename);
4136 #endif /* CLASH_DETECTION */
4137 if (not_regular)
4138 xsignal2 (Qfile_error,
4139 build_string ("not a regular file"), orig_filename);
4142 if (set_coding_system)
4143 Vlast_coding_system_used = coding_system;
4145 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4147 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4148 visit);
4149 if (! NILP (insval))
4151 CHECK_NUMBER (insval);
4152 inserted = XFASTINT (insval);
4156 /* Decode file format. */
4157 if (inserted > 0)
4159 /* Don't run point motion or modification hooks when decoding. */
4160 int count = SPECPDL_INDEX ();
4161 EMACS_INT old_inserted = inserted;
4162 specbind (Qinhibit_point_motion_hooks, Qt);
4163 specbind (Qinhibit_modification_hooks, Qt);
4165 /* Save old undo list and don't record undo for decoding. */
4166 old_undo = current_buffer->undo_list;
4167 current_buffer->undo_list = Qt;
4169 if (NILP (replace))
4171 insval = call3 (Qformat_decode,
4172 Qnil, make_number (inserted), visit);
4173 CHECK_NUMBER (insval);
4174 inserted = XFASTINT (insval);
4176 else
4178 /* If REPLACE is non-nil and we succeeded in not replacing the
4179 beginning or end of the buffer text with the file's contents,
4180 call format-decode with `point' positioned at the beginning
4181 of the buffer and `inserted' equalling the number of
4182 characters in the buffer. Otherwise, format-decode might
4183 fail to correctly analyze the beginning or end of the buffer.
4184 Hence we temporarily save `point' and `inserted' here and
4185 restore `point' iff format-decode did not insert or delete
4186 any text. Otherwise we leave `point' at point-min. */
4187 EMACS_INT opoint = PT;
4188 EMACS_INT opoint_byte = PT_BYTE;
4189 EMACS_INT oinserted = ZV - BEGV;
4190 int ochars_modiff = CHARS_MODIFF;
4192 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4193 insval = call3 (Qformat_decode,
4194 Qnil, make_number (oinserted), visit);
4195 CHECK_NUMBER (insval);
4196 if (ochars_modiff == CHARS_MODIFF)
4197 /* format_decode didn't modify buffer's characters => move
4198 point back to position before inserted text and leave
4199 value of inserted alone. */
4200 SET_PT_BOTH (opoint, opoint_byte);
4201 else
4202 /* format_decode modified buffer's characters => consider
4203 entire buffer changed and leave point at point-min. */
4204 inserted = XFASTINT (insval);
4207 /* For consistency with format-decode call these now iff inserted > 0
4208 (martin 2007-06-28). */
4209 p = Vafter_insert_file_functions;
4210 while (CONSP (p))
4212 if (NILP (replace))
4214 insval = call1 (XCAR (p), make_number (inserted));
4215 if (!NILP (insval))
4217 CHECK_NUMBER (insval);
4218 inserted = XFASTINT (insval);
4221 else
4223 /* For the rationale of this see the comment on
4224 format-decode above. */
4225 EMACS_INT opoint = PT;
4226 EMACS_INT opoint_byte = PT_BYTE;
4227 EMACS_INT oinserted = ZV - BEGV;
4228 int ochars_modiff = CHARS_MODIFF;
4230 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4231 insval = call1 (XCAR (p), make_number (oinserted));
4232 if (!NILP (insval))
4234 CHECK_NUMBER (insval);
4235 if (ochars_modiff == CHARS_MODIFF)
4236 /* after_insert_file_functions didn't modify
4237 buffer's characters => move point back to
4238 position before inserted text and leave value of
4239 inserted alone. */
4240 SET_PT_BOTH (opoint, opoint_byte);
4241 else
4242 /* after_insert_file_functions did modify buffer's
4243 characters => consider entire buffer changed and
4244 leave point at point-min. */
4245 inserted = XFASTINT (insval);
4249 QUIT;
4250 p = XCDR (p);
4253 if (NILP (visit))
4255 current_buffer->undo_list = old_undo;
4256 if (CONSP (old_undo) && inserted != old_inserted)
4258 /* Adjust the last undo record for the size change during
4259 the format conversion. */
4260 Lisp_Object tem = XCAR (old_undo);
4261 if (CONSP (tem) && INTEGERP (XCAR (tem))
4262 && INTEGERP (XCDR (tem))
4263 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4264 XSETCDR (tem, make_number (PT + inserted));
4267 else
4268 /* If undo_list was Qt before, keep it that way.
4269 Otherwise start with an empty undo_list. */
4270 current_buffer->undo_list = EQ (old_undo, Qt) ? Qt : Qnil;
4272 unbind_to (count, Qnil);
4275 /* Call after-change hooks for the inserted text, aside from the case
4276 of normal visiting (not with REPLACE), which is done in a new buffer
4277 "before" the buffer is changed. */
4278 if (inserted > 0 && total > 0
4279 && (NILP (visit) || !NILP (replace)))
4281 signal_after_change (PT, 0, inserted);
4282 update_compositions (PT, PT, CHECK_BORDER);
4285 if (!NILP (visit)
4286 && current_buffer->modtime == -1)
4288 /* If visiting nonexistent file, return nil. */
4289 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4292 if (read_quit)
4293 Fsignal (Qquit, Qnil);
4295 /* ??? Retval needs to be dealt with in all cases consistently. */
4296 if (NILP (val))
4297 val = Fcons (orig_filename,
4298 Fcons (make_number (inserted),
4299 Qnil));
4301 RETURN_UNGCPRO (unbind_to (count, val));
4304 static Lisp_Object build_annotations P_ ((Lisp_Object, Lisp_Object));
4306 static Lisp_Object
4307 build_annotations_unwind (arg)
4308 Lisp_Object arg;
4310 Vwrite_region_annotation_buffers = arg;
4311 return Qnil;
4314 /* Decide the coding-system to encode the data with. */
4316 static Lisp_Object
4317 choose_write_coding_system (start, end, filename,
4318 append, visit, lockname, coding)
4319 Lisp_Object start, end, filename, append, visit, lockname;
4320 struct coding_system *coding;
4322 Lisp_Object val;
4323 Lisp_Object eol_parent = Qnil;
4325 if (auto_saving
4326 && NILP (Fstring_equal (current_buffer->filename,
4327 current_buffer->auto_save_file_name)))
4329 val = Qutf_8_emacs;
4330 eol_parent = Qunix;
4332 else if (!NILP (Vcoding_system_for_write))
4334 val = Vcoding_system_for_write;
4335 if (coding_system_require_warning
4336 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4337 /* Confirm that VAL can surely encode the current region. */
4338 val = call5 (Vselect_safe_coding_system_function,
4339 start, end, Fcons (Qt, Fcons (val, Qnil)),
4340 Qnil, filename);
4342 else
4344 /* If the variable `buffer-file-coding-system' is set locally,
4345 it means that the file was read with some kind of code
4346 conversion or the variable is explicitly set by users. We
4347 had better write it out with the same coding system even if
4348 `enable-multibyte-characters' is nil.
4350 If it is not set locally, we anyway have to convert EOL
4351 format if the default value of `buffer-file-coding-system'
4352 tells that it is not Unix-like (LF only) format. */
4353 int using_default_coding = 0;
4354 int force_raw_text = 0;
4356 val = current_buffer->buffer_file_coding_system;
4357 if (NILP (val)
4358 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4360 val = Qnil;
4361 if (NILP (current_buffer->enable_multibyte_characters))
4362 force_raw_text = 1;
4365 if (NILP (val))
4367 /* Check file-coding-system-alist. */
4368 Lisp_Object args[7], coding_systems;
4370 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4371 args[3] = filename; args[4] = append; args[5] = visit;
4372 args[6] = lockname;
4373 coding_systems = Ffind_operation_coding_system (7, args);
4374 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4375 val = XCDR (coding_systems);
4378 if (NILP (val))
4380 /* If we still have not decided a coding system, use the
4381 default value of buffer-file-coding-system. */
4382 val = current_buffer->buffer_file_coding_system;
4383 using_default_coding = 1;
4386 if (! NILP (val) && ! force_raw_text)
4388 Lisp_Object spec, attrs;
4390 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4391 attrs = AREF (spec, 0);
4392 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4393 force_raw_text = 1;
4396 if (!force_raw_text
4397 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4398 /* Confirm that VAL can surely encode the current region. */
4399 val = call5 (Vselect_safe_coding_system_function,
4400 start, end, val, Qnil, filename);
4402 /* If the decided coding-system doesn't specify end-of-line
4403 format, we use that of
4404 `default-buffer-file-coding-system'. */
4405 if (! using_default_coding
4406 && ! NILP (buffer_defaults.buffer_file_coding_system))
4407 val = (coding_inherit_eol_type
4408 (val, buffer_defaults.buffer_file_coding_system));
4410 /* If we decide not to encode text, use `raw-text' or one of its
4411 subsidiaries. */
4412 if (force_raw_text)
4413 val = raw_text_coding_system (val);
4416 val = coding_inherit_eol_type (val, eol_parent);
4417 setup_coding_system (val, coding);
4419 if (!STRINGP (start) && !NILP (current_buffer->selective_display))
4420 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4421 return val;
4424 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4425 "r\nFWrite region to file: \ni\ni\ni\np",
4426 doc: /* Write current region into specified file.
4427 When called from a program, requires three arguments:
4428 START, END and FILENAME. START and END are normally buffer positions
4429 specifying the part of the buffer to write.
4430 If START is nil, that means to use the entire buffer contents.
4431 If START is a string, then output that string to the file
4432 instead of any buffer contents; END is ignored.
4434 Optional fourth argument APPEND if non-nil means
4435 append to existing file contents (if any). If it is an integer,
4436 seek to that offset in the file before writing.
4437 Optional fifth argument VISIT, if t or a string, means
4438 set the last-save-file-modtime of buffer to this file's modtime
4439 and mark buffer not modified.
4440 If VISIT is a string, it is a second file name;
4441 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4442 VISIT is also the file name to lock and unlock for clash detection.
4443 If VISIT is neither t nor nil nor a string,
4444 that means do not display the \"Wrote file\" message.
4445 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4446 use for locking and unlocking, overriding FILENAME and VISIT.
4447 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4448 for an existing file with the same name. If MUSTBENEW is `excl',
4449 that means to get an error if the file already exists; never overwrite.
4450 If MUSTBENEW is neither nil nor `excl', that means ask for
4451 confirmation before overwriting, but do go ahead and overwrite the file
4452 if the user confirms.
4454 This does code conversion according to the value of
4455 `coding-system-for-write', `buffer-file-coding-system', or
4456 `file-coding-system-alist', and sets the variable
4457 `last-coding-system-used' to the coding system actually used.
4459 This calls `write-region-annotate-functions' at the start, and
4460 `write-region-post-annotation-function' at the end. */)
4461 (start, end, filename, append, visit, lockname, mustbenew)
4462 Lisp_Object start, end, filename, append, visit, lockname, mustbenew;
4464 register int desc;
4465 int failure;
4466 int save_errno = 0;
4467 const unsigned char *fn;
4468 struct stat st;
4469 int count = SPECPDL_INDEX ();
4470 int count1;
4471 Lisp_Object handler;
4472 Lisp_Object visit_file;
4473 Lisp_Object annotations;
4474 Lisp_Object encoded_filename;
4475 int visiting = (EQ (visit, Qt) || STRINGP (visit));
4476 int quietly = !NILP (visit);
4477 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4478 struct buffer *given_buffer;
4479 #ifdef DOS_NT
4480 int buffer_file_type = O_BINARY;
4481 #endif /* DOS_NT */
4482 struct coding_system coding;
4484 if (current_buffer->base_buffer && visiting)
4485 error ("Cannot do file visiting in an indirect buffer");
4487 if (!NILP (start) && !STRINGP (start))
4488 validate_region (&start, &end);
4490 visit_file = Qnil;
4491 GCPRO5 (start, filename, visit, visit_file, lockname);
4493 filename = Fexpand_file_name (filename, Qnil);
4495 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4496 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4498 if (STRINGP (visit))
4499 visit_file = Fexpand_file_name (visit, Qnil);
4500 else
4501 visit_file = filename;
4503 if (NILP (lockname))
4504 lockname = visit_file;
4506 annotations = Qnil;
4508 /* If the file name has special constructs in it,
4509 call the corresponding file handler. */
4510 handler = Ffind_file_name_handler (filename, Qwrite_region);
4511 /* If FILENAME has no handler, see if VISIT has one. */
4512 if (NILP (handler) && STRINGP (visit))
4513 handler = Ffind_file_name_handler (visit, Qwrite_region);
4515 if (!NILP (handler))
4517 Lisp_Object val;
4518 val = call6 (handler, Qwrite_region, start, end,
4519 filename, append, visit);
4521 if (visiting)
4523 SAVE_MODIFF = MODIFF;
4524 XSETFASTINT (current_buffer->save_length, Z - BEG);
4525 current_buffer->filename = visit_file;
4527 UNGCPRO;
4528 return val;
4531 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4533 /* Special kludge to simplify auto-saving. */
4534 if (NILP (start))
4536 /* Do it later, so write-region-annotate-function can work differently
4537 if we save "the buffer" vs "a region".
4538 This is useful in tar-mode. --Stef
4539 XSETFASTINT (start, BEG);
4540 XSETFASTINT (end, Z); */
4541 Fwiden ();
4544 record_unwind_protect (build_annotations_unwind,
4545 Vwrite_region_annotation_buffers);
4546 Vwrite_region_annotation_buffers = Fcons (Fcurrent_buffer (), Qnil);
4547 count1 = SPECPDL_INDEX ();
4549 given_buffer = current_buffer;
4551 if (!STRINGP (start))
4553 annotations = build_annotations (start, end);
4555 if (current_buffer != given_buffer)
4557 XSETFASTINT (start, BEGV);
4558 XSETFASTINT (end, ZV);
4562 if (NILP (start))
4564 XSETFASTINT (start, BEGV);
4565 XSETFASTINT (end, ZV);
4568 UNGCPRO;
4570 GCPRO5 (start, filename, annotations, visit_file, lockname);
4572 /* Decide the coding-system to encode the data with.
4573 We used to make this choice before calling build_annotations, but that
4574 leads to problems when a write-annotate-function takes care of
4575 unsavable chars (as was the case with X-Symbol). */
4576 Vlast_coding_system_used
4577 = choose_write_coding_system (start, end, filename,
4578 append, visit, lockname, &coding);
4580 #ifdef CLASH_DETECTION
4581 if (!auto_saving)
4582 lock_file (lockname);
4583 #endif /* CLASH_DETECTION */
4585 encoded_filename = ENCODE_FILE (filename);
4587 fn = SDATA (encoded_filename);
4588 desc = -1;
4589 if (!NILP (append))
4590 #ifdef DOS_NT
4591 desc = emacs_open (fn, O_WRONLY | buffer_file_type, 0);
4592 #else /* not DOS_NT */
4593 desc = emacs_open (fn, O_WRONLY, 0);
4594 #endif /* not DOS_NT */
4596 if (desc < 0 && (NILP (append) || errno == ENOENT))
4597 #ifdef DOS_NT
4598 desc = emacs_open (fn,
4599 O_WRONLY | O_CREAT | buffer_file_type
4600 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
4601 S_IREAD | S_IWRITE);
4602 #else /* not DOS_NT */
4603 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
4604 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
4605 auto_saving ? auto_save_mode_bits : 0666);
4606 #endif /* not DOS_NT */
4608 if (desc < 0)
4610 #ifdef CLASH_DETECTION
4611 save_errno = errno;
4612 if (!auto_saving) unlock_file (lockname);
4613 errno = save_errno;
4614 #endif /* CLASH_DETECTION */
4615 UNGCPRO;
4616 report_file_error ("Opening output file", Fcons (filename, Qnil));
4619 record_unwind_protect (close_file_unwind, make_number (desc));
4621 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
4623 long ret;
4625 if (NUMBERP (append))
4626 ret = lseek (desc, XINT (append), 1);
4627 else
4628 ret = lseek (desc, 0, 2);
4629 if (ret < 0)
4631 #ifdef CLASH_DETECTION
4632 if (!auto_saving) unlock_file (lockname);
4633 #endif /* CLASH_DETECTION */
4634 UNGCPRO;
4635 report_file_error ("Lseek error", Fcons (filename, Qnil));
4639 UNGCPRO;
4641 failure = 0;
4642 immediate_quit = 1;
4644 if (STRINGP (start))
4646 failure = 0 > a_write (desc, start, 0, SCHARS (start),
4647 &annotations, &coding);
4648 save_errno = errno;
4650 else if (XINT (start) != XINT (end))
4652 failure = 0 > a_write (desc, Qnil,
4653 XINT (start), XINT (end) - XINT (start),
4654 &annotations, &coding);
4655 save_errno = errno;
4657 else
4659 /* If file was empty, still need to write the annotations */
4660 coding.mode |= CODING_MODE_LAST_BLOCK;
4661 failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4662 save_errno = errno;
4665 if (CODING_REQUIRE_FLUSHING (&coding)
4666 && !(coding.mode & CODING_MODE_LAST_BLOCK)
4667 && ! failure)
4669 /* We have to flush out a data. */
4670 coding.mode |= CODING_MODE_LAST_BLOCK;
4671 failure = 0 > e_write (desc, Qnil, 1, 1, &coding);
4672 save_errno = errno;
4675 immediate_quit = 0;
4677 #ifdef HAVE_FSYNC
4678 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4679 Disk full in NFS may be reported here. */
4680 /* mib says that closing the file will try to write as fast as NFS can do
4681 it, and that means the fsync here is not crucial for autosave files. */
4682 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
4684 /* If fsync fails with EINTR, don't treat that as serious. Also
4685 ignore EINVAL which happens when fsync is not supported on this
4686 file. */
4687 if (errno != EINTR && errno != EINVAL)
4688 failure = 1, save_errno = errno;
4690 #endif
4692 /* NFS can report a write failure now. */
4693 if (emacs_close (desc) < 0)
4694 failure = 1, save_errno = errno;
4696 stat (fn, &st);
4698 /* Discard the unwind protect for close_file_unwind. */
4699 specpdl_ptr = specpdl + count1;
4701 /* Call write-region-post-annotation-function. */
4702 while (CONSP (Vwrite_region_annotation_buffers))
4704 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4705 if (!NILP (Fbuffer_live_p (buf)))
4707 Fset_buffer (buf);
4708 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4709 call0 (Vwrite_region_post_annotation_function);
4711 Vwrite_region_annotation_buffers
4712 = XCDR (Vwrite_region_annotation_buffers);
4715 unbind_to (count, Qnil);
4717 #ifdef CLASH_DETECTION
4718 if (!auto_saving)
4719 unlock_file (lockname);
4720 #endif /* CLASH_DETECTION */
4722 /* Do this before reporting IO error
4723 to avoid a "file has changed on disk" warning on
4724 next attempt to save. */
4725 if (visiting)
4726 current_buffer->modtime = st.st_mtime;
4728 if (failure)
4729 error ("IO error writing %s: %s", SDATA (filename),
4730 emacs_strerror (save_errno));
4732 if (visiting)
4734 SAVE_MODIFF = MODIFF;
4735 XSETFASTINT (current_buffer->save_length, Z - BEG);
4736 current_buffer->filename = visit_file;
4737 update_mode_lines++;
4739 else if (quietly)
4741 if (auto_saving
4742 && ! NILP (Fstring_equal (current_buffer->filename,
4743 current_buffer->auto_save_file_name)))
4744 SAVE_MODIFF = MODIFF;
4746 return Qnil;
4749 if (!auto_saving)
4750 message_with_string ((INTEGERP (append)
4751 ? "Updated %s"
4752 : ! NILP (append)
4753 ? "Added to %s"
4754 : "Wrote %s"),
4755 visit_file, 1);
4757 return Qnil;
4760 Lisp_Object merge ();
4762 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4763 doc: /* Return t if (car A) is numerically less than (car B). */)
4764 (a, b)
4765 Lisp_Object a, b;
4767 return Flss (Fcar (a), Fcar (b));
4770 /* Build the complete list of annotations appropriate for writing out
4771 the text between START and END, by calling all the functions in
4772 write-region-annotate-functions and merging the lists they return.
4773 If one of these functions switches to a different buffer, we assume
4774 that buffer contains altered text. Therefore, the caller must
4775 make sure to restore the current buffer in all cases,
4776 as save-excursion would do. */
4778 static Lisp_Object
4779 build_annotations (start, end)
4780 Lisp_Object start, end;
4782 Lisp_Object annotations;
4783 Lisp_Object p, res;
4784 struct gcpro gcpro1, gcpro2;
4785 Lisp_Object original_buffer;
4786 int i, used_global = 0;
4788 XSETBUFFER (original_buffer, current_buffer);
4790 annotations = Qnil;
4791 p = Vwrite_region_annotate_functions;
4792 GCPRO2 (annotations, p);
4793 while (CONSP (p))
4795 struct buffer *given_buffer = current_buffer;
4796 if (EQ (Qt, XCAR (p)) && !used_global)
4797 { /* Use the global value of the hook. */
4798 Lisp_Object arg[2];
4799 used_global = 1;
4800 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
4801 arg[1] = XCDR (p);
4802 p = Fappend (2, arg);
4803 continue;
4805 Vwrite_region_annotations_so_far = annotations;
4806 res = call2 (XCAR (p), start, end);
4807 /* If the function makes a different buffer current,
4808 assume that means this buffer contains altered text to be output.
4809 Reset START and END from the buffer bounds
4810 and discard all previous annotations because they should have
4811 been dealt with by this function. */
4812 if (current_buffer != given_buffer)
4814 Vwrite_region_annotation_buffers
4815 = Fcons (Fcurrent_buffer (),
4816 Vwrite_region_annotation_buffers);
4817 XSETFASTINT (start, BEGV);
4818 XSETFASTINT (end, ZV);
4819 annotations = Qnil;
4821 Flength (res); /* Check basic validity of return value */
4822 annotations = merge (annotations, res, Qcar_less_than_car);
4823 p = XCDR (p);
4826 /* Now do the same for annotation functions implied by the file-format */
4827 if (auto_saving && (!EQ (current_buffer->auto_save_file_format, Qt)))
4828 p = current_buffer->auto_save_file_format;
4829 else
4830 p = current_buffer->file_format;
4831 for (i = 0; CONSP (p); p = XCDR (p), ++i)
4833 struct buffer *given_buffer = current_buffer;
4835 Vwrite_region_annotations_so_far = annotations;
4837 /* Value is either a list of annotations or nil if the function
4838 has written annotations to a temporary buffer, which is now
4839 current. */
4840 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
4841 original_buffer, make_number (i));
4842 if (current_buffer != given_buffer)
4844 XSETFASTINT (start, BEGV);
4845 XSETFASTINT (end, ZV);
4846 annotations = Qnil;
4849 if (CONSP (res))
4850 annotations = merge (annotations, res, Qcar_less_than_car);
4853 UNGCPRO;
4854 return annotations;
4858 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
4859 If STRING is nil, POS is the character position in the current buffer.
4860 Intersperse with them the annotations from *ANNOT
4861 which fall within the range of POS to POS + NCHARS,
4862 each at its appropriate position.
4864 We modify *ANNOT by discarding elements as we use them up.
4866 The return value is negative in case of system call failure. */
4868 static int
4869 a_write (desc, string, pos, nchars, annot, coding)
4870 int desc;
4871 Lisp_Object string;
4872 register int nchars;
4873 int pos;
4874 Lisp_Object *annot;
4875 struct coding_system *coding;
4877 Lisp_Object tem;
4878 int nextpos;
4879 int lastpos = pos + nchars;
4881 while (NILP (*annot) || CONSP (*annot))
4883 tem = Fcar_safe (Fcar (*annot));
4884 nextpos = pos - 1;
4885 if (INTEGERP (tem))
4886 nextpos = XFASTINT (tem);
4888 /* If there are no more annotations in this range,
4889 output the rest of the range all at once. */
4890 if (! (nextpos >= pos && nextpos <= lastpos))
4891 return e_write (desc, string, pos, lastpos, coding);
4893 /* Output buffer text up to the next annotation's position. */
4894 if (nextpos > pos)
4896 if (0 > e_write (desc, string, pos, nextpos, coding))
4897 return -1;
4898 pos = nextpos;
4900 /* Output the annotation. */
4901 tem = Fcdr (Fcar (*annot));
4902 if (STRINGP (tem))
4904 if (0 > e_write (desc, tem, 0, SCHARS (tem), coding))
4905 return -1;
4907 *annot = Fcdr (*annot);
4909 return 0;
4913 /* Write text in the range START and END into descriptor DESC,
4914 encoding them with coding system CODING. If STRING is nil, START
4915 and END are character positions of the current buffer, else they
4916 are indexes to the string STRING. */
4918 static int
4919 e_write (desc, string, start, end, coding)
4920 int desc;
4921 Lisp_Object string;
4922 int start, end;
4923 struct coding_system *coding;
4925 if (STRINGP (string))
4927 start = 0;
4928 end = SCHARS (string);
4931 /* We used to have a code for handling selective display here. But,
4932 now it is handled within encode_coding. */
4934 while (start < end)
4936 if (STRINGP (string))
4938 coding->src_multibyte = SCHARS (string) < SBYTES (string);
4939 if (CODING_REQUIRE_ENCODING (coding))
4941 encode_coding_object (coding, string,
4942 start, string_char_to_byte (string, start),
4943 end, string_char_to_byte (string, end), Qt);
4945 else
4947 coding->dst_object = string;
4948 coding->consumed_char = SCHARS (string);
4949 coding->produced = SBYTES (string);
4952 else
4954 int start_byte = CHAR_TO_BYTE (start);
4955 int end_byte = CHAR_TO_BYTE (end);
4957 coding->src_multibyte = (end - start) < (end_byte - start_byte);
4958 if (CODING_REQUIRE_ENCODING (coding))
4960 encode_coding_object (coding, Fcurrent_buffer (),
4961 start, start_byte, end, end_byte, Qt);
4963 else
4965 coding->dst_object = Qnil;
4966 coding->dst_pos_byte = start_byte;
4967 if (start >= GPT || end <= GPT)
4969 coding->consumed_char = end - start;
4970 coding->produced = end_byte - start_byte;
4972 else
4974 coding->consumed_char = GPT - start;
4975 coding->produced = GPT_BYTE - start_byte;
4980 if (coding->produced > 0)
4982 coding->produced -=
4983 emacs_write (desc,
4984 STRINGP (coding->dst_object)
4985 ? SDATA (coding->dst_object)
4986 : BYTE_POS_ADDR (coding->dst_pos_byte),
4987 coding->produced);
4989 if (coding->produced)
4990 return -1;
4992 start += coding->consumed_char;
4995 return 0;
4998 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
4999 Sverify_visited_file_modtime, 1, 1, 0,
5000 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5001 This means that the file has not been changed since it was visited or saved.
5002 See Info node `(elisp)Modification Time' for more details. */)
5003 (buf)
5004 Lisp_Object buf;
5006 struct buffer *b;
5007 struct stat st;
5008 Lisp_Object handler;
5009 Lisp_Object filename;
5011 CHECK_BUFFER (buf);
5012 b = XBUFFER (buf);
5014 if (!STRINGP (b->filename)) return Qt;
5015 if (b->modtime == 0) return Qt;
5017 /* If the file name has special constructs in it,
5018 call the corresponding file handler. */
5019 handler = Ffind_file_name_handler (b->filename,
5020 Qverify_visited_file_modtime);
5021 if (!NILP (handler))
5022 return call2 (handler, Qverify_visited_file_modtime, buf);
5024 filename = ENCODE_FILE (b->filename);
5026 if (stat (SDATA (filename), &st) < 0)
5028 /* If the file doesn't exist now and didn't exist before,
5029 we say that it isn't modified, provided the error is a tame one. */
5030 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
5031 st.st_mtime = -1;
5032 else
5033 st.st_mtime = 0;
5035 if (st.st_mtime == b->modtime
5036 /* If both are positive, accept them if they are off by one second. */
5037 || (st.st_mtime > 0 && b->modtime > 0
5038 && (st.st_mtime == b->modtime + 1
5039 || st.st_mtime == b->modtime - 1)))
5040 return Qt;
5041 return Qnil;
5044 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5045 Sclear_visited_file_modtime, 0, 0, 0,
5046 doc: /* Clear out records of last mod time of visited file.
5047 Next attempt to save will certainly not complain of a discrepancy. */)
5050 current_buffer->modtime = 0;
5051 return Qnil;
5054 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5055 Svisited_file_modtime, 0, 0, 0,
5056 doc: /* Return the current buffer's recorded visited file modification time.
5057 The value is a list of the form (HIGH LOW), like the time values
5058 that `file-attributes' returns. If the current buffer has no recorded
5059 file modification time, this function returns 0.
5060 See Info node `(elisp)Modification Time' for more details. */)
5063 if (! current_buffer->modtime)
5064 return make_number (0);
5065 return make_time ((time_t) current_buffer->modtime);
5068 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5069 Sset_visited_file_modtime, 0, 1, 0,
5070 doc: /* Update buffer's recorded modification time from the visited file's time.
5071 Useful if the buffer was not read from the file normally
5072 or if the file itself has been changed for some known benign reason.
5073 An argument specifies the modification time value to use
5074 \(instead of that of the visited file), in the form of a list
5075 \(HIGH . LOW) or (HIGH LOW). */)
5076 (time_list)
5077 Lisp_Object time_list;
5079 if (!NILP (time_list))
5080 current_buffer->modtime = cons_to_long (time_list);
5081 else
5083 register Lisp_Object filename;
5084 struct stat st;
5085 Lisp_Object handler;
5087 filename = Fexpand_file_name (current_buffer->filename, Qnil);
5089 /* If the file name has special constructs in it,
5090 call the corresponding file handler. */
5091 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5092 if (!NILP (handler))
5093 /* The handler can find the file name the same way we did. */
5094 return call2 (handler, Qset_visited_file_modtime, Qnil);
5096 filename = ENCODE_FILE (filename);
5098 if (stat (SDATA (filename), &st) >= 0)
5099 current_buffer->modtime = st.st_mtime;
5102 return Qnil;
5105 Lisp_Object
5106 auto_save_error (error)
5107 Lisp_Object error;
5109 Lisp_Object args[3], msg;
5110 int i, nbytes;
5111 struct gcpro gcpro1;
5112 char *msgbuf;
5113 USE_SAFE_ALLOCA;
5115 auto_save_error_occurred = 1;
5117 ring_bell (XFRAME (selected_frame));
5119 args[0] = build_string ("Auto-saving %s: %s");
5120 args[1] = current_buffer->name;
5121 args[2] = Ferror_message_string (error);
5122 msg = Fformat (3, args);
5123 GCPRO1 (msg);
5124 nbytes = SBYTES (msg);
5125 SAFE_ALLOCA (msgbuf, char *, nbytes);
5126 bcopy (SDATA (msg), msgbuf, nbytes);
5128 for (i = 0; i < 3; ++i)
5130 if (i == 0)
5131 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5132 else
5133 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5134 Fsleep_for (make_number (1), Qnil);
5137 SAFE_FREE ();
5138 UNGCPRO;
5139 return Qnil;
5142 Lisp_Object
5143 auto_save_1 ()
5145 struct stat st;
5146 Lisp_Object modes;
5148 auto_save_mode_bits = 0666;
5150 /* Get visited file's mode to become the auto save file's mode. */
5151 if (! NILP (current_buffer->filename))
5153 if (stat (SDATA (current_buffer->filename), &st) >= 0)
5154 /* But make sure we can overwrite it later! */
5155 auto_save_mode_bits = st.st_mode | 0600;
5156 else if ((modes = Ffile_modes (current_buffer->filename),
5157 INTEGERP (modes)))
5158 /* Remote files don't cooperate with stat. */
5159 auto_save_mode_bits = XINT (modes) | 0600;
5162 return
5163 Fwrite_region (Qnil, Qnil, current_buffer->auto_save_file_name, Qnil,
5164 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5165 Qnil, Qnil);
5168 static Lisp_Object
5169 do_auto_save_unwind (arg) /* used as unwind-protect function */
5170 Lisp_Object arg;
5172 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5173 auto_saving = 0;
5174 if (stream != NULL)
5176 BLOCK_INPUT;
5177 fclose (stream);
5178 UNBLOCK_INPUT;
5180 return Qnil;
5183 static Lisp_Object
5184 do_auto_save_unwind_1 (value) /* used as unwind-protect function */
5185 Lisp_Object value;
5187 minibuffer_auto_raise = XINT (value);
5188 return Qnil;
5191 static Lisp_Object
5192 do_auto_save_make_dir (dir)
5193 Lisp_Object dir;
5195 Lisp_Object mode;
5197 call2 (Qmake_directory, dir, Qt);
5198 XSETFASTINT (mode, 0700);
5199 return Fset_file_modes (dir, mode);
5202 static Lisp_Object
5203 do_auto_save_eh (ignore)
5204 Lisp_Object ignore;
5206 return Qnil;
5209 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5210 doc: /* Auto-save all buffers that need it.
5211 This is all buffers that have auto-saving enabled
5212 and are changed since last auto-saved.
5213 Auto-saving writes the buffer into a file
5214 so that your editing is not lost if the system crashes.
5215 This file is not the file you visited; that changes only when you save.
5216 Normally we run the normal hook `auto-save-hook' before saving.
5218 A non-nil NO-MESSAGE argument means do not print any message if successful.
5219 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5220 (no_message, current_only)
5221 Lisp_Object no_message, current_only;
5223 struct buffer *old = current_buffer, *b;
5224 Lisp_Object tail, buf;
5225 int auto_saved = 0;
5226 int do_handled_files;
5227 Lisp_Object oquit;
5228 FILE *stream = NULL;
5229 int count = SPECPDL_INDEX ();
5230 int orig_minibuffer_auto_raise = minibuffer_auto_raise;
5231 int old_message_p = 0;
5232 struct gcpro gcpro1, gcpro2;
5234 if (max_specpdl_size < specpdl_size + 40)
5235 max_specpdl_size = specpdl_size + 40;
5237 if (minibuf_level)
5238 no_message = Qt;
5240 if (NILP (no_message))
5242 old_message_p = push_message ();
5243 record_unwind_protect (pop_message_unwind, Qnil);
5246 /* Ordinarily don't quit within this function,
5247 but don't make it impossible to quit (in case we get hung in I/O). */
5248 oquit = Vquit_flag;
5249 Vquit_flag = Qnil;
5251 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5252 point to non-strings reached from Vbuffer_alist. */
5254 if (!NILP (Vrun_hooks))
5255 call1 (Vrun_hooks, intern ("auto-save-hook"));
5257 if (STRINGP (Vauto_save_list_file_name))
5259 Lisp_Object listfile;
5261 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5263 /* Don't try to create the directory when shutting down Emacs,
5264 because creating the directory might signal an error, and
5265 that would leave Emacs in a strange state. */
5266 if (!NILP (Vrun_hooks))
5268 Lisp_Object dir;
5269 dir = Qnil;
5270 GCPRO2 (dir, listfile);
5271 dir = Ffile_name_directory (listfile);
5272 if (NILP (Ffile_directory_p (dir)))
5273 internal_condition_case_1 (do_auto_save_make_dir,
5274 dir, Fcons (Fcons (Qfile_error, Qnil), Qnil),
5275 do_auto_save_eh);
5276 UNGCPRO;
5279 stream = fopen (SDATA (listfile), "w");
5282 record_unwind_protect (do_auto_save_unwind,
5283 make_save_value (stream, 0));
5284 record_unwind_protect (do_auto_save_unwind_1,
5285 make_number (minibuffer_auto_raise));
5286 minibuffer_auto_raise = 0;
5287 auto_saving = 1;
5288 auto_save_error_occurred = 0;
5290 /* On first pass, save all files that don't have handlers.
5291 On second pass, save all files that do have handlers.
5293 If Emacs is crashing, the handlers may tweak what is causing
5294 Emacs to crash in the first place, and it would be a shame if
5295 Emacs failed to autosave perfectly ordinary files because it
5296 couldn't handle some ange-ftp'd file. */
5298 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5299 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5301 buf = XCDR (XCAR (tail));
5302 b = XBUFFER (buf);
5304 /* Record all the buffers that have auto save mode
5305 in the special file that lists them. For each of these buffers,
5306 Record visited name (if any) and auto save name. */
5307 if (STRINGP (b->auto_save_file_name)
5308 && stream != NULL && do_handled_files == 0)
5310 BLOCK_INPUT;
5311 if (!NILP (b->filename))
5313 fwrite (SDATA (b->filename), 1,
5314 SBYTES (b->filename), stream);
5316 putc ('\n', stream);
5317 fwrite (SDATA (b->auto_save_file_name), 1,
5318 SBYTES (b->auto_save_file_name), stream);
5319 putc ('\n', stream);
5320 UNBLOCK_INPUT;
5323 if (!NILP (current_only)
5324 && b != current_buffer)
5325 continue;
5327 /* Don't auto-save indirect buffers.
5328 The base buffer takes care of it. */
5329 if (b->base_buffer)
5330 continue;
5332 /* Check for auto save enabled
5333 and file changed since last auto save
5334 and file changed since last real save. */
5335 if (STRINGP (b->auto_save_file_name)
5336 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5337 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5338 /* -1 means we've turned off autosaving for a while--see below. */
5339 && XINT (b->save_length) >= 0
5340 && (do_handled_files
5341 || NILP (Ffind_file_name_handler (b->auto_save_file_name,
5342 Qwrite_region))))
5344 EMACS_TIME before_time, after_time;
5346 EMACS_GET_TIME (before_time);
5348 /* If we had a failure, don't try again for 20 minutes. */
5349 if (b->auto_save_failure_time >= 0
5350 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5351 continue;
5353 set_buffer_internal (b);
5354 if (NILP (Vauto_save_include_big_deletions)
5355 && (XFASTINT (b->save_length) * 10
5356 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5357 /* A short file is likely to change a large fraction;
5358 spare the user annoying messages. */
5359 && XFASTINT (b->save_length) > 5000
5360 /* These messages are frequent and annoying for `*mail*'. */
5361 && !EQ (b->filename, Qnil)
5362 && NILP (no_message))
5364 /* It has shrunk too much; turn off auto-saving here. */
5365 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5366 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5367 b->name, 1);
5368 minibuffer_auto_raise = 0;
5369 /* Turn off auto-saving until there's a real save,
5370 and prevent any more warnings. */
5371 XSETINT (b->save_length, -1);
5372 Fsleep_for (make_number (1), Qnil);
5373 continue;
5375 if (!auto_saved && NILP (no_message))
5376 message1 ("Auto-saving...");
5377 internal_condition_case (auto_save_1, Qt, auto_save_error);
5378 auto_saved++;
5379 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5380 XSETFASTINT (current_buffer->save_length, Z - BEG);
5381 set_buffer_internal (old);
5383 EMACS_GET_TIME (after_time);
5385 /* If auto-save took more than 60 seconds,
5386 assume it was an NFS failure that got a timeout. */
5387 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5388 b->auto_save_failure_time = EMACS_SECS (after_time);
5392 /* Prevent another auto save till enough input events come in. */
5393 record_auto_save ();
5395 if (auto_saved && NILP (no_message))
5397 if (old_message_p)
5399 /* If we are going to restore an old message,
5400 give time to read ours. */
5401 sit_for (make_number (1), 0, 0);
5402 restore_message ();
5404 else if (!auto_save_error_occurred)
5405 /* Don't overwrite the error message if an error occurred.
5406 If we displayed a message and then restored a state
5407 with no message, leave a "done" message on the screen. */
5408 message1 ("Auto-saving...done");
5411 Vquit_flag = oquit;
5413 /* This restores the message-stack status. */
5414 unbind_to (count, Qnil);
5415 return Qnil;
5418 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5419 Sset_buffer_auto_saved, 0, 0, 0,
5420 doc: /* Mark current buffer as auto-saved with its current text.
5421 No auto-save file will be written until the buffer changes again. */)
5424 /* FIXME: This should not be called in indirect buffers, since
5425 they're not autosaved. */
5426 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5427 XSETFASTINT (current_buffer->save_length, Z - BEG);
5428 current_buffer->auto_save_failure_time = -1;
5429 return Qnil;
5432 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5433 Sclear_buffer_auto_save_failure, 0, 0, 0,
5434 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5437 current_buffer->auto_save_failure_time = -1;
5438 return Qnil;
5441 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5442 0, 0, 0,
5443 doc: /* Return t if current buffer has been auto-saved recently.
5444 More precisely, if it has been auto-saved since last read from or saved
5445 in the visited file. If the buffer has no visited file,
5446 then any auto-save counts as "recent". */)
5449 /* FIXME: maybe we should return nil for indirect buffers since
5450 they're never autosaved. */
5451 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5454 /* Reading and completing file names */
5456 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5457 Snext_read_file_uses_dialog_p, 0, 0, 0,
5458 doc: /* Return t if a call to `read-file-name' will use a dialog.
5459 The return value is only relevant for a call to `read-file-name' that happens
5460 before any other event (mouse or keypress) is handled. */)
5463 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK)
5464 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5465 && use_dialog_box
5466 && use_file_dialog
5467 && have_menus_p ())
5468 return Qt;
5469 #endif
5470 return Qnil;
5473 Lisp_Object
5474 Fread_file_name (prompt, dir, default_filename, mustmatch, initial, predicate)
5475 Lisp_Object prompt, dir, default_filename, mustmatch, initial, predicate;
5477 struct gcpro gcpro1, gcpro2;
5478 Lisp_Object args[7];
5480 GCPRO1 (default_filename);
5481 args[0] = intern ("read-file-name");
5482 args[1] = prompt;
5483 args[2] = dir;
5484 args[3] = default_filename;
5485 args[4] = mustmatch;
5486 args[5] = initial;
5487 args[6] = predicate;
5488 RETURN_UNGCPRO (Ffuncall (7, args));
5492 void
5493 syms_of_fileio ()
5495 Qoperations = intern_c_string ("operations");
5496 Qexpand_file_name = intern_c_string ("expand-file-name");
5497 Qsubstitute_in_file_name = intern_c_string ("substitute-in-file-name");
5498 Qdirectory_file_name = intern_c_string ("directory-file-name");
5499 Qfile_name_directory = intern_c_string ("file-name-directory");
5500 Qfile_name_nondirectory = intern_c_string ("file-name-nondirectory");
5501 Qunhandled_file_name_directory = intern_c_string ("unhandled-file-name-directory");
5502 Qfile_name_as_directory = intern_c_string ("file-name-as-directory");
5503 Qcopy_file = intern_c_string ("copy-file");
5504 Qmake_directory_internal = intern_c_string ("make-directory-internal");
5505 Qmake_directory = intern_c_string ("make-directory");
5506 Qdelete_directory_internal = intern_c_string ("delete-directory-internal");
5507 Qdelete_file = intern_c_string ("delete-file");
5508 Qrename_file = intern_c_string ("rename-file");
5509 Qadd_name_to_file = intern_c_string ("add-name-to-file");
5510 Qmake_symbolic_link = intern_c_string ("make-symbolic-link");
5511 Qfile_exists_p = intern_c_string ("file-exists-p");
5512 Qfile_executable_p = intern_c_string ("file-executable-p");
5513 Qfile_readable_p = intern_c_string ("file-readable-p");
5514 Qfile_writable_p = intern_c_string ("file-writable-p");
5515 Qfile_symlink_p = intern_c_string ("file-symlink-p");
5516 Qaccess_file = intern_c_string ("access-file");
5517 Qfile_directory_p = intern_c_string ("file-directory-p");
5518 Qfile_regular_p = intern_c_string ("file-regular-p");
5519 Qfile_accessible_directory_p = intern_c_string ("file-accessible-directory-p");
5520 Qfile_modes = intern_c_string ("file-modes");
5521 Qset_file_modes = intern_c_string ("set-file-modes");
5522 Qset_file_times = intern_c_string ("set-file-times");
5523 Qfile_newer_than_file_p = intern_c_string ("file-newer-than-file-p");
5524 Qinsert_file_contents = intern_c_string ("insert-file-contents");
5525 Qwrite_region = intern_c_string ("write-region");
5526 Qverify_visited_file_modtime = intern_c_string ("verify-visited-file-modtime");
5527 Qset_visited_file_modtime = intern_c_string ("set-visited-file-modtime");
5528 Qauto_save_coding = intern_c_string ("auto-save-coding");
5530 staticpro (&Qoperations);
5531 staticpro (&Qexpand_file_name);
5532 staticpro (&Qsubstitute_in_file_name);
5533 staticpro (&Qdirectory_file_name);
5534 staticpro (&Qfile_name_directory);
5535 staticpro (&Qfile_name_nondirectory);
5536 staticpro (&Qunhandled_file_name_directory);
5537 staticpro (&Qfile_name_as_directory);
5538 staticpro (&Qcopy_file);
5539 staticpro (&Qmake_directory_internal);
5540 staticpro (&Qmake_directory);
5541 staticpro (&Qdelete_directory_internal);
5542 staticpro (&Qdelete_file);
5543 staticpro (&Qrename_file);
5544 staticpro (&Qadd_name_to_file);
5545 staticpro (&Qmake_symbolic_link);
5546 staticpro (&Qfile_exists_p);
5547 staticpro (&Qfile_executable_p);
5548 staticpro (&Qfile_readable_p);
5549 staticpro (&Qfile_writable_p);
5550 staticpro (&Qaccess_file);
5551 staticpro (&Qfile_symlink_p);
5552 staticpro (&Qfile_directory_p);
5553 staticpro (&Qfile_regular_p);
5554 staticpro (&Qfile_accessible_directory_p);
5555 staticpro (&Qfile_modes);
5556 staticpro (&Qset_file_modes);
5557 staticpro (&Qset_file_times);
5558 staticpro (&Qfile_newer_than_file_p);
5559 staticpro (&Qinsert_file_contents);
5560 staticpro (&Qwrite_region);
5561 staticpro (&Qverify_visited_file_modtime);
5562 staticpro (&Qset_visited_file_modtime);
5563 staticpro (&Qauto_save_coding);
5565 Qfile_name_history = intern_c_string ("file-name-history");
5566 Fset (Qfile_name_history, Qnil);
5567 staticpro (&Qfile_name_history);
5569 Qfile_error = intern_c_string ("file-error");
5570 staticpro (&Qfile_error);
5571 Qfile_already_exists = intern_c_string ("file-already-exists");
5572 staticpro (&Qfile_already_exists);
5573 Qfile_date_error = intern_c_string ("file-date-error");
5574 staticpro (&Qfile_date_error);
5575 Qexcl = intern_c_string ("excl");
5576 staticpro (&Qexcl);
5578 #ifdef DOS_NT
5579 Qfind_buffer_file_type = intern_c_string ("find-buffer-file-type");
5580 staticpro (&Qfind_buffer_file_type);
5581 #endif /* DOS_NT */
5583 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system,
5584 doc: /* *Coding system for encoding file names.
5585 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5586 Vfile_name_coding_system = Qnil;
5588 DEFVAR_LISP ("default-file-name-coding-system",
5589 &Vdefault_file_name_coding_system,
5590 doc: /* Default coding system for encoding file names.
5591 This variable is used only when `file-name-coding-system' is nil.
5593 This variable is set/changed by the command `set-language-environment'.
5594 User should not set this variable manually,
5595 instead use `file-name-coding-system' to get a constant encoding
5596 of file names regardless of the current language environment. */);
5597 Vdefault_file_name_coding_system = Qnil;
5599 Qformat_decode = intern_c_string ("format-decode");
5600 staticpro (&Qformat_decode);
5601 Qformat_annotate_function = intern_c_string ("format-annotate-function");
5602 staticpro (&Qformat_annotate_function);
5603 Qafter_insert_file_set_coding = intern_c_string ("after-insert-file-set-coding");
5604 staticpro (&Qafter_insert_file_set_coding);
5606 Qcar_less_than_car = intern_c_string ("car-less-than-car");
5607 staticpro (&Qcar_less_than_car);
5609 Fput (Qfile_error, Qerror_conditions,
5610 Fpurecopy (list2 (Qfile_error, Qerror)));
5611 Fput (Qfile_error, Qerror_message,
5612 make_pure_c_string ("File error"));
5614 Fput (Qfile_already_exists, Qerror_conditions,
5615 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5616 Fput (Qfile_already_exists, Qerror_message,
5617 make_pure_c_string ("File already exists"));
5619 Fput (Qfile_date_error, Qerror_conditions,
5620 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5621 Fput (Qfile_date_error, Qerror_message,
5622 make_pure_c_string ("Cannot set file date"));
5624 DEFVAR_LISP ("directory-sep-char", &Vdirectory_sep_char,
5625 doc: /* Directory separator character for built-in functions that return file names.
5626 The value is always ?/. Don't use this variable, just use `/'. */);
5627 XSETFASTINT (Vdirectory_sep_char, '/');
5629 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
5630 doc: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
5631 If a file name matches REGEXP, then all I/O on that file is done by calling
5632 HANDLER.
5634 The first argument given to HANDLER is the name of the I/O primitive
5635 to be handled; the remaining arguments are the arguments that were
5636 passed to that primitive. For example, if you do
5637 (file-exists-p FILENAME)
5638 and FILENAME is handled by HANDLER, then HANDLER is called like this:
5639 (funcall HANDLER 'file-exists-p FILENAME)
5640 The function `find-file-name-handler' checks this list for a handler
5641 for its argument. */);
5642 Vfile_name_handler_alist = Qnil;
5644 DEFVAR_LISP ("set-auto-coding-function",
5645 &Vset_auto_coding_function,
5646 doc: /* If non-nil, a function to call to decide a coding system of file.
5647 Two arguments are passed to this function: the file name
5648 and the length of a file contents following the point.
5649 This function should return a coding system to decode the file contents.
5650 It should check the file name against `auto-coding-alist'.
5651 If no coding system is decided, it should check a coding system
5652 specified in the heading lines with the format:
5653 -*- ... coding: CODING-SYSTEM; ... -*-
5654 or local variable spec of the tailing lines with `coding:' tag. */);
5655 Vset_auto_coding_function = Qnil;
5657 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
5658 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5659 Each is passed one argument, the number of characters inserted,
5660 with point at the start of the inserted text. Each function
5661 should leave point the same, and return the new character count.
5662 If `insert-file-contents' is intercepted by a handler from
5663 `file-name-handler-alist', that handler is responsible for calling the
5664 functions in `after-insert-file-functions' if appropriate. */);
5665 Vafter_insert_file_functions = Qnil;
5667 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
5668 doc: /* A list of functions to be called at the start of `write-region'.
5669 Each is passed two arguments, START and END as for `write-region'.
5670 These are usually two numbers but not always; see the documentation
5671 for `write-region'. The function should return a list of pairs
5672 of the form (POSITION . STRING), consisting of strings to be effectively
5673 inserted at the specified positions of the file being written (1 means to
5674 insert before the first byte written). The POSITIONs must be sorted into
5675 increasing order.
5677 If there are several annotation functions, the lists returned by these
5678 functions are merged destructively. As each annotation function runs,
5679 the variable `write-region-annotations-so-far' contains a list of all
5680 annotations returned by previous annotation functions.
5682 An annotation function can return with a different buffer current.
5683 Doing so removes the annotations returned by previous functions, and
5684 resets START and END to `point-min' and `point-max' of the new buffer.
5686 After `write-region' completes, Emacs calls the function stored in
5687 `write-region-post-annotation-function', once for each buffer that was
5688 current when building the annotations (i.e., at least once), with that
5689 buffer current. */);
5690 Vwrite_region_annotate_functions = Qnil;
5691 staticpro (&Qwrite_region_annotate_functions);
5692 Qwrite_region_annotate_functions
5693 = intern_c_string ("write-region-annotate-functions");
5695 DEFVAR_LISP ("write-region-post-annotation-function",
5696 &Vwrite_region_post_annotation_function,
5697 doc: /* Function to call after `write-region' completes.
5698 The function is called with no arguments. If one or more of the
5699 annotation functions in `write-region-annotate-functions' changed the
5700 current buffer, the function stored in this variable is called for
5701 each of those additional buffers as well, in addition to the original
5702 buffer. The relevant buffer is current during each function call. */);
5703 Vwrite_region_post_annotation_function = Qnil;
5704 staticpro (&Vwrite_region_annotation_buffers);
5706 DEFVAR_LISP ("write-region-annotations-so-far",
5707 &Vwrite_region_annotations_so_far,
5708 doc: /* When an annotation function is called, this holds the previous annotations.
5709 These are the annotations made by other annotation functions
5710 that were already called. See also `write-region-annotate-functions'. */);
5711 Vwrite_region_annotations_so_far = Qnil;
5713 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
5714 doc: /* A list of file name handlers that temporarily should not be used.
5715 This applies only to the operation `inhibit-file-name-operation'. */);
5716 Vinhibit_file_name_handlers = Qnil;
5718 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
5719 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5720 Vinhibit_file_name_operation = Qnil;
5722 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
5723 doc: /* File name in which we write a list of all auto save file names.
5724 This variable is initialized automatically from `auto-save-list-file-prefix'
5725 shortly after Emacs reads your `.emacs' file, if you have not yet given it
5726 a non-nil value. */);
5727 Vauto_save_list_file_name = Qnil;
5729 DEFVAR_LISP ("auto-save-visited-file-name", &Vauto_save_visited_file_name,
5730 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5731 Normally auto-save files are written under other names. */);
5732 Vauto_save_visited_file_name = Qnil;
5734 DEFVAR_LISP ("auto-save-include-big-deletions", &Vauto_save_include_big_deletions,
5735 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5736 If nil, deleting a substantial portion of the text disables auto-save
5737 in the buffer; this is the default behavior, because the auto-save
5738 file is usually more useful if it contains the deleted text. */);
5739 Vauto_save_include_big_deletions = Qnil;
5741 #ifdef HAVE_FSYNC
5742 DEFVAR_BOOL ("write-region-inhibit-fsync", &write_region_inhibit_fsync,
5743 doc: /* *Non-nil means don't call fsync in `write-region'.
5744 This variable affects calls to `write-region' as well as save commands.
5745 A non-nil value may result in data loss! */);
5746 write_region_inhibit_fsync = 0;
5747 #endif
5749 DEFVAR_BOOL ("delete-by-moving-to-trash", &delete_by_moving_to_trash,
5750 doc: /* Specifies whether to use the system's trash can.
5751 When non-nil, the function `move-file-to-trash' will be used by
5752 `delete-file' and `delete-directory'. */);
5753 delete_by_moving_to_trash = 0;
5754 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
5755 Qmove_file_to_trash = intern_c_string ("move-file-to-trash");
5756 staticpro (&Qmove_file_to_trash);
5757 Qcopy_directory = intern_c_string ("copy-directory");
5758 staticpro (&Qcopy_directory);
5759 Qdelete_directory = intern_c_string ("delete-directory");
5760 staticpro (&Qdelete_directory);
5762 defsubr (&Sfind_file_name_handler);
5763 defsubr (&Sfile_name_directory);
5764 defsubr (&Sfile_name_nondirectory);
5765 defsubr (&Sunhandled_file_name_directory);
5766 defsubr (&Sfile_name_as_directory);
5767 defsubr (&Sdirectory_file_name);
5768 defsubr (&Smake_temp_name);
5769 defsubr (&Sexpand_file_name);
5770 defsubr (&Ssubstitute_in_file_name);
5771 defsubr (&Scopy_file);
5772 defsubr (&Smake_directory_internal);
5773 defsubr (&Sdelete_directory_internal);
5774 defsubr (&Sdelete_file);
5775 defsubr (&Srename_file);
5776 defsubr (&Sadd_name_to_file);
5777 defsubr (&Smake_symbolic_link);
5778 defsubr (&Sfile_name_absolute_p);
5779 defsubr (&Sfile_exists_p);
5780 defsubr (&Sfile_executable_p);
5781 defsubr (&Sfile_readable_p);
5782 defsubr (&Sfile_writable_p);
5783 defsubr (&Saccess_file);
5784 defsubr (&Sfile_symlink_p);
5785 defsubr (&Sfile_directory_p);
5786 defsubr (&Sfile_accessible_directory_p);
5787 defsubr (&Sfile_regular_p);
5788 defsubr (&Sfile_modes);
5789 defsubr (&Sset_file_modes);
5790 defsubr (&Sset_file_times);
5791 defsubr (&Sset_default_file_modes);
5792 defsubr (&Sdefault_file_modes);
5793 defsubr (&Sfile_newer_than_file_p);
5794 defsubr (&Sinsert_file_contents);
5795 defsubr (&Swrite_region);
5796 defsubr (&Scar_less_than_car);
5797 defsubr (&Sverify_visited_file_modtime);
5798 defsubr (&Sclear_visited_file_modtime);
5799 defsubr (&Svisited_file_modtime);
5800 defsubr (&Sset_visited_file_modtime);
5801 defsubr (&Sdo_auto_save);
5802 defsubr (&Sset_buffer_auto_saved);
5803 defsubr (&Sclear_buffer_auto_save_failure);
5804 defsubr (&Srecent_auto_save_p);
5806 defsubr (&Snext_read_file_uses_dialog_p);
5808 #ifdef HAVE_SYNC
5809 defsubr (&Sunix_sync);
5810 #endif
5813 /* arch-tag: 64ba3fd7-f844-4fb2-ba4b-427eb928786c
5814 (do not change this comment) */