Merge from mainline.
[emacs.git] / src / fileio.c
blobf4f90658d3a71347f2a511fecf2a12ad0b078470
1 /* File IO for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995, 1996,
3 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <limits.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <setjmp.h>
28 #include <unistd.h>
30 #if !defined (S_ISLNK) && defined (S_IFLNK)
31 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
32 #endif
34 #if !defined (S_ISFIFO) && defined (S_IFIFO)
35 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
36 #endif
38 #if !defined (S_ISREG) && defined (S_IFREG)
39 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
40 #endif
42 #ifdef HAVE_PWD_H
43 #include <pwd.h>
44 #endif
46 #include <ctype.h>
47 #include <errno.h>
49 #ifdef HAVE_LIBSELINUX
50 #include <selinux/selinux.h>
51 #include <selinux/context.h>
52 #endif
54 #include "lisp.h"
55 #include "intervals.h"
56 #include "buffer.h"
57 #include "character.h"
58 #include "coding.h"
59 #include "window.h"
60 #include "blockinput.h"
61 #include "frame.h"
62 #include "dispextern.h"
64 #ifdef WINDOWSNT
65 #define NOMINMAX 1
66 #include <windows.h>
67 #include <fcntl.h>
68 #endif /* not WINDOWSNT */
70 #ifdef MSDOS
71 #include "msdos.h"
72 #include <sys/param.h>
73 #include <fcntl.h>
74 #endif
76 #ifdef DOS_NT
77 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
78 redirector allows the six letters between 'Z' and 'a' as well. */
79 #ifdef MSDOS
80 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
81 #endif
82 #ifdef WINDOWSNT
83 #define IS_DRIVE(x) isalpha (x)
84 #endif
85 /* Need to lower-case the drive letter, or else expanded
86 filenames will sometimes compare inequal, because
87 `expand-file-name' doesn't always down-case the drive letter. */
88 #define DRIVE_LETTER(x) (tolower (x))
89 #endif
91 #include "systime.h"
93 #ifdef HPUX
94 #include <netio.h>
95 #endif
97 #include "commands.h"
99 #ifndef S_ISLNK
100 # define lstat stat
101 #endif
103 #ifndef FILE_SYSTEM_CASE
104 #define FILE_SYSTEM_CASE(filename) (filename)
105 #endif
107 /* Nonzero during writing of auto-save files */
108 int auto_saving;
110 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
111 a new file with the same mode as the original */
112 int auto_save_mode_bits;
114 /* Set by auto_save_1 if an error occurred during the last auto-save. */
115 int auto_save_error_occurred;
117 /* The symbol bound to coding-system-for-read when
118 insert-file-contents is called for recovering a file. This is not
119 an actual coding system name, but just an indicator to tell
120 insert-file-contents to use `emacs-mule' with a special flag for
121 auto saving and recovering a file. */
122 Lisp_Object Qauto_save_coding;
124 /* Coding system for file names, or nil if none. */
125 Lisp_Object Vfile_name_coding_system;
127 /* Coding system for file names used only when
128 Vfile_name_coding_system is nil. */
129 Lisp_Object Vdefault_file_name_coding_system;
131 /* Alist of elements (REGEXP . HANDLER) for file names
132 whose I/O is done with a special handler. */
133 Lisp_Object Vfile_name_handler_alist;
135 /* Property name of a file name handler,
136 which gives a list of operations it handles.. */
137 Lisp_Object Qoperations;
139 /* Lisp functions for translating file formats */
140 Lisp_Object Qformat_decode, Qformat_annotate_function;
142 /* Function to be called to decide a coding system of a reading file. */
143 Lisp_Object Vset_auto_coding_function;
145 /* Functions to be called to process text properties in inserted file. */
146 Lisp_Object Vafter_insert_file_functions;
148 /* Lisp function for setting buffer-file-coding-system and the
149 multibyteness of the current buffer after inserting a file. */
150 Lisp_Object Qafter_insert_file_set_coding;
152 /* Functions to be called to create text property annotations for file. */
153 Lisp_Object Vwrite_region_annotate_functions;
154 Lisp_Object Qwrite_region_annotate_functions;
155 Lisp_Object Vwrite_region_post_annotation_function;
157 /* During build_annotations, each time an annotation function is called,
158 this holds the annotations made by the previous functions. */
159 Lisp_Object Vwrite_region_annotations_so_far;
161 /* Each time an annotation function changes the buffer, the new buffer
162 is added here. */
163 Lisp_Object Vwrite_region_annotation_buffers;
165 /* File name in which we write a list of all our auto save files. */
166 Lisp_Object Vauto_save_list_file_name;
168 /* Whether or not files are auto-saved into themselves. */
169 Lisp_Object Vauto_save_visited_file_name;
171 /* Whether or not to continue auto-saving after a large deletion. */
172 Lisp_Object Vauto_save_include_big_deletions;
174 #ifdef HAVE_FSYNC
175 /* Nonzero means skip the call to fsync in Fwrite-region. */
176 int write_region_inhibit_fsync;
177 #endif
179 /* Non-zero means call move-file-to-trash in Fdelete_file or
180 Fdelete_directory_internal. */
181 int delete_by_moving_to_trash;
183 Lisp_Object Qdelete_by_moving_to_trash;
185 /* Lisp function for moving files to trash. */
186 Lisp_Object Qmove_file_to_trash;
188 /* Lisp function for recursively copying directories. */
189 Lisp_Object Qcopy_directory;
191 /* Lisp function for recursively deleting directories. */
192 Lisp_Object Qdelete_directory;
194 #ifdef WINDOWSNT
195 extern Lisp_Object Vw32_get_true_file_attributes;
196 #endif
198 /* These variables describe handlers that have "already" had a chance
199 to handle the current operation.
201 Vinhibit_file_name_handlers is a list of file name handlers.
202 Vinhibit_file_name_operation is the operation being handled.
203 If we try to handle that operation, we ignore those handlers. */
205 static Lisp_Object Vinhibit_file_name_handlers;
206 static Lisp_Object Vinhibit_file_name_operation;
208 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
209 Lisp_Object Qexcl;
210 Lisp_Object Qfile_name_history;
212 Lisp_Object Qcar_less_than_car;
214 static int a_write (int, Lisp_Object, int, int,
215 Lisp_Object *, struct coding_system *);
216 static int e_write (int, Lisp_Object, int, int, struct coding_system *);
219 void
220 report_file_error (const char *string, Lisp_Object data)
222 Lisp_Object errstring;
223 int errorno = errno;
224 char *str;
226 synchronize_system_messages_locale ();
227 str = strerror (errorno);
228 errstring = code_convert_string_norecord (make_unibyte_string (str,
229 strlen (str)),
230 Vlocale_coding_system, 0);
232 while (1)
233 switch (errorno)
235 case EEXIST:
236 xsignal (Qfile_already_exists, Fcons (errstring, data));
237 break;
238 default:
239 /* System error messages are capitalized. Downcase the initial
240 unless it is followed by a slash. (The slash case caters to
241 error messages that begin with "I/O" or, in German, "E/A".) */
242 if (STRING_MULTIBYTE (errstring)
243 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
245 int c;
247 str = (char *) SDATA (errstring);
248 c = STRING_CHAR (str);
249 Faset (errstring, make_number (0), make_number (DOWNCASE (c)));
252 xsignal (Qfile_error,
253 Fcons (build_string (string), Fcons (errstring, data)));
257 Lisp_Object
258 close_file_unwind (Lisp_Object fd)
260 emacs_close (XFASTINT (fd));
261 return Qnil;
264 /* Restore point, having saved it as a marker. */
266 Lisp_Object
267 restore_point_unwind (Lisp_Object location)
269 Fgoto_char (location);
270 Fset_marker (location, Qnil, Qnil);
271 return Qnil;
275 Lisp_Object Qexpand_file_name;
276 Lisp_Object Qsubstitute_in_file_name;
277 Lisp_Object Qdirectory_file_name;
278 Lisp_Object Qfile_name_directory;
279 Lisp_Object Qfile_name_nondirectory;
280 Lisp_Object Qunhandled_file_name_directory;
281 Lisp_Object Qfile_name_as_directory;
282 Lisp_Object Qcopy_file;
283 Lisp_Object Qmake_directory_internal;
284 Lisp_Object Qmake_directory;
285 Lisp_Object Qdelete_directory_internal;
286 Lisp_Object Qdelete_file;
287 Lisp_Object Qrename_file;
288 Lisp_Object Qadd_name_to_file;
289 Lisp_Object Qmake_symbolic_link;
290 Lisp_Object Qfile_exists_p;
291 Lisp_Object Qfile_executable_p;
292 Lisp_Object Qfile_readable_p;
293 Lisp_Object Qfile_writable_p;
294 Lisp_Object Qfile_symlink_p;
295 Lisp_Object Qaccess_file;
296 Lisp_Object Qfile_directory_p;
297 Lisp_Object Qfile_regular_p;
298 Lisp_Object Qfile_accessible_directory_p;
299 Lisp_Object Qfile_modes;
300 Lisp_Object Qset_file_modes;
301 Lisp_Object Qset_file_times;
302 Lisp_Object Qfile_selinux_context;
303 Lisp_Object Qset_file_selinux_context;
304 Lisp_Object Qfile_newer_than_file_p;
305 Lisp_Object Qinsert_file_contents;
306 Lisp_Object Qwrite_region;
307 Lisp_Object Qverify_visited_file_modtime;
308 Lisp_Object Qset_visited_file_modtime;
310 DEFUN ("find-file-name-handler", Ffind_file_name_handler, Sfind_file_name_handler, 2, 2, 0,
311 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
312 Otherwise, return nil.
313 A file name is handled if one of the regular expressions in
314 `file-name-handler-alist' matches it.
316 If OPERATION equals `inhibit-file-name-operation', then we ignore
317 any handlers that are members of `inhibit-file-name-handlers',
318 but we still do run any other handlers. This lets handlers
319 use the standard functions without calling themselves recursively. */)
320 (Lisp_Object filename, Lisp_Object operation)
322 /* This function must not munge the match data. */
323 Lisp_Object chain, inhibited_handlers, result;
324 int pos = -1;
326 result = Qnil;
327 CHECK_STRING (filename);
329 if (EQ (operation, Vinhibit_file_name_operation))
330 inhibited_handlers = Vinhibit_file_name_handlers;
331 else
332 inhibited_handlers = Qnil;
334 for (chain = Vfile_name_handler_alist; CONSP (chain);
335 chain = XCDR (chain))
337 Lisp_Object elt;
338 elt = XCAR (chain);
339 if (CONSP (elt))
341 Lisp_Object string = XCAR (elt);
342 int match_pos;
343 Lisp_Object handler = XCDR (elt);
344 Lisp_Object operations = Qnil;
346 if (SYMBOLP (handler))
347 operations = Fget (handler, Qoperations);
349 if (STRINGP (string)
350 && (match_pos = fast_string_match (string, filename)) > pos
351 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
353 Lisp_Object tem;
355 handler = XCDR (elt);
356 tem = Fmemq (handler, inhibited_handlers);
357 if (NILP (tem))
359 result = handler;
360 pos = match_pos;
365 QUIT;
367 return result;
370 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
371 1, 1, 0,
372 doc: /* Return the directory component in file name FILENAME.
373 Return nil if FILENAME does not include a directory.
374 Otherwise return a directory name.
375 Given a Unix syntax file name, returns a string ending in slash. */)
376 (Lisp_Object filename)
378 #ifndef DOS_NT
379 register const unsigned char *beg;
380 #else
381 register unsigned char *beg;
382 #endif
383 register const unsigned char *p;
384 Lisp_Object handler;
386 CHECK_STRING (filename);
388 /* If the file name has special constructs in it,
389 call the corresponding file handler. */
390 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
391 if (!NILP (handler))
392 return call2 (handler, Qfile_name_directory, filename);
394 filename = FILE_SYSTEM_CASE (filename);
395 #ifdef DOS_NT
396 beg = (unsigned char *) alloca (SBYTES (filename) + 1);
397 memcpy (beg, SDATA (filename), SBYTES (filename) + 1);
398 #else
399 beg = SDATA (filename);
400 #endif
401 p = beg + SBYTES (filename);
403 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
404 #ifdef DOS_NT
405 /* only recognise drive specifier at the beginning */
406 && !(p[-1] == ':'
407 /* handle the "/:d:foo" and "/:foo" cases correctly */
408 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
409 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
410 #endif
411 ) p--;
413 if (p == beg)
414 return Qnil;
415 #ifdef DOS_NT
416 /* Expansion of "c:" to drive and default directory. */
417 if (p[-1] == ':')
419 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
420 unsigned char *res = alloca (MAXPATHLEN + 1);
421 unsigned char *r = res;
423 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
425 strncpy (res, beg, 2);
426 beg += 2;
427 r += 2;
430 if (getdefdir (toupper (*beg) - 'A' + 1, r))
432 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
433 strcat (res, "/");
434 beg = res;
435 p = beg + strlen (beg);
438 dostounix_filename (beg);
439 #endif /* DOS_NT */
441 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
444 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
445 Sfile_name_nondirectory, 1, 1, 0,
446 doc: /* Return file name FILENAME sans its directory.
447 For example, in a Unix-syntax file name,
448 this is everything after the last slash,
449 or the entire name if it contains no slash. */)
450 (Lisp_Object filename)
452 register const unsigned char *beg, *p, *end;
453 Lisp_Object handler;
455 CHECK_STRING (filename);
457 /* If the file name has special constructs in it,
458 call the corresponding file handler. */
459 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
460 if (!NILP (handler))
461 return call2 (handler, Qfile_name_nondirectory, filename);
463 beg = SDATA (filename);
464 end = p = beg + SBYTES (filename);
466 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
467 #ifdef DOS_NT
468 /* only recognise drive specifier at beginning */
469 && !(p[-1] == ':'
470 /* handle the "/:d:foo" case correctly */
471 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
472 #endif
474 p--;
476 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
479 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
480 Sunhandled_file_name_directory, 1, 1, 0,
481 doc: /* Return a directly usable directory name somehow associated with FILENAME.
482 A `directly usable' directory name is one that may be used without the
483 intervention of any file handler.
484 If FILENAME is a directly usable file itself, return
485 \(file-name-directory FILENAME).
486 If FILENAME refers to a file which is not accessible from a local process,
487 then this should return nil.
488 The `call-process' and `start-process' functions use this function to
489 get a current directory to run processes in. */)
490 (Lisp_Object filename)
492 Lisp_Object handler;
494 /* If the file name has special constructs in it,
495 call the corresponding file handler. */
496 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
497 if (!NILP (handler))
498 return call2 (handler, Qunhandled_file_name_directory, filename);
500 return Ffile_name_directory (filename);
504 char *
505 file_name_as_directory (char *out, char *in)
507 int size = strlen (in) - 1;
509 strcpy (out, in);
511 if (size < 0)
513 out[0] = '.';
514 out[1] = '/';
515 out[2] = 0;
516 return out;
519 /* For Unix syntax, Append a slash if necessary */
520 if (!IS_DIRECTORY_SEP (out[size]))
522 out[size + 1] = DIRECTORY_SEP;
523 out[size + 2] = '\0';
525 #ifdef DOS_NT
526 dostounix_filename (out);
527 #endif
528 return out;
531 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
532 Sfile_name_as_directory, 1, 1, 0,
533 doc: /* Return a string representing the file name FILE interpreted as a directory.
534 This operation exists because a directory is also a file, but its name as
535 a directory is different from its name as a file.
536 The result can be used as the value of `default-directory'
537 or passed as second argument to `expand-file-name'.
538 For a Unix-syntax file name, just appends a slash. */)
539 (Lisp_Object file)
541 char *buf;
542 Lisp_Object handler;
544 CHECK_STRING (file);
545 if (NILP (file))
546 return Qnil;
548 /* If the file name has special constructs in it,
549 call the corresponding file handler. */
550 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
551 if (!NILP (handler))
552 return call2 (handler, Qfile_name_as_directory, file);
554 buf = (char *) alloca (SBYTES (file) + 10);
555 file_name_as_directory (buf, SDATA (file));
556 return make_specified_string (buf, -1, strlen (buf),
557 STRING_MULTIBYTE (file));
561 * Convert from directory name to filename.
562 * On UNIX, it's simple: just make sure there isn't a terminating /
564 * Value is nonzero if the string output is different from the input.
568 directory_file_name (char *src, char *dst)
570 long slen;
572 slen = strlen (src);
574 /* Process as Unix format: just remove any final slash.
575 But leave "/" unchanged; do not change it to "". */
576 strcpy (dst, src);
577 if (slen > 1
578 && IS_DIRECTORY_SEP (dst[slen - 1])
579 #ifdef DOS_NT
580 && !IS_ANY_SEP (dst[slen - 2])
581 #endif
583 dst[slen - 1] = 0;
584 #ifdef DOS_NT
585 dostounix_filename (dst);
586 #endif
587 return 1;
590 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
591 1, 1, 0,
592 doc: /* Returns the file name of the directory named DIRECTORY.
593 This is the name of the file that holds the data for the directory DIRECTORY.
594 This operation exists because a directory is also a file, but its name as
595 a directory is different from its name as a file.
596 In Unix-syntax, this function just removes the final slash. */)
597 (Lisp_Object directory)
599 char *buf;
600 Lisp_Object handler;
602 CHECK_STRING (directory);
604 if (NILP (directory))
605 return Qnil;
607 /* If the file name has special constructs in it,
608 call the corresponding file handler. */
609 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
610 if (!NILP (handler))
611 return call2 (handler, Qdirectory_file_name, directory);
613 buf = (char *) alloca (SBYTES (directory) + 20);
614 directory_file_name (SDATA (directory), buf);
615 return make_specified_string (buf, -1, strlen (buf),
616 STRING_MULTIBYTE (directory));
619 static const char make_temp_name_tbl[64] =
621 'A','B','C','D','E','F','G','H',
622 'I','J','K','L','M','N','O','P',
623 'Q','R','S','T','U','V','W','X',
624 'Y','Z','a','b','c','d','e','f',
625 'g','h','i','j','k','l','m','n',
626 'o','p','q','r','s','t','u','v',
627 'w','x','y','z','0','1','2','3',
628 '4','5','6','7','8','9','-','_'
631 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
633 /* Value is a temporary file name starting with PREFIX, a string.
635 The Emacs process number forms part of the result, so there is
636 no danger of generating a name being used by another process.
637 In addition, this function makes an attempt to choose a name
638 which has no existing file. To make this work, PREFIX should be
639 an absolute file name.
641 BASE64_P non-zero means add the pid as 3 characters in base64
642 encoding. In this case, 6 characters will be added to PREFIX to
643 form the file name. Otherwise, if Emacs is running on a system
644 with long file names, add the pid as a decimal number.
646 This function signals an error if no unique file name could be
647 generated. */
649 Lisp_Object
650 make_temp_name (Lisp_Object prefix, int base64_p)
652 Lisp_Object val;
653 int len, clen;
654 int pid;
655 unsigned char *p, *data;
656 char pidbuf[20];
657 int pidlen;
659 CHECK_STRING (prefix);
661 /* VAL is created by adding 6 characters to PREFIX. The first
662 three are the PID of this process, in base 64, and the second
663 three are incremented if the file already exists. This ensures
664 262144 unique file names per PID per PREFIX. */
666 pid = (int) getpid ();
668 if (base64_p)
670 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
671 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
672 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
673 pidlen = 3;
675 else
677 #ifdef HAVE_LONG_FILE_NAMES
678 sprintf (pidbuf, "%d", pid);
679 pidlen = strlen (pidbuf);
680 #else
681 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
682 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
683 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
684 pidlen = 3;
685 #endif
688 len = SBYTES (prefix); clen = SCHARS (prefix);
689 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
690 if (!STRING_MULTIBYTE (prefix))
691 STRING_SET_UNIBYTE (val);
692 data = SDATA (val);
693 memcpy (data, SDATA (prefix), len);
694 p = data + len;
696 memcpy (p, pidbuf, pidlen);
697 p += pidlen;
699 /* Here we try to minimize useless stat'ing when this function is
700 invoked many times successively with the same PREFIX. We achieve
701 this by initializing count to a random value, and incrementing it
702 afterwards.
704 We don't want make-temp-name to be called while dumping,
705 because then make_temp_name_count_initialized_p would get set
706 and then make_temp_name_count would not be set when Emacs starts. */
708 if (!make_temp_name_count_initialized_p)
710 make_temp_name_count = (unsigned) time (NULL);
711 make_temp_name_count_initialized_p = 1;
714 while (1)
716 struct stat ignored;
717 unsigned num = make_temp_name_count;
719 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
720 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
721 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
723 /* Poor man's congruential RN generator. Replace with
724 ++make_temp_name_count for debugging. */
725 make_temp_name_count += 25229;
726 make_temp_name_count %= 225307;
728 if (stat (data, &ignored) < 0)
730 /* We want to return only if errno is ENOENT. */
731 if (errno == ENOENT)
732 return val;
733 else
734 /* The error here is dubious, but there is little else we
735 can do. The alternatives are to return nil, which is
736 as bad as (and in many cases worse than) throwing the
737 error, or to ignore the error, which will likely result
738 in looping through 225307 stat's, which is not only
739 dog-slow, but also useless since it will fallback to
740 the errow below, anyway. */
741 report_file_error ("Cannot create temporary name for prefix",
742 Fcons (prefix, Qnil));
743 /* not reached */
747 error ("Cannot create temporary name for prefix `%s'",
748 SDATA (prefix));
749 return Qnil;
753 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
754 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
755 The Emacs process number forms part of the result,
756 so there is no danger of generating a name being used by another process.
758 In addition, this function makes an attempt to choose a name
759 which has no existing file. To make this work,
760 PREFIX should be an absolute file name.
762 There is a race condition between calling `make-temp-name' and creating the
763 file which opens all kinds of security holes. For that reason, you should
764 probably use `make-temp-file' instead, except in three circumstances:
766 * If you are creating the file in the user's home directory.
767 * If you are creating a directory rather than an ordinary file.
768 * If you are taking special precautions as `make-temp-file' does. */)
769 (Lisp_Object prefix)
771 return make_temp_name (prefix, 0);
776 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
777 doc: /* Convert filename NAME to absolute, and canonicalize it.
778 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
779 \(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
780 the current buffer's value of `default-directory' is used.
781 NAME should be a string that is a valid file name for the underlying
782 filesystem.
783 File name components that are `.' are removed, and
784 so are file name components followed by `..', along with the `..' itself;
785 note that these simplifications are done without checking the resulting
786 file names in the file system.
787 Multiple consecutive slashes are collapsed into a single slash,
788 except at the beginning of the file name when they are significant (e.g.,
789 UNC file names on MS-Windows.)
790 An initial `~/' expands to your home directory.
791 An initial `~USER/' expands to USER's home directory.
792 See also the function `substitute-in-file-name'.
794 For technical reasons, this function can return correct but
795 non-intuitive results for the root directory; for instance,
796 \(expand-file-name ".." "/") returns "/..". For this reason, use
797 \(directory-file-name (file-name-directory dirname)) to traverse a
798 filesystem tree, not (expand-file-name ".." dirname). */)
799 (Lisp_Object name, Lisp_Object default_directory)
801 /* These point to SDATA and need to be careful with string-relocation
802 during GC (via DECODE_FILE). */
803 unsigned char *nm, *newdir;
804 /* This should only point to alloca'd data. */
805 unsigned char *target;
807 int tlen;
808 struct passwd *pw;
809 #ifdef DOS_NT
810 int drive = 0;
811 int collapse_newdir = 1;
812 int is_escaped = 0;
813 #endif /* DOS_NT */
814 int length;
815 Lisp_Object handler, result;
816 int multibyte;
817 Lisp_Object hdir;
819 CHECK_STRING (name);
821 /* If the file name has special constructs in it,
822 call the corresponding file handler. */
823 handler = Ffind_file_name_handler (name, Qexpand_file_name);
824 if (!NILP (handler))
825 return call3 (handler, Qexpand_file_name, name, default_directory);
827 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
828 if (NILP (default_directory))
829 default_directory = current_buffer->directory;
830 if (! STRINGP (default_directory))
832 #ifdef DOS_NT
833 /* "/" is not considered a root directory on DOS_NT, so using "/"
834 here causes an infinite recursion in, e.g., the following:
836 (let (default-directory)
837 (expand-file-name "a"))
839 To avoid this, we set default_directory to the root of the
840 current drive. */
841 default_directory = build_string (emacs_root_dir ());
842 #else
843 default_directory = build_string ("/");
844 #endif
847 if (!NILP (default_directory))
849 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
850 if (!NILP (handler))
851 return call3 (handler, Qexpand_file_name, name, default_directory);
855 unsigned char *o = SDATA (default_directory);
857 /* Make sure DEFAULT_DIRECTORY is properly expanded.
858 It would be better to do this down below where we actually use
859 default_directory. Unfortunately, calling Fexpand_file_name recursively
860 could invoke GC, and the strings might be relocated. This would
861 be annoying because we have pointers into strings lying around
862 that would need adjusting, and people would add new pointers to
863 the code and forget to adjust them, resulting in intermittent bugs.
864 Putting this call here avoids all that crud.
866 The EQ test avoids infinite recursion. */
867 if (! NILP (default_directory) && !EQ (default_directory, name)
868 /* Save time in some common cases - as long as default_directory
869 is not relative, it can be canonicalized with name below (if it
870 is needed at all) without requiring it to be expanded now. */
871 #ifdef DOS_NT
872 /* Detect MSDOS file names with drive specifiers. */
873 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
874 && IS_DIRECTORY_SEP (o[2]))
875 #ifdef WINDOWSNT
876 /* Detect Windows file names in UNC format. */
877 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
878 #endif
879 #else /* not DOS_NT */
880 /* Detect Unix absolute file names (/... alone is not absolute on
881 DOS or Windows). */
882 && ! (IS_DIRECTORY_SEP (o[0]))
883 #endif /* not DOS_NT */
886 struct gcpro gcpro1;
888 GCPRO1 (name);
889 default_directory = Fexpand_file_name (default_directory, Qnil);
890 UNGCPRO;
893 name = FILE_SYSTEM_CASE (name);
894 multibyte = STRING_MULTIBYTE (name);
895 if (multibyte != STRING_MULTIBYTE (default_directory))
897 if (multibyte)
898 default_directory = string_to_multibyte (default_directory);
899 else
901 name = string_to_multibyte (name);
902 multibyte = 1;
906 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
907 nm = (unsigned char *) alloca (SBYTES (name) + 1);
908 memcpy (nm, SDATA (name), SBYTES (name) + 1);
910 #ifdef DOS_NT
911 /* Note if special escape prefix is present, but remove for now. */
912 if (nm[0] == '/' && nm[1] == ':')
914 is_escaped = 1;
915 nm += 2;
918 /* Find and remove drive specifier if present; this makes nm absolute
919 even if the rest of the name appears to be relative. Only look for
920 drive specifier at the beginning. */
921 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
923 drive = nm[0];
924 nm += 2;
927 #ifdef WINDOWSNT
928 /* If we see "c://somedir", we want to strip the first slash after the
929 colon when stripping the drive letter. Otherwise, this expands to
930 "//somedir". */
931 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
932 nm++;
934 /* Discard any previous drive specifier if nm is now in UNC format. */
935 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
937 drive = 0;
939 #endif /* WINDOWSNT */
940 #endif /* DOS_NT */
942 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
943 none are found, we can probably return right away. We will avoid
944 allocating a new string if name is already fully expanded. */
945 if (
946 IS_DIRECTORY_SEP (nm[0])
947 #ifdef MSDOS
948 && drive && !is_escaped
949 #endif
950 #ifdef WINDOWSNT
951 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
952 #endif
955 /* If it turns out that the filename we want to return is just a
956 suffix of FILENAME, we don't need to go through and edit
957 things; we just need to construct a new string using data
958 starting at the middle of FILENAME. If we set lose to a
959 non-zero value, that means we've discovered that we can't do
960 that cool trick. */
961 int lose = 0;
962 unsigned char *p = nm;
964 while (*p)
966 /* Since we know the name is absolute, we can assume that each
967 element starts with a "/". */
969 /* "." and ".." are hairy. */
970 if (IS_DIRECTORY_SEP (p[0])
971 && p[1] == '.'
972 && (IS_DIRECTORY_SEP (p[2])
973 || p[2] == 0
974 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
975 || p[3] == 0))))
976 lose = 1;
977 /* We want to replace multiple `/' in a row with a single
978 slash. */
979 else if (p > nm
980 && IS_DIRECTORY_SEP (p[0])
981 && IS_DIRECTORY_SEP (p[1]))
982 lose = 1;
983 p++;
985 if (!lose)
987 #ifdef DOS_NT
988 /* Make sure directories are all separated with /, but
989 avoid allocation of a new string when not required. */
990 dostounix_filename (nm);
991 #ifdef WINDOWSNT
992 if (IS_DIRECTORY_SEP (nm[1]))
994 if (strcmp (nm, SDATA (name)) != 0)
995 name = make_specified_string (nm, -1, strlen (nm), multibyte);
997 else
998 #endif
999 /* drive must be set, so this is okay */
1000 if (strcmp (nm - 2, SDATA (name)) != 0)
1002 char temp[] = " :";
1004 name = make_specified_string (nm, -1, p - nm, multibyte);
1005 temp[0] = DRIVE_LETTER (drive);
1006 name = concat2 (build_string (temp), name);
1008 return name;
1009 #else /* not DOS_NT */
1010 if (strcmp (nm, SDATA (name)) == 0)
1011 return name;
1012 return make_specified_string (nm, -1, strlen (nm), multibyte);
1013 #endif /* not DOS_NT */
1017 /* At this point, nm might or might not be an absolute file name. We
1018 need to expand ~ or ~user if present, otherwise prefix nm with
1019 default_directory if nm is not absolute, and finally collapse /./
1020 and /foo/../ sequences.
1022 We set newdir to be the appropriate prefix if one is needed:
1023 - the relevant user directory if nm starts with ~ or ~user
1024 - the specified drive's working dir (DOS/NT only) if nm does not
1025 start with /
1026 - the value of default_directory.
1028 Note that these prefixes are not guaranteed to be absolute (except
1029 for the working dir of a drive). Therefore, to ensure we always
1030 return an absolute name, if the final prefix is not absolute we
1031 append it to the current working directory. */
1033 newdir = 0;
1035 if (nm[0] == '~') /* prefix ~ */
1037 if (IS_DIRECTORY_SEP (nm[1])
1038 || nm[1] == 0) /* ~ by itself */
1040 Lisp_Object tem;
1042 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1043 newdir = (unsigned char *) "";
1044 nm++;
1045 /* egetenv may return a unibyte string, which will bite us since
1046 we expect the directory to be multibyte. */
1047 tem = build_string (newdir);
1048 if (!STRING_MULTIBYTE (tem))
1050 hdir = DECODE_FILE (tem);
1051 newdir = SDATA (hdir);
1053 #ifdef DOS_NT
1054 collapse_newdir = 0;
1055 #endif
1057 else /* ~user/filename */
1059 unsigned char *o, *p;
1060 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
1061 o = alloca (p - nm + 1);
1062 memcpy (o, nm, p - nm);
1063 o [p - nm] = 0;
1065 BLOCK_INPUT;
1066 pw = (struct passwd *) getpwnam (o + 1);
1067 UNBLOCK_INPUT;
1068 if (pw)
1070 newdir = (unsigned char *) pw -> pw_dir;
1071 nm = p;
1072 #ifdef DOS_NT
1073 collapse_newdir = 0;
1074 #endif
1077 /* If we don't find a user of that name, leave the name
1078 unchanged; don't move nm forward to p. */
1082 #ifdef DOS_NT
1083 /* On DOS and Windows, nm is absolute if a drive name was specified;
1084 use the drive's current directory as the prefix if needed. */
1085 if (!newdir && drive)
1087 /* Get default directory if needed to make nm absolute. */
1088 if (!IS_DIRECTORY_SEP (nm[0]))
1090 newdir = alloca (MAXPATHLEN + 1);
1091 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1092 newdir = NULL;
1094 if (!newdir)
1096 /* Either nm starts with /, or drive isn't mounted. */
1097 newdir = alloca (4);
1098 newdir[0] = DRIVE_LETTER (drive);
1099 newdir[1] = ':';
1100 newdir[2] = '/';
1101 newdir[3] = 0;
1104 #endif /* DOS_NT */
1106 /* Finally, if no prefix has been specified and nm is not absolute,
1107 then it must be expanded relative to default_directory. */
1109 if (1
1110 #ifndef DOS_NT
1111 /* /... alone is not absolute on DOS and Windows. */
1112 && !IS_DIRECTORY_SEP (nm[0])
1113 #endif
1114 #ifdef WINDOWSNT
1115 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1116 #endif
1117 && !newdir)
1119 newdir = SDATA (default_directory);
1120 #ifdef DOS_NT
1121 /* Note if special escape prefix is present, but remove for now. */
1122 if (newdir[0] == '/' && newdir[1] == ':')
1124 is_escaped = 1;
1125 newdir += 2;
1127 #endif
1130 #ifdef DOS_NT
1131 if (newdir)
1133 /* First ensure newdir is an absolute name. */
1134 if (
1135 /* Detect MSDOS file names with drive specifiers. */
1136 ! (IS_DRIVE (newdir[0])
1137 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1138 #ifdef WINDOWSNT
1139 /* Detect Windows file names in UNC format. */
1140 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1141 #endif
1144 /* Effectively, let newdir be (expand-file-name newdir cwd).
1145 Because of the admonition against calling expand-file-name
1146 when we have pointers into lisp strings, we accomplish this
1147 indirectly by prepending newdir to nm if necessary, and using
1148 cwd (or the wd of newdir's drive) as the new newdir. */
1150 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1152 drive = newdir[0];
1153 newdir += 2;
1155 if (!IS_DIRECTORY_SEP (nm[0]))
1157 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1158 file_name_as_directory (tmp, newdir);
1159 strcat (tmp, nm);
1160 nm = tmp;
1162 newdir = alloca (MAXPATHLEN + 1);
1163 if (drive)
1165 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1166 newdir = "/";
1168 else
1169 getwd (newdir);
1172 /* Strip off drive name from prefix, if present. */
1173 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1175 drive = newdir[0];
1176 newdir += 2;
1179 /* Keep only a prefix from newdir if nm starts with slash
1180 (//server/share for UNC, nothing otherwise). */
1181 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1183 #ifdef WINDOWSNT
1184 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1186 unsigned char *p;
1187 newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
1188 p = newdir + 2;
1189 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1190 p++;
1191 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1192 *p = 0;
1194 else
1195 #endif
1196 newdir = "";
1199 #endif /* DOS_NT */
1201 if (newdir)
1203 /* Get rid of any slash at the end of newdir, unless newdir is
1204 just / or // (an incomplete UNC name). */
1205 length = strlen (newdir);
1206 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1207 #ifdef WINDOWSNT
1208 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1209 #endif
1212 unsigned char *temp = (unsigned char *) alloca (length);
1213 memcpy (temp, newdir, length - 1);
1214 temp[length - 1] = 0;
1215 newdir = temp;
1217 tlen = length + 1;
1219 else
1220 tlen = 0;
1222 /* Now concatenate the directory and name to new space in the stack frame */
1223 tlen += strlen (nm) + 1;
1224 #ifdef DOS_NT
1225 /* Reserve space for drive specifier and escape prefix, since either
1226 or both may need to be inserted. (The Microsoft x86 compiler
1227 produces incorrect code if the following two lines are combined.) */
1228 target = (unsigned char *) alloca (tlen + 4);
1229 target += 4;
1230 #else /* not DOS_NT */
1231 target = (unsigned char *) alloca (tlen);
1232 #endif /* not DOS_NT */
1233 *target = 0;
1235 if (newdir)
1237 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1239 #ifdef DOS_NT
1240 /* If newdir is effectively "C:/", then the drive letter will have
1241 been stripped and newdir will be "/". Concatenating with an
1242 absolute directory in nm produces "//", which will then be
1243 incorrectly treated as a network share. Ignore newdir in
1244 this case (keeping the drive letter). */
1245 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1246 && newdir[1] == '\0'))
1247 #endif
1248 strcpy (target, newdir);
1250 else
1251 file_name_as_directory (target, newdir);
1254 strcat (target, nm);
1256 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1257 appear. */
1259 unsigned char *p = target;
1260 unsigned char *o = target;
1262 while (*p)
1264 if (!IS_DIRECTORY_SEP (*p))
1266 *o++ = *p++;
1268 else if (p[1] == '.'
1269 && (IS_DIRECTORY_SEP (p[2])
1270 || p[2] == 0))
1272 /* If "/." is the entire filename, keep the "/". Otherwise,
1273 just delete the whole "/.". */
1274 if (o == target && p[2] == '\0')
1275 *o++ = *p;
1276 p += 2;
1278 else if (p[1] == '.' && p[2] == '.'
1279 /* `/../' is the "superroot" on certain file systems.
1280 Turned off on DOS_NT systems because they have no
1281 "superroot" and because this causes us to produce
1282 file names like "d:/../foo" which fail file-related
1283 functions of the underlying OS. (To reproduce, try a
1284 long series of "../../" in default_directory, longer
1285 than the number of levels from the root.) */
1286 #ifndef DOS_NT
1287 && o != target
1288 #endif
1289 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1291 #ifdef WINDOWSNT
1292 unsigned char *prev_o = o;
1293 #endif
1294 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1296 #ifdef WINDOWSNT
1297 /* Don't go below server level in UNC filenames. */
1298 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1299 && IS_DIRECTORY_SEP (*target))
1300 o = prev_o;
1301 else
1302 #endif
1303 /* Keep initial / only if this is the whole name. */
1304 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1305 ++o;
1306 p += 3;
1308 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1309 /* Collapse multiple `/' in a row. */
1310 p++;
1311 else
1313 *o++ = *p++;
1317 #ifdef DOS_NT
1318 /* At last, set drive name. */
1319 #ifdef WINDOWSNT
1320 /* Except for network file name. */
1321 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1322 #endif /* WINDOWSNT */
1324 if (!drive) abort ();
1325 target -= 2;
1326 target[0] = DRIVE_LETTER (drive);
1327 target[1] = ':';
1329 /* Reinsert the escape prefix if required. */
1330 if (is_escaped)
1332 target -= 2;
1333 target[0] = '/';
1334 target[1] = ':';
1336 dostounix_filename (target);
1337 #endif /* DOS_NT */
1339 result = make_specified_string (target, -1, o - target, multibyte);
1342 /* Again look to see if the file name has special constructs in it
1343 and perhaps call the corresponding file handler. This is needed
1344 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1345 the ".." component gives us "/user@host:/bar/../baz" which needs
1346 to be expanded again. */
1347 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1348 if (!NILP (handler))
1349 return call3 (handler, Qexpand_file_name, result, default_directory);
1351 return result;
1354 #if 0
1355 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1356 This is the old version of expand-file-name, before it was thoroughly
1357 rewritten for Emacs 10.31. We leave this version here commented-out,
1358 because the code is very complex and likely to have subtle bugs. If
1359 bugs _are_ found, it might be of interest to look at the old code and
1360 see what did it do in the relevant situation.
1362 Don't remove this code: it's true that it will be accessible
1363 from the repository, but a few years from deletion, people will
1364 forget it is there. */
1366 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1367 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1368 "Convert FILENAME to absolute, and canonicalize it.\n\
1369 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1370 \(does not start with slash); if DEFAULT is nil or missing,\n\
1371 the current buffer's value of default-directory is used.\n\
1372 Filenames containing `.' or `..' as components are simplified;\n\
1373 initial `~/' expands to your home directory.\n\
1374 See also the function `substitute-in-file-name'.")
1375 (name, defalt)
1376 Lisp_Object name, defalt;
1378 unsigned char *nm;
1380 register unsigned char *newdir, *p, *o;
1381 int tlen;
1382 unsigned char *target;
1383 struct passwd *pw;
1384 int lose;
1386 CHECK_STRING (name);
1387 nm = SDATA (name);
1389 /* If nm is absolute, flush ...// and detect /./ and /../.
1390 If no /./ or /../ we can return right away. */
1391 if (nm[0] == '/')
1393 p = nm;
1394 lose = 0;
1395 while (*p)
1397 if (p[0] == '/' && p[1] == '/'
1399 nm = p + 1;
1400 if (p[0] == '/' && p[1] == '~')
1401 nm = p + 1, lose = 1;
1402 if (p[0] == '/' && p[1] == '.'
1403 && (p[2] == '/' || p[2] == 0
1404 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1405 lose = 1;
1406 p++;
1408 if (!lose)
1410 if (nm == SDATA (name))
1411 return name;
1412 return build_string (nm);
1416 /* Now determine directory to start with and put it in NEWDIR */
1418 newdir = 0;
1420 if (nm[0] == '~') /* prefix ~ */
1421 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1423 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1424 newdir = (unsigned char *) "";
1425 nm++;
1427 else /* ~user/filename */
1429 /* Get past ~ to user */
1430 unsigned char *user = nm + 1;
1431 /* Find end of name. */
1432 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1433 int len = ptr ? ptr - user : strlen (user);
1434 /* Copy the user name into temp storage. */
1435 o = (unsigned char *) alloca (len + 1);
1436 memcpy (o, user, len);
1437 o[len] = 0;
1439 /* Look up the user name. */
1440 BLOCK_INPUT;
1441 pw = (struct passwd *) getpwnam (o + 1);
1442 UNBLOCK_INPUT;
1443 if (!pw)
1444 error ("\"%s\" isn't a registered user", o + 1);
1446 newdir = (unsigned char *) pw->pw_dir;
1448 /* Discard the user name from NM. */
1449 nm += len;
1452 if (nm[0] != '/' && !newdir)
1454 if (NILP (defalt))
1455 defalt = current_buffer->directory;
1456 CHECK_STRING (defalt);
1457 newdir = SDATA (defalt);
1460 /* Now concatenate the directory and name to new space in the stack frame */
1462 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1463 target = (unsigned char *) alloca (tlen);
1464 *target = 0;
1466 if (newdir)
1468 if (nm[0] == 0 || nm[0] == '/')
1469 strcpy (target, newdir);
1470 else
1471 file_name_as_directory (target, newdir);
1474 strcat (target, nm);
1476 /* Now canonicalize by removing /. and /foo/.. if they appear */
1478 p = target;
1479 o = target;
1481 while (*p)
1483 if (*p != '/')
1485 *o++ = *p++;
1487 else if (!strncmp (p, "//", 2)
1490 o = target;
1491 p++;
1493 else if (p[0] == '/' && p[1] == '.'
1494 && (p[2] == '/' || p[2] == 0))
1495 p += 2;
1496 else if (!strncmp (p, "/..", 3)
1497 /* `/../' is the "superroot" on certain file systems. */
1498 && o != target
1499 && (p[3] == '/' || p[3] == 0))
1501 while (o != target && *--o != '/')
1503 if (o == target && *o == '/')
1504 ++o;
1505 p += 3;
1507 else
1509 *o++ = *p++;
1513 return make_string (target, o - target);
1515 #endif
1517 /* If /~ or // appears, discard everything through first slash. */
1518 static int
1519 file_name_absolute_p (const unsigned char *filename)
1521 return
1522 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1523 #ifdef DOS_NT
1524 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1525 && IS_DIRECTORY_SEP (filename[2]))
1526 #endif
1530 static unsigned char *
1531 search_embedded_absfilename (unsigned char *nm, unsigned char *endp)
1533 unsigned char *p, *s;
1535 for (p = nm + 1; p < endp; p++)
1537 if ((0
1538 || IS_DIRECTORY_SEP (p[-1]))
1539 && file_name_absolute_p (p)
1540 #if defined (WINDOWSNT) || defined(CYGWIN)
1541 /* // at start of file name is meaningful in Apollo,
1542 WindowsNT and Cygwin systems. */
1543 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1544 #endif /* not (WINDOWSNT || CYGWIN) */
1547 for (s = p; *s && (!IS_DIRECTORY_SEP (*s)); s++);
1548 if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
1550 unsigned char *o = alloca (s - p + 1);
1551 struct passwd *pw;
1552 memcpy (o, p, s - p);
1553 o [s - p] = 0;
1555 /* If we have ~user and `user' exists, discard
1556 everything up to ~. But if `user' does not exist, leave
1557 ~user alone, it might be a literal file name. */
1558 BLOCK_INPUT;
1559 pw = getpwnam (o + 1);
1560 UNBLOCK_INPUT;
1561 if (pw)
1562 return p;
1564 else
1565 return p;
1568 return NULL;
1571 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1572 Ssubstitute_in_file_name, 1, 1, 0,
1573 doc: /* Substitute environment variables referred to in FILENAME.
1574 `$FOO' where FOO is an environment variable name means to substitute
1575 the value of that variable. The variable name should be terminated
1576 with a character not a letter, digit or underscore; otherwise, enclose
1577 the entire variable name in braces.
1579 If `/~' appears, all of FILENAME through that `/' is discarded.
1580 If `//' appears, everything up to and including the first of
1581 those `/' is discarded. */)
1582 (Lisp_Object filename)
1584 unsigned char *nm;
1586 register unsigned char *s, *p, *o, *x, *endp;
1587 unsigned char *target = NULL;
1588 int total = 0;
1589 int substituted = 0;
1590 int multibyte;
1591 unsigned char *xnm;
1592 Lisp_Object handler;
1594 CHECK_STRING (filename);
1596 multibyte = STRING_MULTIBYTE (filename);
1598 /* If the file name has special constructs in it,
1599 call the corresponding file handler. */
1600 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1601 if (!NILP (handler))
1602 return call2 (handler, Qsubstitute_in_file_name, filename);
1604 /* Always work on a copy of the string, in case GC happens during
1605 decode of environment variables, causing the original Lisp_String
1606 data to be relocated. */
1607 nm = (unsigned char *) alloca (SBYTES (filename) + 1);
1608 memcpy (nm, SDATA (filename), SBYTES (filename) + 1);
1610 #ifdef DOS_NT
1611 dostounix_filename (nm);
1612 substituted = (strcmp (nm, SDATA (filename)) != 0);
1613 #endif
1614 endp = nm + SBYTES (filename);
1616 /* If /~ or // appears, discard everything through first slash. */
1617 p = search_embedded_absfilename (nm, endp);
1618 if (p)
1619 /* Start over with the new string, so we check the file-name-handler
1620 again. Important with filenames like "/home/foo//:/hello///there"
1621 which whould substitute to "/:/hello///there" rather than "/there". */
1622 return Fsubstitute_in_file_name
1623 (make_specified_string (p, -1, endp - p, multibyte));
1625 /* See if any variables are substituted into the string
1626 and find the total length of their values in `total' */
1628 for (p = nm; p != endp;)
1629 if (*p != '$')
1630 p++;
1631 else
1633 p++;
1634 if (p == endp)
1635 goto badsubst;
1636 else if (*p == '$')
1638 /* "$$" means a single "$" */
1639 p++;
1640 total -= 1;
1641 substituted = 1;
1642 continue;
1644 else if (*p == '{')
1646 o = ++p;
1647 while (p != endp && *p != '}') p++;
1648 if (*p != '}') goto missingclose;
1649 s = p;
1651 else
1653 o = p;
1654 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1655 s = p;
1658 /* Copy out the variable name */
1659 target = (unsigned char *) alloca (s - o + 1);
1660 strncpy (target, o, s - o);
1661 target[s - o] = 0;
1662 #ifdef DOS_NT
1663 strupr (target); /* $home == $HOME etc. */
1664 #endif /* DOS_NT */
1666 /* Get variable value */
1667 o = (unsigned char *) egetenv (target);
1668 if (o)
1670 /* Don't try to guess a maximum length - UTF8 can use up to
1671 four bytes per character. This code is unlikely to run
1672 in a situation that requires performance, so decoding the
1673 env variables twice should be acceptable. Note that
1674 decoding may cause a garbage collect. */
1675 Lisp_Object orig, decoded;
1676 orig = make_unibyte_string (o, strlen (o));
1677 decoded = DECODE_FILE (orig);
1678 total += SBYTES (decoded);
1679 substituted = 1;
1681 else if (*p == '}')
1682 goto badvar;
1685 if (!substituted)
1686 return filename;
1688 /* If substitution required, recopy the string and do it */
1689 /* Make space in stack frame for the new copy */
1690 xnm = (unsigned char *) alloca (SBYTES (filename) + total + 1);
1691 x = xnm;
1693 /* Copy the rest of the name through, replacing $ constructs with values */
1694 for (p = nm; *p;)
1695 if (*p != '$')
1696 *x++ = *p++;
1697 else
1699 p++;
1700 if (p == endp)
1701 goto badsubst;
1702 else if (*p == '$')
1704 *x++ = *p++;
1705 continue;
1707 else if (*p == '{')
1709 o = ++p;
1710 while (p != endp && *p != '}') p++;
1711 if (*p != '}') goto missingclose;
1712 s = p++;
1714 else
1716 o = p;
1717 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1718 s = p;
1721 /* Copy out the variable name */
1722 target = (unsigned char *) alloca (s - o + 1);
1723 strncpy (target, o, s - o);
1724 target[s - o] = 0;
1725 #ifdef DOS_NT
1726 strupr (target); /* $home == $HOME etc. */
1727 #endif /* DOS_NT */
1729 /* Get variable value */
1730 o = (unsigned char *) egetenv (target);
1731 if (!o)
1733 *x++ = '$';
1734 strcpy (x, target); x+= strlen (target);
1736 else
1738 Lisp_Object orig, decoded;
1739 int orig_length, decoded_length;
1740 orig_length = strlen (o);
1741 orig = make_unibyte_string (o, orig_length);
1742 decoded = DECODE_FILE (orig);
1743 decoded_length = SBYTES (decoded);
1744 strncpy (x, SDATA (decoded), decoded_length);
1745 x += decoded_length;
1747 /* If environment variable needed decoding, return value
1748 needs to be multibyte. */
1749 if (decoded_length != orig_length
1750 || strncmp (SDATA (decoded), o, orig_length))
1751 multibyte = 1;
1755 *x = 0;
1757 /* If /~ or // appears, discard everything through first slash. */
1758 while ((p = search_embedded_absfilename (xnm, x)))
1759 /* This time we do not start over because we've already expanded envvars
1760 and replaced $$ with $. Maybe we should start over as well, but we'd
1761 need to quote some $ to $$ first. */
1762 xnm = p;
1764 return make_specified_string (xnm, -1, x - xnm, multibyte);
1766 badsubst:
1767 error ("Bad format environment-variable substitution");
1768 missingclose:
1769 error ("Missing \"}\" in environment-variable substitution");
1770 badvar:
1771 error ("Substituting nonexistent environment variable \"%s\"", target);
1773 /* NOTREACHED */
1774 return Qnil;
1777 /* A slightly faster and more convenient way to get
1778 (directory-file-name (expand-file-name FOO)). */
1780 Lisp_Object
1781 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1783 register Lisp_Object absname;
1785 absname = Fexpand_file_name (filename, defdir);
1787 /* Remove final slash, if any (unless this is the root dir).
1788 stat behaves differently depending! */
1789 if (SCHARS (absname) > 1
1790 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1791 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
1792 /* We cannot take shortcuts; they might be wrong for magic file names. */
1793 absname = Fdirectory_file_name (absname);
1794 return absname;
1797 /* Signal an error if the file ABSNAME already exists.
1798 If INTERACTIVE is nonzero, ask the user whether to proceed,
1799 and bypass the error if the user says to go ahead.
1800 QUERYSTRING is a name for the action that is being considered
1801 to alter the file.
1803 *STATPTR is used to store the stat information if the file exists.
1804 If the file does not exist, STATPTR->st_mode is set to 0.
1805 If STATPTR is null, we don't store into it.
1807 If QUICK is nonzero, we ask for y or n, not yes or no. */
1809 void
1810 barf_or_query_if_file_exists (Lisp_Object absname, const unsigned char *querystring, int interactive, struct stat *statptr, int quick)
1812 register Lisp_Object tem, encoded_filename;
1813 struct stat statbuf;
1814 struct gcpro gcpro1;
1816 encoded_filename = ENCODE_FILE (absname);
1818 /* stat is a good way to tell whether the file exists,
1819 regardless of what access permissions it has. */
1820 if (lstat (SDATA (encoded_filename), &statbuf) >= 0)
1822 if (! interactive)
1823 xsignal2 (Qfile_already_exists,
1824 build_string ("File already exists"), absname);
1825 GCPRO1 (absname);
1826 tem = format2 ("File %s already exists; %s anyway? ",
1827 absname, build_string (querystring));
1828 if (quick)
1829 tem = call1 (intern ("y-or-n-p"), tem);
1830 else
1831 tem = do_yes_or_no_p (tem);
1832 UNGCPRO;
1833 if (NILP (tem))
1834 xsignal2 (Qfile_already_exists,
1835 build_string ("File already exists"), absname);
1836 if (statptr)
1837 *statptr = statbuf;
1839 else
1841 if (statptr)
1842 statptr->st_mode = 0;
1844 return;
1847 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1848 "fCopy file: \nGCopy %s to file: \np\nP",
1849 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1850 If NEWNAME names a directory, copy FILE there.
1852 This function always sets the file modes of the output file to match
1853 the input file.
1855 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1856 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1857 signal a `file-already-exists' error without overwriting. If
1858 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1859 about overwriting; this is what happens in interactive use with M-x.
1860 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1861 existing file.
1863 Fourth arg KEEP-TIME non-nil means give the output file the same
1864 last-modified time as the old one. (This works on only some systems.)
1866 A prefix arg makes KEEP-TIME non-nil.
1868 If PRESERVE-UID-GID is non-nil, we try to transfer the
1869 uid and gid of FILE to NEWNAME.
1871 If PRESERVE-SELINUX-CONTEXT is non-nil and SELinux is enabled
1872 on the system, we copy the SELinux context of FILE to NEWNAME. */)
1873 (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)
1875 int ifd, ofd, n;
1876 char buf[16 * 1024];
1877 struct stat st, out_st;
1878 Lisp_Object handler;
1879 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1880 int count = SPECPDL_INDEX ();
1881 int input_file_statable_p;
1882 Lisp_Object encoded_file, encoded_newname;
1883 #if HAVE_LIBSELINUX
1884 security_context_t con;
1885 int fail, conlength = 0;
1886 #endif
1888 encoded_file = encoded_newname = Qnil;
1889 GCPRO4 (file, newname, encoded_file, encoded_newname);
1890 CHECK_STRING (file);
1891 CHECK_STRING (newname);
1893 if (!NILP (Ffile_directory_p (newname)))
1894 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1895 else
1896 newname = Fexpand_file_name (newname, Qnil);
1898 file = Fexpand_file_name (file, Qnil);
1900 /* If the input file name has special constructs in it,
1901 call the corresponding file handler. */
1902 handler = Ffind_file_name_handler (file, Qcopy_file);
1903 /* Likewise for output file name. */
1904 if (NILP (handler))
1905 handler = Ffind_file_name_handler (newname, Qcopy_file);
1906 if (!NILP (handler))
1907 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1908 ok_if_already_exists, keep_time, preserve_uid_gid,
1909 preserve_selinux_context));
1911 encoded_file = ENCODE_FILE (file);
1912 encoded_newname = ENCODE_FILE (newname);
1914 if (NILP (ok_if_already_exists)
1915 || INTEGERP (ok_if_already_exists))
1916 barf_or_query_if_file_exists (newname, "copy to it",
1917 INTEGERP (ok_if_already_exists), &out_st, 0);
1918 else if (stat (SDATA (encoded_newname), &out_st) < 0)
1919 out_st.st_mode = 0;
1921 #ifdef WINDOWSNT
1922 if (!CopyFile (SDATA (encoded_file),
1923 SDATA (encoded_newname),
1924 FALSE))
1925 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
1926 /* CopyFile retains the timestamp by default. */
1927 else if (NILP (keep_time))
1929 EMACS_TIME now;
1930 DWORD attributes;
1931 char * filename;
1933 EMACS_GET_TIME (now);
1934 filename = SDATA (encoded_newname);
1936 /* Ensure file is writable while its modified time is set. */
1937 attributes = GetFileAttributes (filename);
1938 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
1939 if (set_file_times (filename, now, now))
1941 /* Restore original attributes. */
1942 SetFileAttributes (filename, attributes);
1943 xsignal2 (Qfile_date_error,
1944 build_string ("Cannot set file date"), newname);
1946 /* Restore original attributes. */
1947 SetFileAttributes (filename, attributes);
1949 #else /* not WINDOWSNT */
1950 immediate_quit = 1;
1951 ifd = emacs_open (SDATA (encoded_file), O_RDONLY, 0);
1952 immediate_quit = 0;
1954 if (ifd < 0)
1955 report_file_error ("Opening input file", Fcons (file, Qnil));
1957 record_unwind_protect (close_file_unwind, make_number (ifd));
1959 /* We can only copy regular files and symbolic links. Other files are not
1960 copyable by us. */
1961 input_file_statable_p = (fstat (ifd, &st) >= 0);
1963 #if HAVE_LIBSELINUX
1964 if (!NILP (preserve_selinux_context) && is_selinux_enabled ())
1966 conlength = fgetfilecon (ifd, &con);
1967 if (conlength == -1)
1968 report_file_error ("Doing fgetfilecon", Fcons (file, Qnil));
1970 #endif
1972 if (out_st.st_mode != 0
1973 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1975 errno = 0;
1976 report_file_error ("Input and output files are the same",
1977 Fcons (file, Fcons (newname, Qnil)));
1980 #if defined (S_ISREG) && defined (S_ISLNK)
1981 if (input_file_statable_p)
1983 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
1985 #if defined (EISDIR)
1986 /* Get a better looking error message. */
1987 errno = EISDIR;
1988 #endif /* EISDIR */
1989 report_file_error ("Non-regular file", Fcons (file, Qnil));
1992 #endif /* S_ISREG && S_ISLNK */
1994 #ifdef MSDOS
1995 /* System's default file type was set to binary by _fmode in emacs.c. */
1996 ofd = emacs_open (SDATA (encoded_newname),
1997 O_WRONLY | O_TRUNC | O_CREAT
1998 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
1999 S_IREAD | S_IWRITE);
2000 #else /* not MSDOS */
2001 ofd = emacs_open (SDATA (encoded_newname),
2002 O_WRONLY | O_TRUNC | O_CREAT
2003 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2004 0666);
2005 #endif /* not MSDOS */
2006 if (ofd < 0)
2007 report_file_error ("Opening output file", Fcons (newname, Qnil));
2009 record_unwind_protect (close_file_unwind, make_number (ofd));
2011 immediate_quit = 1;
2012 QUIT;
2013 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2014 if (emacs_write (ofd, buf, n) != n)
2015 report_file_error ("I/O error", Fcons (newname, Qnil));
2016 immediate_quit = 0;
2018 #ifndef MSDOS
2019 /* Preserve the original file modes, and if requested, also its
2020 owner and group. */
2021 if (input_file_statable_p)
2023 if (! NILP (preserve_uid_gid))
2024 fchown (ofd, st.st_uid, st.st_gid);
2025 fchmod (ofd, st.st_mode & 07777);
2027 #endif /* not MSDOS */
2029 #if HAVE_LIBSELINUX
2030 if (conlength > 0)
2032 /* Set the modified context back to the file. */
2033 fail = fsetfilecon (ofd, con);
2034 if (fail)
2035 report_file_error ("Doing fsetfilecon", Fcons (newname, Qnil));
2037 freecon (con);
2039 #endif
2041 /* Closing the output clobbers the file times on some systems. */
2042 if (emacs_close (ofd) < 0)
2043 report_file_error ("I/O error", Fcons (newname, Qnil));
2045 if (input_file_statable_p)
2047 if (!NILP (keep_time))
2049 EMACS_TIME atime, mtime;
2050 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2051 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2052 if (set_file_times (SDATA (encoded_newname),
2053 atime, mtime))
2054 xsignal2 (Qfile_date_error,
2055 build_string ("Cannot set file date"), newname);
2059 emacs_close (ifd);
2061 #ifdef MSDOS
2062 if (input_file_statable_p)
2064 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2065 and if it can't, it tells so. Otherwise, under MSDOS we usually
2066 get only the READ bit, which will make the copied file read-only,
2067 so it's better not to chmod at all. */
2068 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2069 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2071 #endif /* MSDOS */
2072 #endif /* not WINDOWSNT */
2074 /* Discard the unwind protects. */
2075 specpdl_ptr = specpdl + count;
2077 UNGCPRO;
2078 return Qnil;
2081 DEFUN ("make-directory-internal", Fmake_directory_internal,
2082 Smake_directory_internal, 1, 1, 0,
2083 doc: /* Create a new directory named DIRECTORY. */)
2084 (Lisp_Object directory)
2086 const unsigned char *dir;
2087 Lisp_Object handler;
2088 Lisp_Object encoded_dir;
2090 CHECK_STRING (directory);
2091 directory = Fexpand_file_name (directory, Qnil);
2093 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2094 if (!NILP (handler))
2095 return call2 (handler, Qmake_directory_internal, directory);
2097 encoded_dir = ENCODE_FILE (directory);
2099 dir = SDATA (encoded_dir);
2101 #ifdef WINDOWSNT
2102 if (mkdir (dir) != 0)
2103 #else
2104 if (mkdir (dir, 0777) != 0)
2105 #endif
2106 report_file_error ("Creating directory", list1 (directory));
2108 return Qnil;
2111 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2112 Sdelete_directory_internal, 1, 1, 0,
2113 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2114 (Lisp_Object directory)
2116 const unsigned char *dir;
2117 Lisp_Object handler;
2118 Lisp_Object encoded_dir;
2120 CHECK_STRING (directory);
2121 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2122 encoded_dir = ENCODE_FILE (directory);
2123 dir = SDATA (encoded_dir);
2125 if (rmdir (dir) != 0)
2126 report_file_error ("Removing directory", list1 (directory));
2128 return Qnil;
2131 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2132 "(list (read-file-name \
2133 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2134 \"Move file to trash: \" \"Delete file: \") \
2135 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2136 (null current-prefix-arg))",
2137 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2138 If file has multiple names, it continues to exist with the other names.
2139 TRASH non-nil means to trash the file instead of deleting, provided
2140 `delete-by-moving-to-trash' is non-nil.
2142 When called interactively, TRASH is t if no prefix argument is given.
2143 With a prefix argument, TRASH is nil. */)
2144 (Lisp_Object filename, Lisp_Object trash)
2146 Lisp_Object handler;
2147 Lisp_Object encoded_file;
2148 struct gcpro gcpro1;
2150 GCPRO1 (filename);
2151 if (!NILP (Ffile_directory_p (filename))
2152 && NILP (Ffile_symlink_p (filename)))
2153 xsignal2 (Qfile_error,
2154 build_string ("Removing old name: is a directory"),
2155 filename);
2156 UNGCPRO;
2157 filename = Fexpand_file_name (filename, Qnil);
2159 handler = Ffind_file_name_handler (filename, Qdelete_file);
2160 if (!NILP (handler))
2161 return call3 (handler, Qdelete_file, filename, trash);
2163 if (delete_by_moving_to_trash && !NILP (trash))
2164 return call1 (Qmove_file_to_trash, filename);
2166 encoded_file = ENCODE_FILE (filename);
2168 if (0 > unlink (SDATA (encoded_file)))
2169 report_file_error ("Removing old name", list1 (filename));
2170 return Qnil;
2173 static Lisp_Object
2174 internal_delete_file_1 (Lisp_Object ignore)
2176 return Qt;
2179 /* Delete file FILENAME, returning 1 if successful and 0 if failed.
2180 This ignores `delete-by-moving-to-trash'. */
2183 internal_delete_file (Lisp_Object filename)
2185 Lisp_Object tem;
2187 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2188 Qt, internal_delete_file_1);
2189 return NILP (tem);
2192 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2193 "fRename file: \nGRename %s to file: \np",
2194 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2195 If file has names other than FILE, it continues to have those names.
2196 Signals a `file-already-exists' error if a file NEWNAME already exists
2197 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2198 A number as third arg means request confirmation if NEWNAME already exists.
2199 This is what happens in interactive use with M-x. */)
2200 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2202 Lisp_Object handler;
2203 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2204 Lisp_Object encoded_file, encoded_newname, symlink_target;
2206 symlink_target = encoded_file = encoded_newname = Qnil;
2207 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2208 CHECK_STRING (file);
2209 CHECK_STRING (newname);
2210 file = Fexpand_file_name (file, Qnil);
2212 if ((!NILP (Ffile_directory_p (newname)))
2213 #ifdef DOS_NT
2214 /* If the file names are identical but for the case,
2215 don't attempt to move directory to itself. */
2216 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2217 #endif
2220 Lisp_Object fname = NILP (Ffile_directory_p (file))
2221 ? file : Fdirectory_file_name (file);
2222 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2224 else
2225 newname = Fexpand_file_name (newname, Qnil);
2227 /* If the file name has special constructs in it,
2228 call the corresponding file handler. */
2229 handler = Ffind_file_name_handler (file, Qrename_file);
2230 if (NILP (handler))
2231 handler = Ffind_file_name_handler (newname, Qrename_file);
2232 if (!NILP (handler))
2233 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2234 file, newname, ok_if_already_exists));
2236 encoded_file = ENCODE_FILE (file);
2237 encoded_newname = ENCODE_FILE (newname);
2239 #ifdef DOS_NT
2240 /* If the file names are identical but for the case, don't ask for
2241 confirmation: they simply want to change the letter-case of the
2242 file name. */
2243 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2244 #endif
2245 if (NILP (ok_if_already_exists)
2246 || INTEGERP (ok_if_already_exists))
2247 barf_or_query_if_file_exists (newname, "rename to it",
2248 INTEGERP (ok_if_already_exists), 0, 0);
2249 if (0 > rename (SDATA (encoded_file), SDATA (encoded_newname)))
2251 if (errno == EXDEV)
2253 int count;
2254 #ifdef S_IFLNK
2255 symlink_target = Ffile_symlink_p (file);
2256 if (! NILP (symlink_target))
2257 Fmake_symbolic_link (symlink_target, newname,
2258 NILP (ok_if_already_exists) ? Qnil : Qt);
2259 else
2260 #endif
2261 if (!NILP (Ffile_directory_p (file)))
2262 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2263 else
2264 /* We have already prompted if it was an integer, so don't
2265 have copy-file prompt again. */
2266 Fcopy_file (file, newname,
2267 NILP (ok_if_already_exists) ? Qnil : Qt,
2268 Qt, Qt, Qt);
2270 count = SPECPDL_INDEX ();
2271 specbind (Qdelete_by_moving_to_trash, Qnil);
2273 if (!NILP (Ffile_directory_p (file))
2274 #ifdef S_IFLNK
2275 && NILP (symlink_target)
2276 #endif
2278 call2 (Qdelete_directory, file, Qt);
2279 else
2280 Fdelete_file (file, Qnil);
2281 unbind_to (count, Qnil);
2283 else
2284 report_file_error ("Renaming", list2 (file, newname));
2286 UNGCPRO;
2287 return Qnil;
2290 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2291 "fAdd name to file: \nGName to add to %s: \np",
2292 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2293 Signals a `file-already-exists' error if a file NEWNAME already exists
2294 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2295 A number as third arg means request confirmation if NEWNAME already exists.
2296 This is what happens in interactive use with M-x. */)
2297 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2299 Lisp_Object handler;
2300 Lisp_Object encoded_file, encoded_newname;
2301 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2303 GCPRO4 (file, newname, encoded_file, encoded_newname);
2304 encoded_file = encoded_newname = Qnil;
2305 CHECK_STRING (file);
2306 CHECK_STRING (newname);
2307 file = Fexpand_file_name (file, Qnil);
2309 if (!NILP (Ffile_directory_p (newname)))
2310 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2311 else
2312 newname = Fexpand_file_name (newname, Qnil);
2314 /* If the file name has special constructs in it,
2315 call the corresponding file handler. */
2316 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2317 if (!NILP (handler))
2318 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2319 newname, ok_if_already_exists));
2321 /* If the new name has special constructs in it,
2322 call the corresponding file handler. */
2323 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2324 if (!NILP (handler))
2325 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2326 newname, ok_if_already_exists));
2328 encoded_file = ENCODE_FILE (file);
2329 encoded_newname = ENCODE_FILE (newname);
2331 if (NILP (ok_if_already_exists)
2332 || INTEGERP (ok_if_already_exists))
2333 barf_or_query_if_file_exists (newname, "make it a new name",
2334 INTEGERP (ok_if_already_exists), 0, 0);
2336 unlink (SDATA (newname));
2337 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname)))
2338 report_file_error ("Adding new name", list2 (file, newname));
2340 UNGCPRO;
2341 return Qnil;
2344 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2345 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2346 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2347 Both args must be strings.
2348 Signals a `file-already-exists' error if a file LINKNAME already exists
2349 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2350 A number as third arg means request confirmation if LINKNAME already exists.
2351 This happens for interactive use with M-x. */)
2352 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2354 Lisp_Object handler;
2355 Lisp_Object encoded_filename, encoded_linkname;
2356 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2358 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2359 encoded_filename = encoded_linkname = Qnil;
2360 CHECK_STRING (filename);
2361 CHECK_STRING (linkname);
2362 /* If the link target has a ~, we must expand it to get
2363 a truly valid file name. Otherwise, do not expand;
2364 we want to permit links to relative file names. */
2365 if (SREF (filename, 0) == '~')
2366 filename = Fexpand_file_name (filename, Qnil);
2368 if (!NILP (Ffile_directory_p (linkname)))
2369 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2370 else
2371 linkname = Fexpand_file_name (linkname, Qnil);
2373 /* If the file name has special constructs in it,
2374 call the corresponding file handler. */
2375 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2376 if (!NILP (handler))
2377 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2378 linkname, ok_if_already_exists));
2380 /* If the new link name has special constructs in it,
2381 call the corresponding file handler. */
2382 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2383 if (!NILP (handler))
2384 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2385 linkname, ok_if_already_exists));
2387 #ifdef S_IFLNK
2388 encoded_filename = ENCODE_FILE (filename);
2389 encoded_linkname = ENCODE_FILE (linkname);
2391 if (NILP (ok_if_already_exists)
2392 || INTEGERP (ok_if_already_exists))
2393 barf_or_query_if_file_exists (linkname, "make it a link",
2394 INTEGERP (ok_if_already_exists), 0, 0);
2395 if (0 > symlink (SDATA (encoded_filename),
2396 SDATA (encoded_linkname)))
2398 /* If we didn't complain already, silently delete existing file. */
2399 if (errno == EEXIST)
2401 unlink (SDATA (encoded_linkname));
2402 if (0 <= symlink (SDATA (encoded_filename),
2403 SDATA (encoded_linkname)))
2405 UNGCPRO;
2406 return Qnil;
2410 report_file_error ("Making symbolic link", list2 (filename, linkname));
2412 UNGCPRO;
2413 return Qnil;
2415 #else
2416 UNGCPRO;
2417 xsignal1 (Qfile_error, build_string ("Symbolic links are not supported"));
2419 #endif /* S_IFLNK */
2423 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2424 1, 1, 0,
2425 doc: /* Return t if file FILENAME specifies an absolute file name.
2426 On Unix, this is a name starting with a `/' or a `~'. */)
2427 (Lisp_Object filename)
2429 CHECK_STRING (filename);
2430 return file_name_absolute_p (SDATA (filename)) ? Qt : Qnil;
2433 /* Return nonzero if file FILENAME exists and can be executed. */
2435 static int
2436 check_executable (char *filename)
2438 #ifdef DOS_NT
2439 int len = strlen (filename);
2440 char *suffix;
2441 struct stat st;
2442 if (stat (filename, &st) < 0)
2443 return 0;
2444 return ((st.st_mode & S_IEXEC) != 0);
2445 #else /* not DOS_NT */
2446 #ifdef HAVE_EUIDACCESS
2447 return (euidaccess (filename, 1) >= 0);
2448 #else
2449 /* Access isn't quite right because it uses the real uid
2450 and we really want to test with the effective uid.
2451 But Unix doesn't give us a right way to do it. */
2452 return (access (filename, 1) >= 0);
2453 #endif
2454 #endif /* not DOS_NT */
2457 /* Return nonzero if file FILENAME exists and can be written. */
2459 static int
2460 check_writable (const char *filename)
2462 #ifdef MSDOS
2463 struct stat st;
2464 if (stat (filename, &st) < 0)
2465 return 0;
2466 return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
2467 #else /* not MSDOS */
2468 #ifdef HAVE_EUIDACCESS
2469 return (euidaccess (filename, 2) >= 0);
2470 #else
2471 /* Access isn't quite right because it uses the real uid
2472 and we really want to test with the effective uid.
2473 But Unix doesn't give us a right way to do it.
2474 Opening with O_WRONLY could work for an ordinary file,
2475 but would lose for directories. */
2476 return (access (filename, 2) >= 0);
2477 #endif
2478 #endif /* not MSDOS */
2481 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2482 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2483 See also `file-readable-p' and `file-attributes'.
2484 This returns nil for a symlink to a nonexistent file.
2485 Use `file-symlink-p' to test for such links. */)
2486 (Lisp_Object filename)
2488 Lisp_Object absname;
2489 Lisp_Object handler;
2490 struct stat statbuf;
2492 CHECK_STRING (filename);
2493 absname = Fexpand_file_name (filename, Qnil);
2495 /* If the file name has special constructs in it,
2496 call the corresponding file handler. */
2497 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2498 if (!NILP (handler))
2499 return call2 (handler, Qfile_exists_p, absname);
2501 absname = ENCODE_FILE (absname);
2503 return (stat (SDATA (absname), &statbuf) >= 0) ? Qt : Qnil;
2506 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2507 doc: /* Return t if FILENAME can be executed by you.
2508 For a directory, this means you can access files in that directory. */)
2509 (Lisp_Object filename)
2511 Lisp_Object absname;
2512 Lisp_Object handler;
2514 CHECK_STRING (filename);
2515 absname = Fexpand_file_name (filename, Qnil);
2517 /* If the file name has special constructs in it,
2518 call the corresponding file handler. */
2519 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2520 if (!NILP (handler))
2521 return call2 (handler, Qfile_executable_p, absname);
2523 absname = ENCODE_FILE (absname);
2525 return (check_executable (SDATA (absname)) ? Qt : Qnil);
2528 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2529 doc: /* Return t if file FILENAME exists and you can read it.
2530 See also `file-exists-p' and `file-attributes'. */)
2531 (Lisp_Object filename)
2533 Lisp_Object absname;
2534 Lisp_Object handler;
2535 int desc;
2536 int flags;
2537 struct stat statbuf;
2539 CHECK_STRING (filename);
2540 absname = Fexpand_file_name (filename, Qnil);
2542 /* If the file name has special constructs in it,
2543 call the corresponding file handler. */
2544 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2545 if (!NILP (handler))
2546 return call2 (handler, Qfile_readable_p, absname);
2548 absname = ENCODE_FILE (absname);
2550 #if defined(DOS_NT) || defined(macintosh)
2551 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2552 directories. */
2553 if (access (SDATA (absname), 0) == 0)
2554 return Qt;
2555 return Qnil;
2556 #else /* not DOS_NT and not macintosh */
2557 flags = O_RDONLY;
2558 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
2559 /* Opening a fifo without O_NONBLOCK can wait.
2560 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2561 except in the case of a fifo, on a system which handles it. */
2562 desc = stat (SDATA (absname), &statbuf);
2563 if (desc < 0)
2564 return Qnil;
2565 if (S_ISFIFO (statbuf.st_mode))
2566 flags |= O_NONBLOCK;
2567 #endif
2568 desc = emacs_open (SDATA (absname), flags, 0);
2569 if (desc < 0)
2570 return Qnil;
2571 emacs_close (desc);
2572 return Qt;
2573 #endif /* not DOS_NT and not macintosh */
2576 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2577 on the RT/PC. */
2578 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2579 doc: /* Return t if file FILENAME can be written or created by you. */)
2580 (Lisp_Object filename)
2582 Lisp_Object absname, dir, encoded;
2583 Lisp_Object handler;
2584 struct stat statbuf;
2586 CHECK_STRING (filename);
2587 absname = Fexpand_file_name (filename, Qnil);
2589 /* If the file name has special constructs in it,
2590 call the corresponding file handler. */
2591 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2592 if (!NILP (handler))
2593 return call2 (handler, Qfile_writable_p, absname);
2595 encoded = ENCODE_FILE (absname);
2596 if (stat (SDATA (encoded), &statbuf) >= 0)
2597 return (check_writable (SDATA (encoded))
2598 ? Qt : Qnil);
2600 dir = Ffile_name_directory (absname);
2601 #ifdef MSDOS
2602 if (!NILP (dir))
2603 dir = Fdirectory_file_name (dir);
2604 #endif /* MSDOS */
2606 dir = ENCODE_FILE (dir);
2607 #ifdef WINDOWSNT
2608 /* The read-only attribute of the parent directory doesn't affect
2609 whether a file or directory can be created within it. Some day we
2610 should check ACLs though, which do affect this. */
2611 if (stat (SDATA (dir), &statbuf) < 0)
2612 return Qnil;
2613 return (statbuf.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2614 #else
2615 return (check_writable (!NILP (dir) ? (char *) SDATA (dir) : "")
2616 ? Qt : Qnil);
2617 #endif
2620 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2621 doc: /* Access file FILENAME, and get an error if that does not work.
2622 The second argument STRING is used in the error message.
2623 If there is no error, returns nil. */)
2624 (Lisp_Object filename, Lisp_Object string)
2626 Lisp_Object handler, encoded_filename, absname;
2627 int fd;
2629 CHECK_STRING (filename);
2630 absname = Fexpand_file_name (filename, Qnil);
2632 CHECK_STRING (string);
2634 /* If the file name has special constructs in it,
2635 call the corresponding file handler. */
2636 handler = Ffind_file_name_handler (absname, Qaccess_file);
2637 if (!NILP (handler))
2638 return call3 (handler, Qaccess_file, absname, string);
2640 encoded_filename = ENCODE_FILE (absname);
2642 fd = emacs_open (SDATA (encoded_filename), O_RDONLY, 0);
2643 if (fd < 0)
2644 report_file_error (SDATA (string), Fcons (filename, Qnil));
2645 emacs_close (fd);
2647 return Qnil;
2650 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2651 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2652 The value is the link target, as a string.
2653 Otherwise it returns nil.
2655 This function returns t when given the name of a symlink that
2656 points to a nonexistent file. */)
2657 (Lisp_Object filename)
2659 Lisp_Object handler;
2661 CHECK_STRING (filename);
2662 filename = Fexpand_file_name (filename, Qnil);
2664 /* If the file name has special constructs in it,
2665 call the corresponding file handler. */
2666 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2667 if (!NILP (handler))
2668 return call2 (handler, Qfile_symlink_p, filename);
2670 #ifdef S_IFLNK
2672 char *buf;
2673 int bufsize;
2674 int valsize;
2675 Lisp_Object val;
2677 filename = ENCODE_FILE (filename);
2679 bufsize = 50;
2680 buf = NULL;
2683 bufsize *= 2;
2684 buf = (char *) xrealloc (buf, bufsize);
2685 memset (buf, 0, bufsize);
2687 errno = 0;
2688 valsize = readlink (SDATA (filename), buf, bufsize);
2689 if (valsize == -1)
2691 #ifdef ERANGE
2692 /* HP-UX reports ERANGE if buffer is too small. */
2693 if (errno == ERANGE)
2694 valsize = bufsize;
2695 else
2696 #endif
2698 xfree (buf);
2699 return Qnil;
2703 while (valsize >= bufsize);
2705 val = make_string (buf, valsize);
2706 if (buf[0] == '/' && strchr (buf, ':'))
2707 val = concat2 (build_string ("/:"), val);
2708 xfree (buf);
2709 val = DECODE_FILE (val);
2710 return val;
2712 #else /* not S_IFLNK */
2713 return Qnil;
2714 #endif /* not S_IFLNK */
2717 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2718 doc: /* Return t if FILENAME names an existing directory.
2719 Symbolic links to directories count as directories.
2720 See `file-symlink-p' to distinguish symlinks. */)
2721 (Lisp_Object filename)
2723 register Lisp_Object absname;
2724 struct stat st;
2725 Lisp_Object handler;
2727 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2729 /* If the file name has special constructs in it,
2730 call the corresponding file handler. */
2731 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2732 if (!NILP (handler))
2733 return call2 (handler, Qfile_directory_p, absname);
2735 absname = ENCODE_FILE (absname);
2737 if (stat (SDATA (absname), &st) < 0)
2738 return Qnil;
2739 return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2742 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
2743 doc: /* Return t if file FILENAME names a directory you can open.
2744 For the value to be t, FILENAME must specify the name of a directory as a file,
2745 and the directory must allow you to open files in it. In order to use a
2746 directory as a buffer's current directory, this predicate must return true.
2747 A directory name spec may be given instead; then the value is t
2748 if the directory so specified exists and really is a readable and
2749 searchable directory. */)
2750 (Lisp_Object filename)
2752 Lisp_Object handler;
2753 int tem;
2754 struct gcpro gcpro1;
2756 /* If the file name has special constructs in it,
2757 call the corresponding file handler. */
2758 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
2759 if (!NILP (handler))
2760 return call2 (handler, Qfile_accessible_directory_p, filename);
2762 GCPRO1 (filename);
2763 tem = (NILP (Ffile_directory_p (filename))
2764 || NILP (Ffile_executable_p (filename)));
2765 UNGCPRO;
2766 return tem ? Qnil : Qt;
2769 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2770 doc: /* Return t if FILENAME names a regular file.
2771 This is the sort of file that holds an ordinary stream of data bytes.
2772 Symbolic links to regular files count as regular files.
2773 See `file-symlink-p' to distinguish symlinks. */)
2774 (Lisp_Object filename)
2776 register Lisp_Object absname;
2777 struct stat st;
2778 Lisp_Object handler;
2780 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2782 /* If the file name has special constructs in it,
2783 call the corresponding file handler. */
2784 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2785 if (!NILP (handler))
2786 return call2 (handler, Qfile_regular_p, absname);
2788 absname = ENCODE_FILE (absname);
2790 #ifdef WINDOWSNT
2792 int result;
2793 Lisp_Object tem = Vw32_get_true_file_attributes;
2795 /* Tell stat to use expensive method to get accurate info. */
2796 Vw32_get_true_file_attributes = Qt;
2797 result = stat (SDATA (absname), &st);
2798 Vw32_get_true_file_attributes = tem;
2800 if (result < 0)
2801 return Qnil;
2802 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2804 #else
2805 if (stat (SDATA (absname), &st) < 0)
2806 return Qnil;
2807 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2808 #endif
2811 DEFUN ("file-selinux-context", Ffile_selinux_context,
2812 Sfile_selinux_context, 1, 1, 0,
2813 doc: /* Return SELinux context of file named FILENAME,
2814 as a list ("user", "role", "type", "range"). Return (nil, nil, nil, nil)
2815 if file does not exist, is not accessible, or SELinux is disabled */)
2816 (Lisp_Object filename)
2818 Lisp_Object absname;
2819 Lisp_Object values[4];
2820 Lisp_Object handler;
2821 #if HAVE_LIBSELINUX
2822 security_context_t con;
2823 int conlength;
2824 context_t context;
2825 #endif
2827 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2829 /* If the file name has special constructs in it,
2830 call the corresponding file handler. */
2831 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2832 if (!NILP (handler))
2833 return call2 (handler, Qfile_selinux_context, absname);
2835 absname = ENCODE_FILE (absname);
2837 values[0] = Qnil;
2838 values[1] = Qnil;
2839 values[2] = Qnil;
2840 values[3] = Qnil;
2841 #if HAVE_LIBSELINUX
2842 if (is_selinux_enabled ())
2844 conlength = lgetfilecon (SDATA (absname), &con);
2845 if (conlength > 0)
2847 context = context_new (con);
2848 if (context_user_get (context))
2849 values[0] = build_string (context_user_get (context));
2850 if (context_role_get (context))
2851 values[1] = build_string (context_role_get (context));
2852 if (context_type_get (context))
2853 values[2] = build_string (context_type_get (context));
2854 if (context_range_get (context))
2855 values[3] = build_string (context_range_get (context));
2856 context_free (context);
2858 if (con)
2859 freecon (con);
2861 #endif
2863 return Flist (sizeof(values) / sizeof(values[0]), values);
2866 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2867 Sset_file_selinux_context, 2, 2, 0,
2868 doc: /* Set SELinux context of file named FILENAME to CONTEXT
2869 as a list ("user", "role", "type", "range"). Has no effect if SELinux
2870 is disabled. */)
2871 (Lisp_Object filename, Lisp_Object context)
2873 Lisp_Object absname, encoded_absname;
2874 Lisp_Object handler;
2875 Lisp_Object user = CAR_SAFE (context);
2876 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2877 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2878 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2879 #if HAVE_LIBSELINUX
2880 security_context_t con;
2881 int fail, conlength;
2882 context_t parsed_con;
2883 #endif
2885 absname = Fexpand_file_name (filename, current_buffer->directory);
2887 /* If the file name has special constructs in it,
2888 call the corresponding file handler. */
2889 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2890 if (!NILP (handler))
2891 return call3 (handler, Qset_file_selinux_context, absname, context);
2893 encoded_absname = ENCODE_FILE (absname);
2895 #if HAVE_LIBSELINUX
2896 if (is_selinux_enabled ())
2898 /* Get current file context. */
2899 conlength = lgetfilecon (SDATA (encoded_absname), &con);
2900 if (conlength > 0)
2902 parsed_con = context_new (con);
2903 /* Change the parts defined in the parameter.*/
2904 if (STRINGP (user))
2906 if (context_user_set (parsed_con, SDATA (user)))
2907 error ("Doing context_user_set");
2909 if (STRINGP (role))
2911 if (context_role_set (parsed_con, SDATA (role)))
2912 error ("Doing context_role_set");
2914 if (STRINGP (type))
2916 if (context_type_set (parsed_con, SDATA (type)))
2917 error ("Doing context_type_set");
2919 if (STRINGP (range))
2921 if (context_range_set (parsed_con, SDATA (range)))
2922 error ("Doing context_range_set");
2925 /* Set the modified context back to the file. */
2926 fail = lsetfilecon (SDATA (encoded_absname), context_str (parsed_con));
2927 if (fail)
2928 report_file_error ("Doing lsetfilecon", Fcons (absname, Qnil));
2930 context_free (parsed_con);
2932 else
2933 report_file_error("Doing lgetfilecon", Fcons (absname, Qnil));
2935 if (con)
2936 freecon (con);
2938 #endif
2940 return Qnil;
2943 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
2944 doc: /* Return mode bits of file named FILENAME, as an integer.
2945 Return nil, if file does not exist or is not accessible. */)
2946 (Lisp_Object filename)
2948 Lisp_Object absname;
2949 struct stat st;
2950 Lisp_Object handler;
2952 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2954 /* If the file name has special constructs in it,
2955 call the corresponding file handler. */
2956 handler = Ffind_file_name_handler (absname, Qfile_modes);
2957 if (!NILP (handler))
2958 return call2 (handler, Qfile_modes, absname);
2960 absname = ENCODE_FILE (absname);
2962 if (stat (SDATA (absname), &st) < 0)
2963 return Qnil;
2965 return make_number (st.st_mode & 07777);
2968 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
2969 "(let ((file (read-file-name \"File: \"))) \
2970 (list file (read-file-modes nil file)))",
2971 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
2972 Only the 12 low bits of MODE are used.
2974 Interactively, mode bits are read by `read-file-modes', which accepts
2975 symbolic notation, like the `chmod' command from GNU Coreutils. */)
2976 (Lisp_Object filename, Lisp_Object mode)
2978 Lisp_Object absname, encoded_absname;
2979 Lisp_Object handler;
2981 absname = Fexpand_file_name (filename, current_buffer->directory);
2982 CHECK_NUMBER (mode);
2984 /* If the file name has special constructs in it,
2985 call the corresponding file handler. */
2986 handler = Ffind_file_name_handler (absname, Qset_file_modes);
2987 if (!NILP (handler))
2988 return call3 (handler, Qset_file_modes, absname, mode);
2990 encoded_absname = ENCODE_FILE (absname);
2992 if (chmod (SDATA (encoded_absname), XINT (mode)) < 0)
2993 report_file_error ("Doing chmod", Fcons (absname, Qnil));
2995 return Qnil;
2998 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
2999 doc: /* Set the file permission bits for newly created files.
3000 The argument MODE should be an integer; only the low 9 bits are used.
3001 This setting is inherited by subprocesses. */)
3002 (Lisp_Object mode)
3004 CHECK_NUMBER (mode);
3006 umask ((~ XINT (mode)) & 0777);
3008 return Qnil;
3011 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3012 doc: /* Return the default file protection for created files.
3013 The value is an integer. */)
3014 (void)
3016 int realmask;
3017 Lisp_Object value;
3019 realmask = umask (0);
3020 umask (realmask);
3022 XSETINT (value, (~ realmask) & 0777);
3023 return value;
3027 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3028 doc: /* Set times of file FILENAME to TIME.
3029 Set both access and modification times.
3030 Return t on success, else nil.
3031 Use the current time if TIME is nil. TIME is in the format of
3032 `current-time'. */)
3033 (Lisp_Object filename, Lisp_Object time)
3035 Lisp_Object absname, encoded_absname;
3036 Lisp_Object handler;
3037 time_t sec;
3038 int usec;
3040 if (! lisp_time_argument (time, &sec, &usec))
3041 error ("Invalid time specification");
3043 absname = Fexpand_file_name (filename, current_buffer->directory);
3045 /* If the file name has special constructs in it,
3046 call the corresponding file handler. */
3047 handler = Ffind_file_name_handler (absname, Qset_file_times);
3048 if (!NILP (handler))
3049 return call3 (handler, Qset_file_times, absname, time);
3051 encoded_absname = ENCODE_FILE (absname);
3054 EMACS_TIME t;
3056 EMACS_SET_SECS (t, sec);
3057 EMACS_SET_USECS (t, usec);
3059 if (set_file_times (SDATA (encoded_absname), t, t))
3061 #ifdef DOS_NT
3062 struct stat st;
3064 /* Setting times on a directory always fails. */
3065 if (stat (SDATA (encoded_absname), &st) == 0
3066 && (st.st_mode & S_IFMT) == S_IFDIR)
3067 return Qnil;
3068 #endif
3069 report_file_error ("Setting file times", Fcons (absname, Qnil));
3070 return Qnil;
3074 return Qt;
3077 #ifdef HAVE_SYNC
3078 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3079 doc: /* Tell Unix to finish all pending disk updates. */)
3080 (void)
3082 sync ();
3083 return Qnil;
3086 #endif /* HAVE_SYNC */
3088 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3089 doc: /* Return t if file FILE1 is newer than file FILE2.
3090 If FILE1 does not exist, the answer is nil;
3091 otherwise, if FILE2 does not exist, the answer is t. */)
3092 (Lisp_Object file1, Lisp_Object file2)
3094 Lisp_Object absname1, absname2;
3095 struct stat st;
3096 int mtime1;
3097 Lisp_Object handler;
3098 struct gcpro gcpro1, gcpro2;
3100 CHECK_STRING (file1);
3101 CHECK_STRING (file2);
3103 absname1 = Qnil;
3104 GCPRO2 (absname1, file2);
3105 absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
3106 absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
3107 UNGCPRO;
3109 /* If the file name has special constructs in it,
3110 call the corresponding file handler. */
3111 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3112 if (NILP (handler))
3113 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3114 if (!NILP (handler))
3115 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3117 GCPRO2 (absname1, absname2);
3118 absname1 = ENCODE_FILE (absname1);
3119 absname2 = ENCODE_FILE (absname2);
3120 UNGCPRO;
3122 if (stat (SDATA (absname1), &st) < 0)
3123 return Qnil;
3125 mtime1 = st.st_mtime;
3127 if (stat (SDATA (absname2), &st) < 0)
3128 return Qt;
3130 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3133 #ifdef DOS_NT
3134 Lisp_Object Qfind_buffer_file_type;
3135 #endif /* DOS_NT */
3137 #ifndef READ_BUF_SIZE
3138 #define READ_BUF_SIZE (64 << 10)
3139 #endif
3141 /* This function is called after Lisp functions to decide a coding
3142 system are called, or when they cause an error. Before they are
3143 called, the current buffer is set unibyte and it contains only a
3144 newly inserted text (thus the buffer was empty before the
3145 insertion).
3147 The functions may set markers, overlays, text properties, or even
3148 alter the buffer contents, change the current buffer.
3150 Here, we reset all those changes by:
3151 o set back the current buffer.
3152 o move all markers and overlays to BEG.
3153 o remove all text properties.
3154 o set back the buffer multibyteness. */
3156 static Lisp_Object
3157 decide_coding_unwind (Lisp_Object unwind_data)
3159 Lisp_Object multibyte, undo_list, buffer;
3161 multibyte = XCAR (unwind_data);
3162 unwind_data = XCDR (unwind_data);
3163 undo_list = XCAR (unwind_data);
3164 buffer = XCDR (unwind_data);
3166 if (current_buffer != XBUFFER (buffer))
3167 set_buffer_internal (XBUFFER (buffer));
3168 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3169 adjust_overlays_for_delete (BEG, Z - BEG);
3170 BUF_INTERVALS (current_buffer) = 0;
3171 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3173 /* Now we are safe to change the buffer's multibyteness directly. */
3174 current_buffer->enable_multibyte_characters = multibyte;
3175 current_buffer->undo_list = undo_list;
3177 return Qnil;
3181 /* Used to pass values from insert-file-contents to read_non_regular. */
3183 static int non_regular_fd;
3184 static EMACS_INT non_regular_inserted;
3185 static EMACS_INT non_regular_nbytes;
3188 /* Read from a non-regular file.
3189 Read non_regular_nbytes bytes max from non_regular_fd.
3190 Non_regular_inserted specifies where to put the read bytes.
3191 Value is the number of bytes read. */
3193 static Lisp_Object
3194 read_non_regular (Lisp_Object ignore)
3196 EMACS_INT nbytes;
3198 immediate_quit = 1;
3199 QUIT;
3200 nbytes = emacs_read (non_regular_fd,
3201 BEG_ADDR + PT_BYTE - BEG_BYTE + non_regular_inserted,
3202 non_regular_nbytes);
3203 immediate_quit = 0;
3204 return make_number (nbytes);
3208 /* Condition-case handler used when reading from non-regular files
3209 in insert-file-contents. */
3211 static Lisp_Object
3212 read_non_regular_quit (Lisp_Object ignore)
3214 return Qnil;
3218 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3219 1, 5, 0,
3220 doc: /* Insert contents of file FILENAME after point.
3221 Returns list of absolute file name and number of characters inserted.
3222 If second argument VISIT is non-nil, the buffer's visited filename and
3223 last save file modtime are set, and it is marked unmodified. If
3224 visiting and the file does not exist, visiting is completed before the
3225 error is signaled.
3227 The optional third and fourth arguments BEG and END specify what portion
3228 of the file to insert. These arguments count bytes in the file, not
3229 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3231 If optional fifth argument REPLACE is non-nil, replace the current
3232 buffer contents (in the accessible portion) with the file contents.
3233 This is better than simply deleting and inserting the whole thing
3234 because (1) it preserves some marker positions and (2) it puts less data
3235 in the undo list. When REPLACE is non-nil, the second return value is
3236 the number of characters that replace previous buffer contents.
3238 This function does code conversion according to the value of
3239 `coding-system-for-read' or `file-coding-system-alist', and sets the
3240 variable `last-coding-system-used' to the coding system actually used. */)
3241 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3243 struct stat st;
3244 register int fd;
3245 EMACS_INT inserted = 0;
3246 int nochange = 0;
3247 register EMACS_INT how_much;
3248 register EMACS_INT unprocessed;
3249 int count = SPECPDL_INDEX ();
3250 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3251 Lisp_Object handler, val, insval, orig_filename, old_undo;
3252 Lisp_Object p;
3253 EMACS_INT total = 0;
3254 int not_regular = 0;
3255 unsigned char read_buf[READ_BUF_SIZE];
3256 struct coding_system coding;
3257 unsigned char buffer[1 << 14];
3258 int replace_handled = 0;
3259 int set_coding_system = 0;
3260 Lisp_Object coding_system;
3261 int read_quit = 0;
3262 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3263 int we_locked_file = 0;
3264 int deferred_remove_unwind_protect = 0;
3266 if (current_buffer->base_buffer && ! NILP (visit))
3267 error ("Cannot do file visiting in an indirect buffer");
3269 if (!NILP (current_buffer->read_only))
3270 Fbarf_if_buffer_read_only ();
3272 val = Qnil;
3273 p = Qnil;
3274 orig_filename = Qnil;
3275 old_undo = Qnil;
3277 GCPRO5 (filename, val, p, orig_filename, old_undo);
3279 CHECK_STRING (filename);
3280 filename = Fexpand_file_name (filename, Qnil);
3282 /* The value Qnil means that the coding system is not yet
3283 decided. */
3284 coding_system = Qnil;
3286 /* If the file name has special constructs in it,
3287 call the corresponding file handler. */
3288 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3289 if (!NILP (handler))
3291 val = call6 (handler, Qinsert_file_contents, filename,
3292 visit, beg, end, replace);
3293 if (CONSP (val) && CONSP (XCDR (val)))
3294 inserted = XINT (XCAR (XCDR (val)));
3295 goto handled;
3298 orig_filename = filename;
3299 filename = ENCODE_FILE (filename);
3301 fd = -1;
3303 #ifdef WINDOWSNT
3305 Lisp_Object tem = Vw32_get_true_file_attributes;
3307 /* Tell stat to use expensive method to get accurate info. */
3308 Vw32_get_true_file_attributes = Qt;
3309 total = stat (SDATA (filename), &st);
3310 Vw32_get_true_file_attributes = tem;
3312 if (total < 0)
3313 #else
3314 if (stat (SDATA (filename), &st) < 0)
3315 #endif /* WINDOWSNT */
3317 if (fd >= 0) emacs_close (fd);
3318 badopen:
3319 if (NILP (visit))
3320 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3321 st.st_mtime = -1;
3322 how_much = 0;
3323 if (!NILP (Vcoding_system_for_read))
3324 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3325 goto notfound;
3328 #ifdef S_IFREG
3329 /* This code will need to be changed in order to work on named
3330 pipes, and it's probably just not worth it. So we should at
3331 least signal an error. */
3332 if (!S_ISREG (st.st_mode))
3334 not_regular = 1;
3336 if (! NILP (visit))
3337 goto notfound;
3339 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3340 xsignal2 (Qfile_error,
3341 build_string ("not a regular file"), orig_filename);
3343 #endif
3345 if (fd < 0)
3346 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0)
3347 goto badopen;
3349 /* Replacement should preserve point as it preserves markers. */
3350 if (!NILP (replace))
3351 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3353 record_unwind_protect (close_file_unwind, make_number (fd));
3355 /* Can happen on any platform that uses long as type of off_t, but allows
3356 file sizes to exceed 2Gb, so give a suitable message. */
3357 if (! not_regular && st.st_size < 0)
3358 error ("Maximum buffer size exceeded");
3360 /* Prevent redisplay optimizations. */
3361 current_buffer->clip_changed = 1;
3363 if (!NILP (visit))
3365 if (!NILP (beg) || !NILP (end))
3366 error ("Attempt to visit less than an entire file");
3367 if (BEG < Z && NILP (replace))
3368 error ("Cannot do file visiting in a non-empty buffer");
3371 if (!NILP (beg))
3372 CHECK_NUMBER (beg);
3373 else
3374 XSETFASTINT (beg, 0);
3376 if (!NILP (end))
3377 CHECK_NUMBER (end);
3378 else
3380 if (! not_regular)
3382 XSETINT (end, st.st_size);
3384 /* Arithmetic overflow can occur if an Emacs integer cannot
3385 represent the file size, or if the calculations below
3386 overflow. The calculations below double the file size
3387 twice, so check that it can be multiplied by 4 safely. */
3388 if (XINT (end) != st.st_size
3389 /* Actually, it should test either INT_MAX or LONG_MAX
3390 depending on which one is used for EMACS_INT. But in
3391 any case, in practice, this test is redundant with the
3392 one above.
3393 || st.st_size > INT_MAX / 4 */)
3394 error ("Maximum buffer size exceeded");
3396 /* The file size returned from stat may be zero, but data
3397 may be readable nonetheless, for example when this is a
3398 file in the /proc filesystem. */
3399 if (st.st_size == 0)
3400 XSETINT (end, READ_BUF_SIZE);
3404 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3406 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3407 setup_coding_system (coding_system, &coding);
3408 /* Ensure we set Vlast_coding_system_used. */
3409 set_coding_system = 1;
3411 else if (BEG < Z)
3413 /* Decide the coding system to use for reading the file now
3414 because we can't use an optimized method for handling
3415 `coding:' tag if the current buffer is not empty. */
3416 if (!NILP (Vcoding_system_for_read))
3417 coding_system = Vcoding_system_for_read;
3418 else
3420 /* Don't try looking inside a file for a coding system
3421 specification if it is not seekable. */
3422 if (! not_regular && ! NILP (Vset_auto_coding_function))
3424 /* Find a coding system specified in the heading two
3425 lines or in the tailing several lines of the file.
3426 We assume that the 1K-byte and 3K-byte for heading
3427 and tailing respectively are sufficient for this
3428 purpose. */
3429 EMACS_INT nread;
3431 if (st.st_size <= (1024 * 4))
3432 nread = emacs_read (fd, read_buf, 1024 * 4);
3433 else
3435 nread = emacs_read (fd, read_buf, 1024);
3436 if (nread >= 0)
3438 if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
3439 report_file_error ("Setting file position",
3440 Fcons (orig_filename, Qnil));
3441 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3445 if (nread < 0)
3446 error ("IO error reading %s: %s",
3447 SDATA (orig_filename), emacs_strerror (errno));
3448 else if (nread > 0)
3450 struct buffer *prev = current_buffer;
3451 Lisp_Object buffer;
3452 struct buffer *buf;
3454 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3456 buffer = Fget_buffer_create (build_string (" *code-converting-work*"));
3457 buf = XBUFFER (buffer);
3459 delete_all_overlays (buf);
3460 buf->directory = current_buffer->directory;
3461 buf->read_only = Qnil;
3462 buf->filename = Qnil;
3463 buf->undo_list = Qt;
3464 eassert (buf->overlays_before == NULL);
3465 eassert (buf->overlays_after == NULL);
3467 set_buffer_internal (buf);
3468 Ferase_buffer ();
3469 buf->enable_multibyte_characters = Qnil;
3471 insert_1_both (read_buf, nread, nread, 0, 0, 0);
3472 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3473 coding_system = call2 (Vset_auto_coding_function,
3474 filename, make_number (nread));
3475 set_buffer_internal (prev);
3477 /* Discard the unwind protect for recovering the
3478 current buffer. */
3479 specpdl_ptr--;
3481 /* Rewind the file for the actual read done later. */
3482 if (lseek (fd, 0, 0) < 0)
3483 report_file_error ("Setting file position",
3484 Fcons (orig_filename, Qnil));
3488 if (NILP (coding_system))
3490 /* If we have not yet decided a coding system, check
3491 file-coding-system-alist. */
3492 Lisp_Object args[6];
3494 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3495 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3496 coding_system = Ffind_operation_coding_system (6, args);
3497 if (CONSP (coding_system))
3498 coding_system = XCAR (coding_system);
3502 if (NILP (coding_system))
3503 coding_system = Qundecided;
3504 else
3505 CHECK_CODING_SYSTEM (coding_system);
3507 if (NILP (current_buffer->enable_multibyte_characters))
3508 /* We must suppress all character code conversion except for
3509 end-of-line conversion. */
3510 coding_system = raw_text_coding_system (coding_system);
3512 setup_coding_system (coding_system, &coding);
3513 /* Ensure we set Vlast_coding_system_used. */
3514 set_coding_system = 1;
3517 /* If requested, replace the accessible part of the buffer
3518 with the file contents. Avoid replacing text at the
3519 beginning or end of the buffer that matches the file contents;
3520 that preserves markers pointing to the unchanged parts.
3522 Here we implement this feature in an optimized way
3523 for the case where code conversion is NOT needed.
3524 The following if-statement handles the case of conversion
3525 in a less optimal way.
3527 If the code conversion is "automatic" then we try using this
3528 method and hope for the best.
3529 But if we discover the need for conversion, we give up on this method
3530 and let the following if-statement handle the replace job. */
3531 if (!NILP (replace)
3532 && BEGV < ZV
3533 && (NILP (coding_system)
3534 || ! CODING_REQUIRE_DECODING (&coding)))
3536 /* same_at_start and same_at_end count bytes,
3537 because file access counts bytes
3538 and BEG and END count bytes. */
3539 EMACS_INT same_at_start = BEGV_BYTE;
3540 EMACS_INT same_at_end = ZV_BYTE;
3541 EMACS_INT overlap;
3542 /* There is still a possibility we will find the need to do code
3543 conversion. If that happens, we set this variable to 1 to
3544 give up on handling REPLACE in the optimized way. */
3545 int giveup_match_end = 0;
3547 if (XINT (beg) != 0)
3549 if (lseek (fd, XINT (beg), 0) < 0)
3550 report_file_error ("Setting file position",
3551 Fcons (orig_filename, Qnil));
3554 immediate_quit = 1;
3555 QUIT;
3556 /* Count how many chars at the start of the file
3557 match the text at the beginning of the buffer. */
3558 while (1)
3560 EMACS_INT nread, bufpos;
3562 nread = emacs_read (fd, buffer, sizeof buffer);
3563 if (nread < 0)
3564 error ("IO error reading %s: %s",
3565 SDATA (orig_filename), emacs_strerror (errno));
3566 else if (nread == 0)
3567 break;
3569 if (CODING_REQUIRE_DETECTION (&coding))
3571 coding_system = detect_coding_system (buffer, nread, nread, 1, 0,
3572 coding_system);
3573 setup_coding_system (coding_system, &coding);
3576 if (CODING_REQUIRE_DECODING (&coding))
3577 /* We found that the file should be decoded somehow.
3578 Let's give up here. */
3580 giveup_match_end = 1;
3581 break;
3584 bufpos = 0;
3585 while (bufpos < nread && same_at_start < ZV_BYTE
3586 && FETCH_BYTE (same_at_start) == buffer[bufpos])
3587 same_at_start++, bufpos++;
3588 /* If we found a discrepancy, stop the scan.
3589 Otherwise loop around and scan the next bufferful. */
3590 if (bufpos != nread)
3591 break;
3593 immediate_quit = 0;
3594 /* If the file matches the buffer completely,
3595 there's no need to replace anything. */
3596 if (same_at_start - BEGV_BYTE == XINT (end))
3598 emacs_close (fd);
3599 specpdl_ptr--;
3600 /* Truncate the buffer to the size of the file. */
3601 del_range_1 (same_at_start, same_at_end, 0, 0);
3602 goto handled;
3604 immediate_quit = 1;
3605 QUIT;
3606 /* Count how many chars at the end of the file
3607 match the text at the end of the buffer. But, if we have
3608 already found that decoding is necessary, don't waste time. */
3609 while (!giveup_match_end)
3611 EMACS_INT total_read, nread, bufpos, curpos, trial;
3613 /* At what file position are we now scanning? */
3614 curpos = XINT (end) - (ZV_BYTE - same_at_end);
3615 /* If the entire file matches the buffer tail, stop the scan. */
3616 if (curpos == 0)
3617 break;
3618 /* How much can we scan in the next step? */
3619 trial = min (curpos, sizeof buffer);
3620 if (lseek (fd, curpos - trial, 0) < 0)
3621 report_file_error ("Setting file position",
3622 Fcons (orig_filename, Qnil));
3624 total_read = nread = 0;
3625 while (total_read < trial)
3627 nread = emacs_read (fd, buffer + total_read, trial - total_read);
3628 if (nread < 0)
3629 error ("IO error reading %s: %s",
3630 SDATA (orig_filename), emacs_strerror (errno));
3631 else if (nread == 0)
3632 break;
3633 total_read += nread;
3636 /* Scan this bufferful from the end, comparing with
3637 the Emacs buffer. */
3638 bufpos = total_read;
3640 /* Compare with same_at_start to avoid counting some buffer text
3641 as matching both at the file's beginning and at the end. */
3642 while (bufpos > 0 && same_at_end > same_at_start
3643 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
3644 same_at_end--, bufpos--;
3646 /* If we found a discrepancy, stop the scan.
3647 Otherwise loop around and scan the preceding bufferful. */
3648 if (bufpos != 0)
3650 /* If this discrepancy is because of code conversion,
3651 we cannot use this method; giveup and try the other. */
3652 if (same_at_end > same_at_start
3653 && FETCH_BYTE (same_at_end - 1) >= 0200
3654 && ! NILP (current_buffer->enable_multibyte_characters)
3655 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3656 giveup_match_end = 1;
3657 break;
3660 if (nread == 0)
3661 break;
3663 immediate_quit = 0;
3665 if (! giveup_match_end)
3667 EMACS_INT temp;
3669 /* We win! We can handle REPLACE the optimized way. */
3671 /* Extend the start of non-matching text area to multibyte
3672 character boundary. */
3673 if (! NILP (current_buffer->enable_multibyte_characters))
3674 while (same_at_start > BEGV_BYTE
3675 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3676 same_at_start--;
3678 /* Extend the end of non-matching text area to multibyte
3679 character boundary. */
3680 if (! NILP (current_buffer->enable_multibyte_characters))
3681 while (same_at_end < ZV_BYTE
3682 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3683 same_at_end++;
3685 /* Don't try to reuse the same piece of text twice. */
3686 overlap = (same_at_start - BEGV_BYTE
3687 - (same_at_end + st.st_size - ZV));
3688 if (overlap > 0)
3689 same_at_end += overlap;
3691 /* Arrange to read only the nonmatching middle part of the file. */
3692 XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV_BYTE));
3693 XSETFASTINT (end, XINT (end) - (ZV_BYTE - same_at_end));
3695 del_range_byte (same_at_start, same_at_end, 0);
3696 /* Insert from the file at the proper position. */
3697 temp = BYTE_TO_CHAR (same_at_start);
3698 SET_PT_BOTH (temp, same_at_start);
3700 /* If display currently starts at beginning of line,
3701 keep it that way. */
3702 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3703 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3705 replace_handled = 1;
3709 /* If requested, replace the accessible part of the buffer
3710 with the file contents. Avoid replacing text at the
3711 beginning or end of the buffer that matches the file contents;
3712 that preserves markers pointing to the unchanged parts.
3714 Here we implement this feature for the case where code conversion
3715 is needed, in a simple way that needs a lot of memory.
3716 The preceding if-statement handles the case of no conversion
3717 in a more optimized way. */
3718 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3720 EMACS_INT same_at_start = BEGV_BYTE;
3721 EMACS_INT same_at_end = ZV_BYTE;
3722 EMACS_INT same_at_start_charpos;
3723 EMACS_INT inserted_chars;
3724 EMACS_INT overlap;
3725 EMACS_INT bufpos;
3726 unsigned char *decoded;
3727 EMACS_INT temp;
3728 int this_count = SPECPDL_INDEX ();
3729 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
3730 Lisp_Object conversion_buffer;
3732 conversion_buffer = code_conversion_save (1, multibyte);
3734 /* First read the whole file, performing code conversion into
3735 CONVERSION_BUFFER. */
3737 if (lseek (fd, XINT (beg), 0) < 0)
3738 report_file_error ("Setting file position",
3739 Fcons (orig_filename, Qnil));
3741 total = st.st_size; /* Total bytes in the file. */
3742 how_much = 0; /* Bytes read from file so far. */
3743 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3744 unprocessed = 0; /* Bytes not processed in previous loop. */
3746 GCPRO1 (conversion_buffer);
3747 while (how_much < total)
3749 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
3750 quitting while reading a huge while. */
3751 /* try is reserved in some compilers (Microsoft C) */
3752 EMACS_INT trytry = min (total - how_much,
3753 READ_BUF_SIZE - unprocessed);
3754 EMACS_INT this;
3756 /* Allow quitting out of the actual I/O. */
3757 immediate_quit = 1;
3758 QUIT;
3759 this = emacs_read (fd, read_buf + unprocessed, trytry);
3760 immediate_quit = 0;
3762 if (this <= 0)
3764 if (this < 0)
3765 how_much = this;
3766 break;
3769 how_much += this;
3771 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3772 BUF_Z (XBUFFER (conversion_buffer)));
3773 decode_coding_c_string (&coding, read_buf, unprocessed + this,
3774 conversion_buffer);
3775 unprocessed = coding.carryover_bytes;
3776 if (coding.carryover_bytes > 0)
3777 memcpy (read_buf, coding.carryover, unprocessed);
3779 UNGCPRO;
3780 emacs_close (fd);
3782 /* We should remove the unwind_protect calling
3783 close_file_unwind, but other stuff has been added the stack,
3784 so defer the removal till we reach the `handled' label. */
3785 deferred_remove_unwind_protect = 1;
3787 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
3788 if we couldn't read the file. */
3790 if (how_much < 0)
3791 error ("IO error reading %s: %s",
3792 SDATA (orig_filename), emacs_strerror (errno));
3794 if (unprocessed > 0)
3796 coding.mode |= CODING_MODE_LAST_BLOCK;
3797 decode_coding_c_string (&coding, read_buf, unprocessed,
3798 conversion_buffer);
3799 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3802 coding_system = CODING_ID_NAME (coding.id);
3803 set_coding_system = 1;
3804 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3805 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3806 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3808 /* Compare the beginning of the converted string with the buffer
3809 text. */
3811 bufpos = 0;
3812 while (bufpos < inserted && same_at_start < same_at_end
3813 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3814 same_at_start++, bufpos++;
3816 /* If the file matches the head of buffer completely,
3817 there's no need to replace anything. */
3819 if (bufpos == inserted)
3821 /* Truncate the buffer to the size of the file. */
3822 if (same_at_start == same_at_end)
3823 nochange = 1;
3824 else
3825 del_range_byte (same_at_start, same_at_end, 0);
3826 inserted = 0;
3828 unbind_to (this_count, Qnil);
3829 goto handled;
3832 /* Extend the start of non-matching text area to the previous
3833 multibyte character boundary. */
3834 if (! NILP (current_buffer->enable_multibyte_characters))
3835 while (same_at_start > BEGV_BYTE
3836 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3837 same_at_start--;
3839 /* Scan this bufferful from the end, comparing with
3840 the Emacs buffer. */
3841 bufpos = inserted;
3843 /* Compare with same_at_start to avoid counting some buffer text
3844 as matching both at the file's beginning and at the end. */
3845 while (bufpos > 0 && same_at_end > same_at_start
3846 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3847 same_at_end--, bufpos--;
3849 /* Extend the end of non-matching text area to the next
3850 multibyte character boundary. */
3851 if (! NILP (current_buffer->enable_multibyte_characters))
3852 while (same_at_end < ZV_BYTE
3853 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3854 same_at_end++;
3856 /* Don't try to reuse the same piece of text twice. */
3857 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3858 if (overlap > 0)
3859 same_at_end += overlap;
3861 /* If display currently starts at beginning of line,
3862 keep it that way. */
3863 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3864 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3866 /* Replace the chars that we need to replace,
3867 and update INSERTED to equal the number of bytes
3868 we are taking from the decoded string. */
3869 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3871 if (same_at_end != same_at_start)
3873 del_range_byte (same_at_start, same_at_end, 0);
3874 temp = GPT;
3875 same_at_start = GPT_BYTE;
3877 else
3879 temp = BYTE_TO_CHAR (same_at_start);
3881 /* Insert from the file at the proper position. */
3882 SET_PT_BOTH (temp, same_at_start);
3883 same_at_start_charpos
3884 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3885 same_at_start - BEGV_BYTE
3886 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3887 inserted_chars
3888 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3889 same_at_start + inserted - BEGV_BYTE
3890 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
3891 - same_at_start_charpos);
3892 /* This binding is to avoid ask-user-about-supersession-threat
3893 being called in insert_from_buffer (via in
3894 prepare_to_modify_buffer). */
3895 specbind (intern ("buffer-file-name"), Qnil);
3896 insert_from_buffer (XBUFFER (conversion_buffer),
3897 same_at_start_charpos, inserted_chars, 0);
3898 /* Set `inserted' to the number of inserted characters. */
3899 inserted = PT - temp;
3900 /* Set point before the inserted characters. */
3901 SET_PT_BOTH (temp, same_at_start);
3903 unbind_to (this_count, Qnil);
3905 goto handled;
3908 if (! not_regular)
3910 register Lisp_Object temp;
3912 total = XINT (end) - XINT (beg);
3914 /* Make sure point-max won't overflow after this insertion. */
3915 XSETINT (temp, total);
3916 if (total != XINT (temp))
3917 error ("Maximum buffer size exceeded");
3919 else
3920 /* For a special file, all we can do is guess. */
3921 total = READ_BUF_SIZE;
3923 if (NILP (visit) && inserted > 0)
3925 #ifdef CLASH_DETECTION
3926 if (!NILP (current_buffer->file_truename)
3927 /* Make binding buffer-file-name to nil effective. */
3928 && !NILP (current_buffer->filename)
3929 && SAVE_MODIFF >= MODIFF)
3930 we_locked_file = 1;
3931 #endif /* CLASH_DETECTION */
3932 prepare_to_modify_buffer (GPT, GPT, NULL);
3935 move_gap (PT);
3936 if (GAP_SIZE < total)
3937 make_gap (total - GAP_SIZE);
3939 if (XINT (beg) != 0 || !NILP (replace))
3941 if (lseek (fd, XINT (beg), 0) < 0)
3942 report_file_error ("Setting file position",
3943 Fcons (orig_filename, Qnil));
3946 /* In the following loop, HOW_MUCH contains the total bytes read so
3947 far for a regular file, and not changed for a special file. But,
3948 before exiting the loop, it is set to a negative value if I/O
3949 error occurs. */
3950 how_much = 0;
3952 /* Total bytes inserted. */
3953 inserted = 0;
3955 /* Here, we don't do code conversion in the loop. It is done by
3956 decode_coding_gap after all data are read into the buffer. */
3958 EMACS_INT gap_size = GAP_SIZE;
3960 while (how_much < total)
3962 /* try is reserved in some compilers (Microsoft C) */
3963 EMACS_INT trytry = min (total - how_much, READ_BUF_SIZE);
3964 EMACS_INT this;
3966 if (not_regular)
3968 Lisp_Object val;
3970 /* Maybe make more room. */
3971 if (gap_size < trytry)
3973 make_gap (total - gap_size);
3974 gap_size = GAP_SIZE;
3977 /* Read from the file, capturing `quit'. When an
3978 error occurs, end the loop, and arrange for a quit
3979 to be signaled after decoding the text we read. */
3980 non_regular_fd = fd;
3981 non_regular_inserted = inserted;
3982 non_regular_nbytes = trytry;
3983 val = internal_condition_case_1 (read_non_regular, Qnil, Qerror,
3984 read_non_regular_quit);
3985 if (NILP (val))
3987 read_quit = 1;
3988 break;
3991 this = XINT (val);
3993 else
3995 /* Allow quitting out of the actual I/O. We don't make text
3996 part of the buffer until all the reading is done, so a C-g
3997 here doesn't do any harm. */
3998 immediate_quit = 1;
3999 QUIT;
4000 this = emacs_read (fd, BEG_ADDR + PT_BYTE - BEG_BYTE + inserted, trytry);
4001 immediate_quit = 0;
4004 if (this <= 0)
4006 how_much = this;
4007 break;
4010 gap_size -= this;
4012 /* For a regular file, where TOTAL is the real size,
4013 count HOW_MUCH to compare with it.
4014 For a special file, where TOTAL is just a buffer size,
4015 so don't bother counting in HOW_MUCH.
4016 (INSERTED is where we count the number of characters inserted.) */
4017 if (! not_regular)
4018 how_much += this;
4019 inserted += this;
4023 /* Now we have read all the file data into the gap.
4024 If it was empty, undo marking the buffer modified. */
4026 if (inserted == 0)
4028 #ifdef CLASH_DETECTION
4029 if (we_locked_file)
4030 unlock_file (current_buffer->file_truename);
4031 #endif
4032 Vdeactivate_mark = old_Vdeactivate_mark;
4034 else
4035 Vdeactivate_mark = Qt;
4037 /* Make the text read part of the buffer. */
4038 GAP_SIZE -= inserted;
4039 GPT += inserted;
4040 GPT_BYTE += inserted;
4041 ZV += inserted;
4042 ZV_BYTE += inserted;
4043 Z += inserted;
4044 Z_BYTE += inserted;
4046 if (GAP_SIZE > 0)
4047 /* Put an anchor to ensure multi-byte form ends at gap. */
4048 *GPT_ADDR = 0;
4050 emacs_close (fd);
4052 /* Discard the unwind protect for closing the file. */
4053 specpdl_ptr--;
4055 if (how_much < 0)
4056 error ("IO error reading %s: %s",
4057 SDATA (orig_filename), emacs_strerror (errno));
4059 notfound:
4061 if (NILP (coding_system))
4063 /* The coding system is not yet decided. Decide it by an
4064 optimized method for handling `coding:' tag.
4066 Note that we can get here only if the buffer was empty
4067 before the insertion. */
4069 if (!NILP (Vcoding_system_for_read))
4070 coding_system = Vcoding_system_for_read;
4071 else
4073 /* Since we are sure that the current buffer was empty
4074 before the insertion, we can toggle
4075 enable-multibyte-characters directly here without taking
4076 care of marker adjustment. By this way, we can run Lisp
4077 program safely before decoding the inserted text. */
4078 Lisp_Object unwind_data;
4079 int count = SPECPDL_INDEX ();
4081 unwind_data = Fcons (current_buffer->enable_multibyte_characters,
4082 Fcons (current_buffer->undo_list,
4083 Fcurrent_buffer ()));
4084 current_buffer->enable_multibyte_characters = Qnil;
4085 current_buffer->undo_list = Qt;
4086 record_unwind_protect (decide_coding_unwind, unwind_data);
4088 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4090 coding_system = call2 (Vset_auto_coding_function,
4091 filename, make_number (inserted));
4094 if (NILP (coding_system))
4096 /* If the coding system is not yet decided, check
4097 file-coding-system-alist. */
4098 Lisp_Object args[6];
4100 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4101 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4102 coding_system = Ffind_operation_coding_system (6, args);
4103 if (CONSP (coding_system))
4104 coding_system = XCAR (coding_system);
4106 unbind_to (count, Qnil);
4107 inserted = Z_BYTE - BEG_BYTE;
4110 if (NILP (coding_system))
4111 coding_system = Qundecided;
4112 else
4113 CHECK_CODING_SYSTEM (coding_system);
4115 if (NILP (current_buffer->enable_multibyte_characters))
4116 /* We must suppress all character code conversion except for
4117 end-of-line conversion. */
4118 coding_system = raw_text_coding_system (coding_system);
4119 setup_coding_system (coding_system, &coding);
4120 /* Ensure we set Vlast_coding_system_used. */
4121 set_coding_system = 1;
4124 if (!NILP (visit))
4126 /* When we visit a file by raw-text, we change the buffer to
4127 unibyte. */
4128 if (CODING_FOR_UNIBYTE (&coding)
4129 /* Can't do this if part of the buffer might be preserved. */
4130 && NILP (replace))
4131 /* Visiting a file with these coding system makes the buffer
4132 unibyte. */
4133 current_buffer->enable_multibyte_characters = Qnil;
4136 coding.dst_multibyte = ! NILP (current_buffer->enable_multibyte_characters);
4137 if (CODING_MAY_REQUIRE_DECODING (&coding)
4138 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4140 move_gap_both (PT, PT_BYTE);
4141 GAP_SIZE += inserted;
4142 ZV_BYTE -= inserted;
4143 Z_BYTE -= inserted;
4144 ZV -= inserted;
4145 Z -= inserted;
4146 decode_coding_gap (&coding, inserted, inserted);
4147 inserted = coding.produced_char;
4148 coding_system = CODING_ID_NAME (coding.id);
4150 else if (inserted > 0)
4151 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4152 inserted);
4154 /* Now INSERTED is measured in characters. */
4156 #ifdef DOS_NT
4157 /* Use the conversion type to determine buffer-file-type
4158 (find-buffer-file-type is now used to help determine the
4159 conversion). */
4160 if ((VECTORP (CODING_ID_EOL_TYPE (coding.id))
4161 || EQ (CODING_ID_EOL_TYPE (coding.id), Qunix))
4162 && ! CODING_REQUIRE_DECODING (&coding))
4163 current_buffer->buffer_file_type = Qt;
4164 else
4165 current_buffer->buffer_file_type = Qnil;
4166 #endif
4168 handled:
4170 if (deferred_remove_unwind_protect)
4171 /* If requested above, discard the unwind protect for closing the
4172 file. */
4173 specpdl_ptr--;
4175 if (!NILP (visit))
4177 if (!EQ (current_buffer->undo_list, Qt) && !nochange)
4178 current_buffer->undo_list = Qnil;
4180 if (NILP (handler))
4182 current_buffer->modtime = st.st_mtime;
4183 current_buffer->modtime_size = st.st_size;
4184 current_buffer->filename = orig_filename;
4187 SAVE_MODIFF = MODIFF;
4188 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4189 XSETFASTINT (current_buffer->save_length, Z - BEG);
4190 #ifdef CLASH_DETECTION
4191 if (NILP (handler))
4193 if (!NILP (current_buffer->file_truename))
4194 unlock_file (current_buffer->file_truename);
4195 unlock_file (filename);
4197 #endif /* CLASH_DETECTION */
4198 if (not_regular)
4199 xsignal2 (Qfile_error,
4200 build_string ("not a regular file"), orig_filename);
4203 if (set_coding_system)
4204 Vlast_coding_system_used = coding_system;
4206 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4208 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4209 visit);
4210 if (! NILP (insval))
4212 CHECK_NUMBER (insval);
4213 inserted = XFASTINT (insval);
4217 /* Decode file format. */
4218 if (inserted > 0)
4220 /* Don't run point motion or modification hooks when decoding. */
4221 int count = SPECPDL_INDEX ();
4222 EMACS_INT old_inserted = inserted;
4223 specbind (Qinhibit_point_motion_hooks, Qt);
4224 specbind (Qinhibit_modification_hooks, Qt);
4226 /* Save old undo list and don't record undo for decoding. */
4227 old_undo = current_buffer->undo_list;
4228 current_buffer->undo_list = Qt;
4230 if (NILP (replace))
4232 insval = call3 (Qformat_decode,
4233 Qnil, make_number (inserted), visit);
4234 CHECK_NUMBER (insval);
4235 inserted = XFASTINT (insval);
4237 else
4239 /* If REPLACE is non-nil and we succeeded in not replacing the
4240 beginning or end of the buffer text with the file's contents,
4241 call format-decode with `point' positioned at the beginning
4242 of the buffer and `inserted' equalling the number of
4243 characters in the buffer. Otherwise, format-decode might
4244 fail to correctly analyze the beginning or end of the buffer.
4245 Hence we temporarily save `point' and `inserted' here and
4246 restore `point' iff format-decode did not insert or delete
4247 any text. Otherwise we leave `point' at point-min. */
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 = call3 (Qformat_decode,
4255 Qnil, make_number (oinserted), visit);
4256 CHECK_NUMBER (insval);
4257 if (ochars_modiff == CHARS_MODIFF)
4258 /* format_decode didn't modify buffer's characters => move
4259 point back to position before inserted text and leave
4260 value of inserted alone. */
4261 SET_PT_BOTH (opoint, opoint_byte);
4262 else
4263 /* format_decode modified buffer's characters => consider
4264 entire buffer changed and leave point at point-min. */
4265 inserted = XFASTINT (insval);
4268 /* For consistency with format-decode call these now iff inserted > 0
4269 (martin 2007-06-28). */
4270 p = Vafter_insert_file_functions;
4271 while (CONSP (p))
4273 if (NILP (replace))
4275 insval = call1 (XCAR (p), make_number (inserted));
4276 if (!NILP (insval))
4278 CHECK_NUMBER (insval);
4279 inserted = XFASTINT (insval);
4282 else
4284 /* For the rationale of this see the comment on
4285 format-decode above. */
4286 EMACS_INT opoint = PT;
4287 EMACS_INT opoint_byte = PT_BYTE;
4288 EMACS_INT oinserted = ZV - BEGV;
4289 int ochars_modiff = CHARS_MODIFF;
4291 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4292 insval = call1 (XCAR (p), make_number (oinserted));
4293 if (!NILP (insval))
4295 CHECK_NUMBER (insval);
4296 if (ochars_modiff == CHARS_MODIFF)
4297 /* after_insert_file_functions didn't modify
4298 buffer's characters => move point back to
4299 position before inserted text and leave value of
4300 inserted alone. */
4301 SET_PT_BOTH (opoint, opoint_byte);
4302 else
4303 /* after_insert_file_functions did modify buffer's
4304 characters => consider entire buffer changed and
4305 leave point at point-min. */
4306 inserted = XFASTINT (insval);
4310 QUIT;
4311 p = XCDR (p);
4314 if (NILP (visit))
4316 current_buffer->undo_list = old_undo;
4317 if (CONSP (old_undo) && inserted != old_inserted)
4319 /* Adjust the last undo record for the size change during
4320 the format conversion. */
4321 Lisp_Object tem = XCAR (old_undo);
4322 if (CONSP (tem) && INTEGERP (XCAR (tem))
4323 && INTEGERP (XCDR (tem))
4324 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4325 XSETCDR (tem, make_number (PT + inserted));
4328 else
4329 /* If undo_list was Qt before, keep it that way.
4330 Otherwise start with an empty undo_list. */
4331 current_buffer->undo_list = EQ (old_undo, Qt) ? Qt : Qnil;
4333 unbind_to (count, Qnil);
4336 /* Call after-change hooks for the inserted text, aside from the case
4337 of normal visiting (not with REPLACE), which is done in a new buffer
4338 "before" the buffer is changed. */
4339 if (inserted > 0 && total > 0
4340 && (NILP (visit) || !NILP (replace)))
4342 signal_after_change (PT, 0, inserted);
4343 update_compositions (PT, PT, CHECK_BORDER);
4346 if (!NILP (visit)
4347 && current_buffer->modtime == -1)
4349 /* If visiting nonexistent file, return nil. */
4350 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4353 if (read_quit)
4354 Fsignal (Qquit, Qnil);
4356 /* ??? Retval needs to be dealt with in all cases consistently. */
4357 if (NILP (val))
4358 val = Fcons (orig_filename,
4359 Fcons (make_number (inserted),
4360 Qnil));
4362 RETURN_UNGCPRO (unbind_to (count, val));
4365 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4367 static Lisp_Object
4368 build_annotations_unwind (Lisp_Object arg)
4370 Vwrite_region_annotation_buffers = arg;
4371 return Qnil;
4374 /* Decide the coding-system to encode the data with. */
4376 static Lisp_Object
4377 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4378 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4379 struct coding_system *coding)
4381 Lisp_Object val;
4382 Lisp_Object eol_parent = Qnil;
4384 if (auto_saving
4385 && NILP (Fstring_equal (current_buffer->filename,
4386 current_buffer->auto_save_file_name)))
4388 val = Qutf_8_emacs;
4389 eol_parent = Qunix;
4391 else if (!NILP (Vcoding_system_for_write))
4393 val = Vcoding_system_for_write;
4394 if (coding_system_require_warning
4395 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4396 /* Confirm that VAL can surely encode the current region. */
4397 val = call5 (Vselect_safe_coding_system_function,
4398 start, end, Fcons (Qt, Fcons (val, Qnil)),
4399 Qnil, filename);
4401 else
4403 /* If the variable `buffer-file-coding-system' is set locally,
4404 it means that the file was read with some kind of code
4405 conversion or the variable is explicitly set by users. We
4406 had better write it out with the same coding system even if
4407 `enable-multibyte-characters' is nil.
4409 If it is not set locally, we anyway have to convert EOL
4410 format if the default value of `buffer-file-coding-system'
4411 tells that it is not Unix-like (LF only) format. */
4412 int using_default_coding = 0;
4413 int force_raw_text = 0;
4415 val = current_buffer->buffer_file_coding_system;
4416 if (NILP (val)
4417 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4419 val = Qnil;
4420 if (NILP (current_buffer->enable_multibyte_characters))
4421 force_raw_text = 1;
4424 if (NILP (val))
4426 /* Check file-coding-system-alist. */
4427 Lisp_Object args[7], coding_systems;
4429 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4430 args[3] = filename; args[4] = append; args[5] = visit;
4431 args[6] = lockname;
4432 coding_systems = Ffind_operation_coding_system (7, args);
4433 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4434 val = XCDR (coding_systems);
4437 if (NILP (val))
4439 /* If we still have not decided a coding system, use the
4440 default value of buffer-file-coding-system. */
4441 val = current_buffer->buffer_file_coding_system;
4442 using_default_coding = 1;
4445 if (! NILP (val) && ! force_raw_text)
4447 Lisp_Object spec, attrs;
4449 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4450 attrs = AREF (spec, 0);
4451 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4452 force_raw_text = 1;
4455 if (!force_raw_text
4456 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4457 /* Confirm that VAL can surely encode the current region. */
4458 val = call5 (Vselect_safe_coding_system_function,
4459 start, end, val, Qnil, filename);
4461 /* If the decided coding-system doesn't specify end-of-line
4462 format, we use that of
4463 `default-buffer-file-coding-system'. */
4464 if (! using_default_coding
4465 && ! NILP (buffer_defaults.buffer_file_coding_system))
4466 val = (coding_inherit_eol_type
4467 (val, buffer_defaults.buffer_file_coding_system));
4469 /* If we decide not to encode text, use `raw-text' or one of its
4470 subsidiaries. */
4471 if (force_raw_text)
4472 val = raw_text_coding_system (val);
4475 val = coding_inherit_eol_type (val, eol_parent);
4476 setup_coding_system (val, coding);
4478 if (!STRINGP (start) && !NILP (current_buffer->selective_display))
4479 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4480 return val;
4483 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4484 "r\nFWrite region to file: \ni\ni\ni\np",
4485 doc: /* Write current region into specified file.
4486 When called from a program, requires three arguments:
4487 START, END and FILENAME. START and END are normally buffer positions
4488 specifying the part of the buffer to write.
4489 If START is nil, that means to use the entire buffer contents.
4490 If START is a string, then output that string to the file
4491 instead of any buffer contents; END is ignored.
4493 Optional fourth argument APPEND if non-nil means
4494 append to existing file contents (if any). If it is an integer,
4495 seek to that offset in the file before writing.
4496 Optional fifth argument VISIT, if t or a string, means
4497 set the last-save-file-modtime of buffer to this file's modtime
4498 and mark buffer not modified.
4499 If VISIT is a string, it is a second file name;
4500 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4501 VISIT is also the file name to lock and unlock for clash detection.
4502 If VISIT is neither t nor nil nor a string,
4503 that means do not display the \"Wrote file\" message.
4504 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4505 use for locking and unlocking, overriding FILENAME and VISIT.
4506 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4507 for an existing file with the same name. If MUSTBENEW is `excl',
4508 that means to get an error if the file already exists; never overwrite.
4509 If MUSTBENEW is neither nil nor `excl', that means ask for
4510 confirmation before overwriting, but do go ahead and overwrite the file
4511 if the user confirms.
4513 This does code conversion according to the value of
4514 `coding-system-for-write', `buffer-file-coding-system', or
4515 `file-coding-system-alist', and sets the variable
4516 `last-coding-system-used' to the coding system actually used.
4518 This calls `write-region-annotate-functions' at the start, and
4519 `write-region-post-annotation-function' at the end. */)
4520 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append, Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4522 register int desc;
4523 int failure;
4524 int save_errno = 0;
4525 const unsigned char *fn;
4526 struct stat st;
4527 int count = SPECPDL_INDEX ();
4528 int count1;
4529 Lisp_Object handler;
4530 Lisp_Object visit_file;
4531 Lisp_Object annotations;
4532 Lisp_Object encoded_filename;
4533 int visiting = (EQ (visit, Qt) || STRINGP (visit));
4534 int quietly = !NILP (visit);
4535 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4536 struct buffer *given_buffer;
4537 #ifdef DOS_NT
4538 int buffer_file_type = O_BINARY;
4539 #endif /* DOS_NT */
4540 struct coding_system coding;
4542 if (current_buffer->base_buffer && visiting)
4543 error ("Cannot do file visiting in an indirect buffer");
4545 if (!NILP (start) && !STRINGP (start))
4546 validate_region (&start, &end);
4548 visit_file = Qnil;
4549 GCPRO5 (start, filename, visit, visit_file, lockname);
4551 filename = Fexpand_file_name (filename, Qnil);
4553 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4554 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4556 if (STRINGP (visit))
4557 visit_file = Fexpand_file_name (visit, Qnil);
4558 else
4559 visit_file = filename;
4561 if (NILP (lockname))
4562 lockname = visit_file;
4564 annotations = Qnil;
4566 /* If the file name has special constructs in it,
4567 call the corresponding file handler. */
4568 handler = Ffind_file_name_handler (filename, Qwrite_region);
4569 /* If FILENAME has no handler, see if VISIT has one. */
4570 if (NILP (handler) && STRINGP (visit))
4571 handler = Ffind_file_name_handler (visit, Qwrite_region);
4573 if (!NILP (handler))
4575 Lisp_Object val;
4576 val = call6 (handler, Qwrite_region, start, end,
4577 filename, append, visit);
4579 if (visiting)
4581 SAVE_MODIFF = MODIFF;
4582 XSETFASTINT (current_buffer->save_length, Z - BEG);
4583 current_buffer->filename = visit_file;
4585 UNGCPRO;
4586 return val;
4589 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4591 /* Special kludge to simplify auto-saving. */
4592 if (NILP (start))
4594 /* Do it later, so write-region-annotate-function can work differently
4595 if we save "the buffer" vs "a region".
4596 This is useful in tar-mode. --Stef
4597 XSETFASTINT (start, BEG);
4598 XSETFASTINT (end, Z); */
4599 Fwiden ();
4602 record_unwind_protect (build_annotations_unwind,
4603 Vwrite_region_annotation_buffers);
4604 Vwrite_region_annotation_buffers = Fcons (Fcurrent_buffer (), Qnil);
4605 count1 = SPECPDL_INDEX ();
4607 given_buffer = current_buffer;
4609 if (!STRINGP (start))
4611 annotations = build_annotations (start, end);
4613 if (current_buffer != given_buffer)
4615 XSETFASTINT (start, BEGV);
4616 XSETFASTINT (end, ZV);
4620 if (NILP (start))
4622 XSETFASTINT (start, BEGV);
4623 XSETFASTINT (end, ZV);
4626 UNGCPRO;
4628 GCPRO5 (start, filename, annotations, visit_file, lockname);
4630 /* Decide the coding-system to encode the data with.
4631 We used to make this choice before calling build_annotations, but that
4632 leads to problems when a write-annotate-function takes care of
4633 unsavable chars (as was the case with X-Symbol). */
4634 Vlast_coding_system_used
4635 = choose_write_coding_system (start, end, filename,
4636 append, visit, lockname, &coding);
4638 #ifdef CLASH_DETECTION
4639 if (!auto_saving)
4640 lock_file (lockname);
4641 #endif /* CLASH_DETECTION */
4643 encoded_filename = ENCODE_FILE (filename);
4645 fn = SDATA (encoded_filename);
4646 desc = -1;
4647 if (!NILP (append))
4648 #ifdef DOS_NT
4649 desc = emacs_open (fn, O_WRONLY | buffer_file_type, 0);
4650 #else /* not DOS_NT */
4651 desc = emacs_open (fn, O_WRONLY, 0);
4652 #endif /* not DOS_NT */
4654 if (desc < 0 && (NILP (append) || errno == ENOENT))
4655 #ifdef DOS_NT
4656 desc = emacs_open (fn,
4657 O_WRONLY | O_CREAT | buffer_file_type
4658 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
4659 S_IREAD | S_IWRITE);
4660 #else /* not DOS_NT */
4661 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
4662 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
4663 auto_saving ? auto_save_mode_bits : 0666);
4664 #endif /* not DOS_NT */
4666 if (desc < 0)
4668 #ifdef CLASH_DETECTION
4669 save_errno = errno;
4670 if (!auto_saving) unlock_file (lockname);
4671 errno = save_errno;
4672 #endif /* CLASH_DETECTION */
4673 UNGCPRO;
4674 report_file_error ("Opening output file", Fcons (filename, Qnil));
4677 record_unwind_protect (close_file_unwind, make_number (desc));
4679 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
4681 long ret;
4683 if (NUMBERP (append))
4684 ret = lseek (desc, XINT (append), 1);
4685 else
4686 ret = lseek (desc, 0, 2);
4687 if (ret < 0)
4689 #ifdef CLASH_DETECTION
4690 if (!auto_saving) unlock_file (lockname);
4691 #endif /* CLASH_DETECTION */
4692 UNGCPRO;
4693 report_file_error ("Lseek error", Fcons (filename, Qnil));
4697 UNGCPRO;
4699 failure = 0;
4700 immediate_quit = 1;
4702 if (STRINGP (start))
4704 failure = 0 > a_write (desc, start, 0, SCHARS (start),
4705 &annotations, &coding);
4706 save_errno = errno;
4708 else if (XINT (start) != XINT (end))
4710 failure = 0 > a_write (desc, Qnil,
4711 XINT (start), XINT (end) - XINT (start),
4712 &annotations, &coding);
4713 save_errno = errno;
4715 else
4717 /* If file was empty, still need to write the annotations */
4718 coding.mode |= CODING_MODE_LAST_BLOCK;
4719 failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4720 save_errno = errno;
4723 if (CODING_REQUIRE_FLUSHING (&coding)
4724 && !(coding.mode & CODING_MODE_LAST_BLOCK)
4725 && ! failure)
4727 /* We have to flush out a data. */
4728 coding.mode |= CODING_MODE_LAST_BLOCK;
4729 failure = 0 > e_write (desc, Qnil, 1, 1, &coding);
4730 save_errno = errno;
4733 immediate_quit = 0;
4735 #ifdef HAVE_FSYNC
4736 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4737 Disk full in NFS may be reported here. */
4738 /* mib says that closing the file will try to write as fast as NFS can do
4739 it, and that means the fsync here is not crucial for autosave files. */
4740 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
4742 /* If fsync fails with EINTR, don't treat that as serious. Also
4743 ignore EINVAL which happens when fsync is not supported on this
4744 file. */
4745 if (errno != EINTR && errno != EINVAL)
4746 failure = 1, save_errno = errno;
4748 #endif
4750 /* NFS can report a write failure now. */
4751 if (emacs_close (desc) < 0)
4752 failure = 1, save_errno = errno;
4754 stat (fn, &st);
4756 /* Discard the unwind protect for close_file_unwind. */
4757 specpdl_ptr = specpdl + count1;
4759 /* Call write-region-post-annotation-function. */
4760 while (CONSP (Vwrite_region_annotation_buffers))
4762 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4763 if (!NILP (Fbuffer_live_p (buf)))
4765 Fset_buffer (buf);
4766 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4767 call0 (Vwrite_region_post_annotation_function);
4769 Vwrite_region_annotation_buffers
4770 = XCDR (Vwrite_region_annotation_buffers);
4773 unbind_to (count, Qnil);
4775 #ifdef CLASH_DETECTION
4776 if (!auto_saving)
4777 unlock_file (lockname);
4778 #endif /* CLASH_DETECTION */
4780 /* Do this before reporting IO error
4781 to avoid a "file has changed on disk" warning on
4782 next attempt to save. */
4783 if (visiting)
4785 current_buffer->modtime = st.st_mtime;
4786 current_buffer->modtime_size = st.st_size;
4789 if (failure)
4790 error ("IO error writing %s: %s", SDATA (filename),
4791 emacs_strerror (save_errno));
4793 if (visiting)
4795 SAVE_MODIFF = MODIFF;
4796 XSETFASTINT (current_buffer->save_length, Z - BEG);
4797 current_buffer->filename = visit_file;
4798 update_mode_lines++;
4800 else if (quietly)
4802 if (auto_saving
4803 && ! NILP (Fstring_equal (current_buffer->filename,
4804 current_buffer->auto_save_file_name)))
4805 SAVE_MODIFF = MODIFF;
4807 return Qnil;
4810 if (!auto_saving)
4811 message_with_string ((INTEGERP (append)
4812 ? "Updated %s"
4813 : ! NILP (append)
4814 ? "Added to %s"
4815 : "Wrote %s"),
4816 visit_file, 1);
4818 return Qnil;
4821 Lisp_Object merge (Lisp_Object, Lisp_Object, Lisp_Object);
4823 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4824 doc: /* Return t if (car A) is numerically less than (car B). */)
4825 (Lisp_Object a, Lisp_Object b)
4827 return Flss (Fcar (a), Fcar (b));
4830 /* Build the complete list of annotations appropriate for writing out
4831 the text between START and END, by calling all the functions in
4832 write-region-annotate-functions and merging the lists they return.
4833 If one of these functions switches to a different buffer, we assume
4834 that buffer contains altered text. Therefore, the caller must
4835 make sure to restore the current buffer in all cases,
4836 as save-excursion would do. */
4838 static Lisp_Object
4839 build_annotations (Lisp_Object start, Lisp_Object end)
4841 Lisp_Object annotations;
4842 Lisp_Object p, res;
4843 struct gcpro gcpro1, gcpro2;
4844 Lisp_Object original_buffer;
4845 int i, used_global = 0;
4847 XSETBUFFER (original_buffer, current_buffer);
4849 annotations = Qnil;
4850 p = Vwrite_region_annotate_functions;
4851 GCPRO2 (annotations, p);
4852 while (CONSP (p))
4854 struct buffer *given_buffer = current_buffer;
4855 if (EQ (Qt, XCAR (p)) && !used_global)
4856 { /* Use the global value of the hook. */
4857 Lisp_Object arg[2];
4858 used_global = 1;
4859 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
4860 arg[1] = XCDR (p);
4861 p = Fappend (2, arg);
4862 continue;
4864 Vwrite_region_annotations_so_far = annotations;
4865 res = call2 (XCAR (p), start, end);
4866 /* If the function makes a different buffer current,
4867 assume that means this buffer contains altered text to be output.
4868 Reset START and END from the buffer bounds
4869 and discard all previous annotations because they should have
4870 been dealt with by this function. */
4871 if (current_buffer != given_buffer)
4873 Vwrite_region_annotation_buffers
4874 = Fcons (Fcurrent_buffer (),
4875 Vwrite_region_annotation_buffers);
4876 XSETFASTINT (start, BEGV);
4877 XSETFASTINT (end, ZV);
4878 annotations = Qnil;
4880 Flength (res); /* Check basic validity of return value */
4881 annotations = merge (annotations, res, Qcar_less_than_car);
4882 p = XCDR (p);
4885 /* Now do the same for annotation functions implied by the file-format */
4886 if (auto_saving && (!EQ (current_buffer->auto_save_file_format, Qt)))
4887 p = current_buffer->auto_save_file_format;
4888 else
4889 p = current_buffer->file_format;
4890 for (i = 0; CONSP (p); p = XCDR (p), ++i)
4892 struct buffer *given_buffer = current_buffer;
4894 Vwrite_region_annotations_so_far = annotations;
4896 /* Value is either a list of annotations or nil if the function
4897 has written annotations to a temporary buffer, which is now
4898 current. */
4899 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
4900 original_buffer, make_number (i));
4901 if (current_buffer != given_buffer)
4903 XSETFASTINT (start, BEGV);
4904 XSETFASTINT (end, ZV);
4905 annotations = Qnil;
4908 if (CONSP (res))
4909 annotations = merge (annotations, res, Qcar_less_than_car);
4912 UNGCPRO;
4913 return annotations;
4917 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
4918 If STRING is nil, POS is the character position in the current buffer.
4919 Intersperse with them the annotations from *ANNOT
4920 which fall within the range of POS to POS + NCHARS,
4921 each at its appropriate position.
4923 We modify *ANNOT by discarding elements as we use them up.
4925 The return value is negative in case of system call failure. */
4927 static int
4928 a_write (int desc, Lisp_Object string, int pos, register int nchars, Lisp_Object *annot, struct coding_system *coding)
4930 Lisp_Object tem;
4931 int nextpos;
4932 int lastpos = pos + nchars;
4934 while (NILP (*annot) || CONSP (*annot))
4936 tem = Fcar_safe (Fcar (*annot));
4937 nextpos = pos - 1;
4938 if (INTEGERP (tem))
4939 nextpos = XFASTINT (tem);
4941 /* If there are no more annotations in this range,
4942 output the rest of the range all at once. */
4943 if (! (nextpos >= pos && nextpos <= lastpos))
4944 return e_write (desc, string, pos, lastpos, coding);
4946 /* Output buffer text up to the next annotation's position. */
4947 if (nextpos > pos)
4949 if (0 > e_write (desc, string, pos, nextpos, coding))
4950 return -1;
4951 pos = nextpos;
4953 /* Output the annotation. */
4954 tem = Fcdr (Fcar (*annot));
4955 if (STRINGP (tem))
4957 if (0 > e_write (desc, tem, 0, SCHARS (tem), coding))
4958 return -1;
4960 *annot = Fcdr (*annot);
4962 return 0;
4966 /* Write text in the range START and END into descriptor DESC,
4967 encoding them with coding system CODING. If STRING is nil, START
4968 and END are character positions of the current buffer, else they
4969 are indexes to the string STRING. */
4971 static int
4972 e_write (int desc, Lisp_Object string, int start, int end, struct coding_system *coding)
4974 if (STRINGP (string))
4976 start = 0;
4977 end = SCHARS (string);
4980 /* We used to have a code for handling selective display here. But,
4981 now it is handled within encode_coding. */
4983 while (start < end)
4985 if (STRINGP (string))
4987 coding->src_multibyte = SCHARS (string) < SBYTES (string);
4988 if (CODING_REQUIRE_ENCODING (coding))
4990 encode_coding_object (coding, string,
4991 start, string_char_to_byte (string, start),
4992 end, string_char_to_byte (string, end), Qt);
4994 else
4996 coding->dst_object = string;
4997 coding->consumed_char = SCHARS (string);
4998 coding->produced = SBYTES (string);
5001 else
5003 int start_byte = CHAR_TO_BYTE (start);
5004 int end_byte = CHAR_TO_BYTE (end);
5006 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5007 if (CODING_REQUIRE_ENCODING (coding))
5009 encode_coding_object (coding, Fcurrent_buffer (),
5010 start, start_byte, end, end_byte, Qt);
5012 else
5014 coding->dst_object = Qnil;
5015 coding->dst_pos_byte = start_byte;
5016 if (start >= GPT || end <= GPT)
5018 coding->consumed_char = end - start;
5019 coding->produced = end_byte - start_byte;
5021 else
5023 coding->consumed_char = GPT - start;
5024 coding->produced = GPT_BYTE - start_byte;
5029 if (coding->produced > 0)
5031 coding->produced -=
5032 emacs_write (desc,
5033 STRINGP (coding->dst_object)
5034 ? SDATA (coding->dst_object)
5035 : BYTE_POS_ADDR (coding->dst_pos_byte),
5036 coding->produced);
5038 if (coding->produced)
5039 return -1;
5041 start += coding->consumed_char;
5044 return 0;
5047 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5048 Sverify_visited_file_modtime, 0, 1, 0,
5049 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5050 This means that the file has not been changed since it was visited or saved.
5051 If BUF is omitted or nil, it defaults to the current buffer.
5052 See Info node `(elisp)Modification Time' for more details. */)
5053 (Lisp_Object buf)
5055 struct buffer *b;
5056 struct stat st;
5057 Lisp_Object handler;
5058 Lisp_Object filename;
5060 if (NILP (buf))
5061 b = current_buffer;
5062 else
5064 CHECK_BUFFER (buf);
5065 b = XBUFFER (buf);
5068 if (!STRINGP (b->filename)) return Qt;
5069 if (b->modtime == 0) return Qt;
5071 /* If the file name has special constructs in it,
5072 call the corresponding file handler. */
5073 handler = Ffind_file_name_handler (b->filename,
5074 Qverify_visited_file_modtime);
5075 if (!NILP (handler))
5076 return call2 (handler, Qverify_visited_file_modtime, buf);
5078 filename = ENCODE_FILE (b->filename);
5080 if (stat (SDATA (filename), &st) < 0)
5082 /* If the file doesn't exist now and didn't exist before,
5083 we say that it isn't modified, provided the error is a tame one. */
5084 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
5085 st.st_mtime = -1;
5086 else
5087 st.st_mtime = 0;
5089 if ((st.st_mtime == b->modtime
5090 /* If both are positive, accept them if they are off by one second. */
5091 || (st.st_mtime > 0 && b->modtime > 0
5092 && (st.st_mtime == b->modtime + 1
5093 || st.st_mtime == b->modtime - 1)))
5094 && (st.st_size == b->modtime_size
5095 || b->modtime_size < 0))
5096 return Qt;
5097 return Qnil;
5100 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5101 Sclear_visited_file_modtime, 0, 0, 0,
5102 doc: /* Clear out records of last mod time of visited file.
5103 Next attempt to save will certainly not complain of a discrepancy. */)
5104 (void)
5106 current_buffer->modtime = 0;
5107 current_buffer->modtime_size = -1;
5108 return Qnil;
5111 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5112 Svisited_file_modtime, 0, 0, 0,
5113 doc: /* Return the current buffer's recorded visited file modification time.
5114 The value is a list of the form (HIGH LOW), like the time values
5115 that `file-attributes' returns. If the current buffer has no recorded
5116 file modification time, this function returns 0.
5117 See Info node `(elisp)Modification Time' for more details. */)
5118 (void)
5120 if (! current_buffer->modtime)
5121 return make_number (0);
5122 return make_time ((time_t) current_buffer->modtime);
5125 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5126 Sset_visited_file_modtime, 0, 1, 0,
5127 doc: /* Update buffer's recorded modification time from the visited file's time.
5128 Useful if the buffer was not read from the file normally
5129 or if the file itself has been changed for some known benign reason.
5130 An argument specifies the modification time value to use
5131 \(instead of that of the visited file), in the form of a list
5132 \(HIGH . LOW) or (HIGH LOW). */)
5133 (Lisp_Object time_list)
5135 if (!NILP (time_list))
5137 current_buffer->modtime = cons_to_long (time_list);
5138 current_buffer->modtime_size = -1;
5140 else
5142 register Lisp_Object filename;
5143 struct stat st;
5144 Lisp_Object handler;
5146 filename = Fexpand_file_name (current_buffer->filename, Qnil);
5148 /* If the file name has special constructs in it,
5149 call the corresponding file handler. */
5150 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5151 if (!NILP (handler))
5152 /* The handler can find the file name the same way we did. */
5153 return call2 (handler, Qset_visited_file_modtime, Qnil);
5155 filename = ENCODE_FILE (filename);
5157 if (stat (SDATA (filename), &st) >= 0)
5159 current_buffer->modtime = st.st_mtime;
5160 current_buffer->modtime_size = st.st_size;
5164 return Qnil;
5167 Lisp_Object
5168 auto_save_error (Lisp_Object error)
5170 Lisp_Object args[3], msg;
5171 int i, nbytes;
5172 struct gcpro gcpro1;
5173 char *msgbuf;
5174 USE_SAFE_ALLOCA;
5176 auto_save_error_occurred = 1;
5178 ring_bell (XFRAME (selected_frame));
5180 args[0] = build_string ("Auto-saving %s: %s");
5181 args[1] = current_buffer->name;
5182 args[2] = Ferror_message_string (error);
5183 msg = Fformat (3, args);
5184 GCPRO1 (msg);
5185 nbytes = SBYTES (msg);
5186 SAFE_ALLOCA (msgbuf, char *, nbytes);
5187 memcpy (msgbuf, SDATA (msg), nbytes);
5189 for (i = 0; i < 3; ++i)
5191 if (i == 0)
5192 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5193 else
5194 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5195 Fsleep_for (make_number (1), Qnil);
5198 SAFE_FREE ();
5199 UNGCPRO;
5200 return Qnil;
5203 Lisp_Object
5204 auto_save_1 (void)
5206 struct stat st;
5207 Lisp_Object modes;
5209 auto_save_mode_bits = 0666;
5211 /* Get visited file's mode to become the auto save file's mode. */
5212 if (! NILP (current_buffer->filename))
5214 if (stat (SDATA (current_buffer->filename), &st) >= 0)
5215 /* But make sure we can overwrite it later! */
5216 auto_save_mode_bits = st.st_mode | 0600;
5217 else if ((modes = Ffile_modes (current_buffer->filename),
5218 INTEGERP (modes)))
5219 /* Remote files don't cooperate with stat. */
5220 auto_save_mode_bits = XINT (modes) | 0600;
5223 return
5224 Fwrite_region (Qnil, Qnil, current_buffer->auto_save_file_name, Qnil,
5225 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5226 Qnil, Qnil);
5229 static Lisp_Object
5230 do_auto_save_unwind (Lisp_Object arg) /* used as unwind-protect function */
5233 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5234 auto_saving = 0;
5235 if (stream != NULL)
5237 BLOCK_INPUT;
5238 fclose (stream);
5239 UNBLOCK_INPUT;
5241 return Qnil;
5244 static Lisp_Object
5245 do_auto_save_unwind_1 (Lisp_Object value) /* used as unwind-protect function */
5248 minibuffer_auto_raise = XINT (value);
5249 return Qnil;
5252 static Lisp_Object
5253 do_auto_save_make_dir (Lisp_Object dir)
5255 Lisp_Object mode;
5257 call2 (Qmake_directory, dir, Qt);
5258 XSETFASTINT (mode, 0700);
5259 return Fset_file_modes (dir, mode);
5262 static Lisp_Object
5263 do_auto_save_eh (Lisp_Object ignore)
5265 return Qnil;
5268 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5269 doc: /* Auto-save all buffers that need it.
5270 This is all buffers that have auto-saving enabled
5271 and are changed since last auto-saved.
5272 Auto-saving writes the buffer into a file
5273 so that your editing is not lost if the system crashes.
5274 This file is not the file you visited; that changes only when you save.
5275 Normally we run the normal hook `auto-save-hook' before saving.
5277 A non-nil NO-MESSAGE argument means do not print any message if successful.
5278 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5279 (Lisp_Object no_message, Lisp_Object current_only)
5281 struct buffer *old = current_buffer, *b;
5282 Lisp_Object tail, buf;
5283 int auto_saved = 0;
5284 int do_handled_files;
5285 Lisp_Object oquit;
5286 FILE *stream = NULL;
5287 int count = SPECPDL_INDEX ();
5288 int orig_minibuffer_auto_raise = minibuffer_auto_raise;
5289 int old_message_p = 0;
5290 struct gcpro gcpro1, gcpro2;
5292 if (max_specpdl_size < specpdl_size + 40)
5293 max_specpdl_size = specpdl_size + 40;
5295 if (minibuf_level)
5296 no_message = Qt;
5298 if (NILP (no_message))
5300 old_message_p = push_message ();
5301 record_unwind_protect (pop_message_unwind, Qnil);
5304 /* Ordinarily don't quit within this function,
5305 but don't make it impossible to quit (in case we get hung in I/O). */
5306 oquit = Vquit_flag;
5307 Vquit_flag = Qnil;
5309 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5310 point to non-strings reached from Vbuffer_alist. */
5312 if (!NILP (Vrun_hooks))
5313 call1 (Vrun_hooks, intern ("auto-save-hook"));
5315 if (STRINGP (Vauto_save_list_file_name))
5317 Lisp_Object listfile;
5319 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5321 /* Don't try to create the directory when shutting down Emacs,
5322 because creating the directory might signal an error, and
5323 that would leave Emacs in a strange state. */
5324 if (!NILP (Vrun_hooks))
5326 Lisp_Object dir;
5327 dir = Qnil;
5328 GCPRO2 (dir, listfile);
5329 dir = Ffile_name_directory (listfile);
5330 if (NILP (Ffile_directory_p (dir)))
5331 internal_condition_case_1 (do_auto_save_make_dir,
5332 dir, Fcons (Fcons (Qfile_error, Qnil), Qnil),
5333 do_auto_save_eh);
5334 UNGCPRO;
5337 stream = fopen (SDATA (listfile), "w");
5340 record_unwind_protect (do_auto_save_unwind,
5341 make_save_value (stream, 0));
5342 record_unwind_protect (do_auto_save_unwind_1,
5343 make_number (minibuffer_auto_raise));
5344 minibuffer_auto_raise = 0;
5345 auto_saving = 1;
5346 auto_save_error_occurred = 0;
5348 /* On first pass, save all files that don't have handlers.
5349 On second pass, save all files that do have handlers.
5351 If Emacs is crashing, the handlers may tweak what is causing
5352 Emacs to crash in the first place, and it would be a shame if
5353 Emacs failed to autosave perfectly ordinary files because it
5354 couldn't handle some ange-ftp'd file. */
5356 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5357 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5359 buf = XCDR (XCAR (tail));
5360 b = XBUFFER (buf);
5362 /* Record all the buffers that have auto save mode
5363 in the special file that lists them. For each of these buffers,
5364 Record visited name (if any) and auto save name. */
5365 if (STRINGP (b->auto_save_file_name)
5366 && stream != NULL && do_handled_files == 0)
5368 BLOCK_INPUT;
5369 if (!NILP (b->filename))
5371 fwrite (SDATA (b->filename), 1,
5372 SBYTES (b->filename), stream);
5374 putc ('\n', stream);
5375 fwrite (SDATA (b->auto_save_file_name), 1,
5376 SBYTES (b->auto_save_file_name), stream);
5377 putc ('\n', stream);
5378 UNBLOCK_INPUT;
5381 if (!NILP (current_only)
5382 && b != current_buffer)
5383 continue;
5385 /* Don't auto-save indirect buffers.
5386 The base buffer takes care of it. */
5387 if (b->base_buffer)
5388 continue;
5390 /* Check for auto save enabled
5391 and file changed since last auto save
5392 and file changed since last real save. */
5393 if (STRINGP (b->auto_save_file_name)
5394 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5395 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5396 /* -1 means we've turned off autosaving for a while--see below. */
5397 && XINT (b->save_length) >= 0
5398 && (do_handled_files
5399 || NILP (Ffind_file_name_handler (b->auto_save_file_name,
5400 Qwrite_region))))
5402 EMACS_TIME before_time, after_time;
5404 EMACS_GET_TIME (before_time);
5406 /* If we had a failure, don't try again for 20 minutes. */
5407 if (b->auto_save_failure_time >= 0
5408 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5409 continue;
5411 set_buffer_internal (b);
5412 if (NILP (Vauto_save_include_big_deletions)
5413 && (XFASTINT (b->save_length) * 10
5414 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5415 /* A short file is likely to change a large fraction;
5416 spare the user annoying messages. */
5417 && XFASTINT (b->save_length) > 5000
5418 /* These messages are frequent and annoying for `*mail*'. */
5419 && !EQ (b->filename, Qnil)
5420 && NILP (no_message))
5422 /* It has shrunk too much; turn off auto-saving here. */
5423 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5424 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5425 b->name, 1);
5426 minibuffer_auto_raise = 0;
5427 /* Turn off auto-saving until there's a real save,
5428 and prevent any more warnings. */
5429 XSETINT (b->save_length, -1);
5430 Fsleep_for (make_number (1), Qnil);
5431 continue;
5433 if (!auto_saved && NILP (no_message))
5434 message1 ("Auto-saving...");
5435 internal_condition_case (auto_save_1, Qt, auto_save_error);
5436 auto_saved++;
5437 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5438 XSETFASTINT (current_buffer->save_length, Z - BEG);
5439 set_buffer_internal (old);
5441 EMACS_GET_TIME (after_time);
5443 /* If auto-save took more than 60 seconds,
5444 assume it was an NFS failure that got a timeout. */
5445 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5446 b->auto_save_failure_time = EMACS_SECS (after_time);
5450 /* Prevent another auto save till enough input events come in. */
5451 record_auto_save ();
5453 if (auto_saved && NILP (no_message))
5455 if (old_message_p)
5457 /* If we are going to restore an old message,
5458 give time to read ours. */
5459 sit_for (make_number (1), 0, 0);
5460 restore_message ();
5462 else if (!auto_save_error_occurred)
5463 /* Don't overwrite the error message if an error occurred.
5464 If we displayed a message and then restored a state
5465 with no message, leave a "done" message on the screen. */
5466 message1 ("Auto-saving...done");
5469 Vquit_flag = oquit;
5471 /* This restores the message-stack status. */
5472 unbind_to (count, Qnil);
5473 return Qnil;
5476 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5477 Sset_buffer_auto_saved, 0, 0, 0,
5478 doc: /* Mark current buffer as auto-saved with its current text.
5479 No auto-save file will be written until the buffer changes again. */)
5480 (void)
5482 /* FIXME: This should not be called in indirect buffers, since
5483 they're not autosaved. */
5484 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5485 XSETFASTINT (current_buffer->save_length, Z - BEG);
5486 current_buffer->auto_save_failure_time = -1;
5487 return Qnil;
5490 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5491 Sclear_buffer_auto_save_failure, 0, 0, 0,
5492 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5493 (void)
5495 current_buffer->auto_save_failure_time = -1;
5496 return Qnil;
5499 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5500 0, 0, 0,
5501 doc: /* Return t if current buffer has been auto-saved recently.
5502 More precisely, if it has been auto-saved since last read from or saved
5503 in the visited file. If the buffer has no visited file,
5504 then any auto-save counts as "recent". */)
5505 (void)
5507 /* FIXME: maybe we should return nil for indirect buffers since
5508 they're never autosaved. */
5509 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5512 /* Reading and completing file names */
5514 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5515 Snext_read_file_uses_dialog_p, 0, 0, 0,
5516 doc: /* Return t if a call to `read-file-name' will use a dialog.
5517 The return value is only relevant for a call to `read-file-name' that happens
5518 before any other event (mouse or keypress) is handled. */)
5519 (void)
5521 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK)
5522 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5523 && use_dialog_box
5524 && use_file_dialog
5525 && have_menus_p ())
5526 return Qt;
5527 #endif
5528 return Qnil;
5531 Lisp_Object
5532 Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
5534 struct gcpro gcpro1, gcpro2;
5535 Lisp_Object args[7];
5537 GCPRO1 (default_filename);
5538 args[0] = intern ("read-file-name");
5539 args[1] = prompt;
5540 args[2] = dir;
5541 args[3] = default_filename;
5542 args[4] = mustmatch;
5543 args[5] = initial;
5544 args[6] = predicate;
5545 RETURN_UNGCPRO (Ffuncall (7, args));
5549 void
5550 syms_of_fileio (void)
5552 Qoperations = intern_c_string ("operations");
5553 Qexpand_file_name = intern_c_string ("expand-file-name");
5554 Qsubstitute_in_file_name = intern_c_string ("substitute-in-file-name");
5555 Qdirectory_file_name = intern_c_string ("directory-file-name");
5556 Qfile_name_directory = intern_c_string ("file-name-directory");
5557 Qfile_name_nondirectory = intern_c_string ("file-name-nondirectory");
5558 Qunhandled_file_name_directory = intern_c_string ("unhandled-file-name-directory");
5559 Qfile_name_as_directory = intern_c_string ("file-name-as-directory");
5560 Qcopy_file = intern_c_string ("copy-file");
5561 Qmake_directory_internal = intern_c_string ("make-directory-internal");
5562 Qmake_directory = intern_c_string ("make-directory");
5563 Qdelete_directory_internal = intern_c_string ("delete-directory-internal");
5564 Qdelete_file = intern_c_string ("delete-file");
5565 Qrename_file = intern_c_string ("rename-file");
5566 Qadd_name_to_file = intern_c_string ("add-name-to-file");
5567 Qmake_symbolic_link = intern_c_string ("make-symbolic-link");
5568 Qfile_exists_p = intern_c_string ("file-exists-p");
5569 Qfile_executable_p = intern_c_string ("file-executable-p");
5570 Qfile_readable_p = intern_c_string ("file-readable-p");
5571 Qfile_writable_p = intern_c_string ("file-writable-p");
5572 Qfile_symlink_p = intern_c_string ("file-symlink-p");
5573 Qaccess_file = intern_c_string ("access-file");
5574 Qfile_directory_p = intern_c_string ("file-directory-p");
5575 Qfile_regular_p = intern_c_string ("file-regular-p");
5576 Qfile_accessible_directory_p = intern_c_string ("file-accessible-directory-p");
5577 Qfile_modes = intern_c_string ("file-modes");
5578 Qset_file_modes = intern_c_string ("set-file-modes");
5579 Qset_file_times = intern_c_string ("set-file-times");
5580 Qfile_selinux_context = intern_c_string("file-selinux-context");
5581 Qset_file_selinux_context = intern_c_string("set-file-selinux-context");
5582 Qfile_newer_than_file_p = intern_c_string ("file-newer-than-file-p");
5583 Qinsert_file_contents = intern_c_string ("insert-file-contents");
5584 Qwrite_region = intern_c_string ("write-region");
5585 Qverify_visited_file_modtime = intern_c_string ("verify-visited-file-modtime");
5586 Qset_visited_file_modtime = intern_c_string ("set-visited-file-modtime");
5587 Qauto_save_coding = intern_c_string ("auto-save-coding");
5589 staticpro (&Qoperations);
5590 staticpro (&Qexpand_file_name);
5591 staticpro (&Qsubstitute_in_file_name);
5592 staticpro (&Qdirectory_file_name);
5593 staticpro (&Qfile_name_directory);
5594 staticpro (&Qfile_name_nondirectory);
5595 staticpro (&Qunhandled_file_name_directory);
5596 staticpro (&Qfile_name_as_directory);
5597 staticpro (&Qcopy_file);
5598 staticpro (&Qmake_directory_internal);
5599 staticpro (&Qmake_directory);
5600 staticpro (&Qdelete_directory_internal);
5601 staticpro (&Qdelete_file);
5602 staticpro (&Qrename_file);
5603 staticpro (&Qadd_name_to_file);
5604 staticpro (&Qmake_symbolic_link);
5605 staticpro (&Qfile_exists_p);
5606 staticpro (&Qfile_executable_p);
5607 staticpro (&Qfile_readable_p);
5608 staticpro (&Qfile_writable_p);
5609 staticpro (&Qaccess_file);
5610 staticpro (&Qfile_symlink_p);
5611 staticpro (&Qfile_directory_p);
5612 staticpro (&Qfile_regular_p);
5613 staticpro (&Qfile_accessible_directory_p);
5614 staticpro (&Qfile_modes);
5615 staticpro (&Qset_file_modes);
5616 staticpro (&Qset_file_times);
5617 staticpro (&Qfile_selinux_context);
5618 staticpro (&Qset_file_selinux_context);
5619 staticpro (&Qfile_newer_than_file_p);
5620 staticpro (&Qinsert_file_contents);
5621 staticpro (&Qwrite_region);
5622 staticpro (&Qverify_visited_file_modtime);
5623 staticpro (&Qset_visited_file_modtime);
5624 staticpro (&Qauto_save_coding);
5626 Qfile_name_history = intern_c_string ("file-name-history");
5627 Fset (Qfile_name_history, Qnil);
5628 staticpro (&Qfile_name_history);
5630 Qfile_error = intern_c_string ("file-error");
5631 staticpro (&Qfile_error);
5632 Qfile_already_exists = intern_c_string ("file-already-exists");
5633 staticpro (&Qfile_already_exists);
5634 Qfile_date_error = intern_c_string ("file-date-error");
5635 staticpro (&Qfile_date_error);
5636 Qexcl = intern_c_string ("excl");
5637 staticpro (&Qexcl);
5639 #ifdef DOS_NT
5640 Qfind_buffer_file_type = intern_c_string ("find-buffer-file-type");
5641 staticpro (&Qfind_buffer_file_type);
5642 #endif /* DOS_NT */
5644 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system,
5645 doc: /* *Coding system for encoding file names.
5646 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5647 Vfile_name_coding_system = Qnil;
5649 DEFVAR_LISP ("default-file-name-coding-system",
5650 &Vdefault_file_name_coding_system,
5651 doc: /* Default coding system for encoding file names.
5652 This variable is used only when `file-name-coding-system' is nil.
5654 This variable is set/changed by the command `set-language-environment'.
5655 User should not set this variable manually,
5656 instead use `file-name-coding-system' to get a constant encoding
5657 of file names regardless of the current language environment. */);
5658 Vdefault_file_name_coding_system = Qnil;
5660 Qformat_decode = intern_c_string ("format-decode");
5661 staticpro (&Qformat_decode);
5662 Qformat_annotate_function = intern_c_string ("format-annotate-function");
5663 staticpro (&Qformat_annotate_function);
5664 Qafter_insert_file_set_coding = intern_c_string ("after-insert-file-set-coding");
5665 staticpro (&Qafter_insert_file_set_coding);
5667 Qcar_less_than_car = intern_c_string ("car-less-than-car");
5668 staticpro (&Qcar_less_than_car);
5670 Fput (Qfile_error, Qerror_conditions,
5671 Fpurecopy (list2 (Qfile_error, Qerror)));
5672 Fput (Qfile_error, Qerror_message,
5673 make_pure_c_string ("File error"));
5675 Fput (Qfile_already_exists, Qerror_conditions,
5676 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5677 Fput (Qfile_already_exists, Qerror_message,
5678 make_pure_c_string ("File already exists"));
5680 Fput (Qfile_date_error, Qerror_conditions,
5681 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5682 Fput (Qfile_date_error, Qerror_message,
5683 make_pure_c_string ("Cannot set file date"));
5685 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
5686 doc: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
5687 If a file name matches REGEXP, then all I/O on that file is done by calling
5688 HANDLER.
5690 The first argument given to HANDLER is the name of the I/O primitive
5691 to be handled; the remaining arguments are the arguments that were
5692 passed to that primitive. For example, if you do
5693 (file-exists-p FILENAME)
5694 and FILENAME is handled by HANDLER, then HANDLER is called like this:
5695 (funcall HANDLER 'file-exists-p FILENAME)
5696 The function `find-file-name-handler' checks this list for a handler
5697 for its argument. */);
5698 Vfile_name_handler_alist = Qnil;
5700 DEFVAR_LISP ("set-auto-coding-function",
5701 &Vset_auto_coding_function,
5702 doc: /* If non-nil, a function to call to decide a coding system of file.
5703 Two arguments are passed to this function: the file name
5704 and the length of a file contents following the point.
5705 This function should return a coding system to decode the file contents.
5706 It should check the file name against `auto-coding-alist'.
5707 If no coding system is decided, it should check a coding system
5708 specified in the heading lines with the format:
5709 -*- ... coding: CODING-SYSTEM; ... -*-
5710 or local variable spec of the tailing lines with `coding:' tag. */);
5711 Vset_auto_coding_function = Qnil;
5713 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
5714 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5715 Each is passed one argument, the number of characters inserted,
5716 with point at the start of the inserted text. Each function
5717 should leave point the same, and return the new character count.
5718 If `insert-file-contents' is intercepted by a handler from
5719 `file-name-handler-alist', that handler is responsible for calling the
5720 functions in `after-insert-file-functions' if appropriate. */);
5721 Vafter_insert_file_functions = Qnil;
5723 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
5724 doc: /* A list of functions to be called at the start of `write-region'.
5725 Each is passed two arguments, START and END as for `write-region'.
5726 These are usually two numbers but not always; see the documentation
5727 for `write-region'. The function should return a list of pairs
5728 of the form (POSITION . STRING), consisting of strings to be effectively
5729 inserted at the specified positions of the file being written (1 means to
5730 insert before the first byte written). The POSITIONs must be sorted into
5731 increasing order.
5733 If there are several annotation functions, the lists returned by these
5734 functions are merged destructively. As each annotation function runs,
5735 the variable `write-region-annotations-so-far' contains a list of all
5736 annotations returned by previous annotation functions.
5738 An annotation function can return with a different buffer current.
5739 Doing so removes the annotations returned by previous functions, and
5740 resets START and END to `point-min' and `point-max' of the new buffer.
5742 After `write-region' completes, Emacs calls the function stored in
5743 `write-region-post-annotation-function', once for each buffer that was
5744 current when building the annotations (i.e., at least once), with that
5745 buffer current. */);
5746 Vwrite_region_annotate_functions = Qnil;
5747 staticpro (&Qwrite_region_annotate_functions);
5748 Qwrite_region_annotate_functions
5749 = intern_c_string ("write-region-annotate-functions");
5751 DEFVAR_LISP ("write-region-post-annotation-function",
5752 &Vwrite_region_post_annotation_function,
5753 doc: /* Function to call after `write-region' completes.
5754 The function is called with no arguments. If one or more of the
5755 annotation functions in `write-region-annotate-functions' changed the
5756 current buffer, the function stored in this variable is called for
5757 each of those additional buffers as well, in addition to the original
5758 buffer. The relevant buffer is current during each function call. */);
5759 Vwrite_region_post_annotation_function = Qnil;
5760 staticpro (&Vwrite_region_annotation_buffers);
5762 DEFVAR_LISP ("write-region-annotations-so-far",
5763 &Vwrite_region_annotations_so_far,
5764 doc: /* When an annotation function is called, this holds the previous annotations.
5765 These are the annotations made by other annotation functions
5766 that were already called. See also `write-region-annotate-functions'. */);
5767 Vwrite_region_annotations_so_far = Qnil;
5769 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
5770 doc: /* A list of file name handlers that temporarily should not be used.
5771 This applies only to the operation `inhibit-file-name-operation'. */);
5772 Vinhibit_file_name_handlers = Qnil;
5774 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
5775 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5776 Vinhibit_file_name_operation = Qnil;
5778 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
5779 doc: /* File name in which we write a list of all auto save file names.
5780 This variable is initialized automatically from `auto-save-list-file-prefix'
5781 shortly after Emacs reads your `.emacs' file, if you have not yet given it
5782 a non-nil value. */);
5783 Vauto_save_list_file_name = Qnil;
5785 DEFVAR_LISP ("auto-save-visited-file-name", &Vauto_save_visited_file_name,
5786 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5787 Normally auto-save files are written under other names. */);
5788 Vauto_save_visited_file_name = Qnil;
5790 DEFVAR_LISP ("auto-save-include-big-deletions", &Vauto_save_include_big_deletions,
5791 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5792 If nil, deleting a substantial portion of the text disables auto-save
5793 in the buffer; this is the default behavior, because the auto-save
5794 file is usually more useful if it contains the deleted text. */);
5795 Vauto_save_include_big_deletions = Qnil;
5797 #ifdef HAVE_FSYNC
5798 DEFVAR_BOOL ("write-region-inhibit-fsync", &write_region_inhibit_fsync,
5799 doc: /* *Non-nil means don't call fsync in `write-region'.
5800 This variable affects calls to `write-region' as well as save commands.
5801 A non-nil value may result in data loss! */);
5802 write_region_inhibit_fsync = 0;
5803 #endif
5805 DEFVAR_BOOL ("delete-by-moving-to-trash", &delete_by_moving_to_trash,
5806 doc: /* Specifies whether to use the system's trash can.
5807 When non-nil, certain file deletion commands use the function
5808 `move-file-to-trash' instead of deleting files outright.
5809 This includes interactive calls to `delete-file' and
5810 `delete-directory' and the Dired deletion commands. */);
5811 delete_by_moving_to_trash = 0;
5812 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
5813 Qmove_file_to_trash = intern_c_string ("move-file-to-trash");
5814 staticpro (&Qmove_file_to_trash);
5815 Qcopy_directory = intern_c_string ("copy-directory");
5816 staticpro (&Qcopy_directory);
5817 Qdelete_directory = intern_c_string ("delete-directory");
5818 staticpro (&Qdelete_directory);
5820 defsubr (&Sfind_file_name_handler);
5821 defsubr (&Sfile_name_directory);
5822 defsubr (&Sfile_name_nondirectory);
5823 defsubr (&Sunhandled_file_name_directory);
5824 defsubr (&Sfile_name_as_directory);
5825 defsubr (&Sdirectory_file_name);
5826 defsubr (&Smake_temp_name);
5827 defsubr (&Sexpand_file_name);
5828 defsubr (&Ssubstitute_in_file_name);
5829 defsubr (&Scopy_file);
5830 defsubr (&Smake_directory_internal);
5831 defsubr (&Sdelete_directory_internal);
5832 defsubr (&Sdelete_file);
5833 defsubr (&Srename_file);
5834 defsubr (&Sadd_name_to_file);
5835 defsubr (&Smake_symbolic_link);
5836 defsubr (&Sfile_name_absolute_p);
5837 defsubr (&Sfile_exists_p);
5838 defsubr (&Sfile_executable_p);
5839 defsubr (&Sfile_readable_p);
5840 defsubr (&Sfile_writable_p);
5841 defsubr (&Saccess_file);
5842 defsubr (&Sfile_symlink_p);
5843 defsubr (&Sfile_directory_p);
5844 defsubr (&Sfile_accessible_directory_p);
5845 defsubr (&Sfile_regular_p);
5846 defsubr (&Sfile_modes);
5847 defsubr (&Sset_file_modes);
5848 defsubr (&Sset_file_times);
5849 defsubr (&Sfile_selinux_context);
5850 defsubr (&Sset_file_selinux_context);
5851 defsubr (&Sset_default_file_modes);
5852 defsubr (&Sdefault_file_modes);
5853 defsubr (&Sfile_newer_than_file_p);
5854 defsubr (&Sinsert_file_contents);
5855 defsubr (&Swrite_region);
5856 defsubr (&Scar_less_than_car);
5857 defsubr (&Sverify_visited_file_modtime);
5858 defsubr (&Sclear_visited_file_modtime);
5859 defsubr (&Svisited_file_modtime);
5860 defsubr (&Sset_visited_file_modtime);
5861 defsubr (&Sdo_auto_save);
5862 defsubr (&Sset_buffer_auto_saved);
5863 defsubr (&Sclear_buffer_auto_save_failure);
5864 defsubr (&Srecent_auto_save_p);
5866 defsubr (&Snext_read_file_uses_dialog_p);
5868 #ifdef HAVE_SYNC
5869 defsubr (&Sunix_sync);
5870 #endif