Fix earlier NEWS change
[emacs.git] / src / fileio.c
blobd47d7dd9e0bc20fc7dc570d85f8b5a5577d16880
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2012 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <limits.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #ifdef HAVE_PWD_H
29 #include <pwd.h>
30 #endif
32 #include <errno.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
37 #endif
39 #include <c-ctype.h>
41 #include "lisp.h"
42 #include "intervals.h"
43 #include "character.h"
44 #include "buffer.h"
45 #include "coding.h"
46 #include "window.h"
47 #include "blockinput.h"
48 #include "frame.h"
49 #include "dispextern.h"
51 #ifdef WINDOWSNT
52 #define NOMINMAX 1
53 #include <windows.h>
54 #include <fcntl.h>
55 #include <sys/file.h>
56 #include "w32.h"
57 #endif /* not WINDOWSNT */
59 #ifdef MSDOS
60 #include "msdos.h"
61 #include <sys/param.h>
62 #include <fcntl.h>
63 #endif
65 #ifdef DOS_NT
66 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
67 redirector allows the six letters between 'Z' and 'a' as well. */
68 #ifdef MSDOS
69 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
70 #endif
71 #ifdef WINDOWSNT
72 #define IS_DRIVE(x) c_isalpha (x)
73 #endif
74 /* Need to lower-case the drive letter, or else expanded
75 filenames will sometimes compare unequal, because
76 `expand-file-name' doesn't always down-case the drive letter. */
77 #define DRIVE_LETTER(x) c_tolower (x)
78 #endif
80 #include "systime.h"
81 #include <stat-time.h>
83 #ifdef HPUX
84 #include <netio.h>
85 #endif
87 #include "commands.h"
89 /* True during writing of auto-save files. */
90 static bool auto_saving;
92 /* Nonzero umask during creation of auto-save directories. */
93 static mode_t auto_saving_dir_umask;
95 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
96 a new file with the same mode as the original. */
97 static mode_t auto_save_mode_bits;
99 /* Set by auto_save_1 if an error occurred during the last auto-save. */
100 static bool auto_save_error_occurred;
102 /* The symbol bound to coding-system-for-read when
103 insert-file-contents is called for recovering a file. This is not
104 an actual coding system name, but just an indicator to tell
105 insert-file-contents to use `emacs-mule' with a special flag for
106 auto saving and recovering a file. */
107 static Lisp_Object Qauto_save_coding;
109 /* Property name of a file name handler,
110 which gives a list of operations it handles.. */
111 static Lisp_Object Qoperations;
113 /* Lisp functions for translating file formats. */
114 static Lisp_Object Qformat_decode, Qformat_annotate_function;
116 /* Lisp function for setting buffer-file-coding-system and the
117 multibyteness of the current buffer after inserting a file. */
118 static Lisp_Object Qafter_insert_file_set_coding;
120 static Lisp_Object Qwrite_region_annotate_functions;
121 /* Each time an annotation function changes the buffer, the new buffer
122 is added here. */
123 static Lisp_Object Vwrite_region_annotation_buffers;
125 #ifdef HAVE_FSYNC
126 #endif
128 static Lisp_Object Qdelete_by_moving_to_trash;
130 /* Lisp function for moving files to trash. */
131 static Lisp_Object Qmove_file_to_trash;
133 /* Lisp function for recursively copying directories. */
134 static Lisp_Object Qcopy_directory;
136 /* Lisp function for recursively deleting directories. */
137 static Lisp_Object Qdelete_directory;
139 #ifdef WINDOWSNT
140 #endif
142 Lisp_Object Qfile_error;
143 static Lisp_Object Qfile_already_exists, Qfile_date_error;
144 static Lisp_Object Qexcl;
145 Lisp_Object Qfile_name_history;
147 static Lisp_Object Qcar_less_than_car;
149 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
150 Lisp_Object *, struct coding_system *);
151 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
152 struct coding_system *);
155 void
156 report_file_error (const char *string, Lisp_Object data)
158 Lisp_Object errstring;
159 int errorno = errno;
160 char *str;
162 synchronize_system_messages_locale ();
163 str = strerror (errorno);
164 errstring = code_convert_string_norecord (build_unibyte_string (str),
165 Vlocale_coding_system, 0);
167 while (1)
168 switch (errorno)
170 case EEXIST:
171 xsignal (Qfile_already_exists, Fcons (errstring, data));
172 break;
173 default:
174 /* System error messages are capitalized. Downcase the initial
175 unless it is followed by a slash. (The slash case caters to
176 error messages that begin with "I/O" or, in German, "E/A".) */
177 if (STRING_MULTIBYTE (errstring)
178 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
180 int c;
182 str = SSDATA (errstring);
183 c = STRING_CHAR ((unsigned char *) str);
184 Faset (errstring, make_number (0), make_number (downcase (c)));
187 xsignal (Qfile_error,
188 Fcons (build_string (string), Fcons (errstring, data)));
192 Lisp_Object
193 close_file_unwind (Lisp_Object fd)
195 emacs_close (XFASTINT (fd));
196 return Qnil;
199 /* Restore point, having saved it as a marker. */
201 Lisp_Object
202 restore_point_unwind (Lisp_Object location)
204 Fgoto_char (location);
205 Fset_marker (location, Qnil, Qnil);
206 return Qnil;
210 static Lisp_Object Qexpand_file_name;
211 static Lisp_Object Qsubstitute_in_file_name;
212 static Lisp_Object Qdirectory_file_name;
213 static Lisp_Object Qfile_name_directory;
214 static Lisp_Object Qfile_name_nondirectory;
215 static Lisp_Object Qunhandled_file_name_directory;
216 static Lisp_Object Qfile_name_as_directory;
217 static Lisp_Object Qcopy_file;
218 static Lisp_Object Qmake_directory_internal;
219 static Lisp_Object Qmake_directory;
220 static Lisp_Object Qdelete_directory_internal;
221 Lisp_Object Qdelete_file;
222 static Lisp_Object Qrename_file;
223 static Lisp_Object Qadd_name_to_file;
224 static Lisp_Object Qmake_symbolic_link;
225 Lisp_Object Qfile_exists_p;
226 static Lisp_Object Qfile_executable_p;
227 static Lisp_Object Qfile_readable_p;
228 static Lisp_Object Qfile_writable_p;
229 static Lisp_Object Qfile_symlink_p;
230 static Lisp_Object Qaccess_file;
231 Lisp_Object Qfile_directory_p;
232 static Lisp_Object Qfile_regular_p;
233 static Lisp_Object Qfile_accessible_directory_p;
234 static Lisp_Object Qfile_modes;
235 static Lisp_Object Qset_file_modes;
236 static Lisp_Object Qset_file_times;
237 static Lisp_Object Qfile_selinux_context;
238 static Lisp_Object Qset_file_selinux_context;
239 static Lisp_Object Qfile_newer_than_file_p;
240 Lisp_Object Qinsert_file_contents;
241 Lisp_Object Qwrite_region;
242 static Lisp_Object Qverify_visited_file_modtime;
243 static Lisp_Object Qset_visited_file_modtime;
245 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
246 Sfind_file_name_handler, 2, 2, 0,
247 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
248 Otherwise, return nil.
249 A file name is handled if one of the regular expressions in
250 `file-name-handler-alist' matches it.
252 If OPERATION equals `inhibit-file-name-operation', then we ignore
253 any handlers that are members of `inhibit-file-name-handlers',
254 but we still do run any other handlers. This lets handlers
255 use the standard functions without calling themselves recursively. */)
256 (Lisp_Object filename, Lisp_Object operation)
258 /* This function must not munge the match data. */
259 Lisp_Object chain, inhibited_handlers, result;
260 ptrdiff_t pos = -1;
262 result = Qnil;
263 CHECK_STRING (filename);
265 if (EQ (operation, Vinhibit_file_name_operation))
266 inhibited_handlers = Vinhibit_file_name_handlers;
267 else
268 inhibited_handlers = Qnil;
270 for (chain = Vfile_name_handler_alist; CONSP (chain);
271 chain = XCDR (chain))
273 Lisp_Object elt;
274 elt = XCAR (chain);
275 if (CONSP (elt))
277 Lisp_Object string = XCAR (elt);
278 ptrdiff_t match_pos;
279 Lisp_Object handler = XCDR (elt);
280 Lisp_Object operations = Qnil;
282 if (SYMBOLP (handler))
283 operations = Fget (handler, Qoperations);
285 if (STRINGP (string)
286 && (match_pos = fast_string_match (string, filename)) > pos
287 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
289 Lisp_Object tem;
291 handler = XCDR (elt);
292 tem = Fmemq (handler, inhibited_handlers);
293 if (NILP (tem))
295 result = handler;
296 pos = match_pos;
301 QUIT;
303 return result;
306 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
307 1, 1, 0,
308 doc: /* Return the directory component in file name FILENAME.
309 Return nil if FILENAME does not include a directory.
310 Otherwise return a directory name.
311 Given a Unix syntax file name, returns a string ending in slash. */)
312 (Lisp_Object filename)
314 #ifndef DOS_NT
315 register const char *beg;
316 #else
317 register char *beg;
318 #endif
319 register const char *p;
320 Lisp_Object handler;
322 CHECK_STRING (filename);
324 /* If the file name has special constructs in it,
325 call the corresponding file handler. */
326 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
327 if (!NILP (handler))
329 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
330 filename);
331 return STRINGP (handled_name) ? handled_name : Qnil;
334 #ifdef DOS_NT
335 beg = alloca (SBYTES (filename) + 1);
336 memcpy (beg, SSDATA (filename), SBYTES (filename) + 1);
337 #else
338 beg = SSDATA (filename);
339 #endif
340 p = beg + SBYTES (filename);
342 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
343 #ifdef DOS_NT
344 /* only recognize drive specifier at the beginning */
345 && !(p[-1] == ':'
346 /* handle the "/:d:foo" and "/:foo" cases correctly */
347 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
348 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
349 #endif
350 ) p--;
352 if (p == beg)
353 return Qnil;
354 #ifdef DOS_NT
355 /* Expansion of "c:" to drive and default directory. */
356 if (p[-1] == ':')
358 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
359 char *res = alloca (MAXPATHLEN + 1);
360 char *r = res;
362 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
364 memcpy (res, beg, 2);
365 beg += 2;
366 r += 2;
369 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
371 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
372 strcat (res, "/");
373 beg = res;
374 p = beg + strlen (beg);
377 dostounix_filename (beg);
378 #endif /* DOS_NT */
380 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
383 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
384 Sfile_name_nondirectory, 1, 1, 0,
385 doc: /* Return file name FILENAME sans its directory.
386 For example, in a Unix-syntax file name,
387 this is everything after the last slash,
388 or the entire name if it contains no slash. */)
389 (Lisp_Object filename)
391 register const char *beg, *p, *end;
392 Lisp_Object handler;
394 CHECK_STRING (filename);
396 /* If the file name has special constructs in it,
397 call the corresponding file handler. */
398 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
399 if (!NILP (handler))
401 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
402 filename);
403 if (STRINGP (handled_name))
404 return handled_name;
405 error ("Invalid handler in `file-name-handler-alist'");
408 beg = SSDATA (filename);
409 end = p = beg + SBYTES (filename);
411 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
412 #ifdef DOS_NT
413 /* only recognize drive specifier at beginning */
414 && !(p[-1] == ':'
415 /* handle the "/:d:foo" case correctly */
416 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
417 #endif
419 p--;
421 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
424 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
425 Sunhandled_file_name_directory, 1, 1, 0,
426 doc: /* Return a directly usable directory name somehow associated with FILENAME.
427 A `directly usable' directory name is one that may be used without the
428 intervention of any file handler.
429 If FILENAME is a directly usable file itself, return
430 \(file-name-directory FILENAME).
431 If FILENAME refers to a file which is not accessible from a local process,
432 then this should return nil.
433 The `call-process' and `start-process' functions use this function to
434 get a current directory to run processes in. */)
435 (Lisp_Object filename)
437 Lisp_Object handler;
439 /* If the file name has special constructs in it,
440 call the corresponding file handler. */
441 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
442 if (!NILP (handler))
444 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
445 filename);
446 return STRINGP (handled_name) ? handled_name : Qnil;
449 return Ffile_name_directory (filename);
452 /* Convert from file name SRC of length SRCLEN to directory name
453 in DST. On UNIX, just make sure there is a terminating /.
454 Return the length of DST. */
456 static ptrdiff_t
457 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen)
459 if (srclen == 0)
461 dst[0] = '.';
462 dst[1] = '/';
463 dst[2] = '\0';
464 return 2;
467 strcpy (dst, src);
469 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
471 dst[srclen] = DIRECTORY_SEP;
472 dst[srclen + 1] = '\0';
473 srclen++;
475 #ifdef DOS_NT
476 dostounix_filename (dst);
477 #endif
478 return srclen;
481 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
482 Sfile_name_as_directory, 1, 1, 0,
483 doc: /* Return a string representing the file name FILE interpreted as a directory.
484 This operation exists because a directory is also a file, but its name as
485 a directory is different from its name as a file.
486 The result can be used as the value of `default-directory'
487 or passed as second argument to `expand-file-name'.
488 For a Unix-syntax file name, just appends a slash. */)
489 (Lisp_Object file)
491 char *buf;
492 ptrdiff_t length;
493 Lisp_Object handler;
495 CHECK_STRING (file);
496 if (NILP (file))
497 return Qnil;
499 /* If the file name has special constructs in it,
500 call the corresponding file handler. */
501 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
502 if (!NILP (handler))
504 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
505 file);
506 if (STRINGP (handled_name))
507 return handled_name;
508 error ("Invalid handler in `file-name-handler-alist'");
511 buf = alloca (SBYTES (file) + 10);
512 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file));
513 return make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
516 /* Convert from directory name SRC of length SRCLEN to
517 file name in DST. On UNIX, just make sure there isn't
518 a terminating /. Return the length of DST. */
520 static ptrdiff_t
521 directory_file_name (char *dst, char *src, ptrdiff_t srclen)
523 /* Process as Unix format: just remove any final slash.
524 But leave "/" unchanged; do not change it to "". */
525 strcpy (dst, src);
526 if (srclen > 1
527 && IS_DIRECTORY_SEP (dst[srclen - 1])
528 #ifdef DOS_NT
529 && !IS_ANY_SEP (dst[srclen - 2])
530 #endif
533 dst[srclen - 1] = 0;
534 srclen--;
536 #ifdef DOS_NT
537 dostounix_filename (dst);
538 #endif
539 return srclen;
542 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
543 1, 1, 0,
544 doc: /* Returns the file name of the directory named DIRECTORY.
545 This is the name of the file that holds the data for the directory DIRECTORY.
546 This operation exists because a directory is also a file, but its name as
547 a directory is different from its name as a file.
548 In Unix-syntax, this function just removes the final slash. */)
549 (Lisp_Object directory)
551 char *buf;
552 ptrdiff_t length;
553 Lisp_Object handler;
555 CHECK_STRING (directory);
557 if (NILP (directory))
558 return Qnil;
560 /* If the file name has special constructs in it,
561 call the corresponding file handler. */
562 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
563 if (!NILP (handler))
565 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
566 directory);
567 if (STRINGP (handled_name))
568 return handled_name;
569 error ("Invalid handler in `file-name-handler-alist'");
572 buf = alloca (SBYTES (directory) + 20);
573 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory));
574 return make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
577 static const char make_temp_name_tbl[64] =
579 'A','B','C','D','E','F','G','H',
580 'I','J','K','L','M','N','O','P',
581 'Q','R','S','T','U','V','W','X',
582 'Y','Z','a','b','c','d','e','f',
583 'g','h','i','j','k','l','m','n',
584 'o','p','q','r','s','t','u','v',
585 'w','x','y','z','0','1','2','3',
586 '4','5','6','7','8','9','-','_'
589 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
591 /* Value is a temporary file name starting with PREFIX, a string.
593 The Emacs process number forms part of the result, so there is
594 no danger of generating a name being used by another process.
595 In addition, this function makes an attempt to choose a name
596 which has no existing file. To make this work, PREFIX should be
597 an absolute file name.
599 BASE64_P means add the pid as 3 characters in base64
600 encoding. In this case, 6 characters will be added to PREFIX to
601 form the file name. Otherwise, if Emacs is running on a system
602 with long file names, add the pid as a decimal number.
604 This function signals an error if no unique file name could be
605 generated. */
607 Lisp_Object
608 make_temp_name (Lisp_Object prefix, bool base64_p)
610 Lisp_Object val;
611 int len, clen;
612 printmax_t pid;
613 char *p, *data;
614 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
615 int pidlen;
617 CHECK_STRING (prefix);
619 /* VAL is created by adding 6 characters to PREFIX. The first
620 three are the PID of this process, in base 64, and the second
621 three are incremented if the file already exists. This ensures
622 262144 unique file names per PID per PREFIX. */
624 pid = getpid ();
626 if (base64_p)
628 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
629 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
630 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
631 pidlen = 3;
633 else
635 #ifdef HAVE_LONG_FILE_NAMES
636 pidlen = sprintf (pidbuf, "%"pMd, pid);
637 #else
638 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
639 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
640 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
641 pidlen = 3;
642 #endif
645 len = SBYTES (prefix); clen = SCHARS (prefix);
646 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
647 if (!STRING_MULTIBYTE (prefix))
648 STRING_SET_UNIBYTE (val);
649 data = SSDATA (val);
650 memcpy (data, SSDATA (prefix), len);
651 p = data + len;
653 memcpy (p, pidbuf, pidlen);
654 p += pidlen;
656 /* Here we try to minimize useless stat'ing when this function is
657 invoked many times successively with the same PREFIX. We achieve
658 this by initializing count to a random value, and incrementing it
659 afterwards.
661 We don't want make-temp-name to be called while dumping,
662 because then make_temp_name_count_initialized_p would get set
663 and then make_temp_name_count would not be set when Emacs starts. */
665 if (!make_temp_name_count_initialized_p)
667 make_temp_name_count = time (NULL);
668 make_temp_name_count_initialized_p = 1;
671 while (1)
673 unsigned num = make_temp_name_count;
675 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
676 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
677 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
679 /* Poor man's congruential RN generator. Replace with
680 ++make_temp_name_count for debugging. */
681 make_temp_name_count += 25229;
682 make_temp_name_count %= 225307;
684 if (!check_existing (data))
686 /* We want to return only if errno is ENOENT. */
687 if (errno == ENOENT)
688 return val;
689 else
690 /* The error here is dubious, but there is little else we
691 can do. The alternatives are to return nil, which is
692 as bad as (and in many cases worse than) throwing the
693 error, or to ignore the error, which will likely result
694 in looping through 225307 stat's, which is not only
695 dog-slow, but also useless since eventually nil would
696 have to be returned anyway. */
697 report_file_error ("Cannot create temporary name for prefix",
698 Fcons (prefix, Qnil));
699 /* not reached */
705 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
706 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
707 The Emacs process number forms part of the result,
708 so there is no danger of generating a name being used by another process.
710 In addition, this function makes an attempt to choose a name
711 which has no existing file. To make this work,
712 PREFIX should be an absolute file name.
714 There is a race condition between calling `make-temp-name' and creating the
715 file which opens all kinds of security holes. For that reason, you should
716 probably use `make-temp-file' instead, except in three circumstances:
718 * If you are creating the file in the user's home directory.
719 * If you are creating a directory rather than an ordinary file.
720 * If you are taking special precautions as `make-temp-file' does. */)
721 (Lisp_Object prefix)
723 return make_temp_name (prefix, 0);
728 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
729 doc: /* Convert filename NAME to absolute, and canonicalize it.
730 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
731 \(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
732 the current buffer's value of `default-directory' is used.
733 NAME should be a string that is a valid file name for the underlying
734 filesystem.
735 File name components that are `.' are removed, and
736 so are file name components followed by `..', along with the `..' itself;
737 note that these simplifications are done without checking the resulting
738 file names in the file system.
739 Multiple consecutive slashes are collapsed into a single slash,
740 except at the beginning of the file name when they are significant (e.g.,
741 UNC file names on MS-Windows.)
742 An initial `~/' expands to your home directory.
743 An initial `~USER/' expands to USER's home directory.
744 See also the function `substitute-in-file-name'.
746 For technical reasons, this function can return correct but
747 non-intuitive results for the root directory; for instance,
748 \(expand-file-name ".." "/") returns "/..". For this reason, use
749 \(directory-file-name (file-name-directory dirname)) to traverse a
750 filesystem tree, not (expand-file-name ".." dirname). */)
751 (Lisp_Object name, Lisp_Object default_directory)
753 /* These point to SDATA and need to be careful with string-relocation
754 during GC (via DECODE_FILE). */
755 char *nm;
756 const char *newdir;
757 /* This should only point to alloca'd data. */
758 char *target;
760 ptrdiff_t tlen;
761 struct passwd *pw;
762 #ifdef DOS_NT
763 int drive = 0;
764 bool collapse_newdir = 1;
765 bool is_escaped = 0;
766 #endif /* DOS_NT */
767 ptrdiff_t length;
768 Lisp_Object handler, result, handled_name;
769 bool multibyte;
770 Lisp_Object hdir;
772 CHECK_STRING (name);
774 /* If the file name has special constructs in it,
775 call the corresponding file handler. */
776 handler = Ffind_file_name_handler (name, Qexpand_file_name);
777 if (!NILP (handler))
779 handled_name = call3 (handler, Qexpand_file_name,
780 name, default_directory);
781 if (STRINGP (handled_name))
782 return handled_name;
783 error ("Invalid handler in `file-name-handler-alist'");
787 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
788 if (NILP (default_directory))
789 default_directory = BVAR (current_buffer, directory);
790 if (! STRINGP (default_directory))
792 #ifdef DOS_NT
793 /* "/" is not considered a root directory on DOS_NT, so using "/"
794 here causes an infinite recursion in, e.g., the following:
796 (let (default-directory)
797 (expand-file-name "a"))
799 To avoid this, we set default_directory to the root of the
800 current drive. */
801 default_directory = build_string (emacs_root_dir ());
802 #else
803 default_directory = build_string ("/");
804 #endif
807 if (!NILP (default_directory))
809 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
810 if (!NILP (handler))
812 handled_name = call3 (handler, Qexpand_file_name,
813 name, default_directory);
814 if (STRINGP (handled_name))
815 return handled_name;
816 error ("Invalid handler in `file-name-handler-alist'");
821 char *o = SSDATA (default_directory);
823 /* Make sure DEFAULT_DIRECTORY is properly expanded.
824 It would be better to do this down below where we actually use
825 default_directory. Unfortunately, calling Fexpand_file_name recursively
826 could invoke GC, and the strings might be relocated. This would
827 be annoying because we have pointers into strings lying around
828 that would need adjusting, and people would add new pointers to
829 the code and forget to adjust them, resulting in intermittent bugs.
830 Putting this call here avoids all that crud.
832 The EQ test avoids infinite recursion. */
833 if (! NILP (default_directory) && !EQ (default_directory, name)
834 /* Save time in some common cases - as long as default_directory
835 is not relative, it can be canonicalized with name below (if it
836 is needed at all) without requiring it to be expanded now. */
837 #ifdef DOS_NT
838 /* Detect MSDOS file names with drive specifiers. */
839 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
840 && IS_DIRECTORY_SEP (o[2]))
841 #ifdef WINDOWSNT
842 /* Detect Windows file names in UNC format. */
843 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
844 #endif
845 #else /* not DOS_NT */
846 /* Detect Unix absolute file names (/... alone is not absolute on
847 DOS or Windows). */
848 && ! (IS_DIRECTORY_SEP (o[0]))
849 #endif /* not DOS_NT */
852 struct gcpro gcpro1;
854 GCPRO1 (name);
855 default_directory = Fexpand_file_name (default_directory, Qnil);
856 UNGCPRO;
859 multibyte = STRING_MULTIBYTE (name);
860 if (multibyte != STRING_MULTIBYTE (default_directory))
862 if (multibyte)
863 default_directory = string_to_multibyte (default_directory);
864 else
866 name = string_to_multibyte (name);
867 multibyte = 1;
871 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
872 nm = alloca (SBYTES (name) + 1);
873 memcpy (nm, SSDATA (name), SBYTES (name) + 1);
875 #ifdef DOS_NT
876 /* Note if special escape prefix is present, but remove for now. */
877 if (nm[0] == '/' && nm[1] == ':')
879 is_escaped = 1;
880 nm += 2;
883 /* Find and remove drive specifier if present; this makes nm absolute
884 even if the rest of the name appears to be relative. Only look for
885 drive specifier at the beginning. */
886 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
888 drive = (unsigned char) nm[0];
889 nm += 2;
892 #ifdef WINDOWSNT
893 /* If we see "c://somedir", we want to strip the first slash after the
894 colon when stripping the drive letter. Otherwise, this expands to
895 "//somedir". */
896 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
897 nm++;
899 /* Discard any previous drive specifier if nm is now in UNC format. */
900 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
902 drive = 0;
904 #endif /* WINDOWSNT */
905 #endif /* DOS_NT */
907 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
908 none are found, we can probably return right away. We will avoid
909 allocating a new string if name is already fully expanded. */
910 if (
911 IS_DIRECTORY_SEP (nm[0])
912 #ifdef MSDOS
913 && drive && !is_escaped
914 #endif
915 #ifdef WINDOWSNT
916 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
917 #endif
920 /* If it turns out that the filename we want to return is just a
921 suffix of FILENAME, we don't need to go through and edit
922 things; we just need to construct a new string using data
923 starting at the middle of FILENAME. If we set LOSE, that
924 means we've discovered that we can't do that cool trick. */
925 bool lose = 0;
926 char *p = nm;
928 while (*p)
930 /* Since we know the name is absolute, we can assume that each
931 element starts with a "/". */
933 /* "." and ".." are hairy. */
934 if (IS_DIRECTORY_SEP (p[0])
935 && p[1] == '.'
936 && (IS_DIRECTORY_SEP (p[2])
937 || p[2] == 0
938 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
939 || p[3] == 0))))
940 lose = 1;
941 /* We want to replace multiple `/' in a row with a single
942 slash. */
943 else if (p > nm
944 && IS_DIRECTORY_SEP (p[0])
945 && IS_DIRECTORY_SEP (p[1]))
946 lose = 1;
947 p++;
949 if (!lose)
951 #ifdef DOS_NT
952 /* Make sure directories are all separated with /, but
953 avoid allocation of a new string when not required. */
954 dostounix_filename (nm);
955 #ifdef WINDOWSNT
956 if (IS_DIRECTORY_SEP (nm[1]))
958 if (strcmp (nm, SSDATA (name)) != 0)
959 name = make_specified_string (nm, -1, strlen (nm), multibyte);
961 else
962 #endif
963 /* Drive must be set, so this is okay. */
964 if (strcmp (nm - 2, SSDATA (name)) != 0)
966 char temp[] = " :";
968 name = make_specified_string (nm, -1, p - nm, multibyte);
969 temp[0] = DRIVE_LETTER (drive);
970 name = concat2 (build_string (temp), name);
972 return name;
973 #else /* not DOS_NT */
974 if (strcmp (nm, SSDATA (name)) == 0)
975 return name;
976 return make_specified_string (nm, -1, strlen (nm), multibyte);
977 #endif /* not DOS_NT */
981 /* At this point, nm might or might not be an absolute file name. We
982 need to expand ~ or ~user if present, otherwise prefix nm with
983 default_directory if nm is not absolute, and finally collapse /./
984 and /foo/../ sequences.
986 We set newdir to be the appropriate prefix if one is needed:
987 - the relevant user directory if nm starts with ~ or ~user
988 - the specified drive's working dir (DOS/NT only) if nm does not
989 start with /
990 - the value of default_directory.
992 Note that these prefixes are not guaranteed to be absolute (except
993 for the working dir of a drive). Therefore, to ensure we always
994 return an absolute name, if the final prefix is not absolute we
995 append it to the current working directory. */
997 newdir = 0;
999 if (nm[0] == '~') /* prefix ~ */
1001 if (IS_DIRECTORY_SEP (nm[1])
1002 || nm[1] == 0) /* ~ by itself */
1004 Lisp_Object tem;
1006 if (!(newdir = egetenv ("HOME")))
1007 newdir = "";
1008 nm++;
1009 /* `egetenv' may return a unibyte string, which will bite us since
1010 we expect the directory to be multibyte. */
1011 tem = build_string (newdir);
1012 if (!STRING_MULTIBYTE (tem))
1014 hdir = DECODE_FILE (tem);
1015 newdir = SSDATA (hdir);
1017 #ifdef DOS_NT
1018 collapse_newdir = 0;
1019 #endif
1021 else /* ~user/filename */
1023 char *o, *p;
1024 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
1025 o = alloca (p - nm + 1);
1026 memcpy (o, nm, p - nm);
1027 o [p - nm] = 0;
1029 block_input ();
1030 pw = (struct passwd *) getpwnam (o + 1);
1031 unblock_input ();
1032 if (pw)
1034 newdir = pw->pw_dir;
1035 nm = p;
1036 #ifdef DOS_NT
1037 collapse_newdir = 0;
1038 #endif
1041 /* If we don't find a user of that name, leave the name
1042 unchanged; don't move nm forward to p. */
1046 #ifdef DOS_NT
1047 /* On DOS and Windows, nm is absolute if a drive name was specified;
1048 use the drive's current directory as the prefix if needed. */
1049 if (!newdir && drive)
1051 /* Get default directory if needed to make nm absolute. */
1052 char *adir = NULL;
1053 if (!IS_DIRECTORY_SEP (nm[0]))
1055 adir = alloca (MAXPATHLEN + 1);
1056 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1057 adir = NULL;
1059 if (!adir)
1061 /* Either nm starts with /, or drive isn't mounted. */
1062 adir = alloca (4);
1063 adir[0] = DRIVE_LETTER (drive);
1064 adir[1] = ':';
1065 adir[2] = '/';
1066 adir[3] = 0;
1068 newdir = adir;
1070 #endif /* DOS_NT */
1072 /* Finally, if no prefix has been specified and nm is not absolute,
1073 then it must be expanded relative to default_directory. */
1075 if (1
1076 #ifndef DOS_NT
1077 /* /... alone is not absolute on DOS and Windows. */
1078 && !IS_DIRECTORY_SEP (nm[0])
1079 #endif
1080 #ifdef WINDOWSNT
1081 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1082 #endif
1083 && !newdir)
1085 newdir = SSDATA (default_directory);
1086 #ifdef DOS_NT
1087 /* Note if special escape prefix is present, but remove for now. */
1088 if (newdir[0] == '/' && newdir[1] == ':')
1090 is_escaped = 1;
1091 newdir += 2;
1093 #endif
1096 #ifdef DOS_NT
1097 if (newdir)
1099 /* First ensure newdir is an absolute name. */
1100 if (
1101 /* Detect MSDOS file names with drive specifiers. */
1102 ! (IS_DRIVE (newdir[0])
1103 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1104 #ifdef WINDOWSNT
1105 /* Detect Windows file names in UNC format. */
1106 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1107 #endif
1110 /* Effectively, let newdir be (expand-file-name newdir cwd).
1111 Because of the admonition against calling expand-file-name
1112 when we have pointers into lisp strings, we accomplish this
1113 indirectly by prepending newdir to nm if necessary, and using
1114 cwd (or the wd of newdir's drive) as the new newdir. */
1115 char *adir;
1116 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1118 drive = (unsigned char) newdir[0];
1119 newdir += 2;
1121 if (!IS_DIRECTORY_SEP (nm[0]))
1123 ptrdiff_t newlen = strlen (newdir);
1124 char *tmp = alloca (newlen + strlen (nm) + 2);
1125 file_name_as_directory (tmp, newdir, newlen);
1126 strcat (tmp, nm);
1127 nm = tmp;
1129 adir = alloca (MAXPATHLEN + 1);
1130 if (drive)
1132 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1133 newdir = "/";
1135 else
1136 getwd (adir);
1137 newdir = adir;
1140 /* Strip off drive name from prefix, if present. */
1141 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1143 drive = newdir[0];
1144 newdir += 2;
1147 /* Keep only a prefix from newdir if nm starts with slash
1148 (//server/share for UNC, nothing otherwise). */
1149 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1151 #ifdef WINDOWSNT
1152 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1154 char *adir = strcpy (alloca (strlen (newdir) + 1), newdir);
1155 char *p = adir + 2;
1156 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1157 p++;
1158 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1159 *p = 0;
1160 newdir = adir;
1162 else
1163 #endif
1164 newdir = "";
1167 #endif /* DOS_NT */
1169 if (newdir)
1171 /* Get rid of any slash at the end of newdir, unless newdir is
1172 just / or // (an incomplete UNC name). */
1173 length = strlen (newdir);
1174 tlen = length + 1;
1175 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1176 #ifdef WINDOWSNT
1177 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1178 #endif
1181 char *temp = alloca (length);
1182 memcpy (temp, newdir, length - 1);
1183 temp[length - 1] = 0;
1184 length--;
1185 newdir = temp;
1188 else
1190 length = 0;
1191 tlen = 0;
1194 /* Now concatenate the directory and name to new space in the stack frame. */
1195 tlen += strlen (nm) + 1;
1196 #ifdef DOS_NT
1197 /* Reserve space for drive specifier and escape prefix, since either
1198 or both may need to be inserted. (The Microsoft x86 compiler
1199 produces incorrect code if the following two lines are combined.) */
1200 target = alloca (tlen + 4);
1201 target += 4;
1202 #else /* not DOS_NT */
1203 target = alloca (tlen);
1204 #endif /* not DOS_NT */
1205 *target = 0;
1207 if (newdir)
1209 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1211 #ifdef DOS_NT
1212 /* If newdir is effectively "C:/", then the drive letter will have
1213 been stripped and newdir will be "/". Concatenating with an
1214 absolute directory in nm produces "//", which will then be
1215 incorrectly treated as a network share. Ignore newdir in
1216 this case (keeping the drive letter). */
1217 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1218 && newdir[1] == '\0'))
1219 #endif
1220 strcpy (target, newdir);
1222 else
1223 file_name_as_directory (target, newdir, length);
1226 strcat (target, nm);
1228 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1229 appear. */
1231 char *p = target;
1232 char *o = target;
1234 while (*p)
1236 if (!IS_DIRECTORY_SEP (*p))
1238 *o++ = *p++;
1240 else if (p[1] == '.'
1241 && (IS_DIRECTORY_SEP (p[2])
1242 || p[2] == 0))
1244 /* If "/." is the entire filename, keep the "/". Otherwise,
1245 just delete the whole "/.". */
1246 if (o == target && p[2] == '\0')
1247 *o++ = *p;
1248 p += 2;
1250 else if (p[1] == '.' && p[2] == '.'
1251 /* `/../' is the "superroot" on certain file systems.
1252 Turned off on DOS_NT systems because they have no
1253 "superroot" and because this causes us to produce
1254 file names like "d:/../foo" which fail file-related
1255 functions of the underlying OS. (To reproduce, try a
1256 long series of "../../" in default_directory, longer
1257 than the number of levels from the root.) */
1258 #ifndef DOS_NT
1259 && o != target
1260 #endif
1261 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1263 #ifdef WINDOWSNT
1264 char *prev_o = o;
1265 #endif
1266 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1268 #ifdef WINDOWSNT
1269 /* Don't go below server level in UNC filenames. */
1270 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1271 && IS_DIRECTORY_SEP (*target))
1272 o = prev_o;
1273 else
1274 #endif
1275 /* Keep initial / only if this is the whole name. */
1276 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1277 ++o;
1278 p += 3;
1280 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1281 /* Collapse multiple `/' in a row. */
1282 p++;
1283 else
1285 *o++ = *p++;
1289 #ifdef DOS_NT
1290 /* At last, set drive name. */
1291 #ifdef WINDOWSNT
1292 /* Except for network file name. */
1293 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1294 #endif /* WINDOWSNT */
1296 if (!drive) emacs_abort ();
1297 target -= 2;
1298 target[0] = DRIVE_LETTER (drive);
1299 target[1] = ':';
1301 /* Reinsert the escape prefix if required. */
1302 if (is_escaped)
1304 target -= 2;
1305 target[0] = '/';
1306 target[1] = ':';
1308 dostounix_filename (target);
1309 #endif /* DOS_NT */
1311 result = make_specified_string (target, -1, o - target, multibyte);
1314 /* Again look to see if the file name has special constructs in it
1315 and perhaps call the corresponding file handler. This is needed
1316 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1317 the ".." component gives us "/user@host:/bar/../baz" which needs
1318 to be expanded again. */
1319 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1320 if (!NILP (handler))
1322 handled_name = call3 (handler, Qexpand_file_name,
1323 result, default_directory);
1324 if (STRINGP (handled_name))
1325 return handled_name;
1326 error ("Invalid handler in `file-name-handler-alist'");
1329 return result;
1332 #if 0
1333 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1334 This is the old version of expand-file-name, before it was thoroughly
1335 rewritten for Emacs 10.31. We leave this version here commented-out,
1336 because the code is very complex and likely to have subtle bugs. If
1337 bugs _are_ found, it might be of interest to look at the old code and
1338 see what did it do in the relevant situation.
1340 Don't remove this code: it's true that it will be accessible
1341 from the repository, but a few years from deletion, people will
1342 forget it is there. */
1344 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1345 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1346 "Convert FILENAME to absolute, and canonicalize it.\n\
1347 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1348 \(does not start with slash); if DEFAULT is nil or missing,\n\
1349 the current buffer's value of default-directory is used.\n\
1350 Filenames containing `.' or `..' as components are simplified;\n\
1351 initial `~/' expands to your home directory.\n\
1352 See also the function `substitute-in-file-name'.")
1353 (name, defalt)
1354 Lisp_Object name, defalt;
1356 unsigned char *nm;
1358 register unsigned char *newdir, *p, *o;
1359 ptrdiff_t tlen;
1360 unsigned char *target;
1361 struct passwd *pw;
1363 CHECK_STRING (name);
1364 nm = SDATA (name);
1366 /* If nm is absolute, flush ...// and detect /./ and /../.
1367 If no /./ or /../ we can return right away. */
1368 if (nm[0] == '/')
1370 bool lose = 0;
1371 p = nm;
1372 while (*p)
1374 if (p[0] == '/' && p[1] == '/')
1375 nm = p + 1;
1376 if (p[0] == '/' && p[1] == '~')
1377 nm = p + 1, lose = 1;
1378 if (p[0] == '/' && p[1] == '.'
1379 && (p[2] == '/' || p[2] == 0
1380 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1381 lose = 1;
1382 p++;
1384 if (!lose)
1386 if (nm == SDATA (name))
1387 return name;
1388 return build_string (nm);
1392 /* Now determine directory to start with and put it in NEWDIR. */
1394 newdir = 0;
1396 if (nm[0] == '~') /* prefix ~ */
1397 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1399 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1400 newdir = (unsigned char *) "";
1401 nm++;
1403 else /* ~user/filename */
1405 /* Get past ~ to user. */
1406 unsigned char *user = nm + 1;
1407 /* Find end of name. */
1408 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1409 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1410 /* Copy the user name into temp storage. */
1411 o = alloca (len + 1);
1412 memcpy (o, user, len);
1413 o[len] = 0;
1415 /* Look up the user name. */
1416 block_input ();
1417 pw = (struct passwd *) getpwnam (o + 1);
1418 unblock_input ();
1419 if (!pw)
1420 error ("\"%s\" isn't a registered user", o + 1);
1422 newdir = (unsigned char *) pw->pw_dir;
1424 /* Discard the user name from NM. */
1425 nm += len;
1428 if (nm[0] != '/' && !newdir)
1430 if (NILP (defalt))
1431 defalt = current_buffer->directory;
1432 CHECK_STRING (defalt);
1433 newdir = SDATA (defalt);
1436 /* Now concatenate the directory and name to new space in the stack frame. */
1438 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1439 target = alloca (tlen);
1440 *target = 0;
1442 if (newdir)
1444 if (nm[0] == 0 || nm[0] == '/')
1445 strcpy (target, newdir);
1446 else
1447 file_name_as_directory (target, newdir);
1450 strcat (target, nm);
1452 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1454 p = target;
1455 o = target;
1457 while (*p)
1459 if (*p != '/')
1461 *o++ = *p++;
1463 else if (!strncmp (p, "//", 2)
1466 o = target;
1467 p++;
1469 else if (p[0] == '/' && p[1] == '.'
1470 && (p[2] == '/' || p[2] == 0))
1471 p += 2;
1472 else if (!strncmp (p, "/..", 3)
1473 /* `/../' is the "superroot" on certain file systems. */
1474 && o != target
1475 && (p[3] == '/' || p[3] == 0))
1477 while (o != target && *--o != '/')
1479 if (o == target && *o == '/')
1480 ++o;
1481 p += 3;
1483 else
1485 *o++ = *p++;
1489 return make_string (target, o - target);
1491 #endif
1493 /* If /~ or // appears, discard everything through first slash. */
1494 static bool
1495 file_name_absolute_p (const char *filename)
1497 return
1498 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1499 #ifdef DOS_NT
1500 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1501 && IS_DIRECTORY_SEP (filename[2]))
1502 #endif
1506 static char *
1507 search_embedded_absfilename (char *nm, char *endp)
1509 char *p, *s;
1511 for (p = nm + 1; p < endp; p++)
1513 if (IS_DIRECTORY_SEP (p[-1])
1514 && file_name_absolute_p (p)
1515 #if defined (WINDOWSNT) || defined (CYGWIN)
1516 /* // at start of file name is meaningful in Apollo,
1517 WindowsNT and Cygwin systems. */
1518 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1519 #endif /* not (WINDOWSNT || CYGWIN) */
1522 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1523 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1525 char *o = alloca (s - p + 1);
1526 struct passwd *pw;
1527 memcpy (o, p, s - p);
1528 o [s - p] = 0;
1530 /* If we have ~user and `user' exists, discard
1531 everything up to ~. But if `user' does not exist, leave
1532 ~user alone, it might be a literal file name. */
1533 block_input ();
1534 pw = getpwnam (o + 1);
1535 unblock_input ();
1536 if (pw)
1537 return p;
1539 else
1540 return p;
1543 return NULL;
1546 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1547 Ssubstitute_in_file_name, 1, 1, 0,
1548 doc: /* Substitute environment variables referred to in FILENAME.
1549 `$FOO' where FOO is an environment variable name means to substitute
1550 the value of that variable. The variable name should be terminated
1551 with a character not a letter, digit or underscore; otherwise, enclose
1552 the entire variable name in braces.
1554 If `/~' appears, all of FILENAME through that `/' is discarded.
1555 If `//' appears, everything up to and including the first of
1556 those `/' is discarded. */)
1557 (Lisp_Object filename)
1559 char *nm, *s, *p, *o, *x, *endp;
1560 char *target = NULL;
1561 int total = 0;
1562 bool substituted = 0;
1563 bool multibyte;
1564 char *xnm;
1565 Lisp_Object handler;
1567 CHECK_STRING (filename);
1569 multibyte = STRING_MULTIBYTE (filename);
1571 /* If the file name has special constructs in it,
1572 call the corresponding file handler. */
1573 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1574 if (!NILP (handler))
1576 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1577 filename);
1578 if (STRINGP (handled_name))
1579 return handled_name;
1580 error ("Invalid handler in `file-name-handler-alist'");
1583 /* Always work on a copy of the string, in case GC happens during
1584 decode of environment variables, causing the original Lisp_String
1585 data to be relocated. */
1586 nm = alloca (SBYTES (filename) + 1);
1587 memcpy (nm, SDATA (filename), SBYTES (filename) + 1);
1589 #ifdef DOS_NT
1590 dostounix_filename (nm);
1591 substituted = (strcmp (nm, SDATA (filename)) != 0);
1592 #endif
1593 endp = nm + SBYTES (filename);
1595 /* If /~ or // appears, discard everything through first slash. */
1596 p = search_embedded_absfilename (nm, endp);
1597 if (p)
1598 /* Start over with the new string, so we check the file-name-handler
1599 again. Important with filenames like "/home/foo//:/hello///there"
1600 which would substitute to "/:/hello///there" rather than "/there". */
1601 return Fsubstitute_in_file_name
1602 (make_specified_string (p, -1, endp - p, multibyte));
1604 /* See if any variables are substituted into the string
1605 and find the total length of their values in `total'. */
1607 for (p = nm; p != endp;)
1608 if (*p != '$')
1609 p++;
1610 else
1612 p++;
1613 if (p == endp)
1614 goto badsubst;
1615 else if (*p == '$')
1617 /* "$$" means a single "$". */
1618 p++;
1619 total -= 1;
1620 substituted = 1;
1621 continue;
1623 else if (*p == '{')
1625 o = ++p;
1626 while (p != endp && *p != '}') p++;
1627 if (*p != '}') goto missingclose;
1628 s = p;
1630 else
1632 o = p;
1633 while (p != endp && (c_isalnum (*p) || *p == '_')) p++;
1634 s = p;
1637 /* Copy out the variable name. */
1638 target = alloca (s - o + 1);
1639 memcpy (target, o, s - o);
1640 target[s - o] = 0;
1641 #ifdef DOS_NT
1642 strupr (target); /* $home == $HOME etc. */
1643 #endif /* DOS_NT */
1645 /* Get variable value. */
1646 o = egetenv (target);
1647 if (o)
1649 /* Don't try to guess a maximum length - UTF8 can use up to
1650 four bytes per character. This code is unlikely to run
1651 in a situation that requires performance, so decoding the
1652 env variables twice should be acceptable. Note that
1653 decoding may cause a garbage collect. */
1654 Lisp_Object orig, decoded;
1655 orig = build_unibyte_string (o);
1656 decoded = DECODE_FILE (orig);
1657 total += SBYTES (decoded);
1658 substituted = 1;
1660 else if (*p == '}')
1661 goto badvar;
1664 if (!substituted)
1665 return filename;
1667 /* If substitution required, recopy the string and do it. */
1668 /* Make space in stack frame for the new copy. */
1669 xnm = alloca (SBYTES (filename) + total + 1);
1670 x = xnm;
1672 /* Copy the rest of the name through, replacing $ constructs with values. */
1673 for (p = nm; *p;)
1674 if (*p != '$')
1675 *x++ = *p++;
1676 else
1678 p++;
1679 if (p == endp)
1680 goto badsubst;
1681 else if (*p == '$')
1683 *x++ = *p++;
1684 continue;
1686 else if (*p == '{')
1688 o = ++p;
1689 while (p != endp && *p != '}') p++;
1690 if (*p != '}') goto missingclose;
1691 s = p++;
1693 else
1695 o = p;
1696 while (p != endp && (c_isalnum (*p) || *p == '_')) p++;
1697 s = p;
1700 /* Copy out the variable name. */
1701 target = alloca (s - o + 1);
1702 memcpy (target, o, s - o);
1703 target[s - o] = 0;
1704 #ifdef DOS_NT
1705 strupr (target); /* $home == $HOME etc. */
1706 #endif /* DOS_NT */
1708 /* Get variable value. */
1709 o = egetenv (target);
1710 if (!o)
1712 *x++ = '$';
1713 strcpy (x, target); x+= strlen (target);
1715 else
1717 Lisp_Object orig, decoded;
1718 ptrdiff_t orig_length, decoded_length;
1719 orig_length = strlen (o);
1720 orig = make_unibyte_string (o, orig_length);
1721 decoded = DECODE_FILE (orig);
1722 decoded_length = SBYTES (decoded);
1723 memcpy (x, SDATA (decoded), decoded_length);
1724 x += decoded_length;
1726 /* If environment variable needed decoding, return value
1727 needs to be multibyte. */
1728 if (decoded_length != orig_length
1729 || memcmp (SDATA (decoded), o, orig_length))
1730 multibyte = 1;
1734 *x = 0;
1736 /* If /~ or // appears, discard everything through first slash. */
1737 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1738 /* This time we do not start over because we've already expanded envvars
1739 and replaced $$ with $. Maybe we should start over as well, but we'd
1740 need to quote some $ to $$ first. */
1741 xnm = p;
1743 return make_specified_string (xnm, -1, x - xnm, multibyte);
1745 badsubst:
1746 error ("Bad format environment-variable substitution");
1747 missingclose:
1748 error ("Missing \"}\" in environment-variable substitution");
1749 badvar:
1750 error ("Substituting nonexistent environment variable \"%s\"", target);
1752 /* NOTREACHED */
1753 return Qnil;
1756 /* A slightly faster and more convenient way to get
1757 (directory-file-name (expand-file-name FOO)). */
1759 Lisp_Object
1760 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1762 register Lisp_Object absname;
1764 absname = Fexpand_file_name (filename, defdir);
1766 /* Remove final slash, if any (unless this is the root dir).
1767 stat behaves differently depending! */
1768 if (SCHARS (absname) > 1
1769 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1770 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1771 /* We cannot take shortcuts; they might be wrong for magic file names. */
1772 absname = Fdirectory_file_name (absname);
1773 return absname;
1776 /* Signal an error if the file ABSNAME already exists.
1777 If INTERACTIVE, ask the user whether to proceed,
1778 and bypass the error if the user says to go ahead.
1779 QUERYSTRING is a name for the action that is being considered
1780 to alter the file.
1782 *STATPTR is used to store the stat information if the file exists.
1783 If the file does not exist, STATPTR->st_mode is set to 0.
1784 If STATPTR is null, we don't store into it.
1786 If QUICK, ask for y or n, not yes or no. */
1788 static void
1789 barf_or_query_if_file_exists (Lisp_Object absname, const char *querystring,
1790 bool interactive, struct stat *statptr,
1791 bool quick)
1793 Lisp_Object tem, encoded_filename;
1794 struct stat statbuf;
1795 struct gcpro gcpro1;
1797 encoded_filename = ENCODE_FILE (absname);
1799 /* `stat' is a good way to tell whether the file exists,
1800 regardless of what access permissions it has. */
1801 if (lstat (SSDATA (encoded_filename), &statbuf) >= 0)
1803 if (S_ISDIR (statbuf.st_mode))
1804 xsignal2 (Qfile_error,
1805 build_string ("File is a directory"), absname);
1807 if (! interactive)
1808 xsignal2 (Qfile_already_exists,
1809 build_string ("File already exists"), absname);
1810 GCPRO1 (absname);
1811 tem = format2 ("File %s already exists; %s anyway? ",
1812 absname, build_string (querystring));
1813 if (quick)
1814 tem = call1 (intern ("y-or-n-p"), tem);
1815 else
1816 tem = do_yes_or_no_p (tem);
1817 UNGCPRO;
1818 if (NILP (tem))
1819 xsignal2 (Qfile_already_exists,
1820 build_string ("File already exists"), absname);
1821 if (statptr)
1822 *statptr = statbuf;
1824 else
1826 if (statptr)
1827 statptr->st_mode = 0;
1829 return;
1832 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1833 "fCopy file: \nGCopy %s to file: \np\nP",
1834 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1835 If NEWNAME names a directory, copy FILE there.
1837 This function always sets the file modes of the output file to match
1838 the input file.
1840 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1841 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1842 signal a `file-already-exists' error without overwriting. If
1843 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1844 about overwriting; this is what happens in interactive use with M-x.
1845 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1846 existing file.
1848 Fourth arg KEEP-TIME non-nil means give the output file the same
1849 last-modified time as the old one. (This works on only some systems.)
1851 A prefix arg makes KEEP-TIME non-nil.
1853 If PRESERVE-UID-GID is non-nil, we try to transfer the
1854 uid and gid of FILE to NEWNAME.
1856 If PRESERVE-SELINUX-CONTEXT is non-nil and SELinux is enabled
1857 on the system, we copy the SELinux context of FILE to NEWNAME. */)
1858 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists, Lisp_Object keep_time, Lisp_Object preserve_uid_gid, Lisp_Object preserve_selinux_context)
1860 int ifd, ofd;
1861 int n;
1862 char buf[16 * 1024];
1863 struct stat st, out_st;
1864 Lisp_Object handler;
1865 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1866 ptrdiff_t count = SPECPDL_INDEX ();
1867 bool input_file_statable_p;
1868 Lisp_Object encoded_file, encoded_newname;
1869 #if HAVE_LIBSELINUX
1870 security_context_t con;
1871 int conlength = 0;
1872 #endif
1874 encoded_file = encoded_newname = Qnil;
1875 GCPRO4 (file, newname, encoded_file, encoded_newname);
1876 CHECK_STRING (file);
1877 CHECK_STRING (newname);
1879 if (!NILP (Ffile_directory_p (newname)))
1880 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1881 else
1882 newname = Fexpand_file_name (newname, Qnil);
1884 file = Fexpand_file_name (file, Qnil);
1886 /* If the input file name has special constructs in it,
1887 call the corresponding file handler. */
1888 handler = Ffind_file_name_handler (file, Qcopy_file);
1889 /* Likewise for output file name. */
1890 if (NILP (handler))
1891 handler = Ffind_file_name_handler (newname, Qcopy_file);
1892 if (!NILP (handler))
1893 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1894 ok_if_already_exists, keep_time, preserve_uid_gid,
1895 preserve_selinux_context));
1897 encoded_file = ENCODE_FILE (file);
1898 encoded_newname = ENCODE_FILE (newname);
1900 if (NILP (ok_if_already_exists)
1901 || INTEGERP (ok_if_already_exists))
1902 barf_or_query_if_file_exists (newname, "copy to it",
1903 INTEGERP (ok_if_already_exists), &out_st, 0);
1904 else if (stat (SSDATA (encoded_newname), &out_st) < 0)
1905 out_st.st_mode = 0;
1907 #ifdef WINDOWSNT
1908 if (!CopyFile (SDATA (encoded_file),
1909 SDATA (encoded_newname),
1910 FALSE))
1911 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
1912 /* CopyFile retains the timestamp by default. */
1913 else if (NILP (keep_time))
1915 EMACS_TIME now;
1916 DWORD attributes;
1917 char * filename;
1919 filename = SDATA (encoded_newname);
1921 /* Ensure file is writable while its modified time is set. */
1922 attributes = GetFileAttributes (filename);
1923 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
1924 now = current_emacs_time ();
1925 if (set_file_times (-1, filename, now, now))
1927 /* Restore original attributes. */
1928 SetFileAttributes (filename, attributes);
1929 xsignal2 (Qfile_date_error,
1930 build_string ("Cannot set file date"), newname);
1932 /* Restore original attributes. */
1933 SetFileAttributes (filename, attributes);
1935 #else /* not WINDOWSNT */
1936 immediate_quit = 1;
1937 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1938 immediate_quit = 0;
1940 if (ifd < 0)
1941 report_file_error ("Opening input file", Fcons (file, Qnil));
1943 record_unwind_protect (close_file_unwind, make_number (ifd));
1945 /* We can only copy regular files and symbolic links. Other files are not
1946 copyable by us. */
1947 input_file_statable_p = (fstat (ifd, &st) >= 0);
1949 #if HAVE_LIBSELINUX
1950 if (!NILP (preserve_selinux_context) && is_selinux_enabled ())
1952 conlength = fgetfilecon (ifd, &con);
1953 if (conlength == -1)
1954 report_file_error ("Doing fgetfilecon", Fcons (file, Qnil));
1956 #endif
1958 if (out_st.st_mode != 0
1959 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1961 errno = 0;
1962 report_file_error ("Input and output files are the same",
1963 Fcons (file, Fcons (newname, Qnil)));
1966 if (input_file_statable_p)
1968 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
1970 #if defined (EISDIR)
1971 /* Get a better looking error message. */
1972 errno = EISDIR;
1973 #endif /* EISDIR */
1974 report_file_error ("Non-regular file", Fcons (file, Qnil));
1978 #ifdef MSDOS
1979 /* System's default file type was set to binary by _fmode in emacs.c. */
1980 ofd = emacs_open (SDATA (encoded_newname),
1981 O_WRONLY | O_TRUNC | O_CREAT
1982 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
1983 S_IREAD | S_IWRITE);
1984 #else /* not MSDOS */
1986 mode_t new_mask = 0666;
1987 if (input_file_statable_p)
1989 if (!NILP (preserve_uid_gid))
1990 new_mask = 0600;
1991 new_mask &= st.st_mode;
1993 ofd = emacs_open (SSDATA (encoded_newname),
1994 (O_WRONLY | O_TRUNC | O_CREAT
1995 | (NILP (ok_if_already_exists) ? O_EXCL : 0)),
1996 new_mask);
1998 #endif /* not MSDOS */
1999 if (ofd < 0)
2000 report_file_error ("Opening output file", Fcons (newname, Qnil));
2002 record_unwind_protect (close_file_unwind, make_number (ofd));
2004 immediate_quit = 1;
2005 QUIT;
2006 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2007 if (emacs_write (ofd, buf, n) != n)
2008 report_file_error ("I/O error", Fcons (newname, Qnil));
2009 immediate_quit = 0;
2011 #ifndef MSDOS
2012 /* Preserve the original file modes, and if requested, also its
2013 owner and group. */
2014 if (input_file_statable_p)
2016 mode_t mode_mask = 07777;
2017 if (!NILP (preserve_uid_gid))
2019 /* Attempt to change owner and group. If that doesn't work
2020 attempt to change just the group, as that is sometimes allowed.
2021 Adjust the mode mask to eliminate setuid or setgid bits
2022 that are inappropriate if the owner and group are wrong. */
2023 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2025 mode_mask &= ~06000;
2026 if (fchown (ofd, -1, st.st_gid) == 0)
2027 mode_mask |= 02000;
2030 if (fchmod (ofd, st.st_mode & mode_mask) != 0)
2031 report_file_error ("Doing chmod", Fcons (newname, Qnil));
2033 #endif /* not MSDOS */
2035 #if HAVE_LIBSELINUX
2036 if (conlength > 0)
2038 /* Set the modified context back to the file. */
2039 bool fail = fsetfilecon (ofd, con) != 0;
2040 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2041 if (fail && errno != ENOTSUP)
2042 report_file_error ("Doing fsetfilecon", Fcons (newname, Qnil));
2044 freecon (con);
2046 #endif
2048 if (input_file_statable_p)
2050 if (!NILP (keep_time))
2052 EMACS_TIME atime = get_stat_atime (&st);
2053 EMACS_TIME mtime = get_stat_mtime (&st);
2054 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime))
2055 xsignal2 (Qfile_date_error,
2056 build_string ("Cannot set file date"), newname);
2060 if (emacs_close (ofd) < 0)
2061 report_file_error ("I/O error", Fcons (newname, Qnil));
2063 emacs_close (ifd);
2065 #ifdef MSDOS
2066 if (input_file_statable_p)
2068 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2069 and if it can't, it tells so. Otherwise, under MSDOS we usually
2070 get only the READ bit, which will make the copied file read-only,
2071 so it's better not to chmod at all. */
2072 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2073 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2075 #endif /* MSDOS */
2076 #endif /* not WINDOWSNT */
2078 /* Discard the unwind protects. */
2079 specpdl_ptr = specpdl + count;
2081 UNGCPRO;
2082 return Qnil;
2085 DEFUN ("make-directory-internal", Fmake_directory_internal,
2086 Smake_directory_internal, 1, 1, 0,
2087 doc: /* Create a new directory named DIRECTORY. */)
2088 (Lisp_Object directory)
2090 const char *dir;
2091 Lisp_Object handler;
2092 Lisp_Object encoded_dir;
2094 CHECK_STRING (directory);
2095 directory = Fexpand_file_name (directory, Qnil);
2097 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2098 if (!NILP (handler))
2099 return call2 (handler, Qmake_directory_internal, directory);
2101 encoded_dir = ENCODE_FILE (directory);
2103 dir = SSDATA (encoded_dir);
2105 #ifdef WINDOWSNT
2106 if (mkdir (dir) != 0)
2107 #else
2108 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2109 #endif
2110 report_file_error ("Creating directory", list1 (directory));
2112 return Qnil;
2115 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2116 Sdelete_directory_internal, 1, 1, 0,
2117 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2118 (Lisp_Object directory)
2120 const char *dir;
2121 Lisp_Object encoded_dir;
2123 CHECK_STRING (directory);
2124 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2125 encoded_dir = ENCODE_FILE (directory);
2126 dir = SSDATA (encoded_dir);
2128 if (rmdir (dir) != 0)
2129 report_file_error ("Removing directory", list1 (directory));
2131 return Qnil;
2134 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2135 "(list (read-file-name \
2136 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2137 \"Move file to trash: \" \"Delete file: \") \
2138 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2139 (null current-prefix-arg))",
2140 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2141 If file has multiple names, it continues to exist with the other names.
2142 TRASH non-nil means to trash the file instead of deleting, provided
2143 `delete-by-moving-to-trash' is non-nil.
2145 When called interactively, TRASH is t if no prefix argument is given.
2146 With a prefix argument, TRASH is nil. */)
2147 (Lisp_Object filename, Lisp_Object trash)
2149 Lisp_Object handler;
2150 Lisp_Object encoded_file;
2151 struct gcpro gcpro1;
2153 GCPRO1 (filename);
2154 if (!NILP (Ffile_directory_p (filename))
2155 && NILP (Ffile_symlink_p (filename)))
2156 xsignal2 (Qfile_error,
2157 build_string ("Removing old name: is a directory"),
2158 filename);
2159 UNGCPRO;
2160 filename = Fexpand_file_name (filename, Qnil);
2162 handler = Ffind_file_name_handler (filename, Qdelete_file);
2163 if (!NILP (handler))
2164 return call3 (handler, Qdelete_file, filename, trash);
2166 if (delete_by_moving_to_trash && !NILP (trash))
2167 return call1 (Qmove_file_to_trash, filename);
2169 encoded_file = ENCODE_FILE (filename);
2171 if (unlink (SSDATA (encoded_file)) < 0)
2172 report_file_error ("Removing old name", list1 (filename));
2173 return Qnil;
2176 static Lisp_Object
2177 internal_delete_file_1 (Lisp_Object ignore)
2179 return Qt;
2182 /* Delete file FILENAME.
2183 This ignores `delete-by-moving-to-trash'. */
2185 void
2186 internal_delete_file (Lisp_Object filename)
2188 internal_condition_case_2 (Fdelete_file, filename, Qnil,
2189 Qt, internal_delete_file_1);
2192 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2193 "fRename file: \nGRename %s to file: \np",
2194 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2195 If file has names other than FILE, it continues to have those names.
2196 Signals a `file-already-exists' error if a file NEWNAME already exists
2197 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2198 A number as third arg means request confirmation if NEWNAME already exists.
2199 This is what happens in interactive use with M-x. */)
2200 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2202 Lisp_Object handler;
2203 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2204 Lisp_Object encoded_file, encoded_newname, symlink_target;
2206 symlink_target = encoded_file = encoded_newname = Qnil;
2207 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2208 CHECK_STRING (file);
2209 CHECK_STRING (newname);
2210 file = Fexpand_file_name (file, Qnil);
2212 if ((!NILP (Ffile_directory_p (newname)))
2213 #ifdef DOS_NT
2214 /* If the file names are identical but for the case,
2215 don't attempt to move directory to itself. */
2216 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2217 #endif
2220 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2221 ? file : Fdirectory_file_name (file));
2222 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2224 else
2225 newname = Fexpand_file_name (newname, Qnil);
2227 /* If the file name has special constructs in it,
2228 call the corresponding file handler. */
2229 handler = Ffind_file_name_handler (file, Qrename_file);
2230 if (NILP (handler))
2231 handler = Ffind_file_name_handler (newname, Qrename_file);
2232 if (!NILP (handler))
2233 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2234 file, newname, ok_if_already_exists));
2236 encoded_file = ENCODE_FILE (file);
2237 encoded_newname = ENCODE_FILE (newname);
2239 #ifdef DOS_NT
2240 /* If the file names are identical but for the case, don't ask for
2241 confirmation: they simply want to change the letter-case of the
2242 file name. */
2243 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2244 #endif
2245 if (NILP (ok_if_already_exists)
2246 || INTEGERP (ok_if_already_exists))
2247 barf_or_query_if_file_exists (newname, "rename to it",
2248 INTEGERP (ok_if_already_exists), 0, 0);
2249 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2251 if (errno == EXDEV)
2253 ptrdiff_t count;
2254 symlink_target = Ffile_symlink_p (file);
2255 if (! NILP (symlink_target))
2256 Fmake_symbolic_link (symlink_target, newname,
2257 NILP (ok_if_already_exists) ? Qnil : Qt);
2258 else if (!NILP (Ffile_directory_p (file)))
2259 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2260 else
2261 /* We have already prompted if it was an integer, so don't
2262 have copy-file prompt again. */
2263 Fcopy_file (file, newname,
2264 NILP (ok_if_already_exists) ? Qnil : Qt,
2265 Qt, Qt, Qt);
2267 count = SPECPDL_INDEX ();
2268 specbind (Qdelete_by_moving_to_trash, Qnil);
2270 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2271 call2 (Qdelete_directory, file, Qt);
2272 else
2273 Fdelete_file (file, Qnil);
2274 unbind_to (count, Qnil);
2276 else
2277 report_file_error ("Renaming", list2 (file, newname));
2279 UNGCPRO;
2280 return Qnil;
2283 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2284 "fAdd name to file: \nGName to add to %s: \np",
2285 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2286 Signals a `file-already-exists' error if a file NEWNAME already exists
2287 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2288 A number as third arg means request confirmation if NEWNAME already exists.
2289 This is what happens in interactive use with M-x. */)
2290 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2292 Lisp_Object handler;
2293 Lisp_Object encoded_file, encoded_newname;
2294 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2296 GCPRO4 (file, newname, encoded_file, encoded_newname);
2297 encoded_file = encoded_newname = Qnil;
2298 CHECK_STRING (file);
2299 CHECK_STRING (newname);
2300 file = Fexpand_file_name (file, Qnil);
2302 if (!NILP (Ffile_directory_p (newname)))
2303 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2304 else
2305 newname = Fexpand_file_name (newname, Qnil);
2307 /* If the file name has special constructs in it,
2308 call the corresponding file handler. */
2309 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2310 if (!NILP (handler))
2311 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2312 newname, ok_if_already_exists));
2314 /* If the new name has special constructs in it,
2315 call the corresponding file handler. */
2316 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2317 if (!NILP (handler))
2318 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2319 newname, ok_if_already_exists));
2321 encoded_file = ENCODE_FILE (file);
2322 encoded_newname = ENCODE_FILE (newname);
2324 if (NILP (ok_if_already_exists)
2325 || INTEGERP (ok_if_already_exists))
2326 barf_or_query_if_file_exists (newname, "make it a new name",
2327 INTEGERP (ok_if_already_exists), 0, 0);
2329 unlink (SSDATA (newname));
2330 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2331 report_file_error ("Adding new name", list2 (file, newname));
2333 UNGCPRO;
2334 return Qnil;
2337 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2338 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2339 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2340 Both args must be strings.
2341 Signals a `file-already-exists' error if a file LINKNAME already exists
2342 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2343 A number as third arg means request confirmation if LINKNAME already exists.
2344 This happens for interactive use with M-x. */)
2345 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2347 Lisp_Object handler;
2348 Lisp_Object encoded_filename, encoded_linkname;
2349 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2351 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2352 encoded_filename = encoded_linkname = Qnil;
2353 CHECK_STRING (filename);
2354 CHECK_STRING (linkname);
2355 /* If the link target has a ~, we must expand it to get
2356 a truly valid file name. Otherwise, do not expand;
2357 we want to permit links to relative file names. */
2358 if (SREF (filename, 0) == '~')
2359 filename = Fexpand_file_name (filename, Qnil);
2361 if (!NILP (Ffile_directory_p (linkname)))
2362 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2363 else
2364 linkname = Fexpand_file_name (linkname, Qnil);
2366 /* If the file name has special constructs in it,
2367 call the corresponding file handler. */
2368 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2369 if (!NILP (handler))
2370 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2371 linkname, ok_if_already_exists));
2373 /* If the new link name has special constructs in it,
2374 call the corresponding file handler. */
2375 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2376 if (!NILP (handler))
2377 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2378 linkname, ok_if_already_exists));
2380 encoded_filename = ENCODE_FILE (filename);
2381 encoded_linkname = ENCODE_FILE (linkname);
2383 if (NILP (ok_if_already_exists)
2384 || INTEGERP (ok_if_already_exists))
2385 barf_or_query_if_file_exists (linkname, "make it a link",
2386 INTEGERP (ok_if_already_exists), 0, 0);
2387 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname)) < 0)
2389 /* If we didn't complain already, silently delete existing file. */
2390 if (errno == EEXIST)
2392 unlink (SSDATA (encoded_linkname));
2393 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname))
2394 >= 0)
2396 UNGCPRO;
2397 return Qnil;
2400 if (errno == ENOSYS)
2402 UNGCPRO;
2403 xsignal1 (Qfile_error,
2404 build_string ("Symbolic links are not supported"));
2407 report_file_error ("Making symbolic link", list2 (filename, linkname));
2409 UNGCPRO;
2410 return Qnil;
2414 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2415 1, 1, 0,
2416 doc: /* Return t if file FILENAME specifies an absolute file name.
2417 On Unix, this is a name starting with a `/' or a `~'. */)
2418 (Lisp_Object filename)
2420 CHECK_STRING (filename);
2421 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2424 /* Return true if FILENAME exists. */
2425 bool
2426 check_existing (const char *filename)
2428 #ifdef DOS_NT
2429 /* The full emulation of Posix 'stat' is too expensive on
2430 DOS/Windows, when all we want to know is whether the file exists.
2431 So we use 'access' instead, which is much more lightweight. */
2432 return (access (filename, F_OK) >= 0);
2433 #else
2434 struct stat st;
2435 return (stat (filename, &st) >= 0);
2436 #endif
2439 /* Return true if file FILENAME exists and can be executed. */
2441 static bool
2442 check_executable (char *filename)
2444 #ifdef DOS_NT
2445 struct stat st;
2446 if (stat (filename, &st) < 0)
2447 return 0;
2448 return ((st.st_mode & S_IEXEC) != 0);
2449 #else /* not DOS_NT */
2450 #ifdef HAVE_EUIDACCESS
2451 return (euidaccess (filename, 1) >= 0);
2452 #else
2453 /* Access isn't quite right because it uses the real uid
2454 and we really want to test with the effective uid.
2455 But Unix doesn't give us a right way to do it. */
2456 return (access (filename, 1) >= 0);
2457 #endif
2458 #endif /* not DOS_NT */
2461 /* Return true if file FILENAME exists and can be written. */
2463 static bool
2464 check_writable (const char *filename)
2466 #ifdef MSDOS
2467 struct stat st;
2468 if (stat (filename, &st) < 0)
2469 return 0;
2470 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
2471 #else /* not MSDOS */
2472 #ifdef HAVE_EUIDACCESS
2473 bool res = (euidaccess (filename, 2) >= 0);
2474 #ifdef CYGWIN
2475 /* euidaccess may have returned failure because Cygwin couldn't
2476 determine the file's UID or GID; if so, we return success. */
2477 if (!res)
2479 struct stat st;
2480 if (stat (filename, &st) < 0)
2481 return 0;
2482 res = (st.st_uid == -1 || st.st_gid == -1);
2484 #endif /* CYGWIN */
2485 return res;
2486 #else /* not HAVE_EUIDACCESS */
2487 /* Access isn't quite right because it uses the real uid
2488 and we really want to test with the effective uid.
2489 But Unix doesn't give us a right way to do it.
2490 Opening with O_WRONLY could work for an ordinary file,
2491 but would lose for directories. */
2492 return (access (filename, 2) >= 0);
2493 #endif /* not HAVE_EUIDACCESS */
2494 #endif /* not MSDOS */
2497 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2498 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2499 See also `file-readable-p' and `file-attributes'.
2500 This returns nil for a symlink to a nonexistent file.
2501 Use `file-symlink-p' to test for such links. */)
2502 (Lisp_Object filename)
2504 Lisp_Object absname;
2505 Lisp_Object handler;
2507 CHECK_STRING (filename);
2508 absname = Fexpand_file_name (filename, Qnil);
2510 /* If the file name has special constructs in it,
2511 call the corresponding file handler. */
2512 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2513 if (!NILP (handler))
2514 return call2 (handler, Qfile_exists_p, absname);
2516 absname = ENCODE_FILE (absname);
2518 return (check_existing (SSDATA (absname))) ? Qt : Qnil;
2521 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2522 doc: /* Return t if FILENAME can be executed by you.
2523 For a directory, this means you can access files in that directory. */)
2524 (Lisp_Object filename)
2526 Lisp_Object absname;
2527 Lisp_Object handler;
2529 CHECK_STRING (filename);
2530 absname = Fexpand_file_name (filename, Qnil);
2532 /* If the file name has special constructs in it,
2533 call the corresponding file handler. */
2534 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2535 if (!NILP (handler))
2536 return call2 (handler, Qfile_executable_p, absname);
2538 absname = ENCODE_FILE (absname);
2540 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2543 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2544 doc: /* Return t if file FILENAME exists and you can read it.
2545 See also `file-exists-p' and `file-attributes'. */)
2546 (Lisp_Object filename)
2548 Lisp_Object absname;
2549 Lisp_Object handler;
2550 int desc;
2551 int flags;
2552 struct stat statbuf;
2554 CHECK_STRING (filename);
2555 absname = Fexpand_file_name (filename, Qnil);
2557 /* If the file name has special constructs in it,
2558 call the corresponding file handler. */
2559 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2560 if (!NILP (handler))
2561 return call2 (handler, Qfile_readable_p, absname);
2563 absname = ENCODE_FILE (absname);
2565 #if defined (DOS_NT) || defined (macintosh)
2566 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2567 directories. */
2568 if (access (SDATA (absname), 0) == 0)
2569 return Qt;
2570 return Qnil;
2571 #else /* not DOS_NT and not macintosh */
2572 flags = O_RDONLY;
2573 #ifdef O_NONBLOCK
2574 /* Opening a fifo without O_NONBLOCK can wait.
2575 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2576 except in the case of a fifo, on a system which handles it. */
2577 desc = stat (SSDATA (absname), &statbuf);
2578 if (desc < 0)
2579 return Qnil;
2580 if (S_ISFIFO (statbuf.st_mode))
2581 flags |= O_NONBLOCK;
2582 #endif
2583 desc = emacs_open (SSDATA (absname), flags, 0);
2584 if (desc < 0)
2585 return Qnil;
2586 emacs_close (desc);
2587 return Qt;
2588 #endif /* not DOS_NT and not macintosh */
2591 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2592 on the RT/PC. */
2593 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2594 doc: /* Return t if file FILENAME can be written or created by you. */)
2595 (Lisp_Object filename)
2597 Lisp_Object absname, dir, encoded;
2598 Lisp_Object handler;
2600 CHECK_STRING (filename);
2601 absname = Fexpand_file_name (filename, Qnil);
2603 /* If the file name has special constructs in it,
2604 call the corresponding file handler. */
2605 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2606 if (!NILP (handler))
2607 return call2 (handler, Qfile_writable_p, absname);
2609 encoded = ENCODE_FILE (absname);
2610 if (check_existing (SSDATA (encoded)))
2611 return (check_writable (SSDATA (encoded))
2612 ? Qt : Qnil);
2614 dir = Ffile_name_directory (absname);
2615 #ifdef MSDOS
2616 if (!NILP (dir))
2617 dir = Fdirectory_file_name (dir);
2618 #endif /* MSDOS */
2620 dir = ENCODE_FILE (dir);
2621 #ifdef WINDOWSNT
2622 /* The read-only attribute of the parent directory doesn't affect
2623 whether a file or directory can be created within it. Some day we
2624 should check ACLs though, which do affect this. */
2625 return (access (SDATA (dir), D_OK) < 0) ? Qnil : Qt;
2626 #else
2627 return (check_writable (!NILP (dir) ? SSDATA (dir) : "")
2628 ? Qt : Qnil);
2629 #endif
2632 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2633 doc: /* Access file FILENAME, and get an error if that does not work.
2634 The second argument STRING is used in the error message.
2635 If there is no error, returns nil. */)
2636 (Lisp_Object filename, Lisp_Object string)
2638 Lisp_Object handler, encoded_filename, absname;
2639 int fd;
2641 CHECK_STRING (filename);
2642 absname = Fexpand_file_name (filename, Qnil);
2644 CHECK_STRING (string);
2646 /* If the file name has special constructs in it,
2647 call the corresponding file handler. */
2648 handler = Ffind_file_name_handler (absname, Qaccess_file);
2649 if (!NILP (handler))
2650 return call3 (handler, Qaccess_file, absname, string);
2652 encoded_filename = ENCODE_FILE (absname);
2654 fd = emacs_open (SSDATA (encoded_filename), O_RDONLY, 0);
2655 if (fd < 0)
2656 report_file_error (SSDATA (string), Fcons (filename, Qnil));
2657 emacs_close (fd);
2659 return Qnil;
2662 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2663 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2664 The value is the link target, as a string.
2665 Otherwise it returns nil.
2667 This function returns t when given the name of a symlink that
2668 points to a nonexistent file. */)
2669 (Lisp_Object filename)
2671 Lisp_Object handler;
2672 char *buf;
2673 Lisp_Object val;
2674 char readlink_buf[READLINK_BUFSIZE];
2676 CHECK_STRING (filename);
2677 filename = Fexpand_file_name (filename, Qnil);
2679 /* If the file name has special constructs in it,
2680 call the corresponding file handler. */
2681 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2682 if (!NILP (handler))
2683 return call2 (handler, Qfile_symlink_p, filename);
2685 filename = ENCODE_FILE (filename);
2687 buf = emacs_readlink (SSDATA (filename), readlink_buf);
2688 if (! buf)
2689 return Qnil;
2691 val = build_string (buf);
2692 if (buf[0] == '/' && strchr (buf, ':'))
2693 val = concat2 (build_string ("/:"), val);
2694 if (buf != readlink_buf)
2695 xfree (buf);
2696 val = DECODE_FILE (val);
2697 return val;
2700 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2701 doc: /* Return t if FILENAME names an existing directory.
2702 Symbolic links to directories count as directories.
2703 See `file-symlink-p' to distinguish symlinks. */)
2704 (Lisp_Object filename)
2706 register Lisp_Object absname;
2707 struct stat st;
2708 Lisp_Object handler;
2710 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2712 /* If the file name has special constructs in it,
2713 call the corresponding file handler. */
2714 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2715 if (!NILP (handler))
2716 return call2 (handler, Qfile_directory_p, absname);
2718 absname = ENCODE_FILE (absname);
2720 if (stat (SSDATA (absname), &st) < 0)
2721 return Qnil;
2722 return S_ISDIR (st.st_mode) ? Qt : Qnil;
2725 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2726 Sfile_accessible_directory_p, 1, 1, 0,
2727 doc: /* Return t if file FILENAME names a directory you can open.
2728 For the value to be t, FILENAME must specify the name of a directory as a file,
2729 and the directory must allow you to open files in it. In order to use a
2730 directory as a buffer's current directory, this predicate must return true.
2731 A directory name spec may be given instead; then the value is t
2732 if the directory so specified exists and really is a readable and
2733 searchable directory. */)
2734 (Lisp_Object filename)
2736 Lisp_Object handler;
2737 bool tem;
2738 struct gcpro gcpro1;
2740 /* If the file name has special constructs in it,
2741 call the corresponding file handler. */
2742 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
2743 if (!NILP (handler))
2744 return call2 (handler, Qfile_accessible_directory_p, filename);
2746 GCPRO1 (filename);
2747 tem = (NILP (Ffile_directory_p (filename))
2748 || NILP (Ffile_executable_p (filename)));
2749 UNGCPRO;
2750 return tem ? Qnil : Qt;
2753 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2754 doc: /* Return t if FILENAME names a regular file.
2755 This is the sort of file that holds an ordinary stream of data bytes.
2756 Symbolic links to regular files count as regular files.
2757 See `file-symlink-p' to distinguish symlinks. */)
2758 (Lisp_Object filename)
2760 register Lisp_Object absname;
2761 struct stat st;
2762 Lisp_Object handler;
2764 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2766 /* If the file name has special constructs in it,
2767 call the corresponding file handler. */
2768 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2769 if (!NILP (handler))
2770 return call2 (handler, Qfile_regular_p, absname);
2772 absname = ENCODE_FILE (absname);
2774 #ifdef WINDOWSNT
2776 int result;
2777 Lisp_Object tem = Vw32_get_true_file_attributes;
2779 /* Tell stat to use expensive method to get accurate info. */
2780 Vw32_get_true_file_attributes = Qt;
2781 result = stat (SDATA (absname), &st);
2782 Vw32_get_true_file_attributes = tem;
2784 if (result < 0)
2785 return Qnil;
2786 return S_ISREG (st.st_mode) ? Qt : Qnil;
2788 #else
2789 if (stat (SSDATA (absname), &st) < 0)
2790 return Qnil;
2791 return S_ISREG (st.st_mode) ? Qt : Qnil;
2792 #endif
2795 DEFUN ("file-selinux-context", Ffile_selinux_context,
2796 Sfile_selinux_context, 1, 1, 0,
2797 doc: /* Return SELinux context of file named FILENAME.
2798 The return value is a list (USER ROLE TYPE RANGE), where the list
2799 elements are strings naming the user, role, type, and range of the
2800 file's SELinux security context.
2802 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2803 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2804 (Lisp_Object filename)
2806 Lisp_Object absname;
2807 Lisp_Object values[4];
2808 Lisp_Object handler;
2809 #if HAVE_LIBSELINUX
2810 security_context_t con;
2811 int conlength;
2812 context_t context;
2813 #endif
2815 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2817 /* If the file name has special constructs in it,
2818 call the corresponding file handler. */
2819 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2820 if (!NILP (handler))
2821 return call2 (handler, Qfile_selinux_context, absname);
2823 absname = ENCODE_FILE (absname);
2825 values[0] = Qnil;
2826 values[1] = Qnil;
2827 values[2] = Qnil;
2828 values[3] = Qnil;
2829 #if HAVE_LIBSELINUX
2830 if (is_selinux_enabled ())
2832 conlength = lgetfilecon (SSDATA (absname), &con);
2833 if (conlength > 0)
2835 context = context_new (con);
2836 if (context_user_get (context))
2837 values[0] = build_string (context_user_get (context));
2838 if (context_role_get (context))
2839 values[1] = build_string (context_role_get (context));
2840 if (context_type_get (context))
2841 values[2] = build_string (context_type_get (context));
2842 if (context_range_get (context))
2843 values[3] = build_string (context_range_get (context));
2844 context_free (context);
2845 freecon (con);
2848 #endif
2850 return Flist (sizeof (values) / sizeof (values[0]), values);
2853 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2854 Sset_file_selinux_context, 2, 2, 0,
2855 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2856 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2857 elements are strings naming the components of a SELinux context.
2859 This function does nothing if SELinux is disabled, or if Emacs was not
2860 compiled with SELinux support. */)
2861 (Lisp_Object filename, Lisp_Object context)
2863 Lisp_Object absname;
2864 Lisp_Object handler;
2865 #if HAVE_LIBSELINUX
2866 Lisp_Object encoded_absname;
2867 Lisp_Object user = CAR_SAFE (context);
2868 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2869 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2870 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2871 security_context_t con;
2872 bool fail;
2873 int conlength;
2874 context_t parsed_con;
2875 #endif
2877 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2879 /* If the file name has special constructs in it,
2880 call the corresponding file handler. */
2881 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2882 if (!NILP (handler))
2883 return call3 (handler, Qset_file_selinux_context, absname, context);
2885 #if HAVE_LIBSELINUX
2886 if (is_selinux_enabled ())
2888 /* Get current file context. */
2889 encoded_absname = ENCODE_FILE (absname);
2890 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2891 if (conlength > 0)
2893 parsed_con = context_new (con);
2894 /* Change the parts defined in the parameter.*/
2895 if (STRINGP (user))
2897 if (context_user_set (parsed_con, SSDATA (user)))
2898 error ("Doing context_user_set");
2900 if (STRINGP (role))
2902 if (context_role_set (parsed_con, SSDATA (role)))
2903 error ("Doing context_role_set");
2905 if (STRINGP (type))
2907 if (context_type_set (parsed_con, SSDATA (type)))
2908 error ("Doing context_type_set");
2910 if (STRINGP (range))
2912 if (context_range_set (parsed_con, SSDATA (range)))
2913 error ("Doing context_range_set");
2916 /* Set the modified context back to the file. */
2917 fail = (lsetfilecon (SSDATA (encoded_absname),
2918 context_str (parsed_con))
2919 != 0);
2920 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2921 if (fail && errno != ENOTSUP)
2922 report_file_error ("Doing lsetfilecon", Fcons (absname, Qnil));
2924 context_free (parsed_con);
2925 freecon (con);
2927 else
2928 report_file_error ("Doing lgetfilecon", Fcons (absname, Qnil));
2930 #endif
2932 return Qnil;
2935 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
2936 doc: /* Return mode bits of file named FILENAME, as an integer.
2937 Return nil, if file does not exist or is not accessible. */)
2938 (Lisp_Object filename)
2940 Lisp_Object absname;
2941 struct stat st;
2942 Lisp_Object handler;
2944 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2946 /* If the file name has special constructs in it,
2947 call the corresponding file handler. */
2948 handler = Ffind_file_name_handler (absname, Qfile_modes);
2949 if (!NILP (handler))
2950 return call2 (handler, Qfile_modes, absname);
2952 absname = ENCODE_FILE (absname);
2954 if (stat (SSDATA (absname), &st) < 0)
2955 return Qnil;
2957 return make_number (st.st_mode & 07777);
2960 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
2961 "(let ((file (read-file-name \"File: \"))) \
2962 (list file (read-file-modes nil file)))",
2963 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
2964 Only the 12 low bits of MODE are used.
2966 Interactively, mode bits are read by `read-file-modes', which accepts
2967 symbolic notation, like the `chmod' command from GNU Coreutils. */)
2968 (Lisp_Object filename, Lisp_Object mode)
2970 Lisp_Object absname, encoded_absname;
2971 Lisp_Object handler;
2973 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2974 CHECK_NUMBER (mode);
2976 /* If the file name has special constructs in it,
2977 call the corresponding file handler. */
2978 handler = Ffind_file_name_handler (absname, Qset_file_modes);
2979 if (!NILP (handler))
2980 return call3 (handler, Qset_file_modes, absname, mode);
2982 encoded_absname = ENCODE_FILE (absname);
2984 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
2985 report_file_error ("Doing chmod", Fcons (absname, Qnil));
2987 return Qnil;
2990 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
2991 doc: /* Set the file permission bits for newly created files.
2992 The argument MODE should be an integer; only the low 9 bits are used.
2993 This setting is inherited by subprocesses. */)
2994 (Lisp_Object mode)
2996 CHECK_NUMBER (mode);
2998 umask ((~ XINT (mode)) & 0777);
3000 return Qnil;
3003 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3004 doc: /* Return the default file protection for created files.
3005 The value is an integer. */)
3006 (void)
3008 mode_t realmask;
3009 Lisp_Object value;
3011 block_input ();
3012 realmask = umask (0);
3013 umask (realmask);
3014 unblock_input ();
3016 XSETINT (value, (~ realmask) & 0777);
3017 return value;
3021 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3022 doc: /* Set times of file FILENAME to TIMESTAMP.
3023 Set both access and modification times.
3024 Return t on success, else nil.
3025 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3026 `current-time'. */)
3027 (Lisp_Object filename, Lisp_Object timestamp)
3029 Lisp_Object absname, encoded_absname;
3030 Lisp_Object handler;
3031 EMACS_TIME t = lisp_time_argument (timestamp);
3033 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3035 /* If the file name has special constructs in it,
3036 call the corresponding file handler. */
3037 handler = Ffind_file_name_handler (absname, Qset_file_times);
3038 if (!NILP (handler))
3039 return call3 (handler, Qset_file_times, absname, timestamp);
3041 encoded_absname = ENCODE_FILE (absname);
3044 if (set_file_times (-1, SSDATA (encoded_absname), t, t))
3046 #ifdef MSDOS
3047 struct stat st;
3049 /* Setting times on a directory always fails. */
3050 if (stat (SSDATA (encoded_absname), &st) == 0 && S_ISDIR (st.st_mode))
3051 return Qnil;
3052 #endif
3053 report_file_error ("Setting file times", Fcons (absname, Qnil));
3054 return Qnil;
3058 return Qt;
3061 #ifdef HAVE_SYNC
3062 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3063 doc: /* Tell Unix to finish all pending disk updates. */)
3064 (void)
3066 sync ();
3067 return Qnil;
3070 #endif /* HAVE_SYNC */
3072 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3073 doc: /* Return t if file FILE1 is newer than file FILE2.
3074 If FILE1 does not exist, the answer is nil;
3075 otherwise, if FILE2 does not exist, the answer is t. */)
3076 (Lisp_Object file1, Lisp_Object file2)
3078 Lisp_Object absname1, absname2;
3079 struct stat st1, st2;
3080 Lisp_Object handler;
3081 struct gcpro gcpro1, gcpro2;
3083 CHECK_STRING (file1);
3084 CHECK_STRING (file2);
3086 absname1 = Qnil;
3087 GCPRO2 (absname1, file2);
3088 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3089 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3090 UNGCPRO;
3092 /* If the file name has special constructs in it,
3093 call the corresponding file handler. */
3094 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3095 if (NILP (handler))
3096 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3097 if (!NILP (handler))
3098 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3100 GCPRO2 (absname1, absname2);
3101 absname1 = ENCODE_FILE (absname1);
3102 absname2 = ENCODE_FILE (absname2);
3103 UNGCPRO;
3105 if (stat (SSDATA (absname1), &st1) < 0)
3106 return Qnil;
3108 if (stat (SSDATA (absname2), &st2) < 0)
3109 return Qt;
3111 return (EMACS_TIME_GT (get_stat_mtime (&st1), get_stat_mtime (&st2))
3112 ? Qt : Qnil);
3115 #ifndef READ_BUF_SIZE
3116 #define READ_BUF_SIZE (64 << 10)
3117 #endif
3118 /* Some buffer offsets are stored in 'int' variables. */
3119 verify (READ_BUF_SIZE <= INT_MAX);
3121 /* This function is called after Lisp functions to decide a coding
3122 system are called, or when they cause an error. Before they are
3123 called, the current buffer is set unibyte and it contains only a
3124 newly inserted text (thus the buffer was empty before the
3125 insertion).
3127 The functions may set markers, overlays, text properties, or even
3128 alter the buffer contents, change the current buffer.
3130 Here, we reset all those changes by:
3131 o set back the current buffer.
3132 o move all markers and overlays to BEG.
3133 o remove all text properties.
3134 o set back the buffer multibyteness. */
3136 static Lisp_Object
3137 decide_coding_unwind (Lisp_Object unwind_data)
3139 Lisp_Object multibyte, undo_list, buffer;
3141 multibyte = XCAR (unwind_data);
3142 unwind_data = XCDR (unwind_data);
3143 undo_list = XCAR (unwind_data);
3144 buffer = XCDR (unwind_data);
3146 set_buffer_internal (XBUFFER (buffer));
3147 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3148 adjust_overlays_for_delete (BEG, Z - BEG);
3149 set_buffer_intervals (current_buffer, NULL);
3150 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3152 /* Now we are safe to change the buffer's multibyteness directly. */
3153 bset_enable_multibyte_characters (current_buffer, multibyte);
3154 bset_undo_list (current_buffer, undo_list);
3156 return Qnil;
3160 /* Used to pass values from insert-file-contents to read_non_regular. */
3162 static int non_regular_fd;
3163 static ptrdiff_t non_regular_inserted;
3164 static int non_regular_nbytes;
3167 /* Read from a non-regular file.
3168 Read non_regular_nbytes bytes max from non_regular_fd.
3169 Non_regular_inserted specifies where to put the read bytes.
3170 Value is the number of bytes read. */
3172 static Lisp_Object
3173 read_non_regular (Lisp_Object ignore)
3175 int nbytes;
3177 immediate_quit = 1;
3178 QUIT;
3179 nbytes = emacs_read (non_regular_fd,
3180 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3181 + non_regular_inserted),
3182 non_regular_nbytes);
3183 immediate_quit = 0;
3184 return make_number (nbytes);
3188 /* Condition-case handler used when reading from non-regular files
3189 in insert-file-contents. */
3191 static Lisp_Object
3192 read_non_regular_quit (Lisp_Object ignore)
3194 return Qnil;
3197 /* Reposition FD to OFFSET, based on WHENCE. This acts like lseek
3198 except that it also tests for OFFSET being out of lseek's range. */
3199 static off_t
3200 emacs_lseek (int fd, EMACS_INT offset, int whence)
3202 /* Use "&" rather than "&&" to suppress a bogus GCC warning; see
3203 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43772>. */
3204 if (! ((offset >= TYPE_MINIMUM (off_t)) & (offset <= TYPE_MAXIMUM (off_t))))
3206 errno = EINVAL;
3207 return -1;
3209 return lseek (fd, offset, whence);
3212 /* Return a special time value indicating the error number ERRNUM. */
3213 static EMACS_TIME
3214 time_error_value (int errnum)
3216 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3217 ? NONEXISTENT_MODTIME_NSECS
3218 : UNKNOWN_MODTIME_NSECS);
3219 return make_emacs_time (0, ns);
3222 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3223 1, 5, 0,
3224 doc: /* Insert contents of file FILENAME after point.
3225 Returns list of absolute file name and number of characters inserted.
3226 If second argument VISIT is non-nil, the buffer's visited filename and
3227 last save file modtime are set, and it is marked unmodified. If
3228 visiting and the file does not exist, visiting is completed before the
3229 error is signaled.
3231 The optional third and fourth arguments BEG and END specify what portion
3232 of the file to insert. These arguments count bytes in the file, not
3233 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3235 If optional fifth argument REPLACE is non-nil, replace the current
3236 buffer contents (in the accessible portion) with the file contents.
3237 This is better than simply deleting and inserting the whole thing
3238 because (1) it preserves some marker positions and (2) it puts less data
3239 in the undo list. When REPLACE is non-nil, the second return value is
3240 the number of characters that replace previous buffer contents.
3242 This function does code conversion according to the value of
3243 `coding-system-for-read' or `file-coding-system-alist', and sets the
3244 variable `last-coding-system-used' to the coding system actually used. */)
3245 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3247 struct stat st;
3248 int file_status;
3249 EMACS_TIME mtime;
3250 int fd;
3251 ptrdiff_t inserted = 0;
3252 bool nochange = 0;
3253 ptrdiff_t how_much;
3254 off_t beg_offset, end_offset;
3255 int unprocessed;
3256 ptrdiff_t count = SPECPDL_INDEX ();
3257 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3258 Lisp_Object handler, val, insval, orig_filename, old_undo;
3259 Lisp_Object p;
3260 ptrdiff_t total = 0;
3261 bool not_regular = 0;
3262 int save_errno = 0;
3263 char read_buf[READ_BUF_SIZE];
3264 struct coding_system coding;
3265 char buffer[1 << 14];
3266 bool replace_handled = 0;
3267 bool set_coding_system = 0;
3268 Lisp_Object coding_system;
3269 bool read_quit = 0;
3270 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3271 bool we_locked_file = 0;
3272 bool deferred_remove_unwind_protect = 0;
3274 if (current_buffer->base_buffer && ! NILP (visit))
3275 error ("Cannot do file visiting in an indirect buffer");
3277 if (!NILP (BVAR (current_buffer, read_only)))
3278 Fbarf_if_buffer_read_only ();
3280 val = Qnil;
3281 p = Qnil;
3282 orig_filename = Qnil;
3283 old_undo = Qnil;
3285 GCPRO5 (filename, val, p, orig_filename, old_undo);
3287 CHECK_STRING (filename);
3288 filename = Fexpand_file_name (filename, Qnil);
3290 /* The value Qnil means that the coding system is not yet
3291 decided. */
3292 coding_system = Qnil;
3294 /* If the file name has special constructs in it,
3295 call the corresponding file handler. */
3296 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3297 if (!NILP (handler))
3299 val = call6 (handler, Qinsert_file_contents, filename,
3300 visit, beg, end, replace);
3301 if (CONSP (val) && CONSP (XCDR (val))
3302 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3303 inserted = XINT (XCAR (XCDR (val)));
3304 goto handled;
3307 orig_filename = filename;
3308 filename = ENCODE_FILE (filename);
3310 fd = -1;
3312 #ifdef WINDOWSNT
3314 Lisp_Object tem = Vw32_get_true_file_attributes;
3316 /* Tell stat to use expensive method to get accurate info. */
3317 Vw32_get_true_file_attributes = Qt;
3318 file_status = stat (SSDATA (filename), &st);
3319 Vw32_get_true_file_attributes = tem;
3321 #else
3322 file_status = stat (SSDATA (filename), &st);
3323 #endif /* WINDOWSNT */
3325 if (file_status == 0)
3326 mtime = get_stat_mtime (&st);
3327 else
3329 badopen:
3330 save_errno = errno;
3331 if (NILP (visit))
3332 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3333 mtime = time_error_value (save_errno);
3334 st.st_size = -1;
3335 how_much = 0;
3336 if (!NILP (Vcoding_system_for_read))
3337 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3338 goto notfound;
3341 /* This code will need to be changed in order to work on named
3342 pipes, and it's probably just not worth it. So we should at
3343 least signal an error. */
3344 if (!S_ISREG (st.st_mode))
3346 not_regular = 1;
3348 if (! NILP (visit))
3349 goto notfound;
3351 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3352 xsignal2 (Qfile_error,
3353 build_string ("not a regular file"), orig_filename);
3356 if (fd < 0)
3357 if ((fd = emacs_open (SSDATA (filename), O_RDONLY, 0)) < 0)
3358 goto badopen;
3360 /* Replacement should preserve point as it preserves markers. */
3361 if (!NILP (replace))
3362 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3364 record_unwind_protect (close_file_unwind, make_number (fd));
3367 if (!NILP (visit))
3369 if (!NILP (beg) || !NILP (end))
3370 error ("Attempt to visit less than an entire file");
3371 if (BEG < Z && NILP (replace))
3372 error ("Cannot do file visiting in a non-empty buffer");
3375 if (!NILP (beg))
3377 if (! RANGED_INTEGERP (0, beg, TYPE_MAXIMUM (off_t)))
3378 wrong_type_argument (intern ("file-offset"), beg);
3379 beg_offset = XFASTINT (beg);
3381 else
3382 beg_offset = 0;
3384 if (!NILP (end))
3386 if (! RANGED_INTEGERP (0, end, TYPE_MAXIMUM (off_t)))
3387 wrong_type_argument (intern ("file-offset"), end);
3388 end_offset = XFASTINT (end);
3390 else
3392 if (not_regular)
3393 end_offset = TYPE_MAXIMUM (off_t);
3394 else
3396 end_offset = st.st_size;
3398 /* A negative size can happen on a platform that allows file
3399 sizes greater than the maximum off_t value. */
3400 if (end_offset < 0)
3401 buffer_overflow ();
3403 /* The file size returned from stat may be zero, but data
3404 may be readable nonetheless, for example when this is a
3405 file in the /proc filesystem. */
3406 if (end_offset == 0)
3407 end_offset = READ_BUF_SIZE;
3411 /* Check now whether the buffer will become too large,
3412 in the likely case where the file's length is not changing.
3413 This saves a lot of needless work before a buffer overflow. */
3414 if (! not_regular)
3416 /* The likely offset where we will stop reading. We could read
3417 more (or less), if the file grows (or shrinks) as we read it. */
3418 off_t likely_end = min (end_offset, st.st_size);
3420 if (beg_offset < likely_end)
3422 ptrdiff_t buf_bytes
3423 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3424 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3425 off_t likely_growth = likely_end - beg_offset;
3426 if (buf_growth_max < likely_growth)
3427 buffer_overflow ();
3431 /* Prevent redisplay optimizations. */
3432 current_buffer->clip_changed = 1;
3434 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3436 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3437 setup_coding_system (coding_system, &coding);
3438 /* Ensure we set Vlast_coding_system_used. */
3439 set_coding_system = 1;
3441 else if (BEG < Z)
3443 /* Decide the coding system to use for reading the file now
3444 because we can't use an optimized method for handling
3445 `coding:' tag if the current buffer is not empty. */
3446 if (!NILP (Vcoding_system_for_read))
3447 coding_system = Vcoding_system_for_read;
3448 else
3450 /* Don't try looking inside a file for a coding system
3451 specification if it is not seekable. */
3452 if (! not_regular && ! NILP (Vset_auto_coding_function))
3454 /* Find a coding system specified in the heading two
3455 lines or in the tailing several lines of the file.
3456 We assume that the 1K-byte and 3K-byte for heading
3457 and tailing respectively are sufficient for this
3458 purpose. */
3459 int nread;
3461 if (st.st_size <= (1024 * 4))
3462 nread = emacs_read (fd, read_buf, 1024 * 4);
3463 else
3465 nread = emacs_read (fd, read_buf, 1024);
3466 if (nread >= 0)
3468 if (lseek (fd, st.st_size - (1024 * 3), SEEK_SET) < 0)
3469 report_file_error ("Setting file position",
3470 Fcons (orig_filename, Qnil));
3471 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3475 if (nread < 0)
3476 error ("IO error reading %s: %s",
3477 SDATA (orig_filename), emacs_strerror (errno));
3478 else if (nread > 0)
3480 struct buffer *prev = current_buffer;
3481 Lisp_Object workbuf;
3482 struct buffer *buf;
3484 record_unwind_current_buffer ();
3486 workbuf = Fget_buffer_create (build_string (" *code-converting-work*"));
3487 buf = XBUFFER (workbuf);
3489 delete_all_overlays (buf);
3490 bset_directory (buf, BVAR (current_buffer, directory));
3491 bset_read_only (buf, Qnil);
3492 bset_filename (buf, Qnil);
3493 bset_undo_list (buf, Qt);
3494 eassert (buf->overlays_before == NULL);
3495 eassert (buf->overlays_after == NULL);
3497 set_buffer_internal (buf);
3498 Ferase_buffer ();
3499 bset_enable_multibyte_characters (buf, Qnil);
3501 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3502 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3503 coding_system = call2 (Vset_auto_coding_function,
3504 filename, make_number (nread));
3505 set_buffer_internal (prev);
3507 /* Discard the unwind protect for recovering the
3508 current buffer. */
3509 specpdl_ptr--;
3511 /* Rewind the file for the actual read done later. */
3512 if (lseek (fd, 0, SEEK_SET) < 0)
3513 report_file_error ("Setting file position",
3514 Fcons (orig_filename, Qnil));
3518 if (NILP (coding_system))
3520 /* If we have not yet decided a coding system, check
3521 file-coding-system-alist. */
3522 Lisp_Object args[6];
3524 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3525 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3526 coding_system = Ffind_operation_coding_system (6, args);
3527 if (CONSP (coding_system))
3528 coding_system = XCAR (coding_system);
3532 if (NILP (coding_system))
3533 coding_system = Qundecided;
3534 else
3535 CHECK_CODING_SYSTEM (coding_system);
3537 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3538 /* We must suppress all character code conversion except for
3539 end-of-line conversion. */
3540 coding_system = raw_text_coding_system (coding_system);
3542 setup_coding_system (coding_system, &coding);
3543 /* Ensure we set Vlast_coding_system_used. */
3544 set_coding_system = 1;
3547 /* If requested, replace the accessible part of the buffer
3548 with the file contents. Avoid replacing text at the
3549 beginning or end of the buffer that matches the file contents;
3550 that preserves markers pointing to the unchanged parts.
3552 Here we implement this feature in an optimized way
3553 for the case where code conversion is NOT needed.
3554 The following if-statement handles the case of conversion
3555 in a less optimal way.
3557 If the code conversion is "automatic" then we try using this
3558 method and hope for the best.
3559 But if we discover the need for conversion, we give up on this method
3560 and let the following if-statement handle the replace job. */
3561 if (!NILP (replace)
3562 && BEGV < ZV
3563 && (NILP (coding_system)
3564 || ! CODING_REQUIRE_DECODING (&coding)))
3566 /* same_at_start and same_at_end count bytes,
3567 because file access counts bytes
3568 and BEG and END count bytes. */
3569 ptrdiff_t same_at_start = BEGV_BYTE;
3570 ptrdiff_t same_at_end = ZV_BYTE;
3571 ptrdiff_t overlap;
3572 /* There is still a possibility we will find the need to do code
3573 conversion. If that happens, set this variable to
3574 give up on handling REPLACE in the optimized way. */
3575 bool giveup_match_end = 0;
3577 if (beg_offset != 0)
3579 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3580 report_file_error ("Setting file position",
3581 Fcons (orig_filename, Qnil));
3584 immediate_quit = 1;
3585 QUIT;
3586 /* Count how many chars at the start of the file
3587 match the text at the beginning of the buffer. */
3588 while (1)
3590 int nread, bufpos;
3592 nread = emacs_read (fd, buffer, sizeof buffer);
3593 if (nread < 0)
3594 error ("IO error reading %s: %s",
3595 SSDATA (orig_filename), emacs_strerror (errno));
3596 else if (nread == 0)
3597 break;
3599 if (CODING_REQUIRE_DETECTION (&coding))
3601 coding_system = detect_coding_system ((unsigned char *) buffer,
3602 nread, nread, 1, 0,
3603 coding_system);
3604 setup_coding_system (coding_system, &coding);
3607 if (CODING_REQUIRE_DECODING (&coding))
3608 /* We found that the file should be decoded somehow.
3609 Let's give up here. */
3611 giveup_match_end = 1;
3612 break;
3615 bufpos = 0;
3616 while (bufpos < nread && same_at_start < ZV_BYTE
3617 && FETCH_BYTE (same_at_start) == buffer[bufpos])
3618 same_at_start++, bufpos++;
3619 /* If we found a discrepancy, stop the scan.
3620 Otherwise loop around and scan the next bufferful. */
3621 if (bufpos != nread)
3622 break;
3624 immediate_quit = 0;
3625 /* If the file matches the buffer completely,
3626 there's no need to replace anything. */
3627 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3629 emacs_close (fd);
3630 specpdl_ptr--;
3631 /* Truncate the buffer to the size of the file. */
3632 del_range_1 (same_at_start, same_at_end, 0, 0);
3633 goto handled;
3635 immediate_quit = 1;
3636 QUIT;
3637 /* Count how many chars at the end of the file
3638 match the text at the end of the buffer. But, if we have
3639 already found that decoding is necessary, don't waste time. */
3640 while (!giveup_match_end)
3642 int total_read, nread, bufpos, trial;
3643 off_t curpos;
3645 /* At what file position are we now scanning? */
3646 curpos = end_offset - (ZV_BYTE - same_at_end);
3647 /* If the entire file matches the buffer tail, stop the scan. */
3648 if (curpos == 0)
3649 break;
3650 /* How much can we scan in the next step? */
3651 trial = min (curpos, sizeof buffer);
3652 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3653 report_file_error ("Setting file position",
3654 Fcons (orig_filename, Qnil));
3656 total_read = nread = 0;
3657 while (total_read < trial)
3659 nread = emacs_read (fd, buffer + total_read, trial - total_read);
3660 if (nread < 0)
3661 error ("IO error reading %s: %s",
3662 SDATA (orig_filename), emacs_strerror (errno));
3663 else if (nread == 0)
3664 break;
3665 total_read += nread;
3668 /* Scan this bufferful from the end, comparing with
3669 the Emacs buffer. */
3670 bufpos = total_read;
3672 /* Compare with same_at_start to avoid counting some buffer text
3673 as matching both at the file's beginning and at the end. */
3674 while (bufpos > 0 && same_at_end > same_at_start
3675 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
3676 same_at_end--, bufpos--;
3678 /* If we found a discrepancy, stop the scan.
3679 Otherwise loop around and scan the preceding bufferful. */
3680 if (bufpos != 0)
3682 /* If this discrepancy is because of code conversion,
3683 we cannot use this method; giveup and try the other. */
3684 if (same_at_end > same_at_start
3685 && FETCH_BYTE (same_at_end - 1) >= 0200
3686 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3687 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3688 giveup_match_end = 1;
3689 break;
3692 if (nread == 0)
3693 break;
3695 immediate_quit = 0;
3697 if (! giveup_match_end)
3699 ptrdiff_t temp;
3701 /* We win! We can handle REPLACE the optimized way. */
3703 /* Extend the start of non-matching text area to multibyte
3704 character boundary. */
3705 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3706 while (same_at_start > BEGV_BYTE
3707 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3708 same_at_start--;
3710 /* Extend the end of non-matching text area to multibyte
3711 character boundary. */
3712 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3713 while (same_at_end < ZV_BYTE
3714 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3715 same_at_end++;
3717 /* Don't try to reuse the same piece of text twice. */
3718 overlap = (same_at_start - BEGV_BYTE
3719 - (same_at_end
3720 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3721 if (overlap > 0)
3722 same_at_end += overlap;
3724 /* Arrange to read only the nonmatching middle part of the file. */
3725 beg_offset += same_at_start - BEGV_BYTE;
3726 end_offset -= ZV_BYTE - same_at_end;
3728 del_range_byte (same_at_start, same_at_end, 0);
3729 /* Insert from the file at the proper position. */
3730 temp = BYTE_TO_CHAR (same_at_start);
3731 SET_PT_BOTH (temp, same_at_start);
3733 /* If display currently starts at beginning of line,
3734 keep it that way. */
3735 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3736 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3738 replace_handled = 1;
3742 /* If requested, replace the accessible part of the buffer
3743 with the file contents. Avoid replacing text at the
3744 beginning or end of the buffer that matches the file contents;
3745 that preserves markers pointing to the unchanged parts.
3747 Here we implement this feature for the case where code conversion
3748 is needed, in a simple way that needs a lot of memory.
3749 The preceding if-statement handles the case of no conversion
3750 in a more optimized way. */
3751 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3753 ptrdiff_t same_at_start = BEGV_BYTE;
3754 ptrdiff_t same_at_end = ZV_BYTE;
3755 ptrdiff_t same_at_start_charpos;
3756 ptrdiff_t inserted_chars;
3757 ptrdiff_t overlap;
3758 ptrdiff_t bufpos;
3759 unsigned char *decoded;
3760 ptrdiff_t temp;
3761 ptrdiff_t this = 0;
3762 ptrdiff_t this_count = SPECPDL_INDEX ();
3763 bool multibyte
3764 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3765 Lisp_Object conversion_buffer;
3766 struct gcpro gcpro1;
3768 conversion_buffer = code_conversion_save (1, multibyte);
3770 /* First read the whole file, performing code conversion into
3771 CONVERSION_BUFFER. */
3773 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3774 report_file_error ("Setting file position",
3775 Fcons (orig_filename, Qnil));
3777 total = st.st_size; /* Total bytes in the file. */
3778 how_much = 0; /* Bytes read from file so far. */
3779 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3780 unprocessed = 0; /* Bytes not processed in previous loop. */
3782 GCPRO1 (conversion_buffer);
3783 while (how_much < total)
3785 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
3786 quitting while reading a huge while. */
3787 /* `try'' is reserved in some compilers (Microsoft C). */
3788 int trytry = min (total - how_much, READ_BUF_SIZE - unprocessed);
3790 /* Allow quitting out of the actual I/O. */
3791 immediate_quit = 1;
3792 QUIT;
3793 this = emacs_read (fd, read_buf + unprocessed, trytry);
3794 immediate_quit = 0;
3796 if (this <= 0)
3797 break;
3799 how_much += this;
3801 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3802 BUF_Z (XBUFFER (conversion_buffer)));
3803 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3804 unprocessed + this, conversion_buffer);
3805 unprocessed = coding.carryover_bytes;
3806 if (coding.carryover_bytes > 0)
3807 memcpy (read_buf, coding.carryover, unprocessed);
3809 UNGCPRO;
3810 emacs_close (fd);
3812 /* We should remove the unwind_protect calling
3813 close_file_unwind, but other stuff has been added the stack,
3814 so defer the removal till we reach the `handled' label. */
3815 deferred_remove_unwind_protect = 1;
3817 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
3818 if we couldn't read the file. */
3820 if (this < 0)
3821 error ("IO error reading %s: %s",
3822 SDATA (orig_filename), emacs_strerror (errno));
3824 if (unprocessed > 0)
3826 coding.mode |= CODING_MODE_LAST_BLOCK;
3827 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3828 unprocessed, conversion_buffer);
3829 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3832 coding_system = CODING_ID_NAME (coding.id);
3833 set_coding_system = 1;
3834 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3835 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3836 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3838 /* Compare the beginning of the converted string with the buffer
3839 text. */
3841 bufpos = 0;
3842 while (bufpos < inserted && same_at_start < same_at_end
3843 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3844 same_at_start++, bufpos++;
3846 /* If the file matches the head of buffer completely,
3847 there's no need to replace anything. */
3849 if (bufpos == inserted)
3851 /* Truncate the buffer to the size of the file. */
3852 if (same_at_start == same_at_end)
3853 nochange = 1;
3854 else
3855 del_range_byte (same_at_start, same_at_end, 0);
3856 inserted = 0;
3858 unbind_to (this_count, Qnil);
3859 goto handled;
3862 /* Extend the start of non-matching text area to the previous
3863 multibyte character boundary. */
3864 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3865 while (same_at_start > BEGV_BYTE
3866 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3867 same_at_start--;
3869 /* Scan this bufferful from the end, comparing with
3870 the Emacs buffer. */
3871 bufpos = inserted;
3873 /* Compare with same_at_start to avoid counting some buffer text
3874 as matching both at the file's beginning and at the end. */
3875 while (bufpos > 0 && same_at_end > same_at_start
3876 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3877 same_at_end--, bufpos--;
3879 /* Extend the end of non-matching text area to the next
3880 multibyte character boundary. */
3881 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3882 while (same_at_end < ZV_BYTE
3883 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3884 same_at_end++;
3886 /* Don't try to reuse the same piece of text twice. */
3887 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3888 if (overlap > 0)
3889 same_at_end += overlap;
3891 /* If display currently starts at beginning of line,
3892 keep it that way. */
3893 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3894 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3896 /* Replace the chars that we need to replace,
3897 and update INSERTED to equal the number of bytes
3898 we are taking from the decoded string. */
3899 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3901 if (same_at_end != same_at_start)
3903 del_range_byte (same_at_start, same_at_end, 0);
3904 temp = GPT;
3905 same_at_start = GPT_BYTE;
3907 else
3909 temp = BYTE_TO_CHAR (same_at_start);
3911 /* Insert from the file at the proper position. */
3912 SET_PT_BOTH (temp, same_at_start);
3913 same_at_start_charpos
3914 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3915 same_at_start - BEGV_BYTE
3916 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3917 inserted_chars
3918 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3919 same_at_start + inserted - BEGV_BYTE
3920 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
3921 - same_at_start_charpos);
3922 /* This binding is to avoid ask-user-about-supersession-threat
3923 being called in insert_from_buffer (via in
3924 prepare_to_modify_buffer). */
3925 specbind (intern ("buffer-file-name"), Qnil);
3926 insert_from_buffer (XBUFFER (conversion_buffer),
3927 same_at_start_charpos, inserted_chars, 0);
3928 /* Set `inserted' to the number of inserted characters. */
3929 inserted = PT - temp;
3930 /* Set point before the inserted characters. */
3931 SET_PT_BOTH (temp, same_at_start);
3933 unbind_to (this_count, Qnil);
3935 goto handled;
3938 if (! not_regular)
3939 total = end_offset - beg_offset;
3940 else
3941 /* For a special file, all we can do is guess. */
3942 total = READ_BUF_SIZE;
3944 if (NILP (visit) && total > 0)
3946 #ifdef CLASH_DETECTION
3947 if (!NILP (BVAR (current_buffer, file_truename))
3948 /* Make binding buffer-file-name to nil effective. */
3949 && !NILP (BVAR (current_buffer, filename))
3950 && SAVE_MODIFF >= MODIFF)
3951 we_locked_file = 1;
3952 #endif /* CLASH_DETECTION */
3953 prepare_to_modify_buffer (GPT, GPT, NULL);
3956 move_gap (PT);
3957 if (GAP_SIZE < total)
3958 make_gap (total - GAP_SIZE);
3960 if (beg_offset != 0 || !NILP (replace))
3962 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3963 report_file_error ("Setting file position",
3964 Fcons (orig_filename, Qnil));
3967 /* In the following loop, HOW_MUCH contains the total bytes read so
3968 far for a regular file, and not changed for a special file. But,
3969 before exiting the loop, it is set to a negative value if I/O
3970 error occurs. */
3971 how_much = 0;
3973 /* Total bytes inserted. */
3974 inserted = 0;
3976 /* Here, we don't do code conversion in the loop. It is done by
3977 decode_coding_gap after all data are read into the buffer. */
3979 ptrdiff_t gap_size = GAP_SIZE;
3981 while (how_much < total)
3983 /* try is reserved in some compilers (Microsoft C) */
3984 int trytry = min (total - how_much, READ_BUF_SIZE);
3985 ptrdiff_t this;
3987 if (not_regular)
3989 Lisp_Object nbytes;
3991 /* Maybe make more room. */
3992 if (gap_size < trytry)
3994 make_gap (total - gap_size);
3995 gap_size = GAP_SIZE;
3998 /* Read from the file, capturing `quit'. When an
3999 error occurs, end the loop, and arrange for a quit
4000 to be signaled after decoding the text we read. */
4001 non_regular_fd = fd;
4002 non_regular_inserted = inserted;
4003 non_regular_nbytes = trytry;
4004 nbytes = internal_condition_case_1 (read_non_regular,
4005 Qnil, Qerror,
4006 read_non_regular_quit);
4007 if (NILP (nbytes))
4009 read_quit = 1;
4010 break;
4013 this = XINT (nbytes);
4015 else
4017 /* Allow quitting out of the actual I/O. We don't make text
4018 part of the buffer until all the reading is done, so a C-g
4019 here doesn't do any harm. */
4020 immediate_quit = 1;
4021 QUIT;
4022 this = emacs_read (fd,
4023 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4024 + inserted),
4025 trytry);
4026 immediate_quit = 0;
4029 if (this <= 0)
4031 how_much = this;
4032 break;
4035 gap_size -= this;
4037 /* For a regular file, where TOTAL is the real size,
4038 count HOW_MUCH to compare with it.
4039 For a special file, where TOTAL is just a buffer size,
4040 so don't bother counting in HOW_MUCH.
4041 (INSERTED is where we count the number of characters inserted.) */
4042 if (! not_regular)
4043 how_much += this;
4044 inserted += this;
4048 /* Now we have read all the file data into the gap.
4049 If it was empty, undo marking the buffer modified. */
4051 if (inserted == 0)
4053 #ifdef CLASH_DETECTION
4054 if (we_locked_file)
4055 unlock_file (BVAR (current_buffer, file_truename));
4056 #endif
4057 Vdeactivate_mark = old_Vdeactivate_mark;
4059 else
4060 Vdeactivate_mark = Qt;
4062 /* Make the text read part of the buffer. */
4063 GAP_SIZE -= inserted;
4064 GPT += inserted;
4065 GPT_BYTE += inserted;
4066 ZV += inserted;
4067 ZV_BYTE += inserted;
4068 Z += inserted;
4069 Z_BYTE += inserted;
4071 if (GAP_SIZE > 0)
4072 /* Put an anchor to ensure multi-byte form ends at gap. */
4073 *GPT_ADDR = 0;
4075 emacs_close (fd);
4077 /* Discard the unwind protect for closing the file. */
4078 specpdl_ptr--;
4080 if (how_much < 0)
4081 error ("IO error reading %s: %s",
4082 SDATA (orig_filename), emacs_strerror (errno));
4084 notfound:
4086 if (NILP (coding_system))
4088 /* The coding system is not yet decided. Decide it by an
4089 optimized method for handling `coding:' tag.
4091 Note that we can get here only if the buffer was empty
4092 before the insertion. */
4094 if (!NILP (Vcoding_system_for_read))
4095 coding_system = Vcoding_system_for_read;
4096 else
4098 /* Since we are sure that the current buffer was empty
4099 before the insertion, we can toggle
4100 enable-multibyte-characters directly here without taking
4101 care of marker adjustment. By this way, we can run Lisp
4102 program safely before decoding the inserted text. */
4103 Lisp_Object unwind_data;
4104 ptrdiff_t count1 = SPECPDL_INDEX ();
4106 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4107 Fcons (BVAR (current_buffer, undo_list),
4108 Fcurrent_buffer ()));
4109 bset_enable_multibyte_characters (current_buffer, Qnil);
4110 bset_undo_list (current_buffer, Qt);
4111 record_unwind_protect (decide_coding_unwind, unwind_data);
4113 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4115 coding_system = call2 (Vset_auto_coding_function,
4116 filename, make_number (inserted));
4119 if (NILP (coding_system))
4121 /* If the coding system is not yet decided, check
4122 file-coding-system-alist. */
4123 Lisp_Object args[6];
4125 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4126 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4127 coding_system = Ffind_operation_coding_system (6, args);
4128 if (CONSP (coding_system))
4129 coding_system = XCAR (coding_system);
4131 unbind_to (count1, Qnil);
4132 inserted = Z_BYTE - BEG_BYTE;
4135 if (NILP (coding_system))
4136 coding_system = Qundecided;
4137 else
4138 CHECK_CODING_SYSTEM (coding_system);
4140 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4141 /* We must suppress all character code conversion except for
4142 end-of-line conversion. */
4143 coding_system = raw_text_coding_system (coding_system);
4144 setup_coding_system (coding_system, &coding);
4145 /* Ensure we set Vlast_coding_system_used. */
4146 set_coding_system = 1;
4149 if (!NILP (visit))
4151 /* When we visit a file by raw-text, we change the buffer to
4152 unibyte. */
4153 if (CODING_FOR_UNIBYTE (&coding)
4154 /* Can't do this if part of the buffer might be preserved. */
4155 && NILP (replace))
4156 /* Visiting a file with these coding system makes the buffer
4157 unibyte. */
4158 bset_enable_multibyte_characters (current_buffer, Qnil);
4161 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4162 if (CODING_MAY_REQUIRE_DECODING (&coding)
4163 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4165 move_gap_both (PT, PT_BYTE);
4166 GAP_SIZE += inserted;
4167 ZV_BYTE -= inserted;
4168 Z_BYTE -= inserted;
4169 ZV -= inserted;
4170 Z -= inserted;
4171 decode_coding_gap (&coding, inserted, inserted);
4172 inserted = coding.produced_char;
4173 coding_system = CODING_ID_NAME (coding.id);
4175 else if (inserted > 0)
4176 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4177 inserted);
4179 /* Call after-change hooks for the inserted text, aside from the case
4180 of normal visiting (not with REPLACE), which is done in a new buffer
4181 "before" the buffer is changed. */
4182 if (inserted > 0 && total > 0
4183 && (NILP (visit) || !NILP (replace)))
4185 signal_after_change (PT, 0, inserted);
4186 update_compositions (PT, PT, CHECK_BORDER);
4189 /* Now INSERTED is measured in characters. */
4191 handled:
4193 if (deferred_remove_unwind_protect)
4194 /* If requested above, discard the unwind protect for closing the
4195 file. */
4196 specpdl_ptr--;
4198 if (!NILP (visit))
4200 if (!EQ (BVAR (current_buffer, undo_list), Qt) && !nochange)
4201 bset_undo_list (current_buffer, Qnil);
4203 if (NILP (handler))
4205 current_buffer->modtime = mtime;
4206 current_buffer->modtime_size = st.st_size;
4207 bset_filename (current_buffer, orig_filename);
4210 SAVE_MODIFF = MODIFF;
4211 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4212 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4213 #ifdef CLASH_DETECTION
4214 if (NILP (handler))
4216 if (!NILP (BVAR (current_buffer, file_truename)))
4217 unlock_file (BVAR (current_buffer, file_truename));
4218 unlock_file (filename);
4220 #endif /* CLASH_DETECTION */
4221 if (not_regular)
4222 xsignal2 (Qfile_error,
4223 build_string ("not a regular file"), orig_filename);
4226 if (set_coding_system)
4227 Vlast_coding_system_used = coding_system;
4229 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4231 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4232 visit);
4233 if (! NILP (insval))
4235 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4236 wrong_type_argument (intern ("inserted-chars"), insval);
4237 inserted = XFASTINT (insval);
4241 /* Decode file format. */
4242 if (inserted > 0)
4244 /* Don't run point motion or modification hooks when decoding. */
4245 ptrdiff_t count1 = SPECPDL_INDEX ();
4246 ptrdiff_t old_inserted = inserted;
4247 specbind (Qinhibit_point_motion_hooks, Qt);
4248 specbind (Qinhibit_modification_hooks, Qt);
4250 /* Save old undo list and don't record undo for decoding. */
4251 old_undo = BVAR (current_buffer, undo_list);
4252 bset_undo_list (current_buffer, Qt);
4254 if (NILP (replace))
4256 insval = call3 (Qformat_decode,
4257 Qnil, make_number (inserted), visit);
4258 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4259 wrong_type_argument (intern ("inserted-chars"), insval);
4260 inserted = XFASTINT (insval);
4262 else
4264 /* If REPLACE is non-nil and we succeeded in not replacing the
4265 beginning or end of the buffer text with the file's contents,
4266 call format-decode with `point' positioned at the beginning
4267 of the buffer and `inserted' equaling the number of
4268 characters in the buffer. Otherwise, format-decode might
4269 fail to correctly analyze the beginning or end of the buffer.
4270 Hence we temporarily save `point' and `inserted' here and
4271 restore `point' iff format-decode did not insert or delete
4272 any text. Otherwise we leave `point' at point-min. */
4273 ptrdiff_t opoint = PT;
4274 ptrdiff_t opoint_byte = PT_BYTE;
4275 ptrdiff_t oinserted = ZV - BEGV;
4276 EMACS_INT ochars_modiff = CHARS_MODIFF;
4278 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4279 insval = call3 (Qformat_decode,
4280 Qnil, make_number (oinserted), visit);
4281 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4282 wrong_type_argument (intern ("inserted-chars"), insval);
4283 if (ochars_modiff == CHARS_MODIFF)
4284 /* format_decode didn't modify buffer's characters => move
4285 point back to position before inserted text and leave
4286 value of inserted alone. */
4287 SET_PT_BOTH (opoint, opoint_byte);
4288 else
4289 /* format_decode modified buffer's characters => consider
4290 entire buffer changed and leave point at point-min. */
4291 inserted = XFASTINT (insval);
4294 /* For consistency with format-decode call these now iff inserted > 0
4295 (martin 2007-06-28). */
4296 p = Vafter_insert_file_functions;
4297 while (CONSP (p))
4299 if (NILP (replace))
4301 insval = call1 (XCAR (p), make_number (inserted));
4302 if (!NILP (insval))
4304 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4305 wrong_type_argument (intern ("inserted-chars"), insval);
4306 inserted = XFASTINT (insval);
4309 else
4311 /* For the rationale of this see the comment on
4312 format-decode above. */
4313 ptrdiff_t opoint = PT;
4314 ptrdiff_t opoint_byte = PT_BYTE;
4315 ptrdiff_t oinserted = ZV - BEGV;
4316 EMACS_INT ochars_modiff = CHARS_MODIFF;
4318 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4319 insval = call1 (XCAR (p), make_number (oinserted));
4320 if (!NILP (insval))
4322 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4323 wrong_type_argument (intern ("inserted-chars"), insval);
4324 if (ochars_modiff == CHARS_MODIFF)
4325 /* after_insert_file_functions didn't modify
4326 buffer's characters => move point back to
4327 position before inserted text and leave value of
4328 inserted alone. */
4329 SET_PT_BOTH (opoint, opoint_byte);
4330 else
4331 /* after_insert_file_functions did modify buffer's
4332 characters => consider entire buffer changed and
4333 leave point at point-min. */
4334 inserted = XFASTINT (insval);
4338 QUIT;
4339 p = XCDR (p);
4342 if (NILP (visit))
4344 bset_undo_list (current_buffer, old_undo);
4345 if (CONSP (old_undo) && inserted != old_inserted)
4347 /* Adjust the last undo record for the size change during
4348 the format conversion. */
4349 Lisp_Object tem = XCAR (old_undo);
4350 if (CONSP (tem) && INTEGERP (XCAR (tem))
4351 && INTEGERP (XCDR (tem))
4352 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4353 XSETCDR (tem, make_number (PT + inserted));
4356 else
4357 /* If undo_list was Qt before, keep it that way.
4358 Otherwise start with an empty undo_list. */
4359 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4361 unbind_to (count1, Qnil);
4364 if (!NILP (visit)
4365 && EMACS_NSECS (current_buffer->modtime) == NONEXISTENT_MODTIME_NSECS)
4367 /* If visiting nonexistent file, return nil. */
4368 errno = save_errno;
4369 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4372 if (read_quit)
4373 Fsignal (Qquit, Qnil);
4375 /* ??? Retval needs to be dealt with in all cases consistently. */
4376 if (NILP (val))
4377 val = Fcons (orig_filename,
4378 Fcons (make_number (inserted),
4379 Qnil));
4381 RETURN_UNGCPRO (unbind_to (count, val));
4384 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4386 static Lisp_Object
4387 build_annotations_unwind (Lisp_Object arg)
4389 Vwrite_region_annotation_buffers = arg;
4390 return Qnil;
4393 /* Decide the coding-system to encode the data with. */
4395 static Lisp_Object
4396 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4397 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4398 struct coding_system *coding)
4400 Lisp_Object val;
4401 Lisp_Object eol_parent = Qnil;
4403 if (auto_saving
4404 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4405 BVAR (current_buffer, auto_save_file_name))))
4407 val = Qutf_8_emacs;
4408 eol_parent = Qunix;
4410 else if (!NILP (Vcoding_system_for_write))
4412 val = Vcoding_system_for_write;
4413 if (coding_system_require_warning
4414 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4415 /* Confirm that VAL can surely encode the current region. */
4416 val = call5 (Vselect_safe_coding_system_function,
4417 start, end, Fcons (Qt, Fcons (val, Qnil)),
4418 Qnil, filename);
4420 else
4422 /* If the variable `buffer-file-coding-system' is set locally,
4423 it means that the file was read with some kind of code
4424 conversion or the variable is explicitly set by users. We
4425 had better write it out with the same coding system even if
4426 `enable-multibyte-characters' is nil.
4428 If it is not set locally, we anyway have to convert EOL
4429 format if the default value of `buffer-file-coding-system'
4430 tells that it is not Unix-like (LF only) format. */
4431 bool using_default_coding = 0;
4432 bool force_raw_text = 0;
4434 val = BVAR (current_buffer, buffer_file_coding_system);
4435 if (NILP (val)
4436 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4438 val = Qnil;
4439 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4440 force_raw_text = 1;
4443 if (NILP (val))
4445 /* Check file-coding-system-alist. */
4446 Lisp_Object args[7], coding_systems;
4448 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4449 args[3] = filename; args[4] = append; args[5] = visit;
4450 args[6] = lockname;
4451 coding_systems = Ffind_operation_coding_system (7, args);
4452 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4453 val = XCDR (coding_systems);
4456 if (NILP (val))
4458 /* If we still have not decided a coding system, use the
4459 default value of buffer-file-coding-system. */
4460 val = BVAR (current_buffer, buffer_file_coding_system);
4461 using_default_coding = 1;
4464 if (! NILP (val) && ! force_raw_text)
4466 Lisp_Object spec, attrs;
4468 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4469 attrs = AREF (spec, 0);
4470 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4471 force_raw_text = 1;
4474 if (!force_raw_text
4475 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4476 /* Confirm that VAL can surely encode the current region. */
4477 val = call5 (Vselect_safe_coding_system_function,
4478 start, end, val, Qnil, filename);
4480 /* If the decided coding-system doesn't specify end-of-line
4481 format, we use that of
4482 `default-buffer-file-coding-system'. */
4483 if (! using_default_coding
4484 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4485 val = (coding_inherit_eol_type
4486 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4488 /* If we decide not to encode text, use `raw-text' or one of its
4489 subsidiaries. */
4490 if (force_raw_text)
4491 val = raw_text_coding_system (val);
4494 val = coding_inherit_eol_type (val, eol_parent);
4495 setup_coding_system (val, coding);
4497 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4498 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4499 return val;
4502 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4503 "r\nFWrite region to file: \ni\ni\ni\np",
4504 doc: /* Write current region into specified file.
4505 When called from a program, requires three arguments:
4506 START, END and FILENAME. START and END are normally buffer positions
4507 specifying the part of the buffer to write.
4508 If START is nil, that means to use the entire buffer contents.
4509 If START is a string, then output that string to the file
4510 instead of any buffer contents; END is ignored.
4512 Optional fourth argument APPEND if non-nil means
4513 append to existing file contents (if any). If it is an integer,
4514 seek to that offset in the file before writing.
4515 Optional fifth argument VISIT, if t or a string, means
4516 set the last-save-file-modtime of buffer to this file's modtime
4517 and mark buffer not modified.
4518 If VISIT is a string, it is a second file name;
4519 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4520 VISIT is also the file name to lock and unlock for clash detection.
4521 If VISIT is neither t nor nil nor a string,
4522 that means do not display the \"Wrote file\" message.
4523 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4524 use for locking and unlocking, overriding FILENAME and VISIT.
4525 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4526 for an existing file with the same name. If MUSTBENEW is `excl',
4527 that means to get an error if the file already exists; never overwrite.
4528 If MUSTBENEW is neither nil nor `excl', that means ask for
4529 confirmation before overwriting, but do go ahead and overwrite the file
4530 if the user confirms.
4532 This does code conversion according to the value of
4533 `coding-system-for-write', `buffer-file-coding-system', or
4534 `file-coding-system-alist', and sets the variable
4535 `last-coding-system-used' to the coding system actually used.
4537 This calls `write-region-annotate-functions' at the start, and
4538 `write-region-post-annotation-function' at the end. */)
4539 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append, Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4541 int desc;
4542 bool ok;
4543 int save_errno = 0;
4544 const char *fn;
4545 struct stat st;
4546 EMACS_TIME modtime;
4547 ptrdiff_t count = SPECPDL_INDEX ();
4548 int count1;
4549 Lisp_Object handler;
4550 Lisp_Object visit_file;
4551 Lisp_Object annotations;
4552 Lisp_Object encoded_filename;
4553 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4554 bool quietly = !NILP (visit);
4555 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4556 struct buffer *given_buffer;
4557 struct coding_system coding;
4559 if (current_buffer->base_buffer && visiting)
4560 error ("Cannot do file visiting in an indirect buffer");
4562 if (!NILP (start) && !STRINGP (start))
4563 validate_region (&start, &end);
4565 visit_file = Qnil;
4566 GCPRO5 (start, filename, visit, visit_file, lockname);
4568 filename = Fexpand_file_name (filename, Qnil);
4570 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4571 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4573 if (STRINGP (visit))
4574 visit_file = Fexpand_file_name (visit, Qnil);
4575 else
4576 visit_file = filename;
4578 if (NILP (lockname))
4579 lockname = visit_file;
4581 annotations = Qnil;
4583 /* If the file name has special constructs in it,
4584 call the corresponding file handler. */
4585 handler = Ffind_file_name_handler (filename, Qwrite_region);
4586 /* If FILENAME has no handler, see if VISIT has one. */
4587 if (NILP (handler) && STRINGP (visit))
4588 handler = Ffind_file_name_handler (visit, Qwrite_region);
4590 if (!NILP (handler))
4592 Lisp_Object val;
4593 val = call6 (handler, Qwrite_region, start, end,
4594 filename, append, visit);
4596 if (visiting)
4598 SAVE_MODIFF = MODIFF;
4599 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4600 bset_filename (current_buffer, visit_file);
4602 UNGCPRO;
4603 return val;
4606 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4608 /* Special kludge to simplify auto-saving. */
4609 if (NILP (start))
4611 /* Do it later, so write-region-annotate-function can work differently
4612 if we save "the buffer" vs "a region".
4613 This is useful in tar-mode. --Stef
4614 XSETFASTINT (start, BEG);
4615 XSETFASTINT (end, Z); */
4616 Fwiden ();
4619 record_unwind_protect (build_annotations_unwind,
4620 Vwrite_region_annotation_buffers);
4621 Vwrite_region_annotation_buffers = Fcons (Fcurrent_buffer (), Qnil);
4622 count1 = SPECPDL_INDEX ();
4624 given_buffer = current_buffer;
4626 if (!STRINGP (start))
4628 annotations = build_annotations (start, end);
4630 if (current_buffer != given_buffer)
4632 XSETFASTINT (start, BEGV);
4633 XSETFASTINT (end, ZV);
4637 if (NILP (start))
4639 XSETFASTINT (start, BEGV);
4640 XSETFASTINT (end, ZV);
4643 UNGCPRO;
4645 GCPRO5 (start, filename, annotations, visit_file, lockname);
4647 /* Decide the coding-system to encode the data with.
4648 We used to make this choice before calling build_annotations, but that
4649 leads to problems when a write-annotate-function takes care of
4650 unsavable chars (as was the case with X-Symbol). */
4651 Vlast_coding_system_used
4652 = choose_write_coding_system (start, end, filename,
4653 append, visit, lockname, &coding);
4655 #ifdef CLASH_DETECTION
4656 if (!auto_saving)
4657 lock_file (lockname);
4658 #endif /* CLASH_DETECTION */
4660 encoded_filename = ENCODE_FILE (filename);
4662 fn = SSDATA (encoded_filename);
4663 desc = -1;
4664 if (!NILP (append))
4665 #ifdef DOS_NT
4666 desc = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4667 #else /* not DOS_NT */
4668 desc = emacs_open (fn, O_WRONLY, 0);
4669 #endif /* not DOS_NT */
4671 if (desc < 0 && (NILP (append) || errno == ENOENT))
4672 #ifdef DOS_NT
4673 desc = emacs_open (fn,
4674 O_WRONLY | O_CREAT | O_BINARY
4675 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
4676 S_IREAD | S_IWRITE);
4677 #else /* not DOS_NT */
4678 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
4679 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
4680 auto_saving ? auto_save_mode_bits : 0666);
4681 #endif /* not DOS_NT */
4683 if (desc < 0)
4685 #ifdef CLASH_DETECTION
4686 save_errno = errno;
4687 if (!auto_saving) unlock_file (lockname);
4688 errno = save_errno;
4689 #endif /* CLASH_DETECTION */
4690 UNGCPRO;
4691 report_file_error ("Opening output file", Fcons (filename, Qnil));
4694 record_unwind_protect (close_file_unwind, make_number (desc));
4696 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
4698 off_t ret;
4700 if (NUMBERP (append))
4701 ret = emacs_lseek (desc, XINT (append), SEEK_CUR);
4702 else
4703 ret = lseek (desc, 0, SEEK_END);
4704 if (ret < 0)
4706 #ifdef CLASH_DETECTION
4707 save_errno = errno;
4708 if (!auto_saving) unlock_file (lockname);
4709 errno = save_errno;
4710 #endif /* CLASH_DETECTION */
4711 UNGCPRO;
4712 report_file_error ("Lseek error", Fcons (filename, Qnil));
4716 UNGCPRO;
4718 immediate_quit = 1;
4720 if (STRINGP (start))
4721 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4722 else if (XINT (start) != XINT (end))
4723 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4724 &annotations, &coding);
4725 else
4727 /* If file was empty, still need to write the annotations. */
4728 coding.mode |= CODING_MODE_LAST_BLOCK;
4729 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4731 save_errno = errno;
4733 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4734 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4736 /* We have to flush out a data. */
4737 coding.mode |= CODING_MODE_LAST_BLOCK;
4738 ok = e_write (desc, Qnil, 1, 1, &coding);
4739 save_errno = errno;
4742 immediate_quit = 0;
4744 #ifdef HAVE_FSYNC
4745 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4746 Disk full in NFS may be reported here. */
4747 /* mib says that closing the file will try to write as fast as NFS can do
4748 it, and that means the fsync here is not crucial for autosave files. */
4749 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
4751 /* If fsync fails with EINTR, don't treat that as serious. Also
4752 ignore EINVAL which happens when fsync is not supported on this
4753 file. */
4754 if (errno != EINTR && errno != EINVAL)
4755 ok = 0, save_errno = errno;
4757 #endif
4759 modtime = invalid_emacs_time ();
4760 if (visiting)
4762 if (fstat (desc, &st) == 0)
4763 modtime = get_stat_mtime (&st);
4764 else
4765 ok = 0, save_errno = errno;
4768 /* NFS can report a write failure now. */
4769 if (emacs_close (desc) < 0)
4770 ok = 0, save_errno = errno;
4772 /* Discard the unwind protect for close_file_unwind. */
4773 specpdl_ptr = specpdl + count1;
4775 /* Call write-region-post-annotation-function. */
4776 while (CONSP (Vwrite_region_annotation_buffers))
4778 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4779 if (!NILP (Fbuffer_live_p (buf)))
4781 Fset_buffer (buf);
4782 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4783 call0 (Vwrite_region_post_annotation_function);
4785 Vwrite_region_annotation_buffers
4786 = XCDR (Vwrite_region_annotation_buffers);
4789 unbind_to (count, Qnil);
4791 #ifdef CLASH_DETECTION
4792 if (!auto_saving)
4793 unlock_file (lockname);
4794 #endif /* CLASH_DETECTION */
4796 /* Do this before reporting IO error
4797 to avoid a "file has changed on disk" warning on
4798 next attempt to save. */
4799 if (EMACS_TIME_VALID_P (modtime))
4801 current_buffer->modtime = modtime;
4802 current_buffer->modtime_size = st.st_size;
4805 if (! ok)
4806 error ("IO error writing %s: %s", SDATA (filename),
4807 emacs_strerror (save_errno));
4809 if (visiting)
4811 SAVE_MODIFF = MODIFF;
4812 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4813 bset_filename (current_buffer, visit_file);
4814 update_mode_lines++;
4816 else if (quietly)
4818 if (auto_saving
4819 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
4820 BVAR (current_buffer, auto_save_file_name))))
4821 SAVE_MODIFF = MODIFF;
4823 return Qnil;
4826 if (!auto_saving)
4827 message_with_string ((INTEGERP (append)
4828 ? "Updated %s"
4829 : ! NILP (append)
4830 ? "Added to %s"
4831 : "Wrote %s"),
4832 visit_file, 1);
4834 return Qnil;
4837 Lisp_Object merge (Lisp_Object, Lisp_Object, Lisp_Object);
4839 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4840 doc: /* Return t if (car A) is numerically less than (car B). */)
4841 (Lisp_Object a, Lisp_Object b)
4843 return Flss (Fcar (a), Fcar (b));
4846 /* Build the complete list of annotations appropriate for writing out
4847 the text between START and END, by calling all the functions in
4848 write-region-annotate-functions and merging the lists they return.
4849 If one of these functions switches to a different buffer, we assume
4850 that buffer contains altered text. Therefore, the caller must
4851 make sure to restore the current buffer in all cases,
4852 as save-excursion would do. */
4854 static Lisp_Object
4855 build_annotations (Lisp_Object start, Lisp_Object end)
4857 Lisp_Object annotations;
4858 Lisp_Object p, res;
4859 struct gcpro gcpro1, gcpro2;
4860 Lisp_Object original_buffer;
4861 int i;
4862 bool used_global = 0;
4864 XSETBUFFER (original_buffer, current_buffer);
4866 annotations = Qnil;
4867 p = Vwrite_region_annotate_functions;
4868 GCPRO2 (annotations, p);
4869 while (CONSP (p))
4871 struct buffer *given_buffer = current_buffer;
4872 if (EQ (Qt, XCAR (p)) && !used_global)
4873 { /* Use the global value of the hook. */
4874 Lisp_Object arg[2];
4875 used_global = 1;
4876 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
4877 arg[1] = XCDR (p);
4878 p = Fappend (2, arg);
4879 continue;
4881 Vwrite_region_annotations_so_far = annotations;
4882 res = call2 (XCAR (p), start, end);
4883 /* If the function makes a different buffer current,
4884 assume that means this buffer contains altered text to be output.
4885 Reset START and END from the buffer bounds
4886 and discard all previous annotations because they should have
4887 been dealt with by this function. */
4888 if (current_buffer != given_buffer)
4890 Vwrite_region_annotation_buffers
4891 = Fcons (Fcurrent_buffer (),
4892 Vwrite_region_annotation_buffers);
4893 XSETFASTINT (start, BEGV);
4894 XSETFASTINT (end, ZV);
4895 annotations = Qnil;
4897 Flength (res); /* Check basic validity of return value */
4898 annotations = merge (annotations, res, Qcar_less_than_car);
4899 p = XCDR (p);
4902 /* Now do the same for annotation functions implied by the file-format */
4903 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
4904 p = BVAR (current_buffer, auto_save_file_format);
4905 else
4906 p = BVAR (current_buffer, file_format);
4907 for (i = 0; CONSP (p); p = XCDR (p), ++i)
4909 struct buffer *given_buffer = current_buffer;
4911 Vwrite_region_annotations_so_far = annotations;
4913 /* Value is either a list of annotations or nil if the function
4914 has written annotations to a temporary buffer, which is now
4915 current. */
4916 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
4917 original_buffer, make_number (i));
4918 if (current_buffer != given_buffer)
4920 XSETFASTINT (start, BEGV);
4921 XSETFASTINT (end, ZV);
4922 annotations = Qnil;
4925 if (CONSP (res))
4926 annotations = merge (annotations, res, Qcar_less_than_car);
4929 UNGCPRO;
4930 return annotations;
4934 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
4935 If STRING is nil, POS is the character position in the current buffer.
4936 Intersperse with them the annotations from *ANNOT
4937 which fall within the range of POS to POS + NCHARS,
4938 each at its appropriate position.
4940 We modify *ANNOT by discarding elements as we use them up.
4942 Return true if successful. */
4944 static bool
4945 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
4946 ptrdiff_t nchars, Lisp_Object *annot,
4947 struct coding_system *coding)
4949 Lisp_Object tem;
4950 ptrdiff_t nextpos;
4951 ptrdiff_t lastpos = pos + nchars;
4953 while (NILP (*annot) || CONSP (*annot))
4955 tem = Fcar_safe (Fcar (*annot));
4956 nextpos = pos - 1;
4957 if (INTEGERP (tem))
4958 nextpos = XFASTINT (tem);
4960 /* If there are no more annotations in this range,
4961 output the rest of the range all at once. */
4962 if (! (nextpos >= pos && nextpos <= lastpos))
4963 return e_write (desc, string, pos, lastpos, coding);
4965 /* Output buffer text up to the next annotation's position. */
4966 if (nextpos > pos)
4968 if (!e_write (desc, string, pos, nextpos, coding))
4969 return 0;
4970 pos = nextpos;
4972 /* Output the annotation. */
4973 tem = Fcdr (Fcar (*annot));
4974 if (STRINGP (tem))
4976 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
4977 return 0;
4979 *annot = Fcdr (*annot);
4981 return 1;
4985 /* Write text in the range START and END into descriptor DESC,
4986 encoding them with coding system CODING. If STRING is nil, START
4987 and END are character positions of the current buffer, else they
4988 are indexes to the string STRING. Return true if successful. */
4990 static bool
4991 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
4992 struct coding_system *coding)
4994 if (STRINGP (string))
4996 start = 0;
4997 end = SCHARS (string);
5000 /* We used to have a code for handling selective display here. But,
5001 now it is handled within encode_coding. */
5003 while (start < end)
5005 if (STRINGP (string))
5007 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5008 if (CODING_REQUIRE_ENCODING (coding))
5010 encode_coding_object (coding, string,
5011 start, string_char_to_byte (string, start),
5012 end, string_char_to_byte (string, end), Qt);
5014 else
5016 coding->dst_object = string;
5017 coding->consumed_char = SCHARS (string);
5018 coding->produced = SBYTES (string);
5021 else
5023 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5024 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5026 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5027 if (CODING_REQUIRE_ENCODING (coding))
5029 encode_coding_object (coding, Fcurrent_buffer (),
5030 start, start_byte, end, end_byte, Qt);
5032 else
5034 coding->dst_object = Qnil;
5035 coding->dst_pos_byte = start_byte;
5036 if (start >= GPT || end <= GPT)
5038 coding->consumed_char = end - start;
5039 coding->produced = end_byte - start_byte;
5041 else
5043 coding->consumed_char = GPT - start;
5044 coding->produced = GPT_BYTE - start_byte;
5049 if (coding->produced > 0)
5051 coding->produced
5052 -= emacs_write (desc,
5053 STRINGP (coding->dst_object)
5054 ? SSDATA (coding->dst_object)
5055 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte),
5056 coding->produced);
5058 if (coding->produced)
5059 return 0;
5061 start += coding->consumed_char;
5064 return 1;
5067 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5068 Sverify_visited_file_modtime, 0, 1, 0,
5069 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5070 This means that the file has not been changed since it was visited or saved.
5071 If BUF is omitted or nil, it defaults to the current buffer.
5072 See Info node `(elisp)Modification Time' for more details. */)
5073 (Lisp_Object buf)
5075 struct buffer *b;
5076 struct stat st;
5077 Lisp_Object handler;
5078 Lisp_Object filename;
5079 EMACS_TIME mtime, diff;
5081 if (NILP (buf))
5082 b = current_buffer;
5083 else
5085 CHECK_BUFFER (buf);
5086 b = XBUFFER (buf);
5089 if (!STRINGP (BVAR (b, filename))) return Qt;
5090 if (EMACS_NSECS (b->modtime) == UNKNOWN_MODTIME_NSECS) return Qt;
5092 /* If the file name has special constructs in it,
5093 call the corresponding file handler. */
5094 handler = Ffind_file_name_handler (BVAR (b, filename),
5095 Qverify_visited_file_modtime);
5096 if (!NILP (handler))
5097 return call2 (handler, Qverify_visited_file_modtime, buf);
5099 filename = ENCODE_FILE (BVAR (b, filename));
5101 mtime = (stat (SSDATA (filename), &st) == 0
5102 ? get_stat_mtime (&st)
5103 : time_error_value (errno));
5104 if ((EMACS_TIME_EQ (mtime, b->modtime)
5105 /* If both exist, accept them if they are off by one second. */
5106 || (EMACS_TIME_VALID_P (mtime) && EMACS_TIME_VALID_P (b->modtime)
5107 && ((diff = (EMACS_TIME_LT (mtime, b->modtime)
5108 ? sub_emacs_time (b->modtime, mtime)
5109 : sub_emacs_time (mtime, b->modtime))),
5110 EMACS_TIME_LE (diff, make_emacs_time (1, 0)))))
5111 && (st.st_size == b->modtime_size
5112 || b->modtime_size < 0))
5113 return Qt;
5114 return Qnil;
5117 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5118 Sclear_visited_file_modtime, 0, 0, 0,
5119 doc: /* Clear out records of last mod time of visited file.
5120 Next attempt to save will certainly not complain of a discrepancy. */)
5121 (void)
5123 current_buffer->modtime = make_emacs_time (0, UNKNOWN_MODTIME_NSECS);
5124 current_buffer->modtime_size = -1;
5125 return Qnil;
5128 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5129 Svisited_file_modtime, 0, 0, 0,
5130 doc: /* Return the current buffer's recorded visited file modification time.
5131 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5132 `file-attributes' returns. If the current buffer has no recorded file
5133 modification time, this function returns 0. If the visited file
5134 doesn't exist, HIGH will be -1.
5135 See Info node `(elisp)Modification Time' for more details. */)
5136 (void)
5138 if (EMACS_NSECS (current_buffer->modtime) < 0)
5139 return make_number (0);
5140 return make_lisp_time (current_buffer->modtime);
5143 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5144 Sset_visited_file_modtime, 0, 1, 0,
5145 doc: /* Update buffer's recorded modification time from the visited file's time.
5146 Useful if the buffer was not read from the file normally
5147 or if the file itself has been changed for some known benign reason.
5148 An argument specifies the modification time value to use
5149 \(instead of that of the visited file), in the form of a list
5150 \(HIGH LOW USEC PSEC) as returned by `current-time'. */)
5151 (Lisp_Object time_list)
5153 if (!NILP (time_list))
5155 current_buffer->modtime = lisp_time_argument (time_list);
5156 current_buffer->modtime_size = -1;
5158 else
5160 register Lisp_Object filename;
5161 struct stat st;
5162 Lisp_Object handler;
5164 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5166 /* If the file name has special constructs in it,
5167 call the corresponding file handler. */
5168 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5169 if (!NILP (handler))
5170 /* The handler can find the file name the same way we did. */
5171 return call2 (handler, Qset_visited_file_modtime, Qnil);
5173 filename = ENCODE_FILE (filename);
5175 if (stat (SSDATA (filename), &st) >= 0)
5177 current_buffer->modtime = get_stat_mtime (&st);
5178 current_buffer->modtime_size = st.st_size;
5182 return Qnil;
5185 static Lisp_Object
5186 auto_save_error (Lisp_Object error_val)
5188 Lisp_Object args[3], msg;
5189 int i, nbytes;
5190 struct gcpro gcpro1;
5191 char *msgbuf;
5192 USE_SAFE_ALLOCA;
5194 auto_save_error_occurred = 1;
5196 ring_bell (XFRAME (selected_frame));
5198 args[0] = build_string ("Auto-saving %s: %s");
5199 args[1] = BVAR (current_buffer, name);
5200 args[2] = Ferror_message_string (error_val);
5201 msg = Fformat (3, args);
5202 GCPRO1 (msg);
5203 nbytes = SBYTES (msg);
5204 msgbuf = SAFE_ALLOCA (nbytes);
5205 memcpy (msgbuf, SDATA (msg), nbytes);
5207 for (i = 0; i < 3; ++i)
5209 if (i == 0)
5210 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5211 else
5212 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5213 Fsleep_for (make_number (1), Qnil);
5216 SAFE_FREE ();
5217 UNGCPRO;
5218 return Qnil;
5221 static Lisp_Object
5222 auto_save_1 (void)
5224 struct stat st;
5225 Lisp_Object modes;
5227 auto_save_mode_bits = 0666;
5229 /* Get visited file's mode to become the auto save file's mode. */
5230 if (! NILP (BVAR (current_buffer, filename)))
5232 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5233 /* But make sure we can overwrite it later! */
5234 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5235 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5236 INTEGERP (modes))
5237 /* Remote files don't cooperate with stat. */
5238 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5241 return
5242 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5243 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5244 Qnil, Qnil);
5247 static Lisp_Object
5248 do_auto_save_unwind (Lisp_Object arg) /* used as unwind-protect function */
5251 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5252 auto_saving = 0;
5253 if (stream != NULL)
5255 block_input ();
5256 fclose (stream);
5257 unblock_input ();
5259 return Qnil;
5262 static Lisp_Object
5263 do_auto_save_unwind_1 (Lisp_Object value) /* used as unwind-protect function */
5266 minibuffer_auto_raise = XINT (value);
5267 return Qnil;
5270 static Lisp_Object
5271 do_auto_save_make_dir (Lisp_Object dir)
5273 Lisp_Object result;
5275 auto_saving_dir_umask = 077;
5276 result = call2 (Qmake_directory, dir, Qt);
5277 auto_saving_dir_umask = 0;
5278 return result;
5281 static Lisp_Object
5282 do_auto_save_eh (Lisp_Object ignore)
5284 auto_saving_dir_umask = 0;
5285 return Qnil;
5288 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5289 doc: /* Auto-save all buffers that need it.
5290 This is all buffers that have auto-saving enabled
5291 and are changed since last auto-saved.
5292 Auto-saving writes the buffer into a file
5293 so that your editing is not lost if the system crashes.
5294 This file is not the file you visited; that changes only when you save.
5295 Normally we run the normal hook `auto-save-hook' before saving.
5297 A non-nil NO-MESSAGE argument means do not print any message if successful.
5298 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5299 (Lisp_Object no_message, Lisp_Object current_only)
5301 struct buffer *old = current_buffer, *b;
5302 Lisp_Object tail, buf, hook;
5303 bool auto_saved = 0;
5304 int do_handled_files;
5305 Lisp_Object oquit;
5306 FILE *stream = NULL;
5307 ptrdiff_t count = SPECPDL_INDEX ();
5308 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5309 bool old_message_p = 0;
5310 struct gcpro gcpro1, gcpro2;
5312 if (max_specpdl_size < specpdl_size + 40)
5313 max_specpdl_size = specpdl_size + 40;
5315 if (minibuf_level)
5316 no_message = Qt;
5318 if (NILP (no_message))
5320 old_message_p = push_message ();
5321 record_unwind_protect (pop_message_unwind, Qnil);
5324 /* Ordinarily don't quit within this function,
5325 but don't make it impossible to quit (in case we get hung in I/O). */
5326 oquit = Vquit_flag;
5327 Vquit_flag = Qnil;
5329 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5330 point to non-strings reached from Vbuffer_alist. */
5332 hook = intern ("auto-save-hook");
5333 Frun_hooks (1, &hook);
5335 if (STRINGP (Vauto_save_list_file_name))
5337 Lisp_Object listfile;
5339 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5341 /* Don't try to create the directory when shutting down Emacs,
5342 because creating the directory might signal an error, and
5343 that would leave Emacs in a strange state. */
5344 if (!NILP (Vrun_hooks))
5346 Lisp_Object dir;
5347 dir = Qnil;
5348 GCPRO2 (dir, listfile);
5349 dir = Ffile_name_directory (listfile);
5350 if (NILP (Ffile_directory_p (dir)))
5351 internal_condition_case_1 (do_auto_save_make_dir,
5352 dir, Qt,
5353 do_auto_save_eh);
5354 UNGCPRO;
5357 stream = fopen (SSDATA (listfile), "w");
5360 record_unwind_protect (do_auto_save_unwind,
5361 make_save_value (stream, 0));
5362 record_unwind_protect (do_auto_save_unwind_1,
5363 make_number (minibuffer_auto_raise));
5364 minibuffer_auto_raise = 0;
5365 auto_saving = 1;
5366 auto_save_error_occurred = 0;
5368 /* On first pass, save all files that don't have handlers.
5369 On second pass, save all files that do have handlers.
5371 If Emacs is crashing, the handlers may tweak what is causing
5372 Emacs to crash in the first place, and it would be a shame if
5373 Emacs failed to autosave perfectly ordinary files because it
5374 couldn't handle some ange-ftp'd file. */
5376 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5377 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5379 buf = XCDR (XCAR (tail));
5380 b = XBUFFER (buf);
5382 /* Record all the buffers that have auto save mode
5383 in the special file that lists them. For each of these buffers,
5384 Record visited name (if any) and auto save name. */
5385 if (STRINGP (BVAR (b, auto_save_file_name))
5386 && stream != NULL && do_handled_files == 0)
5388 block_input ();
5389 if (!NILP (BVAR (b, filename)))
5391 fwrite (SDATA (BVAR (b, filename)), 1,
5392 SBYTES (BVAR (b, filename)), stream);
5394 putc ('\n', stream);
5395 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5396 SBYTES (BVAR (b, auto_save_file_name)), stream);
5397 putc ('\n', stream);
5398 unblock_input ();
5401 if (!NILP (current_only)
5402 && b != current_buffer)
5403 continue;
5405 /* Don't auto-save indirect buffers.
5406 The base buffer takes care of it. */
5407 if (b->base_buffer)
5408 continue;
5410 /* Check for auto save enabled
5411 and file changed since last auto save
5412 and file changed since last real save. */
5413 if (STRINGP (BVAR (b, auto_save_file_name))
5414 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5415 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5416 /* -1 means we've turned off autosaving for a while--see below. */
5417 && XINT (BVAR (b, save_length)) >= 0
5418 && (do_handled_files
5419 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5420 Qwrite_region))))
5422 EMACS_TIME before_time = current_emacs_time ();
5423 EMACS_TIME after_time;
5425 /* If we had a failure, don't try again for 20 minutes. */
5426 if (b->auto_save_failure_time > 0
5427 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5428 continue;
5430 set_buffer_internal (b);
5431 if (NILP (Vauto_save_include_big_deletions)
5432 && (XFASTINT (BVAR (b, save_length)) * 10
5433 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5434 /* A short file is likely to change a large fraction;
5435 spare the user annoying messages. */
5436 && XFASTINT (BVAR (b, save_length)) > 5000
5437 /* These messages are frequent and annoying for `*mail*'. */
5438 && !EQ (BVAR (b, filename), Qnil)
5439 && NILP (no_message))
5441 /* It has shrunk too much; turn off auto-saving here. */
5442 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5443 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5444 BVAR (b, name), 1);
5445 minibuffer_auto_raise = 0;
5446 /* Turn off auto-saving until there's a real save,
5447 and prevent any more warnings. */
5448 XSETINT (BVAR (b, save_length), -1);
5449 Fsleep_for (make_number (1), Qnil);
5450 continue;
5452 if (!auto_saved && NILP (no_message))
5453 message1 ("Auto-saving...");
5454 internal_condition_case (auto_save_1, Qt, auto_save_error);
5455 auto_saved = 1;
5456 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5457 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5458 set_buffer_internal (old);
5460 after_time = current_emacs_time ();
5462 /* If auto-save took more than 60 seconds,
5463 assume it was an NFS failure that got a timeout. */
5464 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5465 b->auto_save_failure_time = EMACS_SECS (after_time);
5469 /* Prevent another auto save till enough input events come in. */
5470 record_auto_save ();
5472 if (auto_saved && NILP (no_message))
5474 if (old_message_p)
5476 /* If we are going to restore an old message,
5477 give time to read ours. */
5478 sit_for (make_number (1), 0, 0);
5479 restore_message ();
5481 else if (!auto_save_error_occurred)
5482 /* Don't overwrite the error message if an error occurred.
5483 If we displayed a message and then restored a state
5484 with no message, leave a "done" message on the screen. */
5485 message1 ("Auto-saving...done");
5488 Vquit_flag = oquit;
5490 /* This restores the message-stack status. */
5491 unbind_to (count, Qnil);
5492 return Qnil;
5495 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5496 Sset_buffer_auto_saved, 0, 0, 0,
5497 doc: /* Mark current buffer as auto-saved with its current text.
5498 No auto-save file will be written until the buffer changes again. */)
5499 (void)
5501 /* FIXME: This should not be called in indirect buffers, since
5502 they're not autosaved. */
5503 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5504 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5505 current_buffer->auto_save_failure_time = 0;
5506 return Qnil;
5509 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5510 Sclear_buffer_auto_save_failure, 0, 0, 0,
5511 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5512 (void)
5514 current_buffer->auto_save_failure_time = 0;
5515 return Qnil;
5518 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5519 0, 0, 0,
5520 doc: /* Return t if current buffer has been auto-saved recently.
5521 More precisely, if it has been auto-saved since last read from or saved
5522 in the visited file. If the buffer has no visited file,
5523 then any auto-save counts as "recent". */)
5524 (void)
5526 /* FIXME: maybe we should return nil for indirect buffers since
5527 they're never autosaved. */
5528 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5531 /* Reading and completing file names */
5533 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5534 Snext_read_file_uses_dialog_p, 0, 0, 0,
5535 doc: /* Return t if a call to `read-file-name' will use a dialog.
5536 The return value is only relevant for a call to `read-file-name' that happens
5537 before any other event (mouse or keypress) is handled. */)
5538 (void)
5540 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) \
5541 || defined (HAVE_NS)
5542 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5543 && use_dialog_box
5544 && use_file_dialog
5545 && have_menus_p ())
5546 return Qt;
5547 #endif
5548 return Qnil;
5551 Lisp_Object
5552 Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
5554 struct gcpro gcpro1;
5555 Lisp_Object args[7];
5557 GCPRO1 (default_filename);
5558 args[0] = intern ("read-file-name");
5559 args[1] = prompt;
5560 args[2] = dir;
5561 args[3] = default_filename;
5562 args[4] = mustmatch;
5563 args[5] = initial;
5564 args[6] = predicate;
5565 RETURN_UNGCPRO (Ffuncall (7, args));
5569 void
5570 syms_of_fileio (void)
5572 DEFSYM (Qoperations, "operations");
5573 DEFSYM (Qexpand_file_name, "expand-file-name");
5574 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5575 DEFSYM (Qdirectory_file_name, "directory-file-name");
5576 DEFSYM (Qfile_name_directory, "file-name-directory");
5577 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5578 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5579 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5580 DEFSYM (Qcopy_file, "copy-file");
5581 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5582 DEFSYM (Qmake_directory, "make-directory");
5583 DEFSYM (Qdelete_directory_internal, "delete-directory-internal");
5584 DEFSYM (Qdelete_file, "delete-file");
5585 DEFSYM (Qrename_file, "rename-file");
5586 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5587 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5588 DEFSYM (Qfile_exists_p, "file-exists-p");
5589 DEFSYM (Qfile_executable_p, "file-executable-p");
5590 DEFSYM (Qfile_readable_p, "file-readable-p");
5591 DEFSYM (Qfile_writable_p, "file-writable-p");
5592 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5593 DEFSYM (Qaccess_file, "access-file");
5594 DEFSYM (Qfile_directory_p, "file-directory-p");
5595 DEFSYM (Qfile_regular_p, "file-regular-p");
5596 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5597 DEFSYM (Qfile_modes, "file-modes");
5598 DEFSYM (Qset_file_modes, "set-file-modes");
5599 DEFSYM (Qset_file_times, "set-file-times");
5600 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5601 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5602 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5603 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5604 DEFSYM (Qwrite_region, "write-region");
5605 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5606 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5607 DEFSYM (Qauto_save_coding, "auto-save-coding");
5609 DEFSYM (Qfile_name_history, "file-name-history");
5610 Fset (Qfile_name_history, Qnil);
5612 DEFSYM (Qfile_error, "file-error");
5613 DEFSYM (Qfile_already_exists, "file-already-exists");
5614 DEFSYM (Qfile_date_error, "file-date-error");
5615 DEFSYM (Qexcl, "excl");
5617 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5618 doc: /* Coding system for encoding file names.
5619 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5620 Vfile_name_coding_system = Qnil;
5622 DEFVAR_LISP ("default-file-name-coding-system",
5623 Vdefault_file_name_coding_system,
5624 doc: /* Default coding system for encoding file names.
5625 This variable is used only when `file-name-coding-system' is nil.
5627 This variable is set/changed by the command `set-language-environment'.
5628 User should not set this variable manually,
5629 instead use `file-name-coding-system' to get a constant encoding
5630 of file names regardless of the current language environment. */);
5631 Vdefault_file_name_coding_system = Qnil;
5633 DEFSYM (Qformat_decode, "format-decode");
5634 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5635 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5636 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5638 Fput (Qfile_error, Qerror_conditions,
5639 Fpurecopy (list2 (Qfile_error, Qerror)));
5640 Fput (Qfile_error, Qerror_message,
5641 build_pure_c_string ("File error"));
5643 Fput (Qfile_already_exists, Qerror_conditions,
5644 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5645 Fput (Qfile_already_exists, Qerror_message,
5646 build_pure_c_string ("File already exists"));
5648 Fput (Qfile_date_error, Qerror_conditions,
5649 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5650 Fput (Qfile_date_error, Qerror_message,
5651 build_pure_c_string ("Cannot set file date"));
5653 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5654 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5655 If a file name matches REGEXP, all I/O on that file is done by calling
5656 HANDLER. If a file name matches more than one handler, the handler
5657 whose match starts last in the file name gets precedence. The
5658 function `find-file-name-handler' checks this list for a handler for
5659 its argument.
5661 HANDLER should be a function. The first argument given to it is the
5662 name of the I/O primitive to be handled; the remaining arguments are
5663 the arguments that were passed to that primitive. For example, if you
5664 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5665 HANDLER is called like this:
5667 (funcall HANDLER 'file-exists-p FILENAME)
5669 Note that HANDLER must be able to handle all I/O primitives; if it has
5670 nothing special to do for a primitive, it should reinvoke the
5671 primitive to handle the operation \"the usual way\".
5672 See Info node `(elisp)Magic File Names' for more details. */);
5673 Vfile_name_handler_alist = Qnil;
5675 DEFVAR_LISP ("set-auto-coding-function",
5676 Vset_auto_coding_function,
5677 doc: /* If non-nil, a function to call to decide a coding system of file.
5678 Two arguments are passed to this function: the file name
5679 and the length of a file contents following the point.
5680 This function should return a coding system to decode the file contents.
5681 It should check the file name against `auto-coding-alist'.
5682 If no coding system is decided, it should check a coding system
5683 specified in the heading lines with the format:
5684 -*- ... coding: CODING-SYSTEM; ... -*-
5685 or local variable spec of the tailing lines with `coding:' tag. */);
5686 Vset_auto_coding_function = Qnil;
5688 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5689 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5690 Each is passed one argument, the number of characters inserted,
5691 with point at the start of the inserted text. Each function
5692 should leave point the same, and return the new character count.
5693 If `insert-file-contents' is intercepted by a handler from
5694 `file-name-handler-alist', that handler is responsible for calling the
5695 functions in `after-insert-file-functions' if appropriate. */);
5696 Vafter_insert_file_functions = Qnil;
5698 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5699 doc: /* A list of functions to be called at the start of `write-region'.
5700 Each is passed two arguments, START and END as for `write-region'.
5701 These are usually two numbers but not always; see the documentation
5702 for `write-region'. The function should return a list of pairs
5703 of the form (POSITION . STRING), consisting of strings to be effectively
5704 inserted at the specified positions of the file being written (1 means to
5705 insert before the first byte written). The POSITIONs must be sorted into
5706 increasing order.
5708 If there are several annotation functions, the lists returned by these
5709 functions are merged destructively. As each annotation function runs,
5710 the variable `write-region-annotations-so-far' contains a list of all
5711 annotations returned by previous annotation functions.
5713 An annotation function can return with a different buffer current.
5714 Doing so removes the annotations returned by previous functions, and
5715 resets START and END to `point-min' and `point-max' of the new buffer.
5717 After `write-region' completes, Emacs calls the function stored in
5718 `write-region-post-annotation-function', once for each buffer that was
5719 current when building the annotations (i.e., at least once), with that
5720 buffer current. */);
5721 Vwrite_region_annotate_functions = Qnil;
5722 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5724 DEFVAR_LISP ("write-region-post-annotation-function",
5725 Vwrite_region_post_annotation_function,
5726 doc: /* Function to call after `write-region' completes.
5727 The function is called with no arguments. If one or more of the
5728 annotation functions in `write-region-annotate-functions' changed the
5729 current buffer, the function stored in this variable is called for
5730 each of those additional buffers as well, in addition to the original
5731 buffer. The relevant buffer is current during each function call. */);
5732 Vwrite_region_post_annotation_function = Qnil;
5733 staticpro (&Vwrite_region_annotation_buffers);
5735 DEFVAR_LISP ("write-region-annotations-so-far",
5736 Vwrite_region_annotations_so_far,
5737 doc: /* When an annotation function is called, this holds the previous annotations.
5738 These are the annotations made by other annotation functions
5739 that were already called. See also `write-region-annotate-functions'. */);
5740 Vwrite_region_annotations_so_far = Qnil;
5742 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5743 doc: /* A list of file name handlers that temporarily should not be used.
5744 This applies only to the operation `inhibit-file-name-operation'. */);
5745 Vinhibit_file_name_handlers = Qnil;
5747 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5748 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5749 Vinhibit_file_name_operation = Qnil;
5751 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
5752 doc: /* File name in which we write a list of all auto save file names.
5753 This variable is initialized automatically from `auto-save-list-file-prefix'
5754 shortly after Emacs reads your `.emacs' file, if you have not yet given it
5755 a non-nil value. */);
5756 Vauto_save_list_file_name = Qnil;
5758 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
5759 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5760 Normally auto-save files are written under other names. */);
5761 Vauto_save_visited_file_name = Qnil;
5763 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
5764 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5765 If nil, deleting a substantial portion of the text disables auto-save
5766 in the buffer; this is the default behavior, because the auto-save
5767 file is usually more useful if it contains the deleted text. */);
5768 Vauto_save_include_big_deletions = Qnil;
5770 #ifdef HAVE_FSYNC
5771 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
5772 doc: /* Non-nil means don't call fsync in `write-region'.
5773 This variable affects calls to `write-region' as well as save commands.
5774 A non-nil value may result in data loss! */);
5775 write_region_inhibit_fsync = 0;
5776 #endif
5778 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
5779 doc: /* Specifies whether to use the system's trash can.
5780 When non-nil, certain file deletion commands use the function
5781 `move-file-to-trash' instead of deleting files outright.
5782 This includes interactive calls to `delete-file' and
5783 `delete-directory' and the Dired deletion commands. */);
5784 delete_by_moving_to_trash = 0;
5785 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
5787 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
5788 DEFSYM (Qcopy_directory, "copy-directory");
5789 DEFSYM (Qdelete_directory, "delete-directory");
5791 defsubr (&Sfind_file_name_handler);
5792 defsubr (&Sfile_name_directory);
5793 defsubr (&Sfile_name_nondirectory);
5794 defsubr (&Sunhandled_file_name_directory);
5795 defsubr (&Sfile_name_as_directory);
5796 defsubr (&Sdirectory_file_name);
5797 defsubr (&Smake_temp_name);
5798 defsubr (&Sexpand_file_name);
5799 defsubr (&Ssubstitute_in_file_name);
5800 defsubr (&Scopy_file);
5801 defsubr (&Smake_directory_internal);
5802 defsubr (&Sdelete_directory_internal);
5803 defsubr (&Sdelete_file);
5804 defsubr (&Srename_file);
5805 defsubr (&Sadd_name_to_file);
5806 defsubr (&Smake_symbolic_link);
5807 defsubr (&Sfile_name_absolute_p);
5808 defsubr (&Sfile_exists_p);
5809 defsubr (&Sfile_executable_p);
5810 defsubr (&Sfile_readable_p);
5811 defsubr (&Sfile_writable_p);
5812 defsubr (&Saccess_file);
5813 defsubr (&Sfile_symlink_p);
5814 defsubr (&Sfile_directory_p);
5815 defsubr (&Sfile_accessible_directory_p);
5816 defsubr (&Sfile_regular_p);
5817 defsubr (&Sfile_modes);
5818 defsubr (&Sset_file_modes);
5819 defsubr (&Sset_file_times);
5820 defsubr (&Sfile_selinux_context);
5821 defsubr (&Sset_file_selinux_context);
5822 defsubr (&Sset_default_file_modes);
5823 defsubr (&Sdefault_file_modes);
5824 defsubr (&Sfile_newer_than_file_p);
5825 defsubr (&Sinsert_file_contents);
5826 defsubr (&Swrite_region);
5827 defsubr (&Scar_less_than_car);
5828 defsubr (&Sverify_visited_file_modtime);
5829 defsubr (&Sclear_visited_file_modtime);
5830 defsubr (&Svisited_file_modtime);
5831 defsubr (&Sset_visited_file_modtime);
5832 defsubr (&Sdo_auto_save);
5833 defsubr (&Sset_buffer_auto_saved);
5834 defsubr (&Sclear_buffer_auto_save_failure);
5835 defsubr (&Srecent_auto_save_p);
5837 defsubr (&Snext_read_file_uses_dialog_p);
5839 #ifdef HAVE_SYNC
5840 defsubr (&Sunix_sync);
5841 #endif