Merge changes made in Gnus trunk
[emacs.git] / src / fileio.c
blob9e940c9a3240117226856d20d8f1df6dced673e7
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 <setjmp.h>
27 #include <unistd.h>
29 #ifdef HAVE_PWD_H
30 #include <pwd.h>
31 #endif
33 #include <ctype.h>
34 #include <errno.h>
36 #ifdef HAVE_LIBSELINUX
37 #include <selinux/selinux.h>
38 #include <selinux/context.h>
39 #endif
41 #include "lisp.h"
42 #include "intervals.h"
43 #include "buffer.h"
44 #include "character.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 #endif /* not WINDOWSNT */
57 #ifdef MSDOS
58 #include "msdos.h"
59 #include <sys/param.h>
60 #include <fcntl.h>
61 #endif
63 #ifdef DOS_NT
64 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
65 redirector allows the six letters between 'Z' and 'a' as well. */
66 #ifdef MSDOS
67 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
68 #endif
69 #ifdef WINDOWSNT
70 #define IS_DRIVE(x) isalpha ((unsigned char) (x))
71 #endif
72 /* Need to lower-case the drive letter, or else expanded
73 filenames will sometimes compare unequal, because
74 `expand-file-name' doesn't always down-case the drive letter. */
75 #define DRIVE_LETTER(x) (tolower ((unsigned char) (x)))
76 #endif
78 #include "systime.h"
80 #ifdef HPUX
81 #include <netio.h>
82 #endif
84 #include "commands.h"
86 #ifndef FILE_SYSTEM_CASE
87 #define FILE_SYSTEM_CASE(filename) (filename)
88 #endif
90 /* Nonzero during writing of auto-save files */
91 static int auto_saving;
93 /* Nonzero umask during creation of auto-save directories */
94 static int auto_saving_dir_umask;
96 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
97 a new file with the same mode as the original */
98 static int auto_save_mode_bits;
100 /* Set by auto_save_1 if an error occurred during the last auto-save. */
101 static int auto_save_error_occurred;
103 /* The symbol bound to coding-system-for-read when
104 insert-file-contents is called for recovering a file. This is not
105 an actual coding system name, but just an indicator to tell
106 insert-file-contents to use `emacs-mule' with a special flag for
107 auto saving and recovering a file. */
108 static Lisp_Object Qauto_save_coding;
110 /* Property name of a file name handler,
111 which gives a list of operations it handles.. */
112 static Lisp_Object Qoperations;
114 /* Lisp functions for translating file formats */
115 static Lisp_Object Qformat_decode, Qformat_annotate_function;
117 /* Lisp function for setting buffer-file-coding-system and the
118 multibyteness of the current buffer after inserting a file. */
119 static Lisp_Object Qafter_insert_file_set_coding;
121 static Lisp_Object Qwrite_region_annotate_functions;
122 /* Each time an annotation function changes the buffer, the new buffer
123 is added here. */
124 static Lisp_Object Vwrite_region_annotation_buffers;
126 #ifdef HAVE_FSYNC
127 #endif
129 static Lisp_Object Qdelete_by_moving_to_trash;
131 /* Lisp function for moving files to trash. */
132 static Lisp_Object Qmove_file_to_trash;
134 /* Lisp function for recursively copying directories. */
135 static Lisp_Object Qcopy_directory;
137 /* Lisp function for recursively deleting directories. */
138 static Lisp_Object Qdelete_directory;
140 #ifdef WINDOWSNT
141 #endif
143 Lisp_Object Qfile_error;
144 static Lisp_Object Qfile_already_exists, Qfile_date_error;
145 static Lisp_Object Qexcl;
146 Lisp_Object Qfile_name_history;
148 static Lisp_Object Qcar_less_than_car;
150 static Lisp_Object Fmake_symbolic_link (Lisp_Object, Lisp_Object, Lisp_Object);
151 static int a_write (int, Lisp_Object, EMACS_INT, EMACS_INT,
152 Lisp_Object *, struct coding_system *);
153 static int e_write (int, Lisp_Object, EMACS_INT, EMACS_INT,
154 struct coding_system *);
157 void
158 report_file_error (const char *string, Lisp_Object data)
160 Lisp_Object errstring;
161 int errorno = errno;
162 char *str;
164 synchronize_system_messages_locale ();
165 str = strerror (errorno);
166 errstring = code_convert_string_norecord (make_unibyte_string (str,
167 strlen (str)),
168 Vlocale_coding_system, 0);
170 while (1)
171 switch (errorno)
173 case EEXIST:
174 xsignal (Qfile_already_exists, Fcons (errstring, data));
175 break;
176 default:
177 /* System error messages are capitalized. Downcase the initial
178 unless it is followed by a slash. (The slash case caters to
179 error messages that begin with "I/O" or, in German, "E/A".) */
180 if (STRING_MULTIBYTE (errstring)
181 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
183 int c;
185 str = SSDATA (errstring);
186 c = STRING_CHAR ((unsigned char *) str);
187 Faset (errstring, make_number (0), make_number (downcase (c)));
190 xsignal (Qfile_error,
191 Fcons (build_string (string), Fcons (errstring, data)));
195 Lisp_Object
196 close_file_unwind (Lisp_Object fd)
198 emacs_close (XFASTINT (fd));
199 return Qnil;
202 /* Restore point, having saved it as a marker. */
204 Lisp_Object
205 restore_point_unwind (Lisp_Object location)
207 Fgoto_char (location);
208 Fset_marker (location, Qnil, Qnil);
209 return Qnil;
213 static Lisp_Object Qexpand_file_name;
214 static Lisp_Object Qsubstitute_in_file_name;
215 static Lisp_Object Qdirectory_file_name;
216 static Lisp_Object Qfile_name_directory;
217 static Lisp_Object Qfile_name_nondirectory;
218 static Lisp_Object Qunhandled_file_name_directory;
219 static Lisp_Object Qfile_name_as_directory;
220 static Lisp_Object Qcopy_file;
221 static Lisp_Object Qmake_directory_internal;
222 static Lisp_Object Qmake_directory;
223 static Lisp_Object Qdelete_directory_internal;
224 Lisp_Object Qdelete_file;
225 static Lisp_Object Qrename_file;
226 static Lisp_Object Qadd_name_to_file;
227 static Lisp_Object Qmake_symbolic_link;
228 Lisp_Object Qfile_exists_p;
229 static Lisp_Object Qfile_executable_p;
230 static Lisp_Object Qfile_readable_p;
231 static Lisp_Object Qfile_writable_p;
232 static Lisp_Object Qfile_symlink_p;
233 static Lisp_Object Qaccess_file;
234 Lisp_Object Qfile_directory_p;
235 static Lisp_Object Qfile_regular_p;
236 static Lisp_Object Qfile_accessible_directory_p;
237 static Lisp_Object Qfile_modes;
238 static Lisp_Object Qset_file_modes;
239 static Lisp_Object Qset_file_times;
240 static Lisp_Object Qfile_selinux_context;
241 static Lisp_Object Qset_file_selinux_context;
242 static Lisp_Object Qfile_newer_than_file_p;
243 Lisp_Object Qinsert_file_contents;
244 Lisp_Object Qwrite_region;
245 static Lisp_Object Qverify_visited_file_modtime;
246 static Lisp_Object Qset_visited_file_modtime;
248 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
249 Sfind_file_name_handler, 2, 2, 0,
250 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
251 Otherwise, return nil.
252 A file name is handled if one of the regular expressions in
253 `file-name-handler-alist' matches it.
255 If OPERATION equals `inhibit-file-name-operation', then we ignore
256 any handlers that are members of `inhibit-file-name-handlers',
257 but we still do run any other handlers. This lets handlers
258 use the standard functions without calling themselves recursively. */)
259 (Lisp_Object filename, Lisp_Object operation)
261 /* This function must not munge the match data. */
262 Lisp_Object chain, inhibited_handlers, result;
263 int pos = -1;
265 result = Qnil;
266 CHECK_STRING (filename);
268 if (EQ (operation, Vinhibit_file_name_operation))
269 inhibited_handlers = Vinhibit_file_name_handlers;
270 else
271 inhibited_handlers = Qnil;
273 for (chain = Vfile_name_handler_alist; CONSP (chain);
274 chain = XCDR (chain))
276 Lisp_Object elt;
277 elt = XCAR (chain);
278 if (CONSP (elt))
280 Lisp_Object string = XCAR (elt);
281 EMACS_INT match_pos;
282 Lisp_Object handler = XCDR (elt);
283 Lisp_Object operations = Qnil;
285 if (SYMBOLP (handler))
286 operations = Fget (handler, Qoperations);
288 if (STRINGP (string)
289 && (match_pos = fast_string_match (string, filename)) > pos
290 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
292 Lisp_Object tem;
294 handler = XCDR (elt);
295 tem = Fmemq (handler, inhibited_handlers);
296 if (NILP (tem))
298 result = handler;
299 pos = match_pos;
304 QUIT;
306 return result;
309 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
310 1, 1, 0,
311 doc: /* Return the directory component in file name FILENAME.
312 Return nil if FILENAME does not include a directory.
313 Otherwise return a directory name.
314 Given a Unix syntax file name, returns a string ending in slash. */)
315 (Lisp_Object filename)
317 #ifndef DOS_NT
318 register const char *beg;
319 #else
320 register char *beg;
321 #endif
322 register const char *p;
323 Lisp_Object handler;
325 CHECK_STRING (filename);
327 /* If the file name has special constructs in it,
328 call the corresponding file handler. */
329 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
330 if (!NILP (handler))
331 return call2 (handler, Qfile_name_directory, filename);
333 filename = FILE_SYSTEM_CASE (filename);
334 #ifdef DOS_NT
335 beg = (char *) 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 strncpy (res, beg, 2);
365 beg += 2;
366 r += 2;
369 if (getdefdir (toupper ((unsigned char) *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))
400 return call2 (handler, Qfile_name_nondirectory, filename);
402 beg = SSDATA (filename);
403 end = p = beg + SBYTES (filename);
405 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
406 #ifdef DOS_NT
407 /* only recognize drive specifier at beginning */
408 && !(p[-1] == ':'
409 /* handle the "/:d:foo" case correctly */
410 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
411 #endif
413 p--;
415 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
418 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
419 Sunhandled_file_name_directory, 1, 1, 0,
420 doc: /* Return a directly usable directory name somehow associated with FILENAME.
421 A `directly usable' directory name is one that may be used without the
422 intervention of any file handler.
423 If FILENAME is a directly usable file itself, return
424 \(file-name-directory FILENAME).
425 If FILENAME refers to a file which is not accessible from a local process,
426 then this should return nil.
427 The `call-process' and `start-process' functions use this function to
428 get a current directory to run processes in. */)
429 (Lisp_Object filename)
431 Lisp_Object handler;
433 /* If the file name has special constructs in it,
434 call the corresponding file handler. */
435 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
436 if (!NILP (handler))
437 return call2 (handler, Qunhandled_file_name_directory, filename);
439 return Ffile_name_directory (filename);
443 static char *
444 file_name_as_directory (char *out, const char *in)
446 ptrdiff_t len = strlen (in);
448 if (len == 0)
450 out[0] = '.';
451 out[1] = '/';
452 out[2] = 0;
453 return out;
456 strcpy (out, in);
458 /* For Unix syntax, Append a slash if necessary */
459 if (!IS_DIRECTORY_SEP (out[len - 1]))
461 out[len] = DIRECTORY_SEP;
462 out[len + 1] = '\0';
464 #ifdef DOS_NT
465 dostounix_filename (out);
466 #endif
467 return out;
470 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
471 Sfile_name_as_directory, 1, 1, 0,
472 doc: /* Return a string representing the file name FILE interpreted as a directory.
473 This operation exists because a directory is also a file, but its name as
474 a directory is different from its name as a file.
475 The result can be used as the value of `default-directory'
476 or passed as second argument to `expand-file-name'.
477 For a Unix-syntax file name, just appends a slash. */)
478 (Lisp_Object file)
480 char *buf;
481 Lisp_Object handler;
483 CHECK_STRING (file);
484 if (NILP (file))
485 return Qnil;
487 /* If the file name has special constructs in it,
488 call the corresponding file handler. */
489 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
490 if (!NILP (handler))
491 return call2 (handler, Qfile_name_as_directory, file);
493 buf = (char *) alloca (SBYTES (file) + 10);
494 file_name_as_directory (buf, SSDATA (file));
495 return make_specified_string (buf, -1, strlen (buf),
496 STRING_MULTIBYTE (file));
500 * Convert from directory name to filename.
501 * On UNIX, it's simple: just make sure there isn't a terminating /
503 * Value is nonzero if the string output is different from the input.
506 static int
507 directory_file_name (char *src, char *dst)
509 ptrdiff_t slen;
511 slen = strlen (src);
513 /* Process as Unix format: just remove any final slash.
514 But leave "/" unchanged; do not change it to "". */
515 strcpy (dst, src);
516 if (slen > 1
517 && IS_DIRECTORY_SEP (dst[slen - 1])
518 #ifdef DOS_NT
519 && !IS_ANY_SEP (dst[slen - 2])
520 #endif
522 dst[slen - 1] = 0;
523 #ifdef DOS_NT
524 dostounix_filename (dst);
525 #endif
526 return 1;
529 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
530 1, 1, 0,
531 doc: /* Returns the file name of the directory named DIRECTORY.
532 This is the name of the file that holds the data for the directory DIRECTORY.
533 This operation exists because a directory is also a file, but its name as
534 a directory is different from its name as a file.
535 In Unix-syntax, this function just removes the final slash. */)
536 (Lisp_Object directory)
538 char *buf;
539 Lisp_Object handler;
541 CHECK_STRING (directory);
543 if (NILP (directory))
544 return Qnil;
546 /* If the file name has special constructs in it,
547 call the corresponding file handler. */
548 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
549 if (!NILP (handler))
550 return call2 (handler, Qdirectory_file_name, directory);
552 buf = (char *) alloca (SBYTES (directory) + 20);
553 directory_file_name (SSDATA (directory), buf);
554 return make_specified_string (buf, -1, strlen (buf),
555 STRING_MULTIBYTE (directory));
558 static const char make_temp_name_tbl[64] =
560 'A','B','C','D','E','F','G','H',
561 'I','J','K','L','M','N','O','P',
562 'Q','R','S','T','U','V','W','X',
563 'Y','Z','a','b','c','d','e','f',
564 'g','h','i','j','k','l','m','n',
565 'o','p','q','r','s','t','u','v',
566 'w','x','y','z','0','1','2','3',
567 '4','5','6','7','8','9','-','_'
570 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
572 /* Value is a temporary file name starting with PREFIX, a string.
574 The Emacs process number forms part of the result, so there is
575 no danger of generating a name being used by another process.
576 In addition, this function makes an attempt to choose a name
577 which has no existing file. To make this work, PREFIX should be
578 an absolute file name.
580 BASE64_P non-zero means add the pid as 3 characters in base64
581 encoding. In this case, 6 characters will be added to PREFIX to
582 form the file name. Otherwise, if Emacs is running on a system
583 with long file names, add the pid as a decimal number.
585 This function signals an error if no unique file name could be
586 generated. */
588 Lisp_Object
589 make_temp_name (Lisp_Object prefix, int base64_p)
591 Lisp_Object val;
592 int len, clen;
593 printmax_t pid;
594 char *p, *data;
595 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
596 int pidlen;
598 CHECK_STRING (prefix);
600 /* VAL is created by adding 6 characters to PREFIX. The first
601 three are the PID of this process, in base 64, and the second
602 three are incremented if the file already exists. This ensures
603 262144 unique file names per PID per PREFIX. */
605 pid = getpid ();
607 if (base64_p)
609 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
610 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
611 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
612 pidlen = 3;
614 else
616 #ifdef HAVE_LONG_FILE_NAMES
617 pidlen = sprintf (pidbuf, "%"pMd, pid);
618 #else
619 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
620 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
621 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
622 pidlen = 3;
623 #endif
626 len = SBYTES (prefix); clen = SCHARS (prefix);
627 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
628 if (!STRING_MULTIBYTE (prefix))
629 STRING_SET_UNIBYTE (val);
630 data = SSDATA (val);
631 memcpy (data, SSDATA (prefix), len);
632 p = data + len;
634 memcpy (p, pidbuf, pidlen);
635 p += pidlen;
637 /* Here we try to minimize useless stat'ing when this function is
638 invoked many times successively with the same PREFIX. We achieve
639 this by initializing count to a random value, and incrementing it
640 afterwards.
642 We don't want make-temp-name to be called while dumping,
643 because then make_temp_name_count_initialized_p would get set
644 and then make_temp_name_count would not be set when Emacs starts. */
646 if (!make_temp_name_count_initialized_p)
648 make_temp_name_count = time (NULL);
649 make_temp_name_count_initialized_p = 1;
652 while (1)
654 struct stat ignored;
655 unsigned num = make_temp_name_count;
657 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
658 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
659 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
661 /* Poor man's congruential RN generator. Replace with
662 ++make_temp_name_count for debugging. */
663 make_temp_name_count += 25229;
664 make_temp_name_count %= 225307;
666 if (stat (data, &ignored) < 0)
668 /* We want to return only if errno is ENOENT. */
669 if (errno == ENOENT)
670 return val;
671 else
672 /* The error here is dubious, but there is little else we
673 can do. The alternatives are to return nil, which is
674 as bad as (and in many cases worse than) throwing the
675 error, or to ignore the error, which will likely result
676 in looping through 225307 stat's, which is not only
677 dog-slow, but also useless since eventually nil would
678 have to be returned anyway. */
679 report_file_error ("Cannot create temporary name for prefix",
680 Fcons (prefix, Qnil));
681 /* not reached */
687 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
688 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
689 The Emacs process number forms part of the result,
690 so there is no danger of generating a name being used by another process.
692 In addition, this function makes an attempt to choose a name
693 which has no existing file. To make this work,
694 PREFIX should be an absolute file name.
696 There is a race condition between calling `make-temp-name' and creating the
697 file which opens all kinds of security holes. For that reason, you should
698 probably use `make-temp-file' instead, except in three circumstances:
700 * If you are creating the file in the user's home directory.
701 * If you are creating a directory rather than an ordinary file.
702 * If you are taking special precautions as `make-temp-file' does. */)
703 (Lisp_Object prefix)
705 return make_temp_name (prefix, 0);
710 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
711 doc: /* Convert filename NAME to absolute, and canonicalize it.
712 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
713 \(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
714 the current buffer's value of `default-directory' is used.
715 NAME should be a string that is a valid file name for the underlying
716 filesystem.
717 File name components that are `.' are removed, and
718 so are file name components followed by `..', along with the `..' itself;
719 note that these simplifications are done without checking the resulting
720 file names in the file system.
721 Multiple consecutive slashes are collapsed into a single slash,
722 except at the beginning of the file name when they are significant (e.g.,
723 UNC file names on MS-Windows.)
724 An initial `~/' expands to your home directory.
725 An initial `~USER/' expands to USER's home directory.
726 See also the function `substitute-in-file-name'.
728 For technical reasons, this function can return correct but
729 non-intuitive results for the root directory; for instance,
730 \(expand-file-name ".." "/") returns "/..". For this reason, use
731 \(directory-file-name (file-name-directory dirname)) to traverse a
732 filesystem tree, not (expand-file-name ".." dirname). */)
733 (Lisp_Object name, Lisp_Object default_directory)
735 /* These point to SDATA and need to be careful with string-relocation
736 during GC (via DECODE_FILE). */
737 char *nm;
738 const char *newdir;
739 /* This should only point to alloca'd data. */
740 char *target;
742 ptrdiff_t tlen;
743 struct passwd *pw;
744 #ifdef DOS_NT
745 int drive = 0;
746 int collapse_newdir = 1;
747 int is_escaped = 0;
748 #endif /* DOS_NT */
749 ptrdiff_t length;
750 Lisp_Object handler, result;
751 int multibyte;
752 Lisp_Object hdir;
754 CHECK_STRING (name);
756 /* If the file name has special constructs in it,
757 call the corresponding file handler. */
758 handler = Ffind_file_name_handler (name, Qexpand_file_name);
759 if (!NILP (handler))
760 return call3 (handler, Qexpand_file_name, name, default_directory);
762 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
763 if (NILP (default_directory))
764 default_directory = BVAR (current_buffer, directory);
765 if (! STRINGP (default_directory))
767 #ifdef DOS_NT
768 /* "/" is not considered a root directory on DOS_NT, so using "/"
769 here causes an infinite recursion in, e.g., the following:
771 (let (default-directory)
772 (expand-file-name "a"))
774 To avoid this, we set default_directory to the root of the
775 current drive. */
776 default_directory = build_string (emacs_root_dir ());
777 #else
778 default_directory = build_string ("/");
779 #endif
782 if (!NILP (default_directory))
784 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
785 if (!NILP (handler))
786 return call3 (handler, Qexpand_file_name, name, default_directory);
790 char *o = SSDATA (default_directory);
792 /* Make sure DEFAULT_DIRECTORY is properly expanded.
793 It would be better to do this down below where we actually use
794 default_directory. Unfortunately, calling Fexpand_file_name recursively
795 could invoke GC, and the strings might be relocated. This would
796 be annoying because we have pointers into strings lying around
797 that would need adjusting, and people would add new pointers to
798 the code and forget to adjust them, resulting in intermittent bugs.
799 Putting this call here avoids all that crud.
801 The EQ test avoids infinite recursion. */
802 if (! NILP (default_directory) && !EQ (default_directory, name)
803 /* Save time in some common cases - as long as default_directory
804 is not relative, it can be canonicalized with name below (if it
805 is needed at all) without requiring it to be expanded now. */
806 #ifdef DOS_NT
807 /* Detect MSDOS file names with drive specifiers. */
808 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
809 && IS_DIRECTORY_SEP (o[2]))
810 #ifdef WINDOWSNT
811 /* Detect Windows file names in UNC format. */
812 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
813 #endif
814 #else /* not DOS_NT */
815 /* Detect Unix absolute file names (/... alone is not absolute on
816 DOS or Windows). */
817 && ! (IS_DIRECTORY_SEP (o[0]))
818 #endif /* not DOS_NT */
821 struct gcpro gcpro1;
823 GCPRO1 (name);
824 default_directory = Fexpand_file_name (default_directory, Qnil);
825 UNGCPRO;
828 name = FILE_SYSTEM_CASE (name);
829 multibyte = STRING_MULTIBYTE (name);
830 if (multibyte != STRING_MULTIBYTE (default_directory))
832 if (multibyte)
833 default_directory = string_to_multibyte (default_directory);
834 else
836 name = string_to_multibyte (name);
837 multibyte = 1;
841 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
842 nm = (char *) alloca (SBYTES (name) + 1);
843 memcpy (nm, SSDATA (name), SBYTES (name) + 1);
845 #ifdef DOS_NT
846 /* Note if special escape prefix is present, but remove for now. */
847 if (nm[0] == '/' && nm[1] == ':')
849 is_escaped = 1;
850 nm += 2;
853 /* Find and remove drive specifier if present; this makes nm absolute
854 even if the rest of the name appears to be relative. Only look for
855 drive specifier at the beginning. */
856 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
858 drive = (unsigned char) nm[0];
859 nm += 2;
862 #ifdef WINDOWSNT
863 /* If we see "c://somedir", we want to strip the first slash after the
864 colon when stripping the drive letter. Otherwise, this expands to
865 "//somedir". */
866 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
867 nm++;
869 /* Discard any previous drive specifier if nm is now in UNC format. */
870 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
872 drive = 0;
874 #endif /* WINDOWSNT */
875 #endif /* DOS_NT */
877 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
878 none are found, we can probably return right away. We will avoid
879 allocating a new string if name is already fully expanded. */
880 if (
881 IS_DIRECTORY_SEP (nm[0])
882 #ifdef MSDOS
883 && drive && !is_escaped
884 #endif
885 #ifdef WINDOWSNT
886 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
887 #endif
890 /* If it turns out that the filename we want to return is just a
891 suffix of FILENAME, we don't need to go through and edit
892 things; we just need to construct a new string using data
893 starting at the middle of FILENAME. If we set lose to a
894 non-zero value, that means we've discovered that we can't do
895 that cool trick. */
896 int lose = 0;
897 char *p = nm;
899 while (*p)
901 /* Since we know the name is absolute, we can assume that each
902 element starts with a "/". */
904 /* "." and ".." are hairy. */
905 if (IS_DIRECTORY_SEP (p[0])
906 && p[1] == '.'
907 && (IS_DIRECTORY_SEP (p[2])
908 || p[2] == 0
909 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
910 || p[3] == 0))))
911 lose = 1;
912 /* We want to replace multiple `/' in a row with a single
913 slash. */
914 else if (p > nm
915 && IS_DIRECTORY_SEP (p[0])
916 && IS_DIRECTORY_SEP (p[1]))
917 lose = 1;
918 p++;
920 if (!lose)
922 #ifdef DOS_NT
923 /* Make sure directories are all separated with /, but
924 avoid allocation of a new string when not required. */
925 dostounix_filename (nm);
926 #ifdef WINDOWSNT
927 if (IS_DIRECTORY_SEP (nm[1]))
929 if (strcmp (nm, SSDATA (name)) != 0)
930 name = make_specified_string (nm, -1, strlen (nm), multibyte);
932 else
933 #endif
934 /* drive must be set, so this is okay */
935 if (strcmp (nm - 2, SSDATA (name)) != 0)
937 char temp[] = " :";
939 name = make_specified_string (nm, -1, p - nm, multibyte);
940 temp[0] = DRIVE_LETTER (drive);
941 name = concat2 (build_string (temp), name);
943 return name;
944 #else /* not DOS_NT */
945 if (strcmp (nm, SSDATA (name)) == 0)
946 return name;
947 return make_specified_string (nm, -1, strlen (nm), multibyte);
948 #endif /* not DOS_NT */
952 /* At this point, nm might or might not be an absolute file name. We
953 need to expand ~ or ~user if present, otherwise prefix nm with
954 default_directory if nm is not absolute, and finally collapse /./
955 and /foo/../ sequences.
957 We set newdir to be the appropriate prefix if one is needed:
958 - the relevant user directory if nm starts with ~ or ~user
959 - the specified drive's working dir (DOS/NT only) if nm does not
960 start with /
961 - the value of default_directory.
963 Note that these prefixes are not guaranteed to be absolute (except
964 for the working dir of a drive). Therefore, to ensure we always
965 return an absolute name, if the final prefix is not absolute we
966 append it to the current working directory. */
968 newdir = 0;
970 if (nm[0] == '~') /* prefix ~ */
972 if (IS_DIRECTORY_SEP (nm[1])
973 || nm[1] == 0) /* ~ by itself */
975 Lisp_Object tem;
977 if (!(newdir = egetenv ("HOME")))
978 newdir = "";
979 nm++;
980 /* egetenv may return a unibyte string, which will bite us since
981 we expect the directory to be multibyte. */
982 tem = build_string (newdir);
983 if (!STRING_MULTIBYTE (tem))
985 hdir = DECODE_FILE (tem);
986 newdir = SSDATA (hdir);
988 #ifdef DOS_NT
989 collapse_newdir = 0;
990 #endif
992 else /* ~user/filename */
994 char *o, *p;
995 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
996 o = alloca (p - nm + 1);
997 memcpy (o, nm, p - nm);
998 o [p - nm] = 0;
1000 BLOCK_INPUT;
1001 pw = (struct passwd *) getpwnam (o + 1);
1002 UNBLOCK_INPUT;
1003 if (pw)
1005 newdir = pw->pw_dir;
1006 nm = p;
1007 #ifdef DOS_NT
1008 collapse_newdir = 0;
1009 #endif
1012 /* If we don't find a user of that name, leave the name
1013 unchanged; don't move nm forward to p. */
1017 #ifdef DOS_NT
1018 /* On DOS and Windows, nm is absolute if a drive name was specified;
1019 use the drive's current directory as the prefix if needed. */
1020 if (!newdir && drive)
1022 /* Get default directory if needed to make nm absolute. */
1023 char *adir = NULL;
1024 if (!IS_DIRECTORY_SEP (nm[0]))
1026 adir = alloca (MAXPATHLEN + 1);
1027 if (!getdefdir (toupper (drive) - 'A' + 1, adir))
1028 adir = NULL;
1030 if (!adir)
1032 /* Either nm starts with /, or drive isn't mounted. */
1033 adir = alloca (4);
1034 adir[0] = DRIVE_LETTER (drive);
1035 adir[1] = ':';
1036 adir[2] = '/';
1037 adir[3] = 0;
1039 newdir = adir;
1041 #endif /* DOS_NT */
1043 /* Finally, if no prefix has been specified and nm is not absolute,
1044 then it must be expanded relative to default_directory. */
1046 if (1
1047 #ifndef DOS_NT
1048 /* /... alone is not absolute on DOS and Windows. */
1049 && !IS_DIRECTORY_SEP (nm[0])
1050 #endif
1051 #ifdef WINDOWSNT
1052 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1053 #endif
1054 && !newdir)
1056 newdir = SSDATA (default_directory);
1057 #ifdef DOS_NT
1058 /* Note if special escape prefix is present, but remove for now. */
1059 if (newdir[0] == '/' && newdir[1] == ':')
1061 is_escaped = 1;
1062 newdir += 2;
1064 #endif
1067 #ifdef DOS_NT
1068 if (newdir)
1070 /* First ensure newdir is an absolute name. */
1071 if (
1072 /* Detect MSDOS file names with drive specifiers. */
1073 ! (IS_DRIVE (newdir[0])
1074 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1075 #ifdef WINDOWSNT
1076 /* Detect Windows file names in UNC format. */
1077 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1078 #endif
1081 /* Effectively, let newdir be (expand-file-name newdir cwd).
1082 Because of the admonition against calling expand-file-name
1083 when we have pointers into lisp strings, we accomplish this
1084 indirectly by prepending newdir to nm if necessary, and using
1085 cwd (or the wd of newdir's drive) as the new newdir. */
1086 char *adir;
1087 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1089 drive = (unsigned char) newdir[0];
1090 newdir += 2;
1092 if (!IS_DIRECTORY_SEP (nm[0]))
1094 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1095 file_name_as_directory (tmp, newdir);
1096 strcat (tmp, nm);
1097 nm = tmp;
1099 adir = alloca (MAXPATHLEN + 1);
1100 if (drive)
1102 if (!getdefdir (toupper (drive) - 'A' + 1, adir))
1103 newdir = "/";
1105 else
1106 getwd (adir);
1107 newdir = adir;
1110 /* Strip off drive name from prefix, if present. */
1111 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1113 drive = newdir[0];
1114 newdir += 2;
1117 /* Keep only a prefix from newdir if nm starts with slash
1118 (//server/share for UNC, nothing otherwise). */
1119 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1121 #ifdef WINDOWSNT
1122 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1124 char *adir = strcpy (alloca (strlen (newdir) + 1), newdir);
1125 char *p = adir + 2;
1126 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1127 p++;
1128 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1129 *p = 0;
1130 newdir = adir;
1132 else
1133 #endif
1134 newdir = "";
1137 #endif /* DOS_NT */
1139 if (newdir)
1141 /* Get rid of any slash at the end of newdir, unless newdir is
1142 just / or // (an incomplete UNC name). */
1143 length = strlen (newdir);
1144 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1145 #ifdef WINDOWSNT
1146 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1147 #endif
1150 char *temp = (char *) alloca (length);
1151 memcpy (temp, newdir, length - 1);
1152 temp[length - 1] = 0;
1153 newdir = temp;
1155 tlen = length + 1;
1157 else
1158 tlen = 0;
1160 /* Now concatenate the directory and name to new space in the stack frame */
1161 tlen += strlen (nm) + 1;
1162 #ifdef DOS_NT
1163 /* Reserve space for drive specifier and escape prefix, since either
1164 or both may need to be inserted. (The Microsoft x86 compiler
1165 produces incorrect code if the following two lines are combined.) */
1166 target = (char *) alloca (tlen + 4);
1167 target += 4;
1168 #else /* not DOS_NT */
1169 target = (char *) alloca (tlen);
1170 #endif /* not DOS_NT */
1171 *target = 0;
1173 if (newdir)
1175 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1177 #ifdef DOS_NT
1178 /* If newdir is effectively "C:/", then the drive letter will have
1179 been stripped and newdir will be "/". Concatenating with an
1180 absolute directory in nm produces "//", which will then be
1181 incorrectly treated as a network share. Ignore newdir in
1182 this case (keeping the drive letter). */
1183 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1184 && newdir[1] == '\0'))
1185 #endif
1186 strcpy (target, newdir);
1188 else
1189 file_name_as_directory (target, newdir);
1192 strcat (target, nm);
1194 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1195 appear. */
1197 char *p = target;
1198 char *o = target;
1200 while (*p)
1202 if (!IS_DIRECTORY_SEP (*p))
1204 *o++ = *p++;
1206 else if (p[1] == '.'
1207 && (IS_DIRECTORY_SEP (p[2])
1208 || p[2] == 0))
1210 /* If "/." is the entire filename, keep the "/". Otherwise,
1211 just delete the whole "/.". */
1212 if (o == target && p[2] == '\0')
1213 *o++ = *p;
1214 p += 2;
1216 else if (p[1] == '.' && p[2] == '.'
1217 /* `/../' is the "superroot" on certain file systems.
1218 Turned off on DOS_NT systems because they have no
1219 "superroot" and because this causes us to produce
1220 file names like "d:/../foo" which fail file-related
1221 functions of the underlying OS. (To reproduce, try a
1222 long series of "../../" in default_directory, longer
1223 than the number of levels from the root.) */
1224 #ifndef DOS_NT
1225 && o != target
1226 #endif
1227 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1229 #ifdef WINDOWSNT
1230 char *prev_o = o;
1231 #endif
1232 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1234 #ifdef WINDOWSNT
1235 /* Don't go below server level in UNC filenames. */
1236 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1237 && IS_DIRECTORY_SEP (*target))
1238 o = prev_o;
1239 else
1240 #endif
1241 /* Keep initial / only if this is the whole name. */
1242 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1243 ++o;
1244 p += 3;
1246 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1247 /* Collapse multiple `/' in a row. */
1248 p++;
1249 else
1251 *o++ = *p++;
1255 #ifdef DOS_NT
1256 /* At last, set drive name. */
1257 #ifdef WINDOWSNT
1258 /* Except for network file name. */
1259 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1260 #endif /* WINDOWSNT */
1262 if (!drive) abort ();
1263 target -= 2;
1264 target[0] = DRIVE_LETTER (drive);
1265 target[1] = ':';
1267 /* Reinsert the escape prefix if required. */
1268 if (is_escaped)
1270 target -= 2;
1271 target[0] = '/';
1272 target[1] = ':';
1274 dostounix_filename (target);
1275 #endif /* DOS_NT */
1277 result = make_specified_string (target, -1, o - target, multibyte);
1280 /* Again look to see if the file name has special constructs in it
1281 and perhaps call the corresponding file handler. This is needed
1282 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1283 the ".." component gives us "/user@host:/bar/../baz" which needs
1284 to be expanded again. */
1285 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1286 if (!NILP (handler))
1287 return call3 (handler, Qexpand_file_name, result, default_directory);
1289 return result;
1292 #if 0
1293 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1294 This is the old version of expand-file-name, before it was thoroughly
1295 rewritten for Emacs 10.31. We leave this version here commented-out,
1296 because the code is very complex and likely to have subtle bugs. If
1297 bugs _are_ found, it might be of interest to look at the old code and
1298 see what did it do in the relevant situation.
1300 Don't remove this code: it's true that it will be accessible
1301 from the repository, but a few years from deletion, people will
1302 forget it is there. */
1304 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1305 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1306 "Convert FILENAME to absolute, and canonicalize it.\n\
1307 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1308 \(does not start with slash); if DEFAULT is nil or missing,\n\
1309 the current buffer's value of default-directory is used.\n\
1310 Filenames containing `.' or `..' as components are simplified;\n\
1311 initial `~/' expands to your home directory.\n\
1312 See also the function `substitute-in-file-name'.")
1313 (name, defalt)
1314 Lisp_Object name, defalt;
1316 unsigned char *nm;
1318 register unsigned char *newdir, *p, *o;
1319 ptrdiff_t tlen;
1320 unsigned char *target;
1321 struct passwd *pw;
1322 int lose;
1324 CHECK_STRING (name);
1325 nm = SDATA (name);
1327 /* If nm is absolute, flush ...// and detect /./ and /../.
1328 If no /./ or /../ we can return right away. */
1329 if (nm[0] == '/')
1331 p = nm;
1332 lose = 0;
1333 while (*p)
1335 if (p[0] == '/' && p[1] == '/'
1337 nm = p + 1;
1338 if (p[0] == '/' && p[1] == '~')
1339 nm = p + 1, lose = 1;
1340 if (p[0] == '/' && p[1] == '.'
1341 && (p[2] == '/' || p[2] == 0
1342 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1343 lose = 1;
1344 p++;
1346 if (!lose)
1348 if (nm == SDATA (name))
1349 return name;
1350 return build_string (nm);
1354 /* Now determine directory to start with and put it in NEWDIR */
1356 newdir = 0;
1358 if (nm[0] == '~') /* prefix ~ */
1359 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1361 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1362 newdir = (unsigned char *) "";
1363 nm++;
1365 else /* ~user/filename */
1367 /* Get past ~ to user */
1368 unsigned char *user = nm + 1;
1369 /* Find end of name. */
1370 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1371 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1372 /* Copy the user name into temp storage. */
1373 o = (unsigned char *) alloca (len + 1);
1374 memcpy (o, user, len);
1375 o[len] = 0;
1377 /* Look up the user name. */
1378 BLOCK_INPUT;
1379 pw = (struct passwd *) getpwnam (o + 1);
1380 UNBLOCK_INPUT;
1381 if (!pw)
1382 error ("\"%s\" isn't a registered user", o + 1);
1384 newdir = (unsigned char *) pw->pw_dir;
1386 /* Discard the user name from NM. */
1387 nm += len;
1390 if (nm[0] != '/' && !newdir)
1392 if (NILP (defalt))
1393 defalt = current_buffer->directory;
1394 CHECK_STRING (defalt);
1395 newdir = SDATA (defalt);
1398 /* Now concatenate the directory and name to new space in the stack frame */
1400 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1401 target = (unsigned char *) alloca (tlen);
1402 *target = 0;
1404 if (newdir)
1406 if (nm[0] == 0 || nm[0] == '/')
1407 strcpy (target, newdir);
1408 else
1409 file_name_as_directory (target, newdir);
1412 strcat (target, nm);
1414 /* Now canonicalize by removing /. and /foo/.. if they appear */
1416 p = target;
1417 o = target;
1419 while (*p)
1421 if (*p != '/')
1423 *o++ = *p++;
1425 else if (!strncmp (p, "//", 2)
1428 o = target;
1429 p++;
1431 else if (p[0] == '/' && p[1] == '.'
1432 && (p[2] == '/' || p[2] == 0))
1433 p += 2;
1434 else if (!strncmp (p, "/..", 3)
1435 /* `/../' is the "superroot" on certain file systems. */
1436 && o != target
1437 && (p[3] == '/' || p[3] == 0))
1439 while (o != target && *--o != '/')
1441 if (o == target && *o == '/')
1442 ++o;
1443 p += 3;
1445 else
1447 *o++ = *p++;
1451 return make_string (target, o - target);
1453 #endif
1455 /* If /~ or // appears, discard everything through first slash. */
1456 static int
1457 file_name_absolute_p (const char *filename)
1459 return
1460 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1461 #ifdef DOS_NT
1462 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1463 && IS_DIRECTORY_SEP (filename[2]))
1464 #endif
1468 static char *
1469 search_embedded_absfilename (char *nm, char *endp)
1471 char *p, *s;
1473 for (p = nm + 1; p < endp; p++)
1475 if ((0
1476 || IS_DIRECTORY_SEP (p[-1]))
1477 && file_name_absolute_p (p)
1478 #if defined (WINDOWSNT) || defined (CYGWIN)
1479 /* // at start of file name is meaningful in Apollo,
1480 WindowsNT and Cygwin systems. */
1481 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1482 #endif /* not (WINDOWSNT || CYGWIN) */
1485 for (s = p; *s && (!IS_DIRECTORY_SEP (*s)); s++);
1486 if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
1488 char *o = alloca (s - p + 1);
1489 struct passwd *pw;
1490 memcpy (o, p, s - p);
1491 o [s - p] = 0;
1493 /* If we have ~user and `user' exists, discard
1494 everything up to ~. But if `user' does not exist, leave
1495 ~user alone, it might be a literal file name. */
1496 BLOCK_INPUT;
1497 pw = getpwnam (o + 1);
1498 UNBLOCK_INPUT;
1499 if (pw)
1500 return p;
1502 else
1503 return p;
1506 return NULL;
1509 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1510 Ssubstitute_in_file_name, 1, 1, 0,
1511 doc: /* Substitute environment variables referred to in FILENAME.
1512 `$FOO' where FOO is an environment variable name means to substitute
1513 the value of that variable. The variable name should be terminated
1514 with a character not a letter, digit or underscore; otherwise, enclose
1515 the entire variable name in braces.
1517 If `/~' appears, all of FILENAME through that `/' is discarded.
1518 If `//' appears, everything up to and including the first of
1519 those `/' is discarded. */)
1520 (Lisp_Object filename)
1522 char *nm;
1524 register char *s, *p, *o, *x, *endp;
1525 char *target = NULL;
1526 int total = 0;
1527 int substituted = 0;
1528 int multibyte;
1529 char *xnm;
1530 Lisp_Object handler;
1532 CHECK_STRING (filename);
1534 multibyte = STRING_MULTIBYTE (filename);
1536 /* If the file name has special constructs in it,
1537 call the corresponding file handler. */
1538 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1539 if (!NILP (handler))
1540 return call2 (handler, Qsubstitute_in_file_name, filename);
1542 /* Always work on a copy of the string, in case GC happens during
1543 decode of environment variables, causing the original Lisp_String
1544 data to be relocated. */
1545 nm = (char *) alloca (SBYTES (filename) + 1);
1546 memcpy (nm, SDATA (filename), SBYTES (filename) + 1);
1548 #ifdef DOS_NT
1549 dostounix_filename (nm);
1550 substituted = (strcmp (nm, SDATA (filename)) != 0);
1551 #endif
1552 endp = nm + SBYTES (filename);
1554 /* If /~ or // appears, discard everything through first slash. */
1555 p = search_embedded_absfilename (nm, endp);
1556 if (p)
1557 /* Start over with the new string, so we check the file-name-handler
1558 again. Important with filenames like "/home/foo//:/hello///there"
1559 which would substitute to "/:/hello///there" rather than "/there". */
1560 return Fsubstitute_in_file_name
1561 (make_specified_string (p, -1, endp - p, multibyte));
1563 /* See if any variables are substituted into the string
1564 and find the total length of their values in `total' */
1566 for (p = nm; p != endp;)
1567 if (*p != '$')
1568 p++;
1569 else
1571 p++;
1572 if (p == endp)
1573 goto badsubst;
1574 else if (*p == '$')
1576 /* "$$" means a single "$" */
1577 p++;
1578 total -= 1;
1579 substituted = 1;
1580 continue;
1582 else if (*p == '{')
1584 o = ++p;
1585 while (p != endp && *p != '}') p++;
1586 if (*p != '}') goto missingclose;
1587 s = p;
1589 else
1591 o = p;
1592 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1593 s = p;
1596 /* Copy out the variable name */
1597 target = (char *) alloca (s - o + 1);
1598 strncpy (target, o, s - o);
1599 target[s - o] = 0;
1600 #ifdef DOS_NT
1601 strupr (target); /* $home == $HOME etc. */
1602 #endif /* DOS_NT */
1604 /* Get variable value */
1605 o = egetenv (target);
1606 if (o)
1608 /* Don't try to guess a maximum length - UTF8 can use up to
1609 four bytes per character. This code is unlikely to run
1610 in a situation that requires performance, so decoding the
1611 env variables twice should be acceptable. Note that
1612 decoding may cause a garbage collect. */
1613 Lisp_Object orig, decoded;
1614 orig = make_unibyte_string (o, strlen (o));
1615 decoded = DECODE_FILE (orig);
1616 total += SBYTES (decoded);
1617 substituted = 1;
1619 else if (*p == '}')
1620 goto badvar;
1623 if (!substituted)
1624 return filename;
1626 /* If substitution required, recopy the string and do it */
1627 /* Make space in stack frame for the new copy */
1628 xnm = (char *) alloca (SBYTES (filename) + total + 1);
1629 x = xnm;
1631 /* Copy the rest of the name through, replacing $ constructs with values */
1632 for (p = nm; *p;)
1633 if (*p != '$')
1634 *x++ = *p++;
1635 else
1637 p++;
1638 if (p == endp)
1639 goto badsubst;
1640 else if (*p == '$')
1642 *x++ = *p++;
1643 continue;
1645 else if (*p == '{')
1647 o = ++p;
1648 while (p != endp && *p != '}') p++;
1649 if (*p != '}') goto missingclose;
1650 s = p++;
1652 else
1654 o = p;
1655 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1656 s = p;
1659 /* Copy out the variable name */
1660 target = (char *) alloca (s - o + 1);
1661 strncpy (target, o, s - o);
1662 target[s - o] = 0;
1663 #ifdef DOS_NT
1664 strupr (target); /* $home == $HOME etc. */
1665 #endif /* DOS_NT */
1667 /* Get variable value */
1668 o = egetenv (target);
1669 if (!o)
1671 *x++ = '$';
1672 strcpy (x, target); x+= strlen (target);
1674 else
1676 Lisp_Object orig, decoded;
1677 ptrdiff_t orig_length, decoded_length;
1678 orig_length = strlen (o);
1679 orig = make_unibyte_string (o, orig_length);
1680 decoded = DECODE_FILE (orig);
1681 decoded_length = SBYTES (decoded);
1682 strncpy (x, SSDATA (decoded), decoded_length);
1683 x += decoded_length;
1685 /* If environment variable needed decoding, return value
1686 needs to be multibyte. */
1687 if (decoded_length != orig_length
1688 || strncmp (SSDATA (decoded), o, orig_length))
1689 multibyte = 1;
1693 *x = 0;
1695 /* If /~ or // appears, discard everything through first slash. */
1696 while ((p = search_embedded_absfilename (xnm, x)))
1697 /* This time we do not start over because we've already expanded envvars
1698 and replaced $$ with $. Maybe we should start over as well, but we'd
1699 need to quote some $ to $$ first. */
1700 xnm = p;
1702 return make_specified_string (xnm, -1, x - xnm, multibyte);
1704 badsubst:
1705 error ("Bad format environment-variable substitution");
1706 missingclose:
1707 error ("Missing \"}\" in environment-variable substitution");
1708 badvar:
1709 error ("Substituting nonexistent environment variable \"%s\"", target);
1711 /* NOTREACHED */
1712 return Qnil;
1715 /* A slightly faster and more convenient way to get
1716 (directory-file-name (expand-file-name FOO)). */
1718 Lisp_Object
1719 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1721 register Lisp_Object absname;
1723 absname = Fexpand_file_name (filename, defdir);
1725 /* Remove final slash, if any (unless this is the root dir).
1726 stat behaves differently depending! */
1727 if (SCHARS (absname) > 1
1728 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1729 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
1730 /* We cannot take shortcuts; they might be wrong for magic file names. */
1731 absname = Fdirectory_file_name (absname);
1732 return absname;
1735 /* Signal an error if the file ABSNAME already exists.
1736 If INTERACTIVE is nonzero, ask the user whether to proceed,
1737 and bypass the error if the user says to go ahead.
1738 QUERYSTRING is a name for the action that is being considered
1739 to alter the file.
1741 *STATPTR is used to store the stat information if the file exists.
1742 If the file does not exist, STATPTR->st_mode is set to 0.
1743 If STATPTR is null, we don't store into it.
1745 If QUICK is nonzero, we ask for y or n, not yes or no. */
1747 static void
1748 barf_or_query_if_file_exists (Lisp_Object absname, const char *querystring,
1749 int interactive, struct stat *statptr, int quick)
1751 register Lisp_Object tem, encoded_filename;
1752 struct stat statbuf;
1753 struct gcpro gcpro1;
1755 encoded_filename = ENCODE_FILE (absname);
1757 /* stat is a good way to tell whether the file exists,
1758 regardless of what access permissions it has. */
1759 if (lstat (SSDATA (encoded_filename), &statbuf) >= 0)
1761 if (S_ISDIR (statbuf.st_mode))
1762 xsignal2 (Qfile_error,
1763 build_string ("File is a directory"), absname);
1765 if (! interactive)
1766 xsignal2 (Qfile_already_exists,
1767 build_string ("File already exists"), absname);
1768 GCPRO1 (absname);
1769 tem = format2 ("File %s already exists; %s anyway? ",
1770 absname, build_string (querystring));
1771 if (quick)
1772 tem = call1 (intern ("y-or-n-p"), tem);
1773 else
1774 tem = do_yes_or_no_p (tem);
1775 UNGCPRO;
1776 if (NILP (tem))
1777 xsignal2 (Qfile_already_exists,
1778 build_string ("File already exists"), absname);
1779 if (statptr)
1780 *statptr = statbuf;
1782 else
1784 if (statptr)
1785 statptr->st_mode = 0;
1787 return;
1790 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1791 "fCopy file: \nGCopy %s to file: \np\nP",
1792 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1793 If NEWNAME names a directory, copy FILE there.
1795 This function always sets the file modes of the output file to match
1796 the input file.
1798 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1799 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1800 signal a `file-already-exists' error without overwriting. If
1801 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1802 about overwriting; this is what happens in interactive use with M-x.
1803 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1804 existing file.
1806 Fourth arg KEEP-TIME non-nil means give the output file the same
1807 last-modified time as the old one. (This works on only some systems.)
1809 A prefix arg makes KEEP-TIME non-nil.
1811 If PRESERVE-UID-GID is non-nil, we try to transfer the
1812 uid and gid of FILE to NEWNAME.
1814 If PRESERVE-SELINUX-CONTEXT is non-nil and SELinux is enabled
1815 on the system, we copy the SELinux context of FILE to NEWNAME. */)
1816 (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)
1818 int ifd, ofd;
1819 EMACS_INT n;
1820 char buf[16 * 1024];
1821 struct stat st, out_st;
1822 Lisp_Object handler;
1823 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1824 int count = SPECPDL_INDEX ();
1825 int input_file_statable_p;
1826 Lisp_Object encoded_file, encoded_newname;
1827 #if HAVE_LIBSELINUX
1828 security_context_t con;
1829 int fail, conlength = 0;
1830 #endif
1832 encoded_file = encoded_newname = Qnil;
1833 GCPRO4 (file, newname, encoded_file, encoded_newname);
1834 CHECK_STRING (file);
1835 CHECK_STRING (newname);
1837 if (!NILP (Ffile_directory_p (newname)))
1838 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1839 else
1840 newname = Fexpand_file_name (newname, Qnil);
1842 file = Fexpand_file_name (file, Qnil);
1844 /* If the input file name has special constructs in it,
1845 call the corresponding file handler. */
1846 handler = Ffind_file_name_handler (file, Qcopy_file);
1847 /* Likewise for output file name. */
1848 if (NILP (handler))
1849 handler = Ffind_file_name_handler (newname, Qcopy_file);
1850 if (!NILP (handler))
1851 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1852 ok_if_already_exists, keep_time, preserve_uid_gid,
1853 preserve_selinux_context));
1855 encoded_file = ENCODE_FILE (file);
1856 encoded_newname = ENCODE_FILE (newname);
1858 if (NILP (ok_if_already_exists)
1859 || INTEGERP (ok_if_already_exists))
1860 barf_or_query_if_file_exists (newname, "copy to it",
1861 INTEGERP (ok_if_already_exists), &out_st, 0);
1862 else if (stat (SSDATA (encoded_newname), &out_st) < 0)
1863 out_st.st_mode = 0;
1865 #ifdef WINDOWSNT
1866 if (!CopyFile (SDATA (encoded_file),
1867 SDATA (encoded_newname),
1868 FALSE))
1869 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
1870 /* CopyFile retains the timestamp by default. */
1871 else if (NILP (keep_time))
1873 EMACS_TIME now;
1874 DWORD attributes;
1875 char * filename;
1877 EMACS_GET_TIME (now);
1878 filename = SDATA (encoded_newname);
1880 /* Ensure file is writable while its modified time is set. */
1881 attributes = GetFileAttributes (filename);
1882 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
1883 if (set_file_times (filename, now, now))
1885 /* Restore original attributes. */
1886 SetFileAttributes (filename, attributes);
1887 xsignal2 (Qfile_date_error,
1888 build_string ("Cannot set file date"), newname);
1890 /* Restore original attributes. */
1891 SetFileAttributes (filename, attributes);
1893 #else /* not WINDOWSNT */
1894 immediate_quit = 1;
1895 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1896 immediate_quit = 0;
1898 if (ifd < 0)
1899 report_file_error ("Opening input file", Fcons (file, Qnil));
1901 record_unwind_protect (close_file_unwind, make_number (ifd));
1903 /* We can only copy regular files and symbolic links. Other files are not
1904 copyable by us. */
1905 input_file_statable_p = (fstat (ifd, &st) >= 0);
1907 #if HAVE_LIBSELINUX
1908 if (!NILP (preserve_selinux_context) && is_selinux_enabled ())
1910 conlength = fgetfilecon (ifd, &con);
1911 if (conlength == -1)
1912 report_file_error ("Doing fgetfilecon", Fcons (file, Qnil));
1914 #endif
1916 if (out_st.st_mode != 0
1917 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1919 errno = 0;
1920 report_file_error ("Input and output files are the same",
1921 Fcons (file, Fcons (newname, Qnil)));
1924 if (input_file_statable_p)
1926 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
1928 #if defined (EISDIR)
1929 /* Get a better looking error message. */
1930 errno = EISDIR;
1931 #endif /* EISDIR */
1932 report_file_error ("Non-regular file", Fcons (file, Qnil));
1936 #ifdef MSDOS
1937 /* System's default file type was set to binary by _fmode in emacs.c. */
1938 ofd = emacs_open (SDATA (encoded_newname),
1939 O_WRONLY | O_TRUNC | O_CREAT
1940 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
1941 S_IREAD | S_IWRITE);
1942 #else /* not MSDOS */
1944 int new_mask = 0666;
1945 if (input_file_statable_p)
1947 if (!NILP (preserve_uid_gid))
1948 new_mask = 0600;
1949 new_mask &= st.st_mode;
1951 ofd = emacs_open (SSDATA (encoded_newname),
1952 (O_WRONLY | O_TRUNC | O_CREAT
1953 | (NILP (ok_if_already_exists) ? O_EXCL : 0)),
1954 new_mask);
1956 #endif /* not MSDOS */
1957 if (ofd < 0)
1958 report_file_error ("Opening output file", Fcons (newname, Qnil));
1960 record_unwind_protect (close_file_unwind, make_number (ofd));
1962 immediate_quit = 1;
1963 QUIT;
1964 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
1965 if (emacs_write (ofd, buf, n) != n)
1966 report_file_error ("I/O error", Fcons (newname, Qnil));
1967 immediate_quit = 0;
1969 #ifndef MSDOS
1970 /* Preserve the original file modes, and if requested, also its
1971 owner and group. */
1972 if (input_file_statable_p)
1974 int mode_mask = 07777;
1975 if (!NILP (preserve_uid_gid))
1977 /* Attempt to change owner and group. If that doesn't work
1978 attempt to change just the group, as that is sometimes allowed.
1979 Adjust the mode mask to eliminate setuid or setgid bits
1980 that are inappropriate if the owner and group are wrong. */
1981 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
1983 mode_mask &= ~06000;
1984 if (fchown (ofd, -1, st.st_gid) == 0)
1985 mode_mask |= 02000;
1988 if (fchmod (ofd, st.st_mode & mode_mask) != 0)
1989 report_file_error ("Doing chmod", Fcons (newname, Qnil));
1991 #endif /* not MSDOS */
1993 #if HAVE_LIBSELINUX
1994 if (conlength > 0)
1996 /* Set the modified context back to the file. */
1997 fail = fsetfilecon (ofd, con);
1998 if (fail)
1999 report_file_error ("Doing fsetfilecon", Fcons (newname, Qnil));
2001 freecon (con);
2003 #endif
2005 /* Closing the output clobbers the file times on some systems. */
2006 if (emacs_close (ofd) < 0)
2007 report_file_error ("I/O error", Fcons (newname, Qnil));
2009 if (input_file_statable_p)
2011 if (!NILP (keep_time))
2013 EMACS_TIME atime, mtime;
2014 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2015 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2016 if (set_file_times (SSDATA (encoded_newname),
2017 atime, mtime))
2018 xsignal2 (Qfile_date_error,
2019 build_string ("Cannot set file date"), newname);
2023 emacs_close (ifd);
2025 #ifdef MSDOS
2026 if (input_file_statable_p)
2028 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2029 and if it can't, it tells so. Otherwise, under MSDOS we usually
2030 get only the READ bit, which will make the copied file read-only,
2031 so it's better not to chmod at all. */
2032 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2033 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2035 #endif /* MSDOS */
2036 #endif /* not WINDOWSNT */
2038 /* Discard the unwind protects. */
2039 specpdl_ptr = specpdl + count;
2041 UNGCPRO;
2042 return Qnil;
2045 DEFUN ("make-directory-internal", Fmake_directory_internal,
2046 Smake_directory_internal, 1, 1, 0,
2047 doc: /* Create a new directory named DIRECTORY. */)
2048 (Lisp_Object directory)
2050 const char *dir;
2051 Lisp_Object handler;
2052 Lisp_Object encoded_dir;
2054 CHECK_STRING (directory);
2055 directory = Fexpand_file_name (directory, Qnil);
2057 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2058 if (!NILP (handler))
2059 return call2 (handler, Qmake_directory_internal, directory);
2061 encoded_dir = ENCODE_FILE (directory);
2063 dir = SSDATA (encoded_dir);
2065 #ifdef WINDOWSNT
2066 if (mkdir (dir) != 0)
2067 #else
2068 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2069 #endif
2070 report_file_error ("Creating directory", list1 (directory));
2072 return Qnil;
2075 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2076 Sdelete_directory_internal, 1, 1, 0,
2077 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2078 (Lisp_Object directory)
2080 const char *dir;
2081 Lisp_Object encoded_dir;
2083 CHECK_STRING (directory);
2084 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2085 encoded_dir = ENCODE_FILE (directory);
2086 dir = SSDATA (encoded_dir);
2088 if (rmdir (dir) != 0)
2089 report_file_error ("Removing directory", list1 (directory));
2091 return Qnil;
2094 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2095 "(list (read-file-name \
2096 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2097 \"Move file to trash: \" \"Delete file: \") \
2098 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2099 (null current-prefix-arg))",
2100 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2101 If file has multiple names, it continues to exist with the other names.
2102 TRASH non-nil means to trash the file instead of deleting, provided
2103 `delete-by-moving-to-trash' is non-nil.
2105 When called interactively, TRASH is t if no prefix argument is given.
2106 With a prefix argument, TRASH is nil. */)
2107 (Lisp_Object filename, Lisp_Object trash)
2109 Lisp_Object handler;
2110 Lisp_Object encoded_file;
2111 struct gcpro gcpro1;
2113 GCPRO1 (filename);
2114 if (!NILP (Ffile_directory_p (filename))
2115 && NILP (Ffile_symlink_p (filename)))
2116 xsignal2 (Qfile_error,
2117 build_string ("Removing old name: is a directory"),
2118 filename);
2119 UNGCPRO;
2120 filename = Fexpand_file_name (filename, Qnil);
2122 handler = Ffind_file_name_handler (filename, Qdelete_file);
2123 if (!NILP (handler))
2124 return call3 (handler, Qdelete_file, filename, trash);
2126 if (delete_by_moving_to_trash && !NILP (trash))
2127 return call1 (Qmove_file_to_trash, filename);
2129 encoded_file = ENCODE_FILE (filename);
2131 if (0 > unlink (SSDATA (encoded_file)))
2132 report_file_error ("Removing old name", list1 (filename));
2133 return Qnil;
2136 static Lisp_Object
2137 internal_delete_file_1 (Lisp_Object ignore)
2139 return Qt;
2142 /* Delete file FILENAME, returning 1 if successful and 0 if failed.
2143 This ignores `delete-by-moving-to-trash'. */
2146 internal_delete_file (Lisp_Object filename)
2148 Lisp_Object tem;
2150 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2151 Qt, internal_delete_file_1);
2152 return NILP (tem);
2155 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2156 "fRename file: \nGRename %s to file: \np",
2157 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2158 If file has names other than FILE, it continues to have those names.
2159 Signals a `file-already-exists' error if a file NEWNAME already exists
2160 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2161 A number as third arg means request confirmation if NEWNAME already exists.
2162 This is what happens in interactive use with M-x. */)
2163 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2165 Lisp_Object handler;
2166 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2167 Lisp_Object encoded_file, encoded_newname, symlink_target;
2169 symlink_target = encoded_file = encoded_newname = Qnil;
2170 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2171 CHECK_STRING (file);
2172 CHECK_STRING (newname);
2173 file = Fexpand_file_name (file, Qnil);
2175 if ((!NILP (Ffile_directory_p (newname)))
2176 #ifdef DOS_NT
2177 /* If the file names are identical but for the case,
2178 don't attempt to move directory to itself. */
2179 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2180 #endif
2183 Lisp_Object fname = NILP (Ffile_directory_p (file))
2184 ? file : Fdirectory_file_name (file);
2185 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2187 else
2188 newname = Fexpand_file_name (newname, Qnil);
2190 /* If the file name has special constructs in it,
2191 call the corresponding file handler. */
2192 handler = Ffind_file_name_handler (file, Qrename_file);
2193 if (NILP (handler))
2194 handler = Ffind_file_name_handler (newname, Qrename_file);
2195 if (!NILP (handler))
2196 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2197 file, newname, ok_if_already_exists));
2199 encoded_file = ENCODE_FILE (file);
2200 encoded_newname = ENCODE_FILE (newname);
2202 #ifdef DOS_NT
2203 /* If the file names are identical but for the case, don't ask for
2204 confirmation: they simply want to change the letter-case of the
2205 file name. */
2206 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2207 #endif
2208 if (NILP (ok_if_already_exists)
2209 || INTEGERP (ok_if_already_exists))
2210 barf_or_query_if_file_exists (newname, "rename to it",
2211 INTEGERP (ok_if_already_exists), 0, 0);
2212 if (0 > rename (SSDATA (encoded_file), SSDATA (encoded_newname)))
2214 if (errno == EXDEV)
2216 int count;
2217 symlink_target = Ffile_symlink_p (file);
2218 if (! NILP (symlink_target))
2219 Fmake_symbolic_link (symlink_target, newname,
2220 NILP (ok_if_already_exists) ? Qnil : Qt);
2221 else if (!NILP (Ffile_directory_p (file)))
2222 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2223 else
2224 /* We have already prompted if it was an integer, so don't
2225 have copy-file prompt again. */
2226 Fcopy_file (file, newname,
2227 NILP (ok_if_already_exists) ? Qnil : Qt,
2228 Qt, Qt, Qt);
2230 count = SPECPDL_INDEX ();
2231 specbind (Qdelete_by_moving_to_trash, Qnil);
2233 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2234 call2 (Qdelete_directory, file, Qt);
2235 else
2236 Fdelete_file (file, Qnil);
2237 unbind_to (count, Qnil);
2239 else
2240 report_file_error ("Renaming", list2 (file, newname));
2242 UNGCPRO;
2243 return Qnil;
2246 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2247 "fAdd name to file: \nGName to add to %s: \np",
2248 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2249 Signals a `file-already-exists' error if a file NEWNAME already exists
2250 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2251 A number as third arg means request confirmation if NEWNAME already exists.
2252 This is what happens in interactive use with M-x. */)
2253 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2255 Lisp_Object handler;
2256 Lisp_Object encoded_file, encoded_newname;
2257 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2259 GCPRO4 (file, newname, encoded_file, encoded_newname);
2260 encoded_file = encoded_newname = Qnil;
2261 CHECK_STRING (file);
2262 CHECK_STRING (newname);
2263 file = Fexpand_file_name (file, Qnil);
2265 if (!NILP (Ffile_directory_p (newname)))
2266 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2267 else
2268 newname = Fexpand_file_name (newname, Qnil);
2270 /* If the file name has special constructs in it,
2271 call the corresponding file handler. */
2272 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2273 if (!NILP (handler))
2274 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2275 newname, ok_if_already_exists));
2277 /* If the new name has special constructs in it,
2278 call the corresponding file handler. */
2279 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2280 if (!NILP (handler))
2281 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2282 newname, ok_if_already_exists));
2284 encoded_file = ENCODE_FILE (file);
2285 encoded_newname = ENCODE_FILE (newname);
2287 if (NILP (ok_if_already_exists)
2288 || INTEGERP (ok_if_already_exists))
2289 barf_or_query_if_file_exists (newname, "make it a new name",
2290 INTEGERP (ok_if_already_exists), 0, 0);
2292 unlink (SSDATA (newname));
2293 if (0 > link (SSDATA (encoded_file), SSDATA (encoded_newname)))
2294 report_file_error ("Adding new name", list2 (file, newname));
2296 UNGCPRO;
2297 return Qnil;
2300 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2301 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2302 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2303 Both args must be strings.
2304 Signals a `file-already-exists' error if a file LINKNAME already exists
2305 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2306 A number as third arg means request confirmation if LINKNAME already exists.
2307 This happens for interactive use with M-x. */)
2308 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2310 Lisp_Object handler;
2311 Lisp_Object encoded_filename, encoded_linkname;
2312 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2314 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2315 encoded_filename = encoded_linkname = Qnil;
2316 CHECK_STRING (filename);
2317 CHECK_STRING (linkname);
2318 /* If the link target has a ~, we must expand it to get
2319 a truly valid file name. Otherwise, do not expand;
2320 we want to permit links to relative file names. */
2321 if (SREF (filename, 0) == '~')
2322 filename = Fexpand_file_name (filename, Qnil);
2324 if (!NILP (Ffile_directory_p (linkname)))
2325 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2326 else
2327 linkname = Fexpand_file_name (linkname, Qnil);
2329 /* If the file name has special constructs in it,
2330 call the corresponding file handler. */
2331 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2332 if (!NILP (handler))
2333 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2334 linkname, ok_if_already_exists));
2336 /* If the new link name has special constructs in it,
2337 call the corresponding file handler. */
2338 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2339 if (!NILP (handler))
2340 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2341 linkname, ok_if_already_exists));
2343 encoded_filename = ENCODE_FILE (filename);
2344 encoded_linkname = ENCODE_FILE (linkname);
2346 if (NILP (ok_if_already_exists)
2347 || INTEGERP (ok_if_already_exists))
2348 barf_or_query_if_file_exists (linkname, "make it a link",
2349 INTEGERP (ok_if_already_exists), 0, 0);
2350 if (0 > symlink (SSDATA (encoded_filename),
2351 SSDATA (encoded_linkname)))
2353 /* If we didn't complain already, silently delete existing file. */
2354 if (errno == EEXIST)
2356 unlink (SSDATA (encoded_linkname));
2357 if (0 <= symlink (SSDATA (encoded_filename),
2358 SSDATA (encoded_linkname)))
2360 UNGCPRO;
2361 return Qnil;
2364 if (errno == ENOSYS)
2366 UNGCPRO;
2367 xsignal1 (Qfile_error,
2368 build_string ("Symbolic links are not supported"));
2371 report_file_error ("Making symbolic link", list2 (filename, linkname));
2373 UNGCPRO;
2374 return Qnil;
2378 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2379 1, 1, 0,
2380 doc: /* Return t if file FILENAME specifies an absolute file name.
2381 On Unix, this is a name starting with a `/' or a `~'. */)
2382 (Lisp_Object filename)
2384 CHECK_STRING (filename);
2385 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2388 /* Return nonzero if file FILENAME exists and can be executed. */
2390 static int
2391 check_executable (char *filename)
2393 #ifdef DOS_NT
2394 struct stat st;
2395 if (stat (filename, &st) < 0)
2396 return 0;
2397 return ((st.st_mode & S_IEXEC) != 0);
2398 #else /* not DOS_NT */
2399 #ifdef HAVE_EUIDACCESS
2400 return (euidaccess (filename, 1) >= 0);
2401 #else
2402 /* Access isn't quite right because it uses the real uid
2403 and we really want to test with the effective uid.
2404 But Unix doesn't give us a right way to do it. */
2405 return (access (filename, 1) >= 0);
2406 #endif
2407 #endif /* not DOS_NT */
2410 /* Return nonzero if file FILENAME exists and can be written. */
2412 static int
2413 check_writable (const char *filename)
2415 #ifdef MSDOS
2416 struct stat st;
2417 if (stat (filename, &st) < 0)
2418 return 0;
2419 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
2420 #else /* not MSDOS */
2421 #ifdef HAVE_EUIDACCESS
2422 int res = (euidaccess (filename, 2) >= 0);
2423 #ifdef CYGWIN
2424 /* euidaccess may have returned failure because Cygwin couldn't
2425 determine the file's UID or GID; if so, we return success. */
2426 if (!res)
2428 struct stat st;
2429 if (stat (filename, &st) < 0)
2430 return 0;
2431 res = (st.st_uid == -1 || st.st_gid == -1);
2433 #endif /* CYGWIN */
2434 return res;
2435 #else /* not HAVE_EUIDACCESS */
2436 /* Access isn't quite right because it uses the real uid
2437 and we really want to test with the effective uid.
2438 But Unix doesn't give us a right way to do it.
2439 Opening with O_WRONLY could work for an ordinary file,
2440 but would lose for directories. */
2441 return (access (filename, 2) >= 0);
2442 #endif /* not HAVE_EUIDACCESS */
2443 #endif /* not MSDOS */
2446 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2447 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2448 See also `file-readable-p' and `file-attributes'.
2449 This returns nil for a symlink to a nonexistent file.
2450 Use `file-symlink-p' to test for such links. */)
2451 (Lisp_Object filename)
2453 Lisp_Object absname;
2454 Lisp_Object handler;
2455 struct stat statbuf;
2457 CHECK_STRING (filename);
2458 absname = Fexpand_file_name (filename, Qnil);
2460 /* If the file name has special constructs in it,
2461 call the corresponding file handler. */
2462 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2463 if (!NILP (handler))
2464 return call2 (handler, Qfile_exists_p, absname);
2466 absname = ENCODE_FILE (absname);
2468 return (stat (SSDATA (absname), &statbuf) >= 0) ? Qt : Qnil;
2471 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2472 doc: /* Return t if FILENAME can be executed by you.
2473 For a directory, this means you can access files in that directory. */)
2474 (Lisp_Object filename)
2476 Lisp_Object absname;
2477 Lisp_Object handler;
2479 CHECK_STRING (filename);
2480 absname = Fexpand_file_name (filename, Qnil);
2482 /* If the file name has special constructs in it,
2483 call the corresponding file handler. */
2484 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2485 if (!NILP (handler))
2486 return call2 (handler, Qfile_executable_p, absname);
2488 absname = ENCODE_FILE (absname);
2490 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2493 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2494 doc: /* Return t if file FILENAME exists and you can read it.
2495 See also `file-exists-p' and `file-attributes'. */)
2496 (Lisp_Object filename)
2498 Lisp_Object absname;
2499 Lisp_Object handler;
2500 int desc;
2501 int flags;
2502 struct stat statbuf;
2504 CHECK_STRING (filename);
2505 absname = Fexpand_file_name (filename, Qnil);
2507 /* If the file name has special constructs in it,
2508 call the corresponding file handler. */
2509 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2510 if (!NILP (handler))
2511 return call2 (handler, Qfile_readable_p, absname);
2513 absname = ENCODE_FILE (absname);
2515 #if defined (DOS_NT) || defined (macintosh)
2516 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2517 directories. */
2518 if (access (SDATA (absname), 0) == 0)
2519 return Qt;
2520 return Qnil;
2521 #else /* not DOS_NT and not macintosh */
2522 flags = O_RDONLY;
2523 #ifdef O_NONBLOCK
2524 /* Opening a fifo without O_NONBLOCK can wait.
2525 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2526 except in the case of a fifo, on a system which handles it. */
2527 desc = stat (SSDATA (absname), &statbuf);
2528 if (desc < 0)
2529 return Qnil;
2530 if (S_ISFIFO (statbuf.st_mode))
2531 flags |= O_NONBLOCK;
2532 #endif
2533 desc = emacs_open (SSDATA (absname), flags, 0);
2534 if (desc < 0)
2535 return Qnil;
2536 emacs_close (desc);
2537 return Qt;
2538 #endif /* not DOS_NT and not macintosh */
2541 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2542 on the RT/PC. */
2543 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2544 doc: /* Return t if file FILENAME can be written or created by you. */)
2545 (Lisp_Object filename)
2547 Lisp_Object absname, dir, encoded;
2548 Lisp_Object handler;
2549 struct stat statbuf;
2551 CHECK_STRING (filename);
2552 absname = Fexpand_file_name (filename, Qnil);
2554 /* If the file name has special constructs in it,
2555 call the corresponding file handler. */
2556 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2557 if (!NILP (handler))
2558 return call2 (handler, Qfile_writable_p, absname);
2560 encoded = ENCODE_FILE (absname);
2561 if (stat (SSDATA (encoded), &statbuf) >= 0)
2562 return (check_writable (SSDATA (encoded))
2563 ? Qt : Qnil);
2565 dir = Ffile_name_directory (absname);
2566 #ifdef MSDOS
2567 if (!NILP (dir))
2568 dir = Fdirectory_file_name (dir);
2569 #endif /* MSDOS */
2571 dir = ENCODE_FILE (dir);
2572 #ifdef WINDOWSNT
2573 /* The read-only attribute of the parent directory doesn't affect
2574 whether a file or directory can be created within it. Some day we
2575 should check ACLs though, which do affect this. */
2576 if (stat (SDATA (dir), &statbuf) < 0)
2577 return Qnil;
2578 return S_ISDIR (statbuf.st_mode) ? Qt : Qnil;
2579 #else
2580 return (check_writable (!NILP (dir) ? SSDATA (dir) : "")
2581 ? Qt : Qnil);
2582 #endif
2585 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2586 doc: /* Access file FILENAME, and get an error if that does not work.
2587 The second argument STRING is used in the error message.
2588 If there is no error, returns nil. */)
2589 (Lisp_Object filename, Lisp_Object string)
2591 Lisp_Object handler, encoded_filename, absname;
2592 int fd;
2594 CHECK_STRING (filename);
2595 absname = Fexpand_file_name (filename, Qnil);
2597 CHECK_STRING (string);
2599 /* If the file name has special constructs in it,
2600 call the corresponding file handler. */
2601 handler = Ffind_file_name_handler (absname, Qaccess_file);
2602 if (!NILP (handler))
2603 return call3 (handler, Qaccess_file, absname, string);
2605 encoded_filename = ENCODE_FILE (absname);
2607 fd = emacs_open (SSDATA (encoded_filename), O_RDONLY, 0);
2608 if (fd < 0)
2609 report_file_error (SSDATA (string), Fcons (filename, Qnil));
2610 emacs_close (fd);
2612 return Qnil;
2615 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2616 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2617 The value is the link target, as a string.
2618 Otherwise it returns nil.
2620 This function returns t when given the name of a symlink that
2621 points to a nonexistent file. */)
2622 (Lisp_Object filename)
2624 Lisp_Object handler;
2625 char *buf;
2626 Lisp_Object val;
2627 char readlink_buf[READLINK_BUFSIZE];
2629 CHECK_STRING (filename);
2630 filename = Fexpand_file_name (filename, Qnil);
2632 /* If the file name has special constructs in it,
2633 call the corresponding file handler. */
2634 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2635 if (!NILP (handler))
2636 return call2 (handler, Qfile_symlink_p, filename);
2638 filename = ENCODE_FILE (filename);
2640 buf = emacs_readlink (SSDATA (filename), readlink_buf);
2641 if (! buf)
2642 return Qnil;
2644 val = build_string (buf);
2645 if (buf[0] == '/' && strchr (buf, ':'))
2646 val = concat2 (build_string ("/:"), val);
2647 if (buf != readlink_buf)
2648 xfree (buf);
2649 val = DECODE_FILE (val);
2650 return val;
2653 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2654 doc: /* Return t if FILENAME names an existing directory.
2655 Symbolic links to directories count as directories.
2656 See `file-symlink-p' to distinguish symlinks. */)
2657 (Lisp_Object filename)
2659 register Lisp_Object absname;
2660 struct stat st;
2661 Lisp_Object handler;
2663 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2665 /* If the file name has special constructs in it,
2666 call the corresponding file handler. */
2667 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2668 if (!NILP (handler))
2669 return call2 (handler, Qfile_directory_p, absname);
2671 absname = ENCODE_FILE (absname);
2673 if (stat (SSDATA (absname), &st) < 0)
2674 return Qnil;
2675 return S_ISDIR (st.st_mode) ? Qt : Qnil;
2678 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2679 Sfile_accessible_directory_p, 1, 1, 0,
2680 doc: /* Return t if file FILENAME names a directory you can open.
2681 For the value to be t, FILENAME must specify the name of a directory as a file,
2682 and the directory must allow you to open files in it. In order to use a
2683 directory as a buffer's current directory, this predicate must return true.
2684 A directory name spec may be given instead; then the value is t
2685 if the directory so specified exists and really is a readable and
2686 searchable directory. */)
2687 (Lisp_Object filename)
2689 Lisp_Object handler;
2690 int tem;
2691 struct gcpro gcpro1;
2693 /* If the file name has special constructs in it,
2694 call the corresponding file handler. */
2695 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
2696 if (!NILP (handler))
2697 return call2 (handler, Qfile_accessible_directory_p, filename);
2699 GCPRO1 (filename);
2700 tem = (NILP (Ffile_directory_p (filename))
2701 || NILP (Ffile_executable_p (filename)));
2702 UNGCPRO;
2703 return tem ? Qnil : Qt;
2706 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2707 doc: /* Return t if FILENAME names a regular file.
2708 This is the sort of file that holds an ordinary stream of data bytes.
2709 Symbolic links to regular files count as regular files.
2710 See `file-symlink-p' to distinguish symlinks. */)
2711 (Lisp_Object filename)
2713 register Lisp_Object absname;
2714 struct stat st;
2715 Lisp_Object handler;
2717 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2719 /* If the file name has special constructs in it,
2720 call the corresponding file handler. */
2721 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2722 if (!NILP (handler))
2723 return call2 (handler, Qfile_regular_p, absname);
2725 absname = ENCODE_FILE (absname);
2727 #ifdef WINDOWSNT
2729 int result;
2730 Lisp_Object tem = Vw32_get_true_file_attributes;
2732 /* Tell stat to use expensive method to get accurate info. */
2733 Vw32_get_true_file_attributes = Qt;
2734 result = stat (SDATA (absname), &st);
2735 Vw32_get_true_file_attributes = tem;
2737 if (result < 0)
2738 return Qnil;
2739 return S_ISREG (st.st_mode) ? Qt : Qnil;
2741 #else
2742 if (stat (SSDATA (absname), &st) < 0)
2743 return Qnil;
2744 return S_ISREG (st.st_mode) ? Qt : Qnil;
2745 #endif
2748 DEFUN ("file-selinux-context", Ffile_selinux_context,
2749 Sfile_selinux_context, 1, 1, 0,
2750 doc: /* Return SELinux context of file named FILENAME,
2751 as a list ("user", "role", "type", "range"). Return (nil, nil, nil, nil)
2752 if file does not exist, is not accessible, or SELinux is disabled */)
2753 (Lisp_Object filename)
2755 Lisp_Object absname;
2756 Lisp_Object values[4];
2757 Lisp_Object handler;
2758 #if HAVE_LIBSELINUX
2759 security_context_t con;
2760 int conlength;
2761 context_t context;
2762 #endif
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_selinux_context);
2769 if (!NILP (handler))
2770 return call2 (handler, Qfile_selinux_context, absname);
2772 absname = ENCODE_FILE (absname);
2774 values[0] = Qnil;
2775 values[1] = Qnil;
2776 values[2] = Qnil;
2777 values[3] = Qnil;
2778 #if HAVE_LIBSELINUX
2779 if (is_selinux_enabled ())
2781 conlength = lgetfilecon (SSDATA (absname), &con);
2782 if (conlength > 0)
2784 context = context_new (con);
2785 if (context_user_get (context))
2786 values[0] = build_string (context_user_get (context));
2787 if (context_role_get (context))
2788 values[1] = build_string (context_role_get (context));
2789 if (context_type_get (context))
2790 values[2] = build_string (context_type_get (context));
2791 if (context_range_get (context))
2792 values[3] = build_string (context_range_get (context));
2793 context_free (context);
2795 if (con)
2796 freecon (con);
2798 #endif
2800 return Flist (sizeof (values) / sizeof (values[0]), values);
2803 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2804 Sset_file_selinux_context, 2, 2, 0,
2805 doc: /* Set SELinux context of file named FILENAME to CONTEXT
2806 as a list ("user", "role", "type", "range"). Has no effect if SELinux
2807 is disabled. */)
2808 (Lisp_Object filename, Lisp_Object context)
2810 Lisp_Object absname;
2811 Lisp_Object handler;
2812 #if HAVE_LIBSELINUX
2813 Lisp_Object encoded_absname;
2814 Lisp_Object user = CAR_SAFE (context);
2815 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2816 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2817 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2818 security_context_t con;
2819 int fail, conlength;
2820 context_t parsed_con;
2821 #endif
2823 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2825 /* If the file name has special constructs in it,
2826 call the corresponding file handler. */
2827 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2828 if (!NILP (handler))
2829 return call3 (handler, Qset_file_selinux_context, absname, context);
2831 #if HAVE_LIBSELINUX
2832 if (is_selinux_enabled ())
2834 /* Get current file context. */
2835 encoded_absname = ENCODE_FILE (absname);
2836 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2837 if (conlength > 0)
2839 parsed_con = context_new (con);
2840 /* Change the parts defined in the parameter.*/
2841 if (STRINGP (user))
2843 if (context_user_set (parsed_con, SSDATA (user)))
2844 error ("Doing context_user_set");
2846 if (STRINGP (role))
2848 if (context_role_set (parsed_con, SSDATA (role)))
2849 error ("Doing context_role_set");
2851 if (STRINGP (type))
2853 if (context_type_set (parsed_con, SSDATA (type)))
2854 error ("Doing context_type_set");
2856 if (STRINGP (range))
2858 if (context_range_set (parsed_con, SSDATA (range)))
2859 error ("Doing context_range_set");
2862 /* Set the modified context back to the file. */
2863 fail = lsetfilecon (SSDATA (encoded_absname),
2864 context_str (parsed_con));
2865 if (fail)
2866 report_file_error ("Doing lsetfilecon", Fcons (absname, Qnil));
2868 context_free (parsed_con);
2870 else
2871 report_file_error ("Doing lgetfilecon", Fcons (absname, Qnil));
2873 if (con)
2874 freecon (con);
2876 #endif
2878 return Qnil;
2881 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
2882 doc: /* Return mode bits of file named FILENAME, as an integer.
2883 Return nil, if file does not exist or is not accessible. */)
2884 (Lisp_Object filename)
2886 Lisp_Object absname;
2887 struct stat st;
2888 Lisp_Object handler;
2890 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2892 /* If the file name has special constructs in it,
2893 call the corresponding file handler. */
2894 handler = Ffind_file_name_handler (absname, Qfile_modes);
2895 if (!NILP (handler))
2896 return call2 (handler, Qfile_modes, absname);
2898 absname = ENCODE_FILE (absname);
2900 if (stat (SSDATA (absname), &st) < 0)
2901 return Qnil;
2903 return make_number (st.st_mode & 07777);
2906 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
2907 "(let ((file (read-file-name \"File: \"))) \
2908 (list file (read-file-modes nil file)))",
2909 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
2910 Only the 12 low bits of MODE are used.
2912 Interactively, mode bits are read by `read-file-modes', which accepts
2913 symbolic notation, like the `chmod' command from GNU Coreutils. */)
2914 (Lisp_Object filename, Lisp_Object mode)
2916 Lisp_Object absname, encoded_absname;
2917 Lisp_Object handler;
2919 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2920 CHECK_NUMBER (mode);
2922 /* If the file name has special constructs in it,
2923 call the corresponding file handler. */
2924 handler = Ffind_file_name_handler (absname, Qset_file_modes);
2925 if (!NILP (handler))
2926 return call3 (handler, Qset_file_modes, absname, mode);
2928 encoded_absname = ENCODE_FILE (absname);
2930 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
2931 report_file_error ("Doing chmod", Fcons (absname, Qnil));
2933 return Qnil;
2936 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
2937 doc: /* Set the file permission bits for newly created files.
2938 The argument MODE should be an integer; only the low 9 bits are used.
2939 This setting is inherited by subprocesses. */)
2940 (Lisp_Object mode)
2942 CHECK_NUMBER (mode);
2944 umask ((~ XINT (mode)) & 0777);
2946 return Qnil;
2949 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
2950 doc: /* Return the default file protection for created files.
2951 The value is an integer. */)
2952 (void)
2954 int realmask;
2955 Lisp_Object value;
2957 realmask = umask (0);
2958 umask (realmask);
2960 XSETINT (value, (~ realmask) & 0777);
2961 return value;
2965 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
2966 doc: /* Set times of file FILENAME to TIMESTAMP.
2967 Set both access and modification times.
2968 Return t on success, else nil.
2969 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
2970 `current-time'. */)
2971 (Lisp_Object filename, Lisp_Object timestamp)
2973 Lisp_Object absname, encoded_absname;
2974 Lisp_Object handler;
2975 time_t sec;
2976 int usec;
2978 if (! lisp_time_argument (timestamp, &sec, &usec))
2979 error ("Invalid time specification");
2981 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2983 /* If the file name has special constructs in it,
2984 call the corresponding file handler. */
2985 handler = Ffind_file_name_handler (absname, Qset_file_times);
2986 if (!NILP (handler))
2987 return call3 (handler, Qset_file_times, absname, timestamp);
2989 encoded_absname = ENCODE_FILE (absname);
2992 EMACS_TIME t;
2994 EMACS_SET_SECS (t, sec);
2995 EMACS_SET_USECS (t, usec);
2997 if (set_file_times (SSDATA (encoded_absname), t, t))
2999 #ifdef DOS_NT
3000 struct stat st;
3002 /* Setting times on a directory always fails. */
3003 if (stat (SSDATA (encoded_absname), &st) == 0 && S_ISDIR (st.st_mode))
3004 return Qnil;
3005 #endif
3006 report_file_error ("Setting file times", Fcons (absname, Qnil));
3007 return Qnil;
3011 return Qt;
3014 #ifdef HAVE_SYNC
3015 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3016 doc: /* Tell Unix to finish all pending disk updates. */)
3017 (void)
3019 sync ();
3020 return Qnil;
3023 #endif /* HAVE_SYNC */
3025 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3026 doc: /* Return t if file FILE1 is newer than file FILE2.
3027 If FILE1 does not exist, the answer is nil;
3028 otherwise, if FILE2 does not exist, the answer is t. */)
3029 (Lisp_Object file1, Lisp_Object file2)
3031 Lisp_Object absname1, absname2;
3032 struct stat st;
3033 int mtime1;
3034 Lisp_Object handler;
3035 struct gcpro gcpro1, gcpro2;
3037 CHECK_STRING (file1);
3038 CHECK_STRING (file2);
3040 absname1 = Qnil;
3041 GCPRO2 (absname1, file2);
3042 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3043 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3044 UNGCPRO;
3046 /* If the file name has special constructs in it,
3047 call the corresponding file handler. */
3048 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3049 if (NILP (handler))
3050 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3051 if (!NILP (handler))
3052 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3054 GCPRO2 (absname1, absname2);
3055 absname1 = ENCODE_FILE (absname1);
3056 absname2 = ENCODE_FILE (absname2);
3057 UNGCPRO;
3059 if (stat (SSDATA (absname1), &st) < 0)
3060 return Qnil;
3062 mtime1 = st.st_mtime;
3064 if (stat (SSDATA (absname2), &st) < 0)
3065 return Qt;
3067 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3070 #ifndef READ_BUF_SIZE
3071 #define READ_BUF_SIZE (64 << 10)
3072 #endif
3074 /* This function is called after Lisp functions to decide a coding
3075 system are called, or when they cause an error. Before they are
3076 called, the current buffer is set unibyte and it contains only a
3077 newly inserted text (thus the buffer was empty before the
3078 insertion).
3080 The functions may set markers, overlays, text properties, or even
3081 alter the buffer contents, change the current buffer.
3083 Here, we reset all those changes by:
3084 o set back the current buffer.
3085 o move all markers and overlays to BEG.
3086 o remove all text properties.
3087 o set back the buffer multibyteness. */
3089 static Lisp_Object
3090 decide_coding_unwind (Lisp_Object unwind_data)
3092 Lisp_Object multibyte, undo_list, buffer;
3094 multibyte = XCAR (unwind_data);
3095 unwind_data = XCDR (unwind_data);
3096 undo_list = XCAR (unwind_data);
3097 buffer = XCDR (unwind_data);
3099 if (current_buffer != XBUFFER (buffer))
3100 set_buffer_internal (XBUFFER (buffer));
3101 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3102 adjust_overlays_for_delete (BEG, Z - BEG);
3103 BUF_INTERVALS (current_buffer) = 0;
3104 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3106 /* Now we are safe to change the buffer's multibyteness directly. */
3107 BVAR (current_buffer, enable_multibyte_characters) = multibyte;
3108 BVAR (current_buffer, undo_list) = undo_list;
3110 return Qnil;
3114 /* Used to pass values from insert-file-contents to read_non_regular. */
3116 static int non_regular_fd;
3117 static EMACS_INT non_regular_inserted;
3118 static EMACS_INT non_regular_nbytes;
3121 /* Read from a non-regular file.
3122 Read non_regular_nbytes bytes max from non_regular_fd.
3123 Non_regular_inserted specifies where to put the read bytes.
3124 Value is the number of bytes read. */
3126 static Lisp_Object
3127 read_non_regular (Lisp_Object ignore)
3129 EMACS_INT nbytes;
3131 immediate_quit = 1;
3132 QUIT;
3133 nbytes = emacs_read (non_regular_fd,
3134 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3135 + non_regular_inserted),
3136 non_regular_nbytes);
3137 immediate_quit = 0;
3138 return make_number (nbytes);
3142 /* Condition-case handler used when reading from non-regular files
3143 in insert-file-contents. */
3145 static Lisp_Object
3146 read_non_regular_quit (Lisp_Object ignore)
3148 return Qnil;
3151 /* Reposition FD to OFFSET, based on WHENCE. This acts like lseek
3152 except that it also tests for OFFSET being out of lseek's range. */
3153 static off_t
3154 emacs_lseek (int fd, EMACS_INT offset, int whence)
3156 /* Use "&" rather than "&&" to suppress a bogus GCC warning; see
3157 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43772>. */
3158 if (! ((TYPE_MINIMUM (off_t) <= offset) & (offset <= TYPE_MAXIMUM (off_t))))
3160 errno = EINVAL;
3161 return -1;
3163 return lseek (fd, offset, whence);
3167 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3168 1, 5, 0,
3169 doc: /* Insert contents of file FILENAME after point.
3170 Returns list of absolute file name and number of characters inserted.
3171 If second argument VISIT is non-nil, the buffer's visited filename and
3172 last save file modtime are set, and it is marked unmodified. If
3173 visiting and the file does not exist, visiting is completed before the
3174 error is signaled.
3176 The optional third and fourth arguments BEG and END specify what portion
3177 of the file to insert. These arguments count bytes in the file, not
3178 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3180 If optional fifth argument REPLACE is non-nil, replace the current
3181 buffer contents (in the accessible portion) with the file contents.
3182 This is better than simply deleting and inserting the whole thing
3183 because (1) it preserves some marker positions and (2) it puts less data
3184 in the undo list. When REPLACE is non-nil, the second return value is
3185 the number of characters that replace previous buffer contents.
3187 This function does code conversion according to the value of
3188 `coding-system-for-read' or `file-coding-system-alist', and sets the
3189 variable `last-coding-system-used' to the coding system actually used. */)
3190 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3192 struct stat st;
3193 register int fd;
3194 EMACS_INT inserted = 0;
3195 int nochange = 0;
3196 register EMACS_INT how_much;
3197 off_t beg_offset, end_offset;
3198 register EMACS_INT unprocessed;
3199 int count = SPECPDL_INDEX ();
3200 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3201 Lisp_Object handler, val, insval, orig_filename, old_undo;
3202 Lisp_Object p;
3203 EMACS_INT total = 0;
3204 int not_regular = 0;
3205 int save_errno = 0;
3206 char read_buf[READ_BUF_SIZE];
3207 struct coding_system coding;
3208 char buffer[1 << 14];
3209 int replace_handled = 0;
3210 int set_coding_system = 0;
3211 Lisp_Object coding_system;
3212 int read_quit = 0;
3213 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3214 int we_locked_file = 0;
3215 int deferred_remove_unwind_protect = 0;
3217 if (current_buffer->base_buffer && ! NILP (visit))
3218 error ("Cannot do file visiting in an indirect buffer");
3220 if (!NILP (BVAR (current_buffer, read_only)))
3221 Fbarf_if_buffer_read_only ();
3223 val = Qnil;
3224 p = Qnil;
3225 orig_filename = Qnil;
3226 old_undo = Qnil;
3228 GCPRO5 (filename, val, p, orig_filename, old_undo);
3230 CHECK_STRING (filename);
3231 filename = Fexpand_file_name (filename, Qnil);
3233 /* The value Qnil means that the coding system is not yet
3234 decided. */
3235 coding_system = Qnil;
3237 /* If the file name has special constructs in it,
3238 call the corresponding file handler. */
3239 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3240 if (!NILP (handler))
3242 val = call6 (handler, Qinsert_file_contents, filename,
3243 visit, beg, end, replace);
3244 if (CONSP (val) && CONSP (XCDR (val)))
3245 inserted = XINT (XCAR (XCDR (val)));
3246 goto handled;
3249 orig_filename = filename;
3250 filename = ENCODE_FILE (filename);
3252 fd = -1;
3254 #ifdef WINDOWSNT
3256 Lisp_Object tem = Vw32_get_true_file_attributes;
3258 /* Tell stat to use expensive method to get accurate info. */
3259 Vw32_get_true_file_attributes = Qt;
3260 total = stat (SSDATA (filename), &st);
3261 Vw32_get_true_file_attributes = tem;
3263 if (total < 0)
3264 #else
3265 if (stat (SSDATA (filename), &st) < 0)
3266 #endif /* WINDOWSNT */
3268 badopen:
3269 save_errno = errno;
3270 if (NILP (visit))
3271 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3272 st.st_mtime = -1;
3273 st.st_size = -1;
3274 how_much = 0;
3275 if (!NILP (Vcoding_system_for_read))
3276 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3277 goto notfound;
3280 /* This code will need to be changed in order to work on named
3281 pipes, and it's probably just not worth it. So we should at
3282 least signal an error. */
3283 if (!S_ISREG (st.st_mode))
3285 not_regular = 1;
3287 if (! NILP (visit))
3288 goto notfound;
3290 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3291 xsignal2 (Qfile_error,
3292 build_string ("not a regular file"), orig_filename);
3295 if (fd < 0)
3296 if ((fd = emacs_open (SSDATA (filename), O_RDONLY, 0)) < 0)
3297 goto badopen;
3299 /* Replacement should preserve point as it preserves markers. */
3300 if (!NILP (replace))
3301 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3303 record_unwind_protect (close_file_unwind, make_number (fd));
3306 if (!NILP (visit))
3308 if (!NILP (beg) || !NILP (end))
3309 error ("Attempt to visit less than an entire file");
3310 if (BEG < Z && NILP (replace))
3311 error ("Cannot do file visiting in a non-empty buffer");
3314 if (!NILP (beg))
3316 if (! (RANGED_INTEGERP (0, beg, TYPE_MAXIMUM (off_t))))
3317 wrong_type_argument (intern ("file-offset"), beg);
3318 beg_offset = XFASTINT (beg);
3320 else
3321 beg_offset = 0;
3323 if (!NILP (end))
3325 if (! (RANGED_INTEGERP (0, end, TYPE_MAXIMUM (off_t))))
3326 wrong_type_argument (intern ("file-offset"), end);
3327 end_offset = XFASTINT (end);
3329 else
3331 if (not_regular)
3332 end_offset = TYPE_MAXIMUM (off_t);
3333 else
3335 end_offset = st.st_size;
3337 /* A negative size can happen on a platform that allows file
3338 sizes greater than the maximum off_t value. */
3339 if (end_offset < 0)
3340 buffer_overflow ();
3342 /* The file size returned from stat may be zero, but data
3343 may be readable nonetheless, for example when this is a
3344 file in the /proc filesystem. */
3345 if (end_offset == 0)
3346 end_offset = READ_BUF_SIZE;
3350 /* Check now whether the buffer will become too large,
3351 in the likely case where the file's length is not changing.
3352 This saves a lot of needless work before a buffer overflow. */
3353 if (! not_regular)
3355 /* The likely offset where we will stop reading. We could read
3356 more (or less), if the file grows (or shrinks) as we read it. */
3357 off_t likely_end = min (end_offset, st.st_size);
3359 if (beg_offset < likely_end)
3361 ptrdiff_t buf_bytes =
3362 Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3363 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3364 off_t likely_growth = likely_end - beg_offset;
3365 if (buf_growth_max < likely_growth)
3366 buffer_overflow ();
3370 /* Prevent redisplay optimizations. */
3371 current_buffer->clip_changed = 1;
3373 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3375 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3376 setup_coding_system (coding_system, &coding);
3377 /* Ensure we set Vlast_coding_system_used. */
3378 set_coding_system = 1;
3380 else if (BEG < Z)
3382 /* Decide the coding system to use for reading the file now
3383 because we can't use an optimized method for handling
3384 `coding:' tag if the current buffer is not empty. */
3385 if (!NILP (Vcoding_system_for_read))
3386 coding_system = Vcoding_system_for_read;
3387 else
3389 /* Don't try looking inside a file for a coding system
3390 specification if it is not seekable. */
3391 if (! not_regular && ! NILP (Vset_auto_coding_function))
3393 /* Find a coding system specified in the heading two
3394 lines or in the tailing several lines of the file.
3395 We assume that the 1K-byte and 3K-byte for heading
3396 and tailing respectively are sufficient for this
3397 purpose. */
3398 EMACS_INT nread;
3400 if (st.st_size <= (1024 * 4))
3401 nread = emacs_read (fd, read_buf, 1024 * 4);
3402 else
3404 nread = emacs_read (fd, read_buf, 1024);
3405 if (nread >= 0)
3407 if (lseek (fd, st.st_size - (1024 * 3), SEEK_SET) < 0)
3408 report_file_error ("Setting file position",
3409 Fcons (orig_filename, Qnil));
3410 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3414 if (nread < 0)
3415 error ("IO error reading %s: %s",
3416 SDATA (orig_filename), emacs_strerror (errno));
3417 else if (nread > 0)
3419 struct buffer *prev = current_buffer;
3420 Lisp_Object workbuf;
3421 struct buffer *buf;
3423 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3425 workbuf = Fget_buffer_create (build_string (" *code-converting-work*"));
3426 buf = XBUFFER (workbuf);
3428 delete_all_overlays (buf);
3429 BVAR (buf, directory) = BVAR (current_buffer, directory);
3430 BVAR (buf, read_only) = Qnil;
3431 BVAR (buf, filename) = Qnil;
3432 BVAR (buf, undo_list) = Qt;
3433 eassert (buf->overlays_before == NULL);
3434 eassert (buf->overlays_after == NULL);
3436 set_buffer_internal (buf);
3437 Ferase_buffer ();
3438 BVAR (buf, enable_multibyte_characters) = Qnil;
3440 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3441 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3442 coding_system = call2 (Vset_auto_coding_function,
3443 filename, make_number (nread));
3444 set_buffer_internal (prev);
3446 /* Discard the unwind protect for recovering the
3447 current buffer. */
3448 specpdl_ptr--;
3450 /* Rewind the file for the actual read done later. */
3451 if (lseek (fd, 0, SEEK_SET) < 0)
3452 report_file_error ("Setting file position",
3453 Fcons (orig_filename, Qnil));
3457 if (NILP (coding_system))
3459 /* If we have not yet decided a coding system, check
3460 file-coding-system-alist. */
3461 Lisp_Object args[6];
3463 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3464 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3465 coding_system = Ffind_operation_coding_system (6, args);
3466 if (CONSP (coding_system))
3467 coding_system = XCAR (coding_system);
3471 if (NILP (coding_system))
3472 coding_system = Qundecided;
3473 else
3474 CHECK_CODING_SYSTEM (coding_system);
3476 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3477 /* We must suppress all character code conversion except for
3478 end-of-line conversion. */
3479 coding_system = raw_text_coding_system (coding_system);
3481 setup_coding_system (coding_system, &coding);
3482 /* Ensure we set Vlast_coding_system_used. */
3483 set_coding_system = 1;
3486 /* If requested, replace the accessible part of the buffer
3487 with the file contents. Avoid replacing text at the
3488 beginning or end of the buffer that matches the file contents;
3489 that preserves markers pointing to the unchanged parts.
3491 Here we implement this feature in an optimized way
3492 for the case where code conversion is NOT needed.
3493 The following if-statement handles the case of conversion
3494 in a less optimal way.
3496 If the code conversion is "automatic" then we try using this
3497 method and hope for the best.
3498 But if we discover the need for conversion, we give up on this method
3499 and let the following if-statement handle the replace job. */
3500 if (!NILP (replace)
3501 && BEGV < ZV
3502 && (NILP (coding_system)
3503 || ! CODING_REQUIRE_DECODING (&coding)))
3505 /* same_at_start and same_at_end count bytes,
3506 because file access counts bytes
3507 and BEG and END count bytes. */
3508 EMACS_INT same_at_start = BEGV_BYTE;
3509 EMACS_INT same_at_end = ZV_BYTE;
3510 EMACS_INT overlap;
3511 /* There is still a possibility we will find the need to do code
3512 conversion. If that happens, we set this variable to 1 to
3513 give up on handling REPLACE in the optimized way. */
3514 int giveup_match_end = 0;
3516 if (beg_offset != 0)
3518 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3519 report_file_error ("Setting file position",
3520 Fcons (orig_filename, Qnil));
3523 immediate_quit = 1;
3524 QUIT;
3525 /* Count how many chars at the start of the file
3526 match the text at the beginning of the buffer. */
3527 while (1)
3529 EMACS_INT nread, bufpos;
3531 nread = emacs_read (fd, buffer, sizeof buffer);
3532 if (nread < 0)
3533 error ("IO error reading %s: %s",
3534 SSDATA (orig_filename), emacs_strerror (errno));
3535 else if (nread == 0)
3536 break;
3538 if (CODING_REQUIRE_DETECTION (&coding))
3540 coding_system = detect_coding_system ((unsigned char *) buffer,
3541 nread, nread, 1, 0,
3542 coding_system);
3543 setup_coding_system (coding_system, &coding);
3546 if (CODING_REQUIRE_DECODING (&coding))
3547 /* We found that the file should be decoded somehow.
3548 Let's give up here. */
3550 giveup_match_end = 1;
3551 break;
3554 bufpos = 0;
3555 while (bufpos < nread && same_at_start < ZV_BYTE
3556 && FETCH_BYTE (same_at_start) == buffer[bufpos])
3557 same_at_start++, bufpos++;
3558 /* If we found a discrepancy, stop the scan.
3559 Otherwise loop around and scan the next bufferful. */
3560 if (bufpos != nread)
3561 break;
3563 immediate_quit = 0;
3564 /* If the file matches the buffer completely,
3565 there's no need to replace anything. */
3566 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3568 emacs_close (fd);
3569 specpdl_ptr--;
3570 /* Truncate the buffer to the size of the file. */
3571 del_range_1 (same_at_start, same_at_end, 0, 0);
3572 goto handled;
3574 immediate_quit = 1;
3575 QUIT;
3576 /* Count how many chars at the end of the file
3577 match the text at the end of the buffer. But, if we have
3578 already found that decoding is necessary, don't waste time. */
3579 while (!giveup_match_end)
3581 int total_read, nread, bufpos, trial;
3582 off_t curpos;
3584 /* At what file position are we now scanning? */
3585 curpos = end_offset - (ZV_BYTE - same_at_end);
3586 /* If the entire file matches the buffer tail, stop the scan. */
3587 if (curpos == 0)
3588 break;
3589 /* How much can we scan in the next step? */
3590 trial = min (curpos, sizeof buffer);
3591 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3592 report_file_error ("Setting file position",
3593 Fcons (orig_filename, Qnil));
3595 total_read = nread = 0;
3596 while (total_read < trial)
3598 nread = emacs_read (fd, buffer + total_read, trial - total_read);
3599 if (nread < 0)
3600 error ("IO error reading %s: %s",
3601 SDATA (orig_filename), emacs_strerror (errno));
3602 else if (nread == 0)
3603 break;
3604 total_read += nread;
3607 /* Scan this bufferful from the end, comparing with
3608 the Emacs buffer. */
3609 bufpos = total_read;
3611 /* Compare with same_at_start to avoid counting some buffer text
3612 as matching both at the file's beginning and at the end. */
3613 while (bufpos > 0 && same_at_end > same_at_start
3614 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
3615 same_at_end--, bufpos--;
3617 /* If we found a discrepancy, stop the scan.
3618 Otherwise loop around and scan the preceding bufferful. */
3619 if (bufpos != 0)
3621 /* If this discrepancy is because of code conversion,
3622 we cannot use this method; giveup and try the other. */
3623 if (same_at_end > same_at_start
3624 && FETCH_BYTE (same_at_end - 1) >= 0200
3625 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3626 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3627 giveup_match_end = 1;
3628 break;
3631 if (nread == 0)
3632 break;
3634 immediate_quit = 0;
3636 if (! giveup_match_end)
3638 EMACS_INT temp;
3640 /* We win! We can handle REPLACE the optimized way. */
3642 /* Extend the start of non-matching text area to multibyte
3643 character boundary. */
3644 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3645 while (same_at_start > BEGV_BYTE
3646 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3647 same_at_start--;
3649 /* Extend the end of non-matching text area to multibyte
3650 character boundary. */
3651 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3652 while (same_at_end < ZV_BYTE
3653 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3654 same_at_end++;
3656 /* Don't try to reuse the same piece of text twice. */
3657 overlap = (same_at_start - BEGV_BYTE
3658 - (same_at_end
3659 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3660 if (overlap > 0)
3661 same_at_end += overlap;
3663 /* Arrange to read only the nonmatching middle part of the file. */
3664 beg_offset += same_at_start - BEGV_BYTE;
3665 end_offset -= ZV_BYTE - same_at_end;
3667 del_range_byte (same_at_start, same_at_end, 0);
3668 /* Insert from the file at the proper position. */
3669 temp = BYTE_TO_CHAR (same_at_start);
3670 SET_PT_BOTH (temp, same_at_start);
3672 /* If display currently starts at beginning of line,
3673 keep it that way. */
3674 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3675 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3677 replace_handled = 1;
3681 /* If requested, replace the accessible part of the buffer
3682 with the file contents. Avoid replacing text at the
3683 beginning or end of the buffer that matches the file contents;
3684 that preserves markers pointing to the unchanged parts.
3686 Here we implement this feature for the case where code conversion
3687 is needed, in a simple way that needs a lot of memory.
3688 The preceding if-statement handles the case of no conversion
3689 in a more optimized way. */
3690 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3692 EMACS_INT same_at_start = BEGV_BYTE;
3693 EMACS_INT same_at_end = ZV_BYTE;
3694 EMACS_INT same_at_start_charpos;
3695 EMACS_INT inserted_chars;
3696 EMACS_INT overlap;
3697 EMACS_INT bufpos;
3698 unsigned char *decoded;
3699 EMACS_INT temp;
3700 EMACS_INT this = 0;
3701 int this_count = SPECPDL_INDEX ();
3702 int multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3703 Lisp_Object conversion_buffer;
3704 struct gcpro gcpro1;
3706 conversion_buffer = code_conversion_save (1, multibyte);
3708 /* First read the whole file, performing code conversion into
3709 CONVERSION_BUFFER. */
3711 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3712 report_file_error ("Setting file position",
3713 Fcons (orig_filename, Qnil));
3715 total = st.st_size; /* Total bytes in the file. */
3716 how_much = 0; /* Bytes read from file so far. */
3717 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3718 unprocessed = 0; /* Bytes not processed in previous loop. */
3720 GCPRO1 (conversion_buffer);
3721 while (how_much < total)
3723 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
3724 quitting while reading a huge while. */
3725 /* `try'' is reserved in some compilers (Microsoft C). */
3726 EMACS_INT trytry = min (total - how_much,
3727 READ_BUF_SIZE - unprocessed);
3729 /* Allow quitting out of the actual I/O. */
3730 immediate_quit = 1;
3731 QUIT;
3732 this = emacs_read (fd, read_buf + unprocessed, trytry);
3733 immediate_quit = 0;
3735 if (this <= 0)
3736 break;
3738 how_much += this;
3740 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3741 BUF_Z (XBUFFER (conversion_buffer)));
3742 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3743 unprocessed + this, conversion_buffer);
3744 unprocessed = coding.carryover_bytes;
3745 if (coding.carryover_bytes > 0)
3746 memcpy (read_buf, coding.carryover, unprocessed);
3748 UNGCPRO;
3749 emacs_close (fd);
3751 /* We should remove the unwind_protect calling
3752 close_file_unwind, but other stuff has been added the stack,
3753 so defer the removal till we reach the `handled' label. */
3754 deferred_remove_unwind_protect = 1;
3756 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
3757 if we couldn't read the file. */
3759 if (this < 0)
3760 error ("IO error reading %s: %s",
3761 SDATA (orig_filename), emacs_strerror (errno));
3763 if (unprocessed > 0)
3765 coding.mode |= CODING_MODE_LAST_BLOCK;
3766 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3767 unprocessed, conversion_buffer);
3768 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3771 coding_system = CODING_ID_NAME (coding.id);
3772 set_coding_system = 1;
3773 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3774 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3775 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3777 /* Compare the beginning of the converted string with the buffer
3778 text. */
3780 bufpos = 0;
3781 while (bufpos < inserted && same_at_start < same_at_end
3782 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3783 same_at_start++, bufpos++;
3785 /* If the file matches the head of buffer completely,
3786 there's no need to replace anything. */
3788 if (bufpos == inserted)
3790 /* Truncate the buffer to the size of the file. */
3791 if (same_at_start == same_at_end)
3792 nochange = 1;
3793 else
3794 del_range_byte (same_at_start, same_at_end, 0);
3795 inserted = 0;
3797 unbind_to (this_count, Qnil);
3798 goto handled;
3801 /* Extend the start of non-matching text area to the previous
3802 multibyte character boundary. */
3803 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3804 while (same_at_start > BEGV_BYTE
3805 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3806 same_at_start--;
3808 /* Scan this bufferful from the end, comparing with
3809 the Emacs buffer. */
3810 bufpos = inserted;
3812 /* Compare with same_at_start to avoid counting some buffer text
3813 as matching both at the file's beginning and at the end. */
3814 while (bufpos > 0 && same_at_end > same_at_start
3815 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3816 same_at_end--, bufpos--;
3818 /* Extend the end of non-matching text area to the next
3819 multibyte character boundary. */
3820 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3821 while (same_at_end < ZV_BYTE
3822 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3823 same_at_end++;
3825 /* Don't try to reuse the same piece of text twice. */
3826 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3827 if (overlap > 0)
3828 same_at_end += overlap;
3830 /* If display currently starts at beginning of line,
3831 keep it that way. */
3832 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3833 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3835 /* Replace the chars that we need to replace,
3836 and update INSERTED to equal the number of bytes
3837 we are taking from the decoded string. */
3838 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3840 if (same_at_end != same_at_start)
3842 del_range_byte (same_at_start, same_at_end, 0);
3843 temp = GPT;
3844 same_at_start = GPT_BYTE;
3846 else
3848 temp = BYTE_TO_CHAR (same_at_start);
3850 /* Insert from the file at the proper position. */
3851 SET_PT_BOTH (temp, same_at_start);
3852 same_at_start_charpos
3853 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3854 same_at_start - BEGV_BYTE
3855 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3856 inserted_chars
3857 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3858 same_at_start + inserted - BEGV_BYTE
3859 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
3860 - same_at_start_charpos);
3861 /* This binding is to avoid ask-user-about-supersession-threat
3862 being called in insert_from_buffer (via in
3863 prepare_to_modify_buffer). */
3864 specbind (intern ("buffer-file-name"), Qnil);
3865 insert_from_buffer (XBUFFER (conversion_buffer),
3866 same_at_start_charpos, inserted_chars, 0);
3867 /* Set `inserted' to the number of inserted characters. */
3868 inserted = PT - temp;
3869 /* Set point before the inserted characters. */
3870 SET_PT_BOTH (temp, same_at_start);
3872 unbind_to (this_count, Qnil);
3874 goto handled;
3877 if (! not_regular)
3878 total = end_offset - beg_offset;
3879 else
3880 /* For a special file, all we can do is guess. */
3881 total = READ_BUF_SIZE;
3883 if (NILP (visit) && total > 0)
3885 #ifdef CLASH_DETECTION
3886 if (!NILP (BVAR (current_buffer, file_truename))
3887 /* Make binding buffer-file-name to nil effective. */
3888 && !NILP (BVAR (current_buffer, filename))
3889 && SAVE_MODIFF >= MODIFF)
3890 we_locked_file = 1;
3891 #endif /* CLASH_DETECTION */
3892 prepare_to_modify_buffer (GPT, GPT, NULL);
3895 move_gap (PT);
3896 if (GAP_SIZE < total)
3897 make_gap (total - GAP_SIZE);
3899 if (beg_offset != 0 || !NILP (replace))
3901 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3902 report_file_error ("Setting file position",
3903 Fcons (orig_filename, Qnil));
3906 /* In the following loop, HOW_MUCH contains the total bytes read so
3907 far for a regular file, and not changed for a special file. But,
3908 before exiting the loop, it is set to a negative value if I/O
3909 error occurs. */
3910 how_much = 0;
3912 /* Total bytes inserted. */
3913 inserted = 0;
3915 /* Here, we don't do code conversion in the loop. It is done by
3916 decode_coding_gap after all data are read into the buffer. */
3918 EMACS_INT gap_size = GAP_SIZE;
3920 while (how_much < total)
3922 /* try is reserved in some compilers (Microsoft C) */
3923 EMACS_INT trytry = min (total - how_much, READ_BUF_SIZE);
3924 EMACS_INT this;
3926 if (not_regular)
3928 Lisp_Object nbytes;
3930 /* Maybe make more room. */
3931 if (gap_size < trytry)
3933 make_gap (total - gap_size);
3934 gap_size = GAP_SIZE;
3937 /* Read from the file, capturing `quit'. When an
3938 error occurs, end the loop, and arrange for a quit
3939 to be signaled after decoding the text we read. */
3940 non_regular_fd = fd;
3941 non_regular_inserted = inserted;
3942 non_regular_nbytes = trytry;
3943 nbytes = internal_condition_case_1 (read_non_regular,
3944 Qnil, Qerror,
3945 read_non_regular_quit);
3946 if (NILP (nbytes))
3948 read_quit = 1;
3949 break;
3952 this = XINT (nbytes);
3954 else
3956 /* Allow quitting out of the actual I/O. We don't make text
3957 part of the buffer until all the reading is done, so a C-g
3958 here doesn't do any harm. */
3959 immediate_quit = 1;
3960 QUIT;
3961 this = emacs_read (fd,
3962 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3963 + inserted),
3964 trytry);
3965 immediate_quit = 0;
3968 if (this <= 0)
3970 how_much = this;
3971 break;
3974 gap_size -= this;
3976 /* For a regular file, where TOTAL is the real size,
3977 count HOW_MUCH to compare with it.
3978 For a special file, where TOTAL is just a buffer size,
3979 so don't bother counting in HOW_MUCH.
3980 (INSERTED is where we count the number of characters inserted.) */
3981 if (! not_regular)
3982 how_much += this;
3983 inserted += this;
3987 /* Now we have read all the file data into the gap.
3988 If it was empty, undo marking the buffer modified. */
3990 if (inserted == 0)
3992 #ifdef CLASH_DETECTION
3993 if (we_locked_file)
3994 unlock_file (BVAR (current_buffer, file_truename));
3995 #endif
3996 Vdeactivate_mark = old_Vdeactivate_mark;
3998 else
3999 Vdeactivate_mark = Qt;
4001 /* Make the text read part of the buffer. */
4002 GAP_SIZE -= inserted;
4003 GPT += inserted;
4004 GPT_BYTE += inserted;
4005 ZV += inserted;
4006 ZV_BYTE += inserted;
4007 Z += inserted;
4008 Z_BYTE += inserted;
4010 if (GAP_SIZE > 0)
4011 /* Put an anchor to ensure multi-byte form ends at gap. */
4012 *GPT_ADDR = 0;
4014 emacs_close (fd);
4016 /* Discard the unwind protect for closing the file. */
4017 specpdl_ptr--;
4019 if (how_much < 0)
4020 error ("IO error reading %s: %s",
4021 SDATA (orig_filename), emacs_strerror (errno));
4023 notfound:
4025 if (NILP (coding_system))
4027 /* The coding system is not yet decided. Decide it by an
4028 optimized method for handling `coding:' tag.
4030 Note that we can get here only if the buffer was empty
4031 before the insertion. */
4033 if (!NILP (Vcoding_system_for_read))
4034 coding_system = Vcoding_system_for_read;
4035 else
4037 /* Since we are sure that the current buffer was empty
4038 before the insertion, we can toggle
4039 enable-multibyte-characters directly here without taking
4040 care of marker adjustment. By this way, we can run Lisp
4041 program safely before decoding the inserted text. */
4042 Lisp_Object unwind_data;
4043 int count1 = SPECPDL_INDEX ();
4045 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4046 Fcons (BVAR (current_buffer, undo_list),
4047 Fcurrent_buffer ()));
4048 BVAR (current_buffer, enable_multibyte_characters) = Qnil;
4049 BVAR (current_buffer, undo_list) = Qt;
4050 record_unwind_protect (decide_coding_unwind, unwind_data);
4052 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4054 coding_system = call2 (Vset_auto_coding_function,
4055 filename, make_number (inserted));
4058 if (NILP (coding_system))
4060 /* If the coding system is not yet decided, check
4061 file-coding-system-alist. */
4062 Lisp_Object args[6];
4064 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4065 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4066 coding_system = Ffind_operation_coding_system (6, args);
4067 if (CONSP (coding_system))
4068 coding_system = XCAR (coding_system);
4070 unbind_to (count1, Qnil);
4071 inserted = Z_BYTE - BEG_BYTE;
4074 if (NILP (coding_system))
4075 coding_system = Qundecided;
4076 else
4077 CHECK_CODING_SYSTEM (coding_system);
4079 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4080 /* We must suppress all character code conversion except for
4081 end-of-line conversion. */
4082 coding_system = raw_text_coding_system (coding_system);
4083 setup_coding_system (coding_system, &coding);
4084 /* Ensure we set Vlast_coding_system_used. */
4085 set_coding_system = 1;
4088 if (!NILP (visit))
4090 /* When we visit a file by raw-text, we change the buffer to
4091 unibyte. */
4092 if (CODING_FOR_UNIBYTE (&coding)
4093 /* Can't do this if part of the buffer might be preserved. */
4094 && NILP (replace))
4095 /* Visiting a file with these coding system makes the buffer
4096 unibyte. */
4097 BVAR (current_buffer, enable_multibyte_characters) = Qnil;
4100 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4101 if (CODING_MAY_REQUIRE_DECODING (&coding)
4102 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4104 move_gap_both (PT, PT_BYTE);
4105 GAP_SIZE += inserted;
4106 ZV_BYTE -= inserted;
4107 Z_BYTE -= inserted;
4108 ZV -= inserted;
4109 Z -= inserted;
4110 decode_coding_gap (&coding, inserted, inserted);
4111 inserted = coding.produced_char;
4112 coding_system = CODING_ID_NAME (coding.id);
4114 else if (inserted > 0)
4115 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4116 inserted);
4118 /* Call after-change hooks for the inserted text, aside from the case
4119 of normal visiting (not with REPLACE), which is done in a new buffer
4120 "before" the buffer is changed. */
4121 if (inserted > 0 && total > 0
4122 && (NILP (visit) || !NILP (replace)))
4124 signal_after_change (PT, 0, inserted);
4125 update_compositions (PT, PT, CHECK_BORDER);
4128 /* Now INSERTED is measured in characters. */
4130 handled:
4132 if (deferred_remove_unwind_protect)
4133 /* If requested above, discard the unwind protect for closing the
4134 file. */
4135 specpdl_ptr--;
4137 if (!NILP (visit))
4139 if (!EQ (BVAR (current_buffer, undo_list), Qt) && !nochange)
4140 BVAR (current_buffer, undo_list) = Qnil;
4142 if (NILP (handler))
4144 current_buffer->modtime = st.st_mtime;
4145 current_buffer->modtime_size = st.st_size;
4146 BVAR (current_buffer, filename) = orig_filename;
4149 SAVE_MODIFF = MODIFF;
4150 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4151 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4152 #ifdef CLASH_DETECTION
4153 if (NILP (handler))
4155 if (!NILP (BVAR (current_buffer, file_truename)))
4156 unlock_file (BVAR (current_buffer, file_truename));
4157 unlock_file (filename);
4159 #endif /* CLASH_DETECTION */
4160 if (not_regular)
4161 xsignal2 (Qfile_error,
4162 build_string ("not a regular file"), orig_filename);
4165 if (set_coding_system)
4166 Vlast_coding_system_used = coding_system;
4168 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4170 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4171 visit);
4172 if (! NILP (insval))
4174 CHECK_NUMBER (insval);
4175 inserted = XFASTINT (insval);
4179 /* Decode file format. */
4180 if (inserted > 0)
4182 /* Don't run point motion or modification hooks when decoding. */
4183 int count1 = SPECPDL_INDEX ();
4184 EMACS_INT old_inserted = inserted;
4185 specbind (Qinhibit_point_motion_hooks, Qt);
4186 specbind (Qinhibit_modification_hooks, Qt);
4188 /* Save old undo list and don't record undo for decoding. */
4189 old_undo = BVAR (current_buffer, undo_list);
4190 BVAR (current_buffer, undo_list) = Qt;
4192 if (NILP (replace))
4194 insval = call3 (Qformat_decode,
4195 Qnil, make_number (inserted), visit);
4196 CHECK_NUMBER (insval);
4197 inserted = XFASTINT (insval);
4199 else
4201 /* If REPLACE is non-nil and we succeeded in not replacing the
4202 beginning or end of the buffer text with the file's contents,
4203 call format-decode with `point' positioned at the beginning
4204 of the buffer and `inserted' equaling the number of
4205 characters in the buffer. Otherwise, format-decode might
4206 fail to correctly analyze the beginning or end of the buffer.
4207 Hence we temporarily save `point' and `inserted' here and
4208 restore `point' iff format-decode did not insert or delete
4209 any text. Otherwise we leave `point' at point-min. */
4210 EMACS_INT opoint = PT;
4211 EMACS_INT opoint_byte = PT_BYTE;
4212 EMACS_INT oinserted = ZV - BEGV;
4213 int ochars_modiff = CHARS_MODIFF;
4215 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4216 insval = call3 (Qformat_decode,
4217 Qnil, make_number (oinserted), visit);
4218 CHECK_NUMBER (insval);
4219 if (ochars_modiff == CHARS_MODIFF)
4220 /* format_decode didn't modify buffer's characters => move
4221 point back to position before inserted text and leave
4222 value of inserted alone. */
4223 SET_PT_BOTH (opoint, opoint_byte);
4224 else
4225 /* format_decode modified buffer's characters => consider
4226 entire buffer changed and leave point at point-min. */
4227 inserted = XFASTINT (insval);
4230 /* For consistency with format-decode call these now iff inserted > 0
4231 (martin 2007-06-28). */
4232 p = Vafter_insert_file_functions;
4233 while (CONSP (p))
4235 if (NILP (replace))
4237 insval = call1 (XCAR (p), make_number (inserted));
4238 if (!NILP (insval))
4240 CHECK_NUMBER (insval);
4241 inserted = XFASTINT (insval);
4244 else
4246 /* For the rationale of this see the comment on
4247 format-decode above. */
4248 EMACS_INT opoint = PT;
4249 EMACS_INT opoint_byte = PT_BYTE;
4250 EMACS_INT oinserted = ZV - BEGV;
4251 int ochars_modiff = CHARS_MODIFF;
4253 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4254 insval = call1 (XCAR (p), make_number (oinserted));
4255 if (!NILP (insval))
4257 CHECK_NUMBER (insval);
4258 if (ochars_modiff == CHARS_MODIFF)
4259 /* after_insert_file_functions didn't modify
4260 buffer's characters => move point back to
4261 position before inserted text and leave value of
4262 inserted alone. */
4263 SET_PT_BOTH (opoint, opoint_byte);
4264 else
4265 /* after_insert_file_functions did modify buffer's
4266 characters => consider entire buffer changed and
4267 leave point at point-min. */
4268 inserted = XFASTINT (insval);
4272 QUIT;
4273 p = XCDR (p);
4276 if (NILP (visit))
4278 BVAR (current_buffer, undo_list) = old_undo;
4279 if (CONSP (old_undo) && inserted != old_inserted)
4281 /* Adjust the last undo record for the size change during
4282 the format conversion. */
4283 Lisp_Object tem = XCAR (old_undo);
4284 if (CONSP (tem) && INTEGERP (XCAR (tem))
4285 && INTEGERP (XCDR (tem))
4286 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4287 XSETCDR (tem, make_number (PT + inserted));
4290 else
4291 /* If undo_list was Qt before, keep it that way.
4292 Otherwise start with an empty undo_list. */
4293 BVAR (current_buffer, undo_list) = EQ (old_undo, Qt) ? Qt : Qnil;
4295 unbind_to (count1, Qnil);
4298 if (!NILP (visit)
4299 && current_buffer->modtime == -1)
4301 /* If visiting nonexistent file, return nil. */
4302 errno = save_errno;
4303 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4306 if (read_quit)
4307 Fsignal (Qquit, Qnil);
4309 /* ??? Retval needs to be dealt with in all cases consistently. */
4310 if (NILP (val))
4311 val = Fcons (orig_filename,
4312 Fcons (make_number (inserted),
4313 Qnil));
4315 RETURN_UNGCPRO (unbind_to (count, val));
4318 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4320 static Lisp_Object
4321 build_annotations_unwind (Lisp_Object arg)
4323 Vwrite_region_annotation_buffers = arg;
4324 return Qnil;
4327 /* Decide the coding-system to encode the data with. */
4329 static Lisp_Object
4330 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4331 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4332 struct coding_system *coding)
4334 Lisp_Object val;
4335 Lisp_Object eol_parent = Qnil;
4337 if (auto_saving
4338 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4339 BVAR (current_buffer, auto_save_file_name))))
4341 val = Qutf_8_emacs;
4342 eol_parent = Qunix;
4344 else if (!NILP (Vcoding_system_for_write))
4346 val = Vcoding_system_for_write;
4347 if (coding_system_require_warning
4348 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4349 /* Confirm that VAL can surely encode the current region. */
4350 val = call5 (Vselect_safe_coding_system_function,
4351 start, end, Fcons (Qt, Fcons (val, Qnil)),
4352 Qnil, filename);
4354 else
4356 /* If the variable `buffer-file-coding-system' is set locally,
4357 it means that the file was read with some kind of code
4358 conversion or the variable is explicitly set by users. We
4359 had better write it out with the same coding system even if
4360 `enable-multibyte-characters' is nil.
4362 If it is not set locally, we anyway have to convert EOL
4363 format if the default value of `buffer-file-coding-system'
4364 tells that it is not Unix-like (LF only) format. */
4365 int using_default_coding = 0;
4366 int force_raw_text = 0;
4368 val = BVAR (current_buffer, buffer_file_coding_system);
4369 if (NILP (val)
4370 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4372 val = Qnil;
4373 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4374 force_raw_text = 1;
4377 if (NILP (val))
4379 /* Check file-coding-system-alist. */
4380 Lisp_Object args[7], coding_systems;
4382 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4383 args[3] = filename; args[4] = append; args[5] = visit;
4384 args[6] = lockname;
4385 coding_systems = Ffind_operation_coding_system (7, args);
4386 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4387 val = XCDR (coding_systems);
4390 if (NILP (val))
4392 /* If we still have not decided a coding system, use the
4393 default value of buffer-file-coding-system. */
4394 val = BVAR (current_buffer, buffer_file_coding_system);
4395 using_default_coding = 1;
4398 if (! NILP (val) && ! force_raw_text)
4400 Lisp_Object spec, attrs;
4402 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4403 attrs = AREF (spec, 0);
4404 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4405 force_raw_text = 1;
4408 if (!force_raw_text
4409 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4410 /* Confirm that VAL can surely encode the current region. */
4411 val = call5 (Vselect_safe_coding_system_function,
4412 start, end, val, Qnil, filename);
4414 /* If the decided coding-system doesn't specify end-of-line
4415 format, we use that of
4416 `default-buffer-file-coding-system'. */
4417 if (! using_default_coding
4418 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4419 val = (coding_inherit_eol_type
4420 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4422 /* If we decide not to encode text, use `raw-text' or one of its
4423 subsidiaries. */
4424 if (force_raw_text)
4425 val = raw_text_coding_system (val);
4428 val = coding_inherit_eol_type (val, eol_parent);
4429 setup_coding_system (val, coding);
4431 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4432 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4433 return val;
4436 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4437 "r\nFWrite region to file: \ni\ni\ni\np",
4438 doc: /* Write current region into specified file.
4439 When called from a program, requires three arguments:
4440 START, END and FILENAME. START and END are normally buffer positions
4441 specifying the part of the buffer to write.
4442 If START is nil, that means to use the entire buffer contents.
4443 If START is a string, then output that string to the file
4444 instead of any buffer contents; END is ignored.
4446 Optional fourth argument APPEND if non-nil means
4447 append to existing file contents (if any). If it is an integer,
4448 seek to that offset in the file before writing.
4449 Optional fifth argument VISIT, if t or a string, means
4450 set the last-save-file-modtime of buffer to this file's modtime
4451 and mark buffer not modified.
4452 If VISIT is a string, it is a second file name;
4453 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4454 VISIT is also the file name to lock and unlock for clash detection.
4455 If VISIT is neither t nor nil nor a string,
4456 that means do not display the \"Wrote file\" message.
4457 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4458 use for locking and unlocking, overriding FILENAME and VISIT.
4459 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4460 for an existing file with the same name. If MUSTBENEW is `excl',
4461 that means to get an error if the file already exists; never overwrite.
4462 If MUSTBENEW is neither nil nor `excl', that means ask for
4463 confirmation before overwriting, but do go ahead and overwrite the file
4464 if the user confirms.
4466 This does code conversion according to the value of
4467 `coding-system-for-write', `buffer-file-coding-system', or
4468 `file-coding-system-alist', and sets the variable
4469 `last-coding-system-used' to the coding system actually used.
4471 This calls `write-region-annotate-functions' at the start, and
4472 `write-region-post-annotation-function' at the end. */)
4473 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append, Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4475 register int desc;
4476 int failure;
4477 int save_errno = 0;
4478 const char *fn;
4479 struct stat st;
4480 int count = SPECPDL_INDEX ();
4481 int count1;
4482 Lisp_Object handler;
4483 Lisp_Object visit_file;
4484 Lisp_Object annotations;
4485 Lisp_Object encoded_filename;
4486 int visiting = (EQ (visit, Qt) || STRINGP (visit));
4487 int quietly = !NILP (visit);
4488 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4489 struct buffer *given_buffer;
4490 struct coding_system coding;
4492 if (current_buffer->base_buffer && visiting)
4493 error ("Cannot do file visiting in an indirect buffer");
4495 if (!NILP (start) && !STRINGP (start))
4496 validate_region (&start, &end);
4498 visit_file = Qnil;
4499 GCPRO5 (start, filename, visit, visit_file, lockname);
4501 filename = Fexpand_file_name (filename, Qnil);
4503 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4504 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4506 if (STRINGP (visit))
4507 visit_file = Fexpand_file_name (visit, Qnil);
4508 else
4509 visit_file = filename;
4511 if (NILP (lockname))
4512 lockname = visit_file;
4514 annotations = Qnil;
4516 /* If the file name has special constructs in it,
4517 call the corresponding file handler. */
4518 handler = Ffind_file_name_handler (filename, Qwrite_region);
4519 /* If FILENAME has no handler, see if VISIT has one. */
4520 if (NILP (handler) && STRINGP (visit))
4521 handler = Ffind_file_name_handler (visit, Qwrite_region);
4523 if (!NILP (handler))
4525 Lisp_Object val;
4526 val = call6 (handler, Qwrite_region, start, end,
4527 filename, append, visit);
4529 if (visiting)
4531 SAVE_MODIFF = MODIFF;
4532 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4533 BVAR (current_buffer, filename) = visit_file;
4535 UNGCPRO;
4536 return val;
4539 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4541 /* Special kludge to simplify auto-saving. */
4542 if (NILP (start))
4544 /* Do it later, so write-region-annotate-function can work differently
4545 if we save "the buffer" vs "a region".
4546 This is useful in tar-mode. --Stef
4547 XSETFASTINT (start, BEG);
4548 XSETFASTINT (end, Z); */
4549 Fwiden ();
4552 record_unwind_protect (build_annotations_unwind,
4553 Vwrite_region_annotation_buffers);
4554 Vwrite_region_annotation_buffers = Fcons (Fcurrent_buffer (), Qnil);
4555 count1 = SPECPDL_INDEX ();
4557 given_buffer = current_buffer;
4559 if (!STRINGP (start))
4561 annotations = build_annotations (start, end);
4563 if (current_buffer != given_buffer)
4565 XSETFASTINT (start, BEGV);
4566 XSETFASTINT (end, ZV);
4570 if (NILP (start))
4572 XSETFASTINT (start, BEGV);
4573 XSETFASTINT (end, ZV);
4576 UNGCPRO;
4578 GCPRO5 (start, filename, annotations, visit_file, lockname);
4580 /* Decide the coding-system to encode the data with.
4581 We used to make this choice before calling build_annotations, but that
4582 leads to problems when a write-annotate-function takes care of
4583 unsavable chars (as was the case with X-Symbol). */
4584 Vlast_coding_system_used
4585 = choose_write_coding_system (start, end, filename,
4586 append, visit, lockname, &coding);
4588 #ifdef CLASH_DETECTION
4589 if (!auto_saving)
4590 lock_file (lockname);
4591 #endif /* CLASH_DETECTION */
4593 encoded_filename = ENCODE_FILE (filename);
4595 fn = SSDATA (encoded_filename);
4596 desc = -1;
4597 if (!NILP (append))
4598 #ifdef DOS_NT
4599 desc = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4600 #else /* not DOS_NT */
4601 desc = emacs_open (fn, O_WRONLY, 0);
4602 #endif /* not DOS_NT */
4604 if (desc < 0 && (NILP (append) || errno == ENOENT))
4605 #ifdef DOS_NT
4606 desc = emacs_open (fn,
4607 O_WRONLY | O_CREAT | O_BINARY
4608 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
4609 S_IREAD | S_IWRITE);
4610 #else /* not DOS_NT */
4611 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
4612 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
4613 auto_saving ? auto_save_mode_bits : 0666);
4614 #endif /* not DOS_NT */
4616 if (desc < 0)
4618 #ifdef CLASH_DETECTION
4619 save_errno = errno;
4620 if (!auto_saving) unlock_file (lockname);
4621 errno = save_errno;
4622 #endif /* CLASH_DETECTION */
4623 UNGCPRO;
4624 report_file_error ("Opening output file", Fcons (filename, Qnil));
4627 record_unwind_protect (close_file_unwind, make_number (desc));
4629 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
4631 off_t ret;
4633 if (NUMBERP (append))
4634 ret = emacs_lseek (desc, XINT (append), SEEK_CUR);
4635 else
4636 ret = lseek (desc, 0, SEEK_END);
4637 if (ret < 0)
4639 #ifdef CLASH_DETECTION
4640 save_errno = errno;
4641 if (!auto_saving) unlock_file (lockname);
4642 errno = save_errno;
4643 #endif /* CLASH_DETECTION */
4644 UNGCPRO;
4645 report_file_error ("Lseek error", Fcons (filename, Qnil));
4649 UNGCPRO;
4651 failure = 0;
4652 immediate_quit = 1;
4654 if (STRINGP (start))
4656 failure = 0 > a_write (desc, start, 0, SCHARS (start),
4657 &annotations, &coding);
4658 save_errno = errno;
4660 else if (XINT (start) != XINT (end))
4662 failure = 0 > a_write (desc, Qnil,
4663 XINT (start), XINT (end) - XINT (start),
4664 &annotations, &coding);
4665 save_errno = errno;
4667 else
4669 /* If file was empty, still need to write the annotations */
4670 coding.mode |= CODING_MODE_LAST_BLOCK;
4671 failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4672 save_errno = errno;
4675 if (CODING_REQUIRE_FLUSHING (&coding)
4676 && !(coding.mode & CODING_MODE_LAST_BLOCK)
4677 && ! failure)
4679 /* We have to flush out a data. */
4680 coding.mode |= CODING_MODE_LAST_BLOCK;
4681 failure = 0 > e_write (desc, Qnil, 1, 1, &coding);
4682 save_errno = errno;
4685 immediate_quit = 0;
4687 #ifdef HAVE_FSYNC
4688 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4689 Disk full in NFS may be reported here. */
4690 /* mib says that closing the file will try to write as fast as NFS can do
4691 it, and that means the fsync here is not crucial for autosave files. */
4692 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
4694 /* If fsync fails with EINTR, don't treat that as serious. Also
4695 ignore EINVAL which happens when fsync is not supported on this
4696 file. */
4697 if (errno != EINTR && errno != EINVAL)
4698 failure = 1, save_errno = errno;
4700 #endif
4702 /* NFS can report a write failure now. */
4703 if (emacs_close (desc) < 0)
4704 failure = 1, save_errno = errno;
4706 stat (fn, &st);
4708 /* Discard the unwind protect for close_file_unwind. */
4709 specpdl_ptr = specpdl + count1;
4711 /* Call write-region-post-annotation-function. */
4712 while (CONSP (Vwrite_region_annotation_buffers))
4714 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4715 if (!NILP (Fbuffer_live_p (buf)))
4717 Fset_buffer (buf);
4718 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4719 call0 (Vwrite_region_post_annotation_function);
4721 Vwrite_region_annotation_buffers
4722 = XCDR (Vwrite_region_annotation_buffers);
4725 unbind_to (count, Qnil);
4727 #ifdef CLASH_DETECTION
4728 if (!auto_saving)
4729 unlock_file (lockname);
4730 #endif /* CLASH_DETECTION */
4732 /* Do this before reporting IO error
4733 to avoid a "file has changed on disk" warning on
4734 next attempt to save. */
4735 if (visiting)
4737 current_buffer->modtime = st.st_mtime;
4738 current_buffer->modtime_size = st.st_size;
4741 if (failure)
4742 error ("IO error writing %s: %s", SDATA (filename),
4743 emacs_strerror (save_errno));
4745 if (visiting)
4747 SAVE_MODIFF = MODIFF;
4748 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4749 BVAR (current_buffer, filename) = visit_file;
4750 update_mode_lines++;
4752 else if (quietly)
4754 if (auto_saving
4755 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
4756 BVAR (current_buffer, auto_save_file_name))))
4757 SAVE_MODIFF = MODIFF;
4759 return Qnil;
4762 if (!auto_saving)
4763 message_with_string ((INTEGERP (append)
4764 ? "Updated %s"
4765 : ! NILP (append)
4766 ? "Added to %s"
4767 : "Wrote %s"),
4768 visit_file, 1);
4770 return Qnil;
4773 Lisp_Object merge (Lisp_Object, Lisp_Object, Lisp_Object);
4775 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4776 doc: /* Return t if (car A) is numerically less than (car B). */)
4777 (Lisp_Object a, Lisp_Object b)
4779 return Flss (Fcar (a), Fcar (b));
4782 /* Build the complete list of annotations appropriate for writing out
4783 the text between START and END, by calling all the functions in
4784 write-region-annotate-functions and merging the lists they return.
4785 If one of these functions switches to a different buffer, we assume
4786 that buffer contains altered text. Therefore, the caller must
4787 make sure to restore the current buffer in all cases,
4788 as save-excursion would do. */
4790 static Lisp_Object
4791 build_annotations (Lisp_Object start, Lisp_Object end)
4793 Lisp_Object annotations;
4794 Lisp_Object p, res;
4795 struct gcpro gcpro1, gcpro2;
4796 Lisp_Object original_buffer;
4797 int i, used_global = 0;
4799 XSETBUFFER (original_buffer, current_buffer);
4801 annotations = Qnil;
4802 p = Vwrite_region_annotate_functions;
4803 GCPRO2 (annotations, p);
4804 while (CONSP (p))
4806 struct buffer *given_buffer = current_buffer;
4807 if (EQ (Qt, XCAR (p)) && !used_global)
4808 { /* Use the global value of the hook. */
4809 Lisp_Object arg[2];
4810 used_global = 1;
4811 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
4812 arg[1] = XCDR (p);
4813 p = Fappend (2, arg);
4814 continue;
4816 Vwrite_region_annotations_so_far = annotations;
4817 res = call2 (XCAR (p), start, end);
4818 /* If the function makes a different buffer current,
4819 assume that means this buffer contains altered text to be output.
4820 Reset START and END from the buffer bounds
4821 and discard all previous annotations because they should have
4822 been dealt with by this function. */
4823 if (current_buffer != given_buffer)
4825 Vwrite_region_annotation_buffers
4826 = Fcons (Fcurrent_buffer (),
4827 Vwrite_region_annotation_buffers);
4828 XSETFASTINT (start, BEGV);
4829 XSETFASTINT (end, ZV);
4830 annotations = Qnil;
4832 Flength (res); /* Check basic validity of return value */
4833 annotations = merge (annotations, res, Qcar_less_than_car);
4834 p = XCDR (p);
4837 /* Now do the same for annotation functions implied by the file-format */
4838 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
4839 p = BVAR (current_buffer, auto_save_file_format);
4840 else
4841 p = BVAR (current_buffer, file_format);
4842 for (i = 0; CONSP (p); p = XCDR (p), ++i)
4844 struct buffer *given_buffer = current_buffer;
4846 Vwrite_region_annotations_so_far = annotations;
4848 /* Value is either a list of annotations or nil if the function
4849 has written annotations to a temporary buffer, which is now
4850 current. */
4851 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
4852 original_buffer, make_number (i));
4853 if (current_buffer != given_buffer)
4855 XSETFASTINT (start, BEGV);
4856 XSETFASTINT (end, ZV);
4857 annotations = Qnil;
4860 if (CONSP (res))
4861 annotations = merge (annotations, res, Qcar_less_than_car);
4864 UNGCPRO;
4865 return annotations;
4869 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
4870 If STRING is nil, POS is the character position in the current buffer.
4871 Intersperse with them the annotations from *ANNOT
4872 which fall within the range of POS to POS + NCHARS,
4873 each at its appropriate position.
4875 We modify *ANNOT by discarding elements as we use them up.
4877 The return value is negative in case of system call failure. */
4879 static int
4880 a_write (int desc, Lisp_Object string, EMACS_INT pos,
4881 register EMACS_INT nchars, Lisp_Object *annot,
4882 struct coding_system *coding)
4884 Lisp_Object tem;
4885 EMACS_INT nextpos;
4886 EMACS_INT lastpos = pos + nchars;
4888 while (NILP (*annot) || CONSP (*annot))
4890 tem = Fcar_safe (Fcar (*annot));
4891 nextpos = pos - 1;
4892 if (INTEGERP (tem))
4893 nextpos = XFASTINT (tem);
4895 /* If there are no more annotations in this range,
4896 output the rest of the range all at once. */
4897 if (! (nextpos >= pos && nextpos <= lastpos))
4898 return e_write (desc, string, pos, lastpos, coding);
4900 /* Output buffer text up to the next annotation's position. */
4901 if (nextpos > pos)
4903 if (0 > e_write (desc, string, pos, nextpos, coding))
4904 return -1;
4905 pos = nextpos;
4907 /* Output the annotation. */
4908 tem = Fcdr (Fcar (*annot));
4909 if (STRINGP (tem))
4911 if (0 > e_write (desc, tem, 0, SCHARS (tem), coding))
4912 return -1;
4914 *annot = Fcdr (*annot);
4916 return 0;
4920 /* Write text in the range START and END into descriptor DESC,
4921 encoding them with coding system CODING. If STRING is nil, START
4922 and END are character positions of the current buffer, else they
4923 are indexes to the string STRING. */
4925 static int
4926 e_write (int desc, Lisp_Object string, EMACS_INT start, EMACS_INT end,
4927 struct coding_system *coding)
4929 if (STRINGP (string))
4931 start = 0;
4932 end = SCHARS (string);
4935 /* We used to have a code for handling selective display here. But,
4936 now it is handled within encode_coding. */
4938 while (start < end)
4940 if (STRINGP (string))
4942 coding->src_multibyte = SCHARS (string) < SBYTES (string);
4943 if (CODING_REQUIRE_ENCODING (coding))
4945 encode_coding_object (coding, string,
4946 start, string_char_to_byte (string, start),
4947 end, string_char_to_byte (string, end), Qt);
4949 else
4951 coding->dst_object = string;
4952 coding->consumed_char = SCHARS (string);
4953 coding->produced = SBYTES (string);
4956 else
4958 EMACS_INT start_byte = CHAR_TO_BYTE (start);
4959 EMACS_INT end_byte = CHAR_TO_BYTE (end);
4961 coding->src_multibyte = (end - start) < (end_byte - start_byte);
4962 if (CODING_REQUIRE_ENCODING (coding))
4964 encode_coding_object (coding, Fcurrent_buffer (),
4965 start, start_byte, end, end_byte, Qt);
4967 else
4969 coding->dst_object = Qnil;
4970 coding->dst_pos_byte = start_byte;
4971 if (start >= GPT || end <= GPT)
4973 coding->consumed_char = end - start;
4974 coding->produced = end_byte - start_byte;
4976 else
4978 coding->consumed_char = GPT - start;
4979 coding->produced = GPT_BYTE - start_byte;
4984 if (coding->produced > 0)
4986 coding->produced -=
4987 emacs_write (desc,
4988 STRINGP (coding->dst_object)
4989 ? SSDATA (coding->dst_object)
4990 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte),
4991 coding->produced);
4993 if (coding->produced)
4994 return -1;
4996 start += coding->consumed_char;
4999 return 0;
5002 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5003 Sverify_visited_file_modtime, 0, 1, 0,
5004 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5005 This means that the file has not been changed since it was visited or saved.
5006 If BUF is omitted or nil, it defaults to the current buffer.
5007 See Info node `(elisp)Modification Time' for more details. */)
5008 (Lisp_Object buf)
5010 struct buffer *b;
5011 struct stat st;
5012 Lisp_Object handler;
5013 Lisp_Object filename;
5015 if (NILP (buf))
5016 b = current_buffer;
5017 else
5019 CHECK_BUFFER (buf);
5020 b = XBUFFER (buf);
5023 if (!STRINGP (BVAR (b, filename))) return Qt;
5024 if (b->modtime == 0) return Qt;
5026 /* If the file name has special constructs in it,
5027 call the corresponding file handler. */
5028 handler = Ffind_file_name_handler (BVAR (b, filename),
5029 Qverify_visited_file_modtime);
5030 if (!NILP (handler))
5031 return call2 (handler, Qverify_visited_file_modtime, buf);
5033 filename = ENCODE_FILE (BVAR (b, filename));
5035 if (stat (SSDATA (filename), &st) < 0)
5037 /* If the file doesn't exist now and didn't exist before,
5038 we say that it isn't modified, provided the error is a tame one. */
5039 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
5040 st.st_mtime = -1;
5041 else
5042 st.st_mtime = 0;
5044 if ((st.st_mtime == b->modtime
5045 /* If both are positive, accept them if they are off by one second. */
5046 || (st.st_mtime > 0 && b->modtime > 0
5047 && (st.st_mtime - 1 == b->modtime
5048 || st.st_mtime == b->modtime - 1)))
5049 && (st.st_size == b->modtime_size
5050 || b->modtime_size < 0))
5051 return Qt;
5052 return Qnil;
5055 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5056 Sclear_visited_file_modtime, 0, 0, 0,
5057 doc: /* Clear out records of last mod time of visited file.
5058 Next attempt to save will certainly not complain of a discrepancy. */)
5059 (void)
5061 current_buffer->modtime = 0;
5062 current_buffer->modtime_size = -1;
5063 return Qnil;
5066 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5067 Svisited_file_modtime, 0, 0, 0,
5068 doc: /* Return the current buffer's recorded visited file modification time.
5069 The value is a list of the form (HIGH LOW), like the time values that
5070 `file-attributes' returns. If the current buffer has no recorded file
5071 modification time, this function returns 0. If the visited file
5072 doesn't exist, HIGH will be -1.
5073 See Info node `(elisp)Modification Time' for more details. */)
5074 (void)
5076 if (! current_buffer->modtime)
5077 return make_number (0);
5078 return make_time (current_buffer->modtime);
5081 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5082 Sset_visited_file_modtime, 0, 1, 0,
5083 doc: /* Update buffer's recorded modification time from the visited file's time.
5084 Useful if the buffer was not read from the file normally
5085 or if the file itself has been changed for some known benign reason.
5086 An argument specifies the modification time value to use
5087 \(instead of that of the visited file), in the form of a list
5088 \(HIGH . LOW) or (HIGH LOW). */)
5089 (Lisp_Object time_list)
5091 if (!NILP (time_list))
5093 CONS_TO_INTEGER (time_list, time_t, current_buffer->modtime);
5094 current_buffer->modtime_size = -1;
5096 else
5098 register Lisp_Object filename;
5099 struct stat st;
5100 Lisp_Object handler;
5102 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5104 /* If the file name has special constructs in it,
5105 call the corresponding file handler. */
5106 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5107 if (!NILP (handler))
5108 /* The handler can find the file name the same way we did. */
5109 return call2 (handler, Qset_visited_file_modtime, Qnil);
5111 filename = ENCODE_FILE (filename);
5113 if (stat (SSDATA (filename), &st) >= 0)
5115 current_buffer->modtime = st.st_mtime;
5116 current_buffer->modtime_size = st.st_size;
5120 return Qnil;
5123 static Lisp_Object
5124 auto_save_error (Lisp_Object error_val)
5126 Lisp_Object args[3], msg;
5127 int i, nbytes;
5128 struct gcpro gcpro1;
5129 char *msgbuf;
5130 USE_SAFE_ALLOCA;
5132 auto_save_error_occurred = 1;
5134 ring_bell (XFRAME (selected_frame));
5136 args[0] = build_string ("Auto-saving %s: %s");
5137 args[1] = BVAR (current_buffer, name);
5138 args[2] = Ferror_message_string (error_val);
5139 msg = Fformat (3, args);
5140 GCPRO1 (msg);
5141 nbytes = SBYTES (msg);
5142 SAFE_ALLOCA (msgbuf, char *, nbytes);
5143 memcpy (msgbuf, SDATA (msg), nbytes);
5145 for (i = 0; i < 3; ++i)
5147 if (i == 0)
5148 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5149 else
5150 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5151 Fsleep_for (make_number (1), Qnil);
5154 SAFE_FREE ();
5155 UNGCPRO;
5156 return Qnil;
5159 static Lisp_Object
5160 auto_save_1 (void)
5162 struct stat st;
5163 Lisp_Object modes;
5165 auto_save_mode_bits = 0666;
5167 /* Get visited file's mode to become the auto save file's mode. */
5168 if (! NILP (BVAR (current_buffer, filename)))
5170 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5171 /* But make sure we can overwrite it later! */
5172 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5173 else if ((modes = Ffile_modes (BVAR (current_buffer, filename)),
5174 INTEGERP (modes)))
5175 /* Remote files don't cooperate with stat. */
5176 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5179 return
5180 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5181 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5182 Qnil, Qnil);
5185 static Lisp_Object
5186 do_auto_save_unwind (Lisp_Object arg) /* used as unwind-protect function */
5189 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5190 auto_saving = 0;
5191 if (stream != NULL)
5193 BLOCK_INPUT;
5194 fclose (stream);
5195 UNBLOCK_INPUT;
5197 return Qnil;
5200 static Lisp_Object
5201 do_auto_save_unwind_1 (Lisp_Object value) /* used as unwind-protect function */
5204 minibuffer_auto_raise = XINT (value);
5205 return Qnil;
5208 static Lisp_Object
5209 do_auto_save_make_dir (Lisp_Object dir)
5211 Lisp_Object result;
5213 auto_saving_dir_umask = 077;
5214 result = call2 (Qmake_directory, dir, Qt);
5215 auto_saving_dir_umask = 0;
5216 return result;
5219 static Lisp_Object
5220 do_auto_save_eh (Lisp_Object ignore)
5222 auto_saving_dir_umask = 0;
5223 return Qnil;
5226 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5227 doc: /* Auto-save all buffers that need it.
5228 This is all buffers that have auto-saving enabled
5229 and are changed since last auto-saved.
5230 Auto-saving writes the buffer into a file
5231 so that your editing is not lost if the system crashes.
5232 This file is not the file you visited; that changes only when you save.
5233 Normally we run the normal hook `auto-save-hook' before saving.
5235 A non-nil NO-MESSAGE argument means do not print any message if successful.
5236 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5237 (Lisp_Object no_message, Lisp_Object current_only)
5239 struct buffer *old = current_buffer, *b;
5240 Lisp_Object tail, buf, hook;
5241 int auto_saved = 0;
5242 int do_handled_files;
5243 Lisp_Object oquit;
5244 FILE *stream = NULL;
5245 int count = SPECPDL_INDEX ();
5246 int orig_minibuffer_auto_raise = minibuffer_auto_raise;
5247 int old_message_p = 0;
5248 struct gcpro gcpro1, gcpro2;
5250 if (max_specpdl_size < specpdl_size + 40)
5251 max_specpdl_size = specpdl_size + 40;
5253 if (minibuf_level)
5254 no_message = Qt;
5256 if (NILP (no_message))
5258 old_message_p = push_message ();
5259 record_unwind_protect (pop_message_unwind, Qnil);
5262 /* Ordinarily don't quit within this function,
5263 but don't make it impossible to quit (in case we get hung in I/O). */
5264 oquit = Vquit_flag;
5265 Vquit_flag = Qnil;
5267 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5268 point to non-strings reached from Vbuffer_alist. */
5270 hook = intern ("auto-save-hook");
5271 Frun_hooks (1, &hook);
5273 if (STRINGP (Vauto_save_list_file_name))
5275 Lisp_Object listfile;
5277 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5279 /* Don't try to create the directory when shutting down Emacs,
5280 because creating the directory might signal an error, and
5281 that would leave Emacs in a strange state. */
5282 if (!NILP (Vrun_hooks))
5284 Lisp_Object dir;
5285 dir = Qnil;
5286 GCPRO2 (dir, listfile);
5287 dir = Ffile_name_directory (listfile);
5288 if (NILP (Ffile_directory_p (dir)))
5289 internal_condition_case_1 (do_auto_save_make_dir,
5290 dir, Qt,
5291 do_auto_save_eh);
5292 UNGCPRO;
5295 stream = fopen (SSDATA (listfile), "w");
5298 record_unwind_protect (do_auto_save_unwind,
5299 make_save_value (stream, 0));
5300 record_unwind_protect (do_auto_save_unwind_1,
5301 make_number (minibuffer_auto_raise));
5302 minibuffer_auto_raise = 0;
5303 auto_saving = 1;
5304 auto_save_error_occurred = 0;
5306 /* On first pass, save all files that don't have handlers.
5307 On second pass, save all files that do have handlers.
5309 If Emacs is crashing, the handlers may tweak what is causing
5310 Emacs to crash in the first place, and it would be a shame if
5311 Emacs failed to autosave perfectly ordinary files because it
5312 couldn't handle some ange-ftp'd file. */
5314 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5315 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5317 buf = XCDR (XCAR (tail));
5318 b = XBUFFER (buf);
5320 /* Record all the buffers that have auto save mode
5321 in the special file that lists them. For each of these buffers,
5322 Record visited name (if any) and auto save name. */
5323 if (STRINGP (BVAR (b, auto_save_file_name))
5324 && stream != NULL && do_handled_files == 0)
5326 BLOCK_INPUT;
5327 if (!NILP (BVAR (b, filename)))
5329 fwrite (SDATA (BVAR (b, filename)), 1,
5330 SBYTES (BVAR (b, filename)), stream);
5332 putc ('\n', stream);
5333 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5334 SBYTES (BVAR (b, auto_save_file_name)), stream);
5335 putc ('\n', stream);
5336 UNBLOCK_INPUT;
5339 if (!NILP (current_only)
5340 && b != current_buffer)
5341 continue;
5343 /* Don't auto-save indirect buffers.
5344 The base buffer takes care of it. */
5345 if (b->base_buffer)
5346 continue;
5348 /* Check for auto save enabled
5349 and file changed since last auto save
5350 and file changed since last real save. */
5351 if (STRINGP (BVAR (b, auto_save_file_name))
5352 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5353 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5354 /* -1 means we've turned off autosaving for a while--see below. */
5355 && XINT (BVAR (b, save_length)) >= 0
5356 && (do_handled_files
5357 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5358 Qwrite_region))))
5360 EMACS_TIME before_time, after_time;
5362 EMACS_GET_TIME (before_time);
5364 /* If we had a failure, don't try again for 20 minutes. */
5365 if (b->auto_save_failure_time > 0
5366 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5367 continue;
5369 set_buffer_internal (b);
5370 if (NILP (Vauto_save_include_big_deletions)
5371 && (XFASTINT (BVAR (b, save_length)) * 10
5372 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5373 /* A short file is likely to change a large fraction;
5374 spare the user annoying messages. */
5375 && XFASTINT (BVAR (b, save_length)) > 5000
5376 /* These messages are frequent and annoying for `*mail*'. */
5377 && !EQ (BVAR (b, filename), Qnil)
5378 && NILP (no_message))
5380 /* It has shrunk too much; turn off auto-saving here. */
5381 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5382 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5383 BVAR (b, name), 1);
5384 minibuffer_auto_raise = 0;
5385 /* Turn off auto-saving until there's a real save,
5386 and prevent any more warnings. */
5387 XSETINT (BVAR (b, save_length), -1);
5388 Fsleep_for (make_number (1), Qnil);
5389 continue;
5391 if (!auto_saved && NILP (no_message))
5392 message1 ("Auto-saving...");
5393 internal_condition_case (auto_save_1, Qt, auto_save_error);
5394 auto_saved++;
5395 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5396 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5397 set_buffer_internal (old);
5399 EMACS_GET_TIME (after_time);
5401 /* If auto-save took more than 60 seconds,
5402 assume it was an NFS failure that got a timeout. */
5403 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5404 b->auto_save_failure_time = EMACS_SECS (after_time);
5408 /* Prevent another auto save till enough input events come in. */
5409 record_auto_save ();
5411 if (auto_saved && NILP (no_message))
5413 if (old_message_p)
5415 /* If we are going to restore an old message,
5416 give time to read ours. */
5417 sit_for (make_number (1), 0, 0);
5418 restore_message ();
5420 else if (!auto_save_error_occurred)
5421 /* Don't overwrite the error message if an error occurred.
5422 If we displayed a message and then restored a state
5423 with no message, leave a "done" message on the screen. */
5424 message1 ("Auto-saving...done");
5427 Vquit_flag = oquit;
5429 /* This restores the message-stack status. */
5430 unbind_to (count, Qnil);
5431 return Qnil;
5434 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5435 Sset_buffer_auto_saved, 0, 0, 0,
5436 doc: /* Mark current buffer as auto-saved with its current text.
5437 No auto-save file will be written until the buffer changes again. */)
5438 (void)
5440 /* FIXME: This should not be called in indirect buffers, since
5441 they're not autosaved. */
5442 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5443 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5444 current_buffer->auto_save_failure_time = 0;
5445 return Qnil;
5448 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5449 Sclear_buffer_auto_save_failure, 0, 0, 0,
5450 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5451 (void)
5453 current_buffer->auto_save_failure_time = 0;
5454 return Qnil;
5457 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5458 0, 0, 0,
5459 doc: /* Return t if current buffer has been auto-saved recently.
5460 More precisely, if it has been auto-saved since last read from or saved
5461 in the visited file. If the buffer has no visited file,
5462 then any auto-save counts as "recent". */)
5463 (void)
5465 /* FIXME: maybe we should return nil for indirect buffers since
5466 they're never autosaved. */
5467 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5470 /* Reading and completing file names */
5472 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5473 Snext_read_file_uses_dialog_p, 0, 0, 0,
5474 doc: /* Return t if a call to `read-file-name' will use a dialog.
5475 The return value is only relevant for a call to `read-file-name' that happens
5476 before any other event (mouse or keypress) is handled. */)
5477 (void)
5479 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK)
5480 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5481 && use_dialog_box
5482 && use_file_dialog
5483 && have_menus_p ())
5484 return Qt;
5485 #endif
5486 return Qnil;
5489 Lisp_Object
5490 Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
5492 struct gcpro gcpro1;
5493 Lisp_Object args[7];
5495 GCPRO1 (default_filename);
5496 args[0] = intern ("read-file-name");
5497 args[1] = prompt;
5498 args[2] = dir;
5499 args[3] = default_filename;
5500 args[4] = mustmatch;
5501 args[5] = initial;
5502 args[6] = predicate;
5503 RETURN_UNGCPRO (Ffuncall (7, args));
5507 void
5508 syms_of_fileio (void)
5510 DEFSYM (Qoperations, "operations");
5511 DEFSYM (Qexpand_file_name, "expand-file-name");
5512 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5513 DEFSYM (Qdirectory_file_name, "directory-file-name");
5514 DEFSYM (Qfile_name_directory, "file-name-directory");
5515 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5516 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5517 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5518 DEFSYM (Qcopy_file, "copy-file");
5519 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5520 DEFSYM (Qmake_directory, "make-directory");
5521 DEFSYM (Qdelete_directory_internal, "delete-directory-internal");
5522 DEFSYM (Qdelete_file, "delete-file");
5523 DEFSYM (Qrename_file, "rename-file");
5524 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5525 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5526 DEFSYM (Qfile_exists_p, "file-exists-p");
5527 DEFSYM (Qfile_executable_p, "file-executable-p");
5528 DEFSYM (Qfile_readable_p, "file-readable-p");
5529 DEFSYM (Qfile_writable_p, "file-writable-p");
5530 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5531 DEFSYM (Qaccess_file, "access-file");
5532 DEFSYM (Qfile_directory_p, "file-directory-p");
5533 DEFSYM (Qfile_regular_p, "file-regular-p");
5534 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5535 DEFSYM (Qfile_modes, "file-modes");
5536 DEFSYM (Qset_file_modes, "set-file-modes");
5537 DEFSYM (Qset_file_times, "set-file-times");
5538 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5539 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5540 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5541 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5542 DEFSYM (Qwrite_region, "write-region");
5543 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5544 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5545 DEFSYM (Qauto_save_coding, "auto-save-coding");
5547 DEFSYM (Qfile_name_history, "file-name-history");
5548 Fset (Qfile_name_history, Qnil);
5550 DEFSYM (Qfile_error, "file-error");
5551 DEFSYM (Qfile_already_exists, "file-already-exists");
5552 DEFSYM (Qfile_date_error, "file-date-error");
5553 DEFSYM (Qexcl, "excl");
5555 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5556 doc: /* *Coding system for encoding file names.
5557 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5558 Vfile_name_coding_system = Qnil;
5560 DEFVAR_LISP ("default-file-name-coding-system",
5561 Vdefault_file_name_coding_system,
5562 doc: /* Default coding system for encoding file names.
5563 This variable is used only when `file-name-coding-system' is nil.
5565 This variable is set/changed by the command `set-language-environment'.
5566 User should not set this variable manually,
5567 instead use `file-name-coding-system' to get a constant encoding
5568 of file names regardless of the current language environment. */);
5569 Vdefault_file_name_coding_system = Qnil;
5571 DEFSYM (Qformat_decode, "format-decode");
5572 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5573 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5574 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5576 Fput (Qfile_error, Qerror_conditions,
5577 Fpurecopy (list2 (Qfile_error, Qerror)));
5578 Fput (Qfile_error, Qerror_message,
5579 make_pure_c_string ("File error"));
5581 Fput (Qfile_already_exists, Qerror_conditions,
5582 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5583 Fput (Qfile_already_exists, Qerror_message,
5584 make_pure_c_string ("File already exists"));
5586 Fput (Qfile_date_error, Qerror_conditions,
5587 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5588 Fput (Qfile_date_error, Qerror_message,
5589 make_pure_c_string ("Cannot set file date"));
5591 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5592 doc: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
5593 If a file name matches REGEXP, then all I/O on that file is done by calling
5594 HANDLER.
5596 The first argument given to HANDLER is the name of the I/O primitive
5597 to be handled; the remaining arguments are the arguments that were
5598 passed to that primitive. For example, if you do
5599 (file-exists-p FILENAME)
5600 and FILENAME is handled by HANDLER, then HANDLER is called like this:
5601 (funcall HANDLER 'file-exists-p FILENAME)
5602 The function `find-file-name-handler' checks this list for a handler
5603 for its argument. */);
5604 Vfile_name_handler_alist = Qnil;
5606 DEFVAR_LISP ("set-auto-coding-function",
5607 Vset_auto_coding_function,
5608 doc: /* If non-nil, a function to call to decide a coding system of file.
5609 Two arguments are passed to this function: the file name
5610 and the length of a file contents following the point.
5611 This function should return a coding system to decode the file contents.
5612 It should check the file name against `auto-coding-alist'.
5613 If no coding system is decided, it should check a coding system
5614 specified in the heading lines with the format:
5615 -*- ... coding: CODING-SYSTEM; ... -*-
5616 or local variable spec of the tailing lines with `coding:' tag. */);
5617 Vset_auto_coding_function = Qnil;
5619 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5620 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5621 Each is passed one argument, the number of characters inserted,
5622 with point at the start of the inserted text. Each function
5623 should leave point the same, and return the new character count.
5624 If `insert-file-contents' is intercepted by a handler from
5625 `file-name-handler-alist', that handler is responsible for calling the
5626 functions in `after-insert-file-functions' if appropriate. */);
5627 Vafter_insert_file_functions = Qnil;
5629 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5630 doc: /* A list of functions to be called at the start of `write-region'.
5631 Each is passed two arguments, START and END as for `write-region'.
5632 These are usually two numbers but not always; see the documentation
5633 for `write-region'. The function should return a list of pairs
5634 of the form (POSITION . STRING), consisting of strings to be effectively
5635 inserted at the specified positions of the file being written (1 means to
5636 insert before the first byte written). The POSITIONs must be sorted into
5637 increasing order.
5639 If there are several annotation functions, the lists returned by these
5640 functions are merged destructively. As each annotation function runs,
5641 the variable `write-region-annotations-so-far' contains a list of all
5642 annotations returned by previous annotation functions.
5644 An annotation function can return with a different buffer current.
5645 Doing so removes the annotations returned by previous functions, and
5646 resets START and END to `point-min' and `point-max' of the new buffer.
5648 After `write-region' completes, Emacs calls the function stored in
5649 `write-region-post-annotation-function', once for each buffer that was
5650 current when building the annotations (i.e., at least once), with that
5651 buffer current. */);
5652 Vwrite_region_annotate_functions = Qnil;
5653 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5655 DEFVAR_LISP ("write-region-post-annotation-function",
5656 Vwrite_region_post_annotation_function,
5657 doc: /* Function to call after `write-region' completes.
5658 The function is called with no arguments. If one or more of the
5659 annotation functions in `write-region-annotate-functions' changed the
5660 current buffer, the function stored in this variable is called for
5661 each of those additional buffers as well, in addition to the original
5662 buffer. The relevant buffer is current during each function call. */);
5663 Vwrite_region_post_annotation_function = Qnil;
5664 staticpro (&Vwrite_region_annotation_buffers);
5666 DEFVAR_LISP ("write-region-annotations-so-far",
5667 Vwrite_region_annotations_so_far,
5668 doc: /* When an annotation function is called, this holds the previous annotations.
5669 These are the annotations made by other annotation functions
5670 that were already called. See also `write-region-annotate-functions'. */);
5671 Vwrite_region_annotations_so_far = Qnil;
5673 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5674 doc: /* A list of file name handlers that temporarily should not be used.
5675 This applies only to the operation `inhibit-file-name-operation'. */);
5676 Vinhibit_file_name_handlers = Qnil;
5678 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5679 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5680 Vinhibit_file_name_operation = Qnil;
5682 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
5683 doc: /* File name in which we write a list of all auto save file names.
5684 This variable is initialized automatically from `auto-save-list-file-prefix'
5685 shortly after Emacs reads your `.emacs' file, if you have not yet given it
5686 a non-nil value. */);
5687 Vauto_save_list_file_name = Qnil;
5689 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
5690 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5691 Normally auto-save files are written under other names. */);
5692 Vauto_save_visited_file_name = Qnil;
5694 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
5695 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5696 If nil, deleting a substantial portion of the text disables auto-save
5697 in the buffer; this is the default behavior, because the auto-save
5698 file is usually more useful if it contains the deleted text. */);
5699 Vauto_save_include_big_deletions = Qnil;
5701 #ifdef HAVE_FSYNC
5702 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
5703 doc: /* *Non-nil means don't call fsync in `write-region'.
5704 This variable affects calls to `write-region' as well as save commands.
5705 A non-nil value may result in data loss! */);
5706 write_region_inhibit_fsync = 0;
5707 #endif
5709 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
5710 doc: /* Specifies whether to use the system's trash can.
5711 When non-nil, certain file deletion commands use the function
5712 `move-file-to-trash' instead of deleting files outright.
5713 This includes interactive calls to `delete-file' and
5714 `delete-directory' and the Dired deletion commands. */);
5715 delete_by_moving_to_trash = 0;
5716 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
5718 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
5719 DEFSYM (Qcopy_directory, "copy-directory");
5720 DEFSYM (Qdelete_directory, "delete-directory");
5722 defsubr (&Sfind_file_name_handler);
5723 defsubr (&Sfile_name_directory);
5724 defsubr (&Sfile_name_nondirectory);
5725 defsubr (&Sunhandled_file_name_directory);
5726 defsubr (&Sfile_name_as_directory);
5727 defsubr (&Sdirectory_file_name);
5728 defsubr (&Smake_temp_name);
5729 defsubr (&Sexpand_file_name);
5730 defsubr (&Ssubstitute_in_file_name);
5731 defsubr (&Scopy_file);
5732 defsubr (&Smake_directory_internal);
5733 defsubr (&Sdelete_directory_internal);
5734 defsubr (&Sdelete_file);
5735 defsubr (&Srename_file);
5736 defsubr (&Sadd_name_to_file);
5737 defsubr (&Smake_symbolic_link);
5738 defsubr (&Sfile_name_absolute_p);
5739 defsubr (&Sfile_exists_p);
5740 defsubr (&Sfile_executable_p);
5741 defsubr (&Sfile_readable_p);
5742 defsubr (&Sfile_writable_p);
5743 defsubr (&Saccess_file);
5744 defsubr (&Sfile_symlink_p);
5745 defsubr (&Sfile_directory_p);
5746 defsubr (&Sfile_accessible_directory_p);
5747 defsubr (&Sfile_regular_p);
5748 defsubr (&Sfile_modes);
5749 defsubr (&Sset_file_modes);
5750 defsubr (&Sset_file_times);
5751 defsubr (&Sfile_selinux_context);
5752 defsubr (&Sset_file_selinux_context);
5753 defsubr (&Sset_default_file_modes);
5754 defsubr (&Sdefault_file_modes);
5755 defsubr (&Sfile_newer_than_file_p);
5756 defsubr (&Sinsert_file_contents);
5757 defsubr (&Swrite_region);
5758 defsubr (&Scar_less_than_car);
5759 defsubr (&Sverify_visited_file_modtime);
5760 defsubr (&Sclear_visited_file_modtime);
5761 defsubr (&Svisited_file_modtime);
5762 defsubr (&Sset_visited_file_modtime);
5763 defsubr (&Sdo_auto_save);
5764 defsubr (&Sset_buffer_auto_saved);
5765 defsubr (&Sclear_buffer_auto_save_failure);
5766 defsubr (&Srecent_auto_save_p);
5768 defsubr (&Snext_read_file_uses_dialog_p);
5770 #ifdef HAVE_SYNC
5771 defsubr (&Sunix_sync);
5772 #endif