* lisp/gnus/smime.el (smime-mode): Use define-derived-mode.
[emacs.git] / src / fileio.c
blob36b6cc3ca8bb6af7c30ba5d17fb3eac6bbb9ba11
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995, 1996, 1997,
4 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
5 2009, 2010 Free Software Foundation, Inc.
7 This file is part of GNU Emacs.
9 GNU Emacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 GNU Emacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <setjmp.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
34 #if !defined (S_ISLNK) && defined (S_IFLNK)
35 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
36 #endif
38 #if !defined (S_ISFIFO) && defined (S_IFIFO)
39 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
40 #endif
42 #if !defined (S_ISREG) && defined (S_IFREG)
43 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
44 #endif
46 #ifdef HAVE_PWD_H
47 #include <pwd.h>
48 #endif
50 #include <ctype.h>
51 #include <errno.h>
53 #ifdef HAVE_LIBSELINUX
54 #include <selinux/selinux.h>
55 #include <selinux/context.h>
56 #endif
58 #include "lisp.h"
59 #include "intervals.h"
60 #include "buffer.h"
61 #include "character.h"
62 #include "coding.h"
63 #include "window.h"
64 #include "blockinput.h"
65 #include "frame.h"
66 #include "dispextern.h"
68 #ifdef WINDOWSNT
69 #define NOMINMAX 1
70 #include <windows.h>
71 #include <fcntl.h>
72 #endif /* not WINDOWSNT */
74 #ifdef MSDOS
75 #include "msdos.h"
76 #include <sys/param.h>
77 #include <fcntl.h>
78 #endif
80 #ifdef DOS_NT
81 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
82 redirector allows the six letters between 'Z' and 'a' as well. */
83 #ifdef MSDOS
84 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
85 #endif
86 #ifdef WINDOWSNT
87 #define IS_DRIVE(x) isalpha (x)
88 #endif
89 /* Need to lower-case the drive letter, or else expanded
90 filenames will sometimes compare inequal, because
91 `expand-file-name' doesn't always down-case the drive letter. */
92 #define DRIVE_LETTER(x) (tolower (x))
93 #endif
95 #include "systime.h"
97 #ifdef HPUX
98 #include <netio.h>
99 #endif
101 #include "commands.h"
103 #ifndef S_ISLNK
104 # define lstat stat
105 #endif
107 #ifndef FILE_SYSTEM_CASE
108 #define FILE_SYSTEM_CASE(filename) (filename)
109 #endif
111 /* Nonzero during writing of auto-save files */
112 int auto_saving;
114 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
115 a new file with the same mode as the original */
116 int auto_save_mode_bits;
118 /* Set by auto_save_1 if an error occurred during the last auto-save. */
119 int auto_save_error_occurred;
121 /* The symbol bound to coding-system-for-read when
122 insert-file-contents is called for recovering a file. This is not
123 an actual coding system name, but just an indicator to tell
124 insert-file-contents to use `emacs-mule' with a special flag for
125 auto saving and recovering a file. */
126 Lisp_Object Qauto_save_coding;
128 /* Coding system for file names, or nil if none. */
129 Lisp_Object Vfile_name_coding_system;
131 /* Coding system for file names used only when
132 Vfile_name_coding_system is nil. */
133 Lisp_Object Vdefault_file_name_coding_system;
135 /* Alist of elements (REGEXP . HANDLER) for file names
136 whose I/O is done with a special handler. */
137 Lisp_Object Vfile_name_handler_alist;
139 /* Property name of a file name handler,
140 which gives a list of operations it handles.. */
141 Lisp_Object Qoperations;
143 /* Lisp functions for translating file formats */
144 Lisp_Object Qformat_decode, Qformat_annotate_function;
146 /* Function to be called to decide a coding system of a reading file. */
147 Lisp_Object Vset_auto_coding_function;
149 /* Functions to be called to process text properties in inserted file. */
150 Lisp_Object Vafter_insert_file_functions;
152 /* Lisp function for setting buffer-file-coding-system and the
153 multibyteness of the current buffer after inserting a file. */
154 Lisp_Object Qafter_insert_file_set_coding;
156 /* Functions to be called to create text property annotations for file. */
157 Lisp_Object Vwrite_region_annotate_functions;
158 Lisp_Object Qwrite_region_annotate_functions;
159 Lisp_Object Vwrite_region_post_annotation_function;
161 /* During build_annotations, each time an annotation function is called,
162 this holds the annotations made by the previous functions. */
163 Lisp_Object Vwrite_region_annotations_so_far;
165 /* Each time an annotation function changes the buffer, the new buffer
166 is added here. */
167 Lisp_Object Vwrite_region_annotation_buffers;
169 /* File name in which we write a list of all our auto save files. */
170 Lisp_Object Vauto_save_list_file_name;
172 /* Whether or not files are auto-saved into themselves. */
173 Lisp_Object Vauto_save_visited_file_name;
175 /* Whether or not to continue auto-saving after a large deletion. */
176 Lisp_Object Vauto_save_include_big_deletions;
178 #ifdef HAVE_FSYNC
179 /* Nonzero means skip the call to fsync in Fwrite-region. */
180 int write_region_inhibit_fsync;
181 #endif
183 /* Non-zero means call move-file-to-trash in Fdelete_file or
184 Fdelete_directory_internal. */
185 int delete_by_moving_to_trash;
187 Lisp_Object Qdelete_by_moving_to_trash;
189 /* Lisp function for moving files to trash. */
190 Lisp_Object Qmove_file_to_trash;
192 /* Lisp function for recursively copying directories. */
193 Lisp_Object Qcopy_directory;
195 /* Lisp function for recursively deleting directories. */
196 Lisp_Object Qdelete_directory;
198 #ifdef WINDOWSNT
199 extern Lisp_Object Vw32_get_true_file_attributes;
200 #endif
202 /* These variables describe handlers that have "already" had a chance
203 to handle the current operation.
205 Vinhibit_file_name_handlers is a list of file name handlers.
206 Vinhibit_file_name_operation is the operation being handled.
207 If we try to handle that operation, we ignore those handlers. */
209 static Lisp_Object Vinhibit_file_name_handlers;
210 static Lisp_Object Vinhibit_file_name_operation;
212 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
213 Lisp_Object Qexcl;
214 Lisp_Object Qfile_name_history;
216 Lisp_Object Qcar_less_than_car;
218 static int a_write (int, Lisp_Object, int, int,
219 Lisp_Object *, struct coding_system *);
220 static int e_write (int, Lisp_Object, int, int, struct coding_system *);
223 void
224 report_file_error (const char *string, Lisp_Object data)
226 Lisp_Object errstring;
227 int errorno = errno;
228 char *str;
230 synchronize_system_messages_locale ();
231 str = strerror (errorno);
232 errstring = code_convert_string_norecord (make_unibyte_string (str,
233 strlen (str)),
234 Vlocale_coding_system, 0);
236 while (1)
237 switch (errorno)
239 case EEXIST:
240 xsignal (Qfile_already_exists, Fcons (errstring, data));
241 break;
242 default:
243 /* System error messages are capitalized. Downcase the initial
244 unless it is followed by a slash. (The slash case caters to
245 error messages that begin with "I/O" or, in German, "E/A".) */
246 if (STRING_MULTIBYTE (errstring)
247 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
249 int c;
251 str = (char *) SDATA (errstring);
252 c = STRING_CHAR (str);
253 Faset (errstring, make_number (0), make_number (DOWNCASE (c)));
256 xsignal (Qfile_error,
257 Fcons (build_string (string), Fcons (errstring, data)));
261 Lisp_Object
262 close_file_unwind (Lisp_Object fd)
264 emacs_close (XFASTINT (fd));
265 return Qnil;
268 /* Restore point, having saved it as a marker. */
270 Lisp_Object
271 restore_point_unwind (Lisp_Object location)
273 Fgoto_char (location);
274 Fset_marker (location, Qnil, Qnil);
275 return Qnil;
279 Lisp_Object Qexpand_file_name;
280 Lisp_Object Qsubstitute_in_file_name;
281 Lisp_Object Qdirectory_file_name;
282 Lisp_Object Qfile_name_directory;
283 Lisp_Object Qfile_name_nondirectory;
284 Lisp_Object Qunhandled_file_name_directory;
285 Lisp_Object Qfile_name_as_directory;
286 Lisp_Object Qcopy_file;
287 Lisp_Object Qmake_directory_internal;
288 Lisp_Object Qmake_directory;
289 Lisp_Object Qdelete_directory_internal;
290 Lisp_Object Qdelete_file;
291 Lisp_Object Qrename_file;
292 Lisp_Object Qadd_name_to_file;
293 Lisp_Object Qmake_symbolic_link;
294 Lisp_Object Qfile_exists_p;
295 Lisp_Object Qfile_executable_p;
296 Lisp_Object Qfile_readable_p;
297 Lisp_Object Qfile_writable_p;
298 Lisp_Object Qfile_symlink_p;
299 Lisp_Object Qaccess_file;
300 Lisp_Object Qfile_directory_p;
301 Lisp_Object Qfile_regular_p;
302 Lisp_Object Qfile_accessible_directory_p;
303 Lisp_Object Qfile_modes;
304 Lisp_Object Qset_file_modes;
305 Lisp_Object Qset_file_times;
306 Lisp_Object Qfile_selinux_context;
307 Lisp_Object Qset_file_selinux_context;
308 Lisp_Object Qfile_newer_than_file_p;
309 Lisp_Object Qinsert_file_contents;
310 Lisp_Object Qwrite_region;
311 Lisp_Object Qverify_visited_file_modtime;
312 Lisp_Object Qset_visited_file_modtime;
314 DEFUN ("find-file-name-handler", Ffind_file_name_handler, Sfind_file_name_handler, 2, 2, 0,
315 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
316 Otherwise, return nil.
317 A file name is handled if one of the regular expressions in
318 `file-name-handler-alist' matches it.
320 If OPERATION equals `inhibit-file-name-operation', then we ignore
321 any handlers that are members of `inhibit-file-name-handlers',
322 but we still do run any other handlers. This lets handlers
323 use the standard functions without calling themselves recursively. */)
324 (Lisp_Object filename, Lisp_Object operation)
326 /* This function must not munge the match data. */
327 Lisp_Object chain, inhibited_handlers, result;
328 int pos = -1;
330 result = Qnil;
331 CHECK_STRING (filename);
333 if (EQ (operation, Vinhibit_file_name_operation))
334 inhibited_handlers = Vinhibit_file_name_handlers;
335 else
336 inhibited_handlers = Qnil;
338 for (chain = Vfile_name_handler_alist; CONSP (chain);
339 chain = XCDR (chain))
341 Lisp_Object elt;
342 elt = XCAR (chain);
343 if (CONSP (elt))
345 Lisp_Object string = XCAR (elt);
346 int match_pos;
347 Lisp_Object handler = XCDR (elt);
348 Lisp_Object operations = Qnil;
350 if (SYMBOLP (handler))
351 operations = Fget (handler, Qoperations);
353 if (STRINGP (string)
354 && (match_pos = fast_string_match (string, filename)) > pos
355 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
357 Lisp_Object tem;
359 handler = XCDR (elt);
360 tem = Fmemq (handler, inhibited_handlers);
361 if (NILP (tem))
363 result = handler;
364 pos = match_pos;
369 QUIT;
371 return result;
374 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
375 1, 1, 0,
376 doc: /* Return the directory component in file name FILENAME.
377 Return nil if FILENAME does not include a directory.
378 Otherwise return a directory name.
379 Given a Unix syntax file name, returns a string ending in slash. */)
380 (Lisp_Object filename)
382 #ifndef DOS_NT
383 register const unsigned char *beg;
384 #else
385 register unsigned char *beg;
386 #endif
387 register const unsigned char *p;
388 Lisp_Object handler;
390 CHECK_STRING (filename);
392 /* If the file name has special constructs in it,
393 call the corresponding file handler. */
394 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
395 if (!NILP (handler))
396 return call2 (handler, Qfile_name_directory, filename);
398 filename = FILE_SYSTEM_CASE (filename);
399 #ifdef DOS_NT
400 beg = (unsigned char *) alloca (SBYTES (filename) + 1);
401 memcpy (beg, SDATA (filename), SBYTES (filename) + 1);
402 #else
403 beg = SDATA (filename);
404 #endif
405 p = beg + SBYTES (filename);
407 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
408 #ifdef DOS_NT
409 /* only recognise drive specifier at the beginning */
410 && !(p[-1] == ':'
411 /* handle the "/:d:foo" and "/:foo" cases correctly */
412 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
413 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
414 #endif
415 ) p--;
417 if (p == beg)
418 return Qnil;
419 #ifdef DOS_NT
420 /* Expansion of "c:" to drive and default directory. */
421 if (p[-1] == ':')
423 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
424 unsigned char *res = alloca (MAXPATHLEN + 1);
425 unsigned char *r = res;
427 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
429 strncpy (res, beg, 2);
430 beg += 2;
431 r += 2;
434 if (getdefdir (toupper (*beg) - 'A' + 1, r))
436 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
437 strcat (res, "/");
438 beg = res;
439 p = beg + strlen (beg);
442 dostounix_filename (beg);
443 #endif /* DOS_NT */
445 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
448 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
449 Sfile_name_nondirectory, 1, 1, 0,
450 doc: /* Return file name FILENAME sans its directory.
451 For example, in a Unix-syntax file name,
452 this is everything after the last slash,
453 or the entire name if it contains no slash. */)
454 (Lisp_Object filename)
456 register const unsigned char *beg, *p, *end;
457 Lisp_Object handler;
459 CHECK_STRING (filename);
461 /* If the file name has special constructs in it,
462 call the corresponding file handler. */
463 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
464 if (!NILP (handler))
465 return call2 (handler, Qfile_name_nondirectory, filename);
467 beg = SDATA (filename);
468 end = p = beg + SBYTES (filename);
470 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
471 #ifdef DOS_NT
472 /* only recognise drive specifier at beginning */
473 && !(p[-1] == ':'
474 /* handle the "/:d:foo" case correctly */
475 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
476 #endif
478 p--;
480 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
483 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
484 Sunhandled_file_name_directory, 1, 1, 0,
485 doc: /* Return a directly usable directory name somehow associated with FILENAME.
486 A `directly usable' directory name is one that may be used without the
487 intervention of any file handler.
488 If FILENAME is a directly usable file itself, return
489 \(file-name-directory FILENAME).
490 If FILENAME refers to a file which is not accessible from a local process,
491 then this should return nil.
492 The `call-process' and `start-process' functions use this function to
493 get a current directory to run processes in. */)
494 (Lisp_Object filename)
496 Lisp_Object handler;
498 /* If the file name has special constructs in it,
499 call the corresponding file handler. */
500 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
501 if (!NILP (handler))
502 return call2 (handler, Qunhandled_file_name_directory, filename);
504 return Ffile_name_directory (filename);
508 char *
509 file_name_as_directory (char *out, char *in)
511 int size = strlen (in) - 1;
513 strcpy (out, in);
515 if (size < 0)
517 out[0] = '.';
518 out[1] = '/';
519 out[2] = 0;
520 return out;
523 /* For Unix syntax, Append a slash if necessary */
524 if (!IS_DIRECTORY_SEP (out[size]))
526 out[size + 1] = DIRECTORY_SEP;
527 out[size + 2] = '\0';
529 #ifdef DOS_NT
530 dostounix_filename (out);
531 #endif
532 return out;
535 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
536 Sfile_name_as_directory, 1, 1, 0,
537 doc: /* Return a string representing the file name FILE interpreted as a directory.
538 This operation exists because a directory is also a file, but its name as
539 a directory is different from its name as a file.
540 The result can be used as the value of `default-directory'
541 or passed as second argument to `expand-file-name'.
542 For a Unix-syntax file name, just appends a slash. */)
543 (Lisp_Object file)
545 char *buf;
546 Lisp_Object handler;
548 CHECK_STRING (file);
549 if (NILP (file))
550 return Qnil;
552 /* If the file name has special constructs in it,
553 call the corresponding file handler. */
554 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
555 if (!NILP (handler))
556 return call2 (handler, Qfile_name_as_directory, file);
558 buf = (char *) alloca (SBYTES (file) + 10);
559 file_name_as_directory (buf, SDATA (file));
560 return make_specified_string (buf, -1, strlen (buf),
561 STRING_MULTIBYTE (file));
565 * Convert from directory name to filename.
566 * On UNIX, it's simple: just make sure there isn't a terminating /
568 * Value is nonzero if the string output is different from the input.
572 directory_file_name (char *src, char *dst)
574 long slen;
576 slen = strlen (src);
578 /* Process as Unix format: just remove any final slash.
579 But leave "/" unchanged; do not change it to "". */
580 strcpy (dst, src);
581 if (slen > 1
582 && IS_DIRECTORY_SEP (dst[slen - 1])
583 #ifdef DOS_NT
584 && !IS_ANY_SEP (dst[slen - 2])
585 #endif
587 dst[slen - 1] = 0;
588 #ifdef DOS_NT
589 dostounix_filename (dst);
590 #endif
591 return 1;
594 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
595 1, 1, 0,
596 doc: /* Returns the file name of the directory named DIRECTORY.
597 This is the name of the file that holds the data for the directory DIRECTORY.
598 This operation exists because a directory is also a file, but its name as
599 a directory is different from its name as a file.
600 In Unix-syntax, this function just removes the final slash. */)
601 (Lisp_Object directory)
603 char *buf;
604 Lisp_Object handler;
606 CHECK_STRING (directory);
608 if (NILP (directory))
609 return Qnil;
611 /* If the file name has special constructs in it,
612 call the corresponding file handler. */
613 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
614 if (!NILP (handler))
615 return call2 (handler, Qdirectory_file_name, directory);
617 buf = (char *) alloca (SBYTES (directory) + 20);
618 directory_file_name (SDATA (directory), buf);
619 return make_specified_string (buf, -1, strlen (buf),
620 STRING_MULTIBYTE (directory));
623 static const char make_temp_name_tbl[64] =
625 'A','B','C','D','E','F','G','H',
626 'I','J','K','L','M','N','O','P',
627 'Q','R','S','T','U','V','W','X',
628 'Y','Z','a','b','c','d','e','f',
629 'g','h','i','j','k','l','m','n',
630 'o','p','q','r','s','t','u','v',
631 'w','x','y','z','0','1','2','3',
632 '4','5','6','7','8','9','-','_'
635 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
637 /* Value is a temporary file name starting with PREFIX, a string.
639 The Emacs process number forms part of the result, so there is
640 no danger of generating a name being used by another process.
641 In addition, this function makes an attempt to choose a name
642 which has no existing file. To make this work, PREFIX should be
643 an absolute file name.
645 BASE64_P non-zero means add the pid as 3 characters in base64
646 encoding. In this case, 6 characters will be added to PREFIX to
647 form the file name. Otherwise, if Emacs is running on a system
648 with long file names, add the pid as a decimal number.
650 This function signals an error if no unique file name could be
651 generated. */
653 Lisp_Object
654 make_temp_name (Lisp_Object prefix, int base64_p)
656 Lisp_Object val;
657 int len, clen;
658 int pid;
659 unsigned char *p, *data;
660 char pidbuf[20];
661 int pidlen;
663 CHECK_STRING (prefix);
665 /* VAL is created by adding 6 characters to PREFIX. The first
666 three are the PID of this process, in base 64, and the second
667 three are incremented if the file already exists. This ensures
668 262144 unique file names per PID per PREFIX. */
670 pid = (int) getpid ();
672 if (base64_p)
674 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
675 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
676 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
677 pidlen = 3;
679 else
681 #ifdef HAVE_LONG_FILE_NAMES
682 sprintf (pidbuf, "%d", pid);
683 pidlen = strlen (pidbuf);
684 #else
685 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
686 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
687 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
688 pidlen = 3;
689 #endif
692 len = SBYTES (prefix); clen = SCHARS (prefix);
693 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
694 if (!STRING_MULTIBYTE (prefix))
695 STRING_SET_UNIBYTE (val);
696 data = SDATA (val);
697 memcpy (data, SDATA (prefix), len);
698 p = data + len;
700 memcpy (p, pidbuf, pidlen);
701 p += pidlen;
703 /* Here we try to minimize useless stat'ing when this function is
704 invoked many times successively with the same PREFIX. We achieve
705 this by initializing count to a random value, and incrementing it
706 afterwards.
708 We don't want make-temp-name to be called while dumping,
709 because then make_temp_name_count_initialized_p would get set
710 and then make_temp_name_count would not be set when Emacs starts. */
712 if (!make_temp_name_count_initialized_p)
714 make_temp_name_count = (unsigned) time (NULL);
715 make_temp_name_count_initialized_p = 1;
718 while (1)
720 struct stat ignored;
721 unsigned num = make_temp_name_count;
723 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
724 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
725 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
727 /* Poor man's congruential RN generator. Replace with
728 ++make_temp_name_count for debugging. */
729 make_temp_name_count += 25229;
730 make_temp_name_count %= 225307;
732 if (stat (data, &ignored) < 0)
734 /* We want to return only if errno is ENOENT. */
735 if (errno == ENOENT)
736 return val;
737 else
738 /* The error here is dubious, but there is little else we
739 can do. The alternatives are to return nil, which is
740 as bad as (and in many cases worse than) throwing the
741 error, or to ignore the error, which will likely result
742 in looping through 225307 stat's, which is not only
743 dog-slow, but also useless since it will fallback to
744 the errow below, anyway. */
745 report_file_error ("Cannot create temporary name for prefix",
746 Fcons (prefix, Qnil));
747 /* not reached */
751 error ("Cannot create temporary name for prefix `%s'",
752 SDATA (prefix));
753 return Qnil;
757 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
758 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
759 The Emacs process number forms part of the result,
760 so there is no danger of generating a name being used by another process.
762 In addition, this function makes an attempt to choose a name
763 which has no existing file. To make this work,
764 PREFIX should be an absolute file name.
766 There is a race condition between calling `make-temp-name' and creating the
767 file which opens all kinds of security holes. For that reason, you should
768 probably use `make-temp-file' instead, except in three circumstances:
770 * If you are creating the file in the user's home directory.
771 * If you are creating a directory rather than an ordinary file.
772 * If you are taking special precautions as `make-temp-file' does. */)
773 (Lisp_Object prefix)
775 return make_temp_name (prefix, 0);
780 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
781 doc: /* Convert filename NAME to absolute, and canonicalize it.
782 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
783 \(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
784 the current buffer's value of `default-directory' is used.
785 File name components that are `.' are removed, and
786 so are file name components followed by `..', along with the `..' itself;
787 note that these simplifications are done without checking the resulting
788 file names in the file system.
789 An initial `~/' expands to your home directory.
790 An initial `~USER/' expands to USER's home directory.
791 See also the function `substitute-in-file-name'.
793 For technical reasons, this function can return correct but
794 non-intuitive results for the root directory; for instance,
795 \(expand-file-name ".." "/") returns "/..". For this reason, use
796 (directory-file-name (file-name-directory dirname)) to traverse a
797 filesystem tree, not (expand-file-name ".." dirname). */)
798 (Lisp_Object name, Lisp_Object default_directory)
800 /* These point to SDATA and need to be careful with string-relocation
801 during GC (via DECODE_FILE). */
802 unsigned char *nm, *newdir;
803 /* This should only point to alloca'd data. */
804 unsigned char *target;
806 int tlen;
807 struct passwd *pw;
808 #ifdef DOS_NT
809 int drive = 0;
810 int collapse_newdir = 1;
811 int is_escaped = 0;
812 #endif /* DOS_NT */
813 int length;
814 Lisp_Object handler, result;
815 int multibyte;
816 Lisp_Object hdir;
818 CHECK_STRING (name);
820 /* If the file name has special constructs in it,
821 call the corresponding file handler. */
822 handler = Ffind_file_name_handler (name, Qexpand_file_name);
823 if (!NILP (handler))
824 return call3 (handler, Qexpand_file_name, name, default_directory);
826 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
827 if (NILP (default_directory))
828 default_directory = current_buffer->directory;
829 if (! STRINGP (default_directory))
831 #ifdef DOS_NT
832 /* "/" is not considered a root directory on DOS_NT, so using "/"
833 here causes an infinite recursion in, e.g., the following:
835 (let (default-directory)
836 (expand-file-name "a"))
838 To avoid this, we set default_directory to the root of the
839 current drive. */
840 default_directory = build_string (emacs_root_dir ());
841 #else
842 default_directory = build_string ("/");
843 #endif
846 if (!NILP (default_directory))
848 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
849 if (!NILP (handler))
850 return call3 (handler, Qexpand_file_name, name, default_directory);
854 unsigned char *o = SDATA (default_directory);
856 /* Make sure DEFAULT_DIRECTORY is properly expanded.
857 It would be better to do this down below where we actually use
858 default_directory. Unfortunately, calling Fexpand_file_name recursively
859 could invoke GC, and the strings might be relocated. This would
860 be annoying because we have pointers into strings lying around
861 that would need adjusting, and people would add new pointers to
862 the code and forget to adjust them, resulting in intermittent bugs.
863 Putting this call here avoids all that crud.
865 The EQ test avoids infinite recursion. */
866 if (! NILP (default_directory) && !EQ (default_directory, name)
867 /* Save time in some common cases - as long as default_directory
868 is not relative, it can be canonicalized with name below (if it
869 is needed at all) without requiring it to be expanded now. */
870 #ifdef DOS_NT
871 /* Detect MSDOS file names with drive specifiers. */
872 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
873 && IS_DIRECTORY_SEP (o[2]))
874 #ifdef WINDOWSNT
875 /* Detect Windows file names in UNC format. */
876 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
877 #endif
878 #else /* not DOS_NT */
879 /* Detect Unix absolute file names (/... alone is not absolute on
880 DOS or Windows). */
881 && ! (IS_DIRECTORY_SEP (o[0]))
882 #endif /* not DOS_NT */
885 struct gcpro gcpro1;
887 GCPRO1 (name);
888 default_directory = Fexpand_file_name (default_directory, Qnil);
889 UNGCPRO;
892 name = FILE_SYSTEM_CASE (name);
893 multibyte = STRING_MULTIBYTE (name);
894 if (multibyte != STRING_MULTIBYTE (default_directory))
896 if (multibyte)
897 default_directory = string_to_multibyte (default_directory);
898 else
900 name = string_to_multibyte (name);
901 multibyte = 1;
905 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
906 nm = (unsigned char *) alloca (SBYTES (name) + 1);
907 memcpy (nm, SDATA (name), SBYTES (name) + 1);
909 #ifdef DOS_NT
910 /* Note if special escape prefix is present, but remove for now. */
911 if (nm[0] == '/' && nm[1] == ':')
913 is_escaped = 1;
914 nm += 2;
917 /* Find and remove drive specifier if present; this makes nm absolute
918 even if the rest of the name appears to be relative. Only look for
919 drive specifier at the beginning. */
920 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
922 drive = nm[0];
923 nm += 2;
926 #ifdef WINDOWSNT
927 /* If we see "c://somedir", we want to strip the first slash after the
928 colon when stripping the drive letter. Otherwise, this expands to
929 "//somedir". */
930 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
931 nm++;
933 /* Discard any previous drive specifier if nm is now in UNC format. */
934 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
936 drive = 0;
938 #endif /* WINDOWSNT */
939 #endif /* DOS_NT */
941 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
942 none are found, we can probably return right away. We will avoid
943 allocating a new string if name is already fully expanded. */
944 if (
945 IS_DIRECTORY_SEP (nm[0])
946 #ifdef MSDOS
947 && drive && !is_escaped
948 #endif
949 #ifdef WINDOWSNT
950 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
951 #endif
954 /* If it turns out that the filename we want to return is just a
955 suffix of FILENAME, we don't need to go through and edit
956 things; we just need to construct a new string using data
957 starting at the middle of FILENAME. If we set lose to a
958 non-zero value, that means we've discovered that we can't do
959 that cool trick. */
960 int lose = 0;
961 unsigned char *p = nm;
963 while (*p)
965 /* Since we know the name is absolute, we can assume that each
966 element starts with a "/". */
968 /* "." and ".." are hairy. */
969 if (IS_DIRECTORY_SEP (p[0])
970 && p[1] == '.'
971 && (IS_DIRECTORY_SEP (p[2])
972 || p[2] == 0
973 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
974 || p[3] == 0))))
975 lose = 1;
976 /* We want to replace multiple `/' in a row with a single
977 slash. */
978 else if (p > nm
979 && IS_DIRECTORY_SEP (p[0])
980 && IS_DIRECTORY_SEP (p[1]))
981 lose = 1;
982 p++;
984 if (!lose)
986 #ifdef DOS_NT
987 /* Make sure directories are all separated with /, but
988 avoid allocation of a new string when not required. */
989 dostounix_filename (nm);
990 #ifdef WINDOWSNT
991 if (IS_DIRECTORY_SEP (nm[1]))
993 if (strcmp (nm, SDATA (name)) != 0)
994 name = make_specified_string (nm, -1, strlen (nm), multibyte);
996 else
997 #endif
998 /* drive must be set, so this is okay */
999 if (strcmp (nm - 2, SDATA (name)) != 0)
1001 char temp[] = " :";
1003 name = make_specified_string (nm, -1, p - nm, multibyte);
1004 temp[0] = DRIVE_LETTER (drive);
1005 name = concat2 (build_string (temp), name);
1007 return name;
1008 #else /* not DOS_NT */
1009 if (strcmp (nm, SDATA (name)) == 0)
1010 return name;
1011 return make_specified_string (nm, -1, strlen (nm), multibyte);
1012 #endif /* not DOS_NT */
1016 /* At this point, nm might or might not be an absolute file name. We
1017 need to expand ~ or ~user if present, otherwise prefix nm with
1018 default_directory if nm is not absolute, and finally collapse /./
1019 and /foo/../ sequences.
1021 We set newdir to be the appropriate prefix if one is needed:
1022 - the relevant user directory if nm starts with ~ or ~user
1023 - the specified drive's working dir (DOS/NT only) if nm does not
1024 start with /
1025 - the value of default_directory.
1027 Note that these prefixes are not guaranteed to be absolute (except
1028 for the working dir of a drive). Therefore, to ensure we always
1029 return an absolute name, if the final prefix is not absolute we
1030 append it to the current working directory. */
1032 newdir = 0;
1034 if (nm[0] == '~') /* prefix ~ */
1036 if (IS_DIRECTORY_SEP (nm[1])
1037 || nm[1] == 0) /* ~ by itself */
1039 Lisp_Object tem;
1041 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1042 newdir = (unsigned char *) "";
1043 nm++;
1044 /* egetenv may return a unibyte string, which will bite us since
1045 we expect the directory to be multibyte. */
1046 tem = build_string (newdir);
1047 if (!STRING_MULTIBYTE (tem))
1049 hdir = DECODE_FILE (tem);
1050 newdir = SDATA (hdir);
1052 #ifdef DOS_NT
1053 collapse_newdir = 0;
1054 #endif
1056 else /* ~user/filename */
1058 unsigned char *o, *p;
1059 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
1060 o = alloca (p - nm + 1);
1061 memcpy (o, nm, p - nm);
1062 o [p - nm] = 0;
1064 BLOCK_INPUT;
1065 pw = (struct passwd *) getpwnam (o + 1);
1066 UNBLOCK_INPUT;
1067 if (pw)
1069 newdir = (unsigned char *) pw -> pw_dir;
1070 nm = p;
1071 #ifdef DOS_NT
1072 collapse_newdir = 0;
1073 #endif
1076 /* If we don't find a user of that name, leave the name
1077 unchanged; don't move nm forward to p. */
1081 #ifdef DOS_NT
1082 /* On DOS and Windows, nm is absolute if a drive name was specified;
1083 use the drive's current directory as the prefix if needed. */
1084 if (!newdir && drive)
1086 /* Get default directory if needed to make nm absolute. */
1087 if (!IS_DIRECTORY_SEP (nm[0]))
1089 newdir = alloca (MAXPATHLEN + 1);
1090 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1091 newdir = NULL;
1093 if (!newdir)
1095 /* Either nm starts with /, or drive isn't mounted. */
1096 newdir = alloca (4);
1097 newdir[0] = DRIVE_LETTER (drive);
1098 newdir[1] = ':';
1099 newdir[2] = '/';
1100 newdir[3] = 0;
1103 #endif /* DOS_NT */
1105 /* Finally, if no prefix has been specified and nm is not absolute,
1106 then it must be expanded relative to default_directory. */
1108 if (1
1109 #ifndef DOS_NT
1110 /* /... alone is not absolute on DOS and Windows. */
1111 && !IS_DIRECTORY_SEP (nm[0])
1112 #endif
1113 #ifdef WINDOWSNT
1114 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1115 #endif
1116 && !newdir)
1118 newdir = SDATA (default_directory);
1119 #ifdef DOS_NT
1120 /* Note if special escape prefix is present, but remove for now. */
1121 if (newdir[0] == '/' && newdir[1] == ':')
1123 is_escaped = 1;
1124 newdir += 2;
1126 #endif
1129 #ifdef DOS_NT
1130 if (newdir)
1132 /* First ensure newdir is an absolute name. */
1133 if (
1134 /* Detect MSDOS file names with drive specifiers. */
1135 ! (IS_DRIVE (newdir[0])
1136 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1137 #ifdef WINDOWSNT
1138 /* Detect Windows file names in UNC format. */
1139 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1140 #endif
1143 /* Effectively, let newdir be (expand-file-name newdir cwd).
1144 Because of the admonition against calling expand-file-name
1145 when we have pointers into lisp strings, we accomplish this
1146 indirectly by prepending newdir to nm if necessary, and using
1147 cwd (or the wd of newdir's drive) as the new newdir. */
1149 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1151 drive = newdir[0];
1152 newdir += 2;
1154 if (!IS_DIRECTORY_SEP (nm[0]))
1156 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1157 file_name_as_directory (tmp, newdir);
1158 strcat (tmp, nm);
1159 nm = tmp;
1161 newdir = alloca (MAXPATHLEN + 1);
1162 if (drive)
1164 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1165 newdir = "/";
1167 else
1168 getwd (newdir);
1171 /* Strip off drive name from prefix, if present. */
1172 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1174 drive = newdir[0];
1175 newdir += 2;
1178 /* Keep only a prefix from newdir if nm starts with slash
1179 (//server/share for UNC, nothing otherwise). */
1180 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1182 #ifdef WINDOWSNT
1183 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1185 unsigned char *p;
1186 newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
1187 p = newdir + 2;
1188 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1189 p++;
1190 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1191 *p = 0;
1193 else
1194 #endif
1195 newdir = "";
1198 #endif /* DOS_NT */
1200 if (newdir)
1202 /* Get rid of any slash at the end of newdir, unless newdir is
1203 just / or // (an incomplete UNC name). */
1204 length = strlen (newdir);
1205 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1206 #ifdef WINDOWSNT
1207 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1208 #endif
1211 unsigned char *temp = (unsigned char *) alloca (length);
1212 memcpy (temp, newdir, length - 1);
1213 temp[length - 1] = 0;
1214 newdir = temp;
1216 tlen = length + 1;
1218 else
1219 tlen = 0;
1221 /* Now concatenate the directory and name to new space in the stack frame */
1222 tlen += strlen (nm) + 1;
1223 #ifdef DOS_NT
1224 /* Reserve space for drive specifier and escape prefix, since either
1225 or both may need to be inserted. (The Microsoft x86 compiler
1226 produces incorrect code if the following two lines are combined.) */
1227 target = (unsigned char *) alloca (tlen + 4);
1228 target += 4;
1229 #else /* not DOS_NT */
1230 target = (unsigned char *) alloca (tlen);
1231 #endif /* not DOS_NT */
1232 *target = 0;
1234 if (newdir)
1236 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1238 #ifdef DOS_NT
1239 /* If newdir is effectively "C:/", then the drive letter will have
1240 been stripped and newdir will be "/". Concatenating with an
1241 absolute directory in nm produces "//", which will then be
1242 incorrectly treated as a network share. Ignore newdir in
1243 this case (keeping the drive letter). */
1244 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1245 && newdir[1] == '\0'))
1246 #endif
1247 strcpy (target, newdir);
1249 else
1250 file_name_as_directory (target, newdir);
1253 strcat (target, nm);
1255 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1256 appear. */
1258 unsigned char *p = target;
1259 unsigned char *o = target;
1261 while (*p)
1263 if (!IS_DIRECTORY_SEP (*p))
1265 *o++ = *p++;
1267 else if (p[1] == '.'
1268 && (IS_DIRECTORY_SEP (p[2])
1269 || p[2] == 0))
1271 /* If "/." is the entire filename, keep the "/". Otherwise,
1272 just delete the whole "/.". */
1273 if (o == target && p[2] == '\0')
1274 *o++ = *p;
1275 p += 2;
1277 else if (p[1] == '.' && p[2] == '.'
1278 /* `/../' is the "superroot" on certain file systems.
1279 Turned off on DOS_NT systems because they have no
1280 "superroot" and because this causes us to produce
1281 file names like "d:/../foo" which fail file-related
1282 functions of the underlying OS. (To reproduce, try a
1283 long series of "../../" in default_directory, longer
1284 than the number of levels from the root.) */
1285 #ifndef DOS_NT
1286 && o != target
1287 #endif
1288 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1290 #ifdef WINDOWSNT
1291 unsigned char *prev_o = o;
1292 #endif
1293 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1295 #ifdef WINDOWSNT
1296 /* Don't go below server level in UNC filenames. */
1297 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1298 && IS_DIRECTORY_SEP (*target))
1299 o = prev_o;
1300 else
1301 #endif
1302 /* Keep initial / only if this is the whole name. */
1303 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1304 ++o;
1305 p += 3;
1307 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1308 /* Collapse multiple `/' in a row. */
1309 p++;
1310 else
1312 *o++ = *p++;
1316 #ifdef DOS_NT
1317 /* At last, set drive name. */
1318 #ifdef WINDOWSNT
1319 /* Except for network file name. */
1320 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1321 #endif /* WINDOWSNT */
1323 if (!drive) abort ();
1324 target -= 2;
1325 target[0] = DRIVE_LETTER (drive);
1326 target[1] = ':';
1328 /* Reinsert the escape prefix if required. */
1329 if (is_escaped)
1331 target -= 2;
1332 target[0] = '/';
1333 target[1] = ':';
1335 dostounix_filename (target);
1336 #endif /* DOS_NT */
1338 result = make_specified_string (target, -1, o - target, multibyte);
1341 /* Again look to see if the file name has special constructs in it
1342 and perhaps call the corresponding file handler. This is needed
1343 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1344 the ".." component gives us "/user@host:/bar/../baz" which needs
1345 to be expanded again. */
1346 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1347 if (!NILP (handler))
1348 return call3 (handler, Qexpand_file_name, result, default_directory);
1350 return result;
1353 #if 0
1354 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1355 This is the old version of expand-file-name, before it was thoroughly
1356 rewritten for Emacs 10.31. We leave this version here commented-out,
1357 because the code is very complex and likely to have subtle bugs. If
1358 bugs _are_ found, it might be of interest to look at the old code and
1359 see what did it do in the relevant situation.
1361 Don't remove this code: it's true that it will be accessible
1362 from the repository, but a few years from deletion, people will
1363 forget it is there. */
1365 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1366 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1367 "Convert FILENAME to absolute, and canonicalize it.\n\
1368 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1369 \(does not start with slash); if DEFAULT is nil or missing,\n\
1370 the current buffer's value of default-directory is used.\n\
1371 Filenames containing `.' or `..' as components are simplified;\n\
1372 initial `~/' expands to your home directory.\n\
1373 See also the function `substitute-in-file-name'.")
1374 (name, defalt)
1375 Lisp_Object name, defalt;
1377 unsigned char *nm;
1379 register unsigned char *newdir, *p, *o;
1380 int tlen;
1381 unsigned char *target;
1382 struct passwd *pw;
1383 int lose;
1385 CHECK_STRING (name);
1386 nm = SDATA (name);
1388 /* If nm is absolute, flush ...// and detect /./ and /../.
1389 If no /./ or /../ we can return right away. */
1390 if (nm[0] == '/')
1392 p = nm;
1393 lose = 0;
1394 while (*p)
1396 if (p[0] == '/' && p[1] == '/'
1398 nm = p + 1;
1399 if (p[0] == '/' && p[1] == '~')
1400 nm = p + 1, lose = 1;
1401 if (p[0] == '/' && p[1] == '.'
1402 && (p[2] == '/' || p[2] == 0
1403 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1404 lose = 1;
1405 p++;
1407 if (!lose)
1409 if (nm == SDATA (name))
1410 return name;
1411 return build_string (nm);
1415 /* Now determine directory to start with and put it in NEWDIR */
1417 newdir = 0;
1419 if (nm[0] == '~') /* prefix ~ */
1420 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1422 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1423 newdir = (unsigned char *) "";
1424 nm++;
1426 else /* ~user/filename */
1428 /* Get past ~ to user */
1429 unsigned char *user = nm + 1;
1430 /* Find end of name. */
1431 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1432 int len = ptr ? ptr - user : strlen (user);
1433 /* Copy the user name into temp storage. */
1434 o = (unsigned char *) alloca (len + 1);
1435 memcpy (o, user, len);
1436 o[len] = 0;
1438 /* Look up the user name. */
1439 BLOCK_INPUT;
1440 pw = (struct passwd *) getpwnam (o + 1);
1441 UNBLOCK_INPUT;
1442 if (!pw)
1443 error ("\"%s\" isn't a registered user", o + 1);
1445 newdir = (unsigned char *) pw->pw_dir;
1447 /* Discard the user name from NM. */
1448 nm += len;
1451 if (nm[0] != '/' && !newdir)
1453 if (NILP (defalt))
1454 defalt = current_buffer->directory;
1455 CHECK_STRING (defalt);
1456 newdir = SDATA (defalt);
1459 /* Now concatenate the directory and name to new space in the stack frame */
1461 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1462 target = (unsigned char *) alloca (tlen);
1463 *target = 0;
1465 if (newdir)
1467 if (nm[0] == 0 || nm[0] == '/')
1468 strcpy (target, newdir);
1469 else
1470 file_name_as_directory (target, newdir);
1473 strcat (target, nm);
1475 /* Now canonicalize by removing /. and /foo/.. if they appear */
1477 p = target;
1478 o = target;
1480 while (*p)
1482 if (*p != '/')
1484 *o++ = *p++;
1486 else if (!strncmp (p, "//", 2)
1489 o = target;
1490 p++;
1492 else if (p[0] == '/' && p[1] == '.'
1493 && (p[2] == '/' || p[2] == 0))
1494 p += 2;
1495 else if (!strncmp (p, "/..", 3)
1496 /* `/../' is the "superroot" on certain file systems. */
1497 && o != target
1498 && (p[3] == '/' || p[3] == 0))
1500 while (o != target && *--o != '/')
1502 if (o == target && *o == '/')
1503 ++o;
1504 p += 3;
1506 else
1508 *o++ = *p++;
1512 return make_string (target, o - target);
1514 #endif
1516 /* If /~ or // appears, discard everything through first slash. */
1517 static int
1518 file_name_absolute_p (const unsigned char *filename)
1520 return
1521 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1522 #ifdef DOS_NT
1523 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1524 && IS_DIRECTORY_SEP (filename[2]))
1525 #endif
1529 static unsigned char *
1530 search_embedded_absfilename (unsigned char *nm, unsigned char *endp)
1532 unsigned char *p, *s;
1534 for (p = nm + 1; p < endp; p++)
1536 if ((0
1537 || IS_DIRECTORY_SEP (p[-1]))
1538 && file_name_absolute_p (p)
1539 #if defined (WINDOWSNT) || defined(CYGWIN)
1540 /* // at start of file name is meaningful in Apollo,
1541 WindowsNT and Cygwin systems. */
1542 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1543 #endif /* not (WINDOWSNT || CYGWIN) */
1546 for (s = p; *s && (!IS_DIRECTORY_SEP (*s)); s++);
1547 if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
1549 unsigned char *o = alloca (s - p + 1);
1550 struct passwd *pw;
1551 memcpy (o, p, s - p);
1552 o [s - p] = 0;
1554 /* If we have ~user and `user' exists, discard
1555 everything up to ~. But if `user' does not exist, leave
1556 ~user alone, it might be a literal file name. */
1557 BLOCK_INPUT;
1558 pw = getpwnam (o + 1);
1559 UNBLOCK_INPUT;
1560 if (pw)
1561 return p;
1563 else
1564 return p;
1567 return NULL;
1570 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1571 Ssubstitute_in_file_name, 1, 1, 0,
1572 doc: /* Substitute environment variables referred to in FILENAME.
1573 `$FOO' where FOO is an environment variable name means to substitute
1574 the value of that variable. The variable name should be terminated
1575 with a character not a letter, digit or underscore; otherwise, enclose
1576 the entire variable name in braces.
1578 If `/~' appears, all of FILENAME through that `/' is discarded.
1579 If `//' appears, everything up to and including the first of
1580 those `/' is discarded. */)
1581 (Lisp_Object filename)
1583 unsigned char *nm;
1585 register unsigned char *s, *p, *o, *x, *endp;
1586 unsigned char *target = NULL;
1587 int total = 0;
1588 int substituted = 0;
1589 int multibyte;
1590 unsigned char *xnm;
1591 Lisp_Object handler;
1593 CHECK_STRING (filename);
1595 multibyte = STRING_MULTIBYTE (filename);
1597 /* If the file name has special constructs in it,
1598 call the corresponding file handler. */
1599 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1600 if (!NILP (handler))
1601 return call2 (handler, Qsubstitute_in_file_name, filename);
1603 /* Always work on a copy of the string, in case GC happens during
1604 decode of environment variables, causing the original Lisp_String
1605 data to be relocated. */
1606 nm = (unsigned char *) alloca (SBYTES (filename) + 1);
1607 memcpy (nm, SDATA (filename), SBYTES (filename) + 1);
1609 #ifdef DOS_NT
1610 dostounix_filename (nm);
1611 substituted = (strcmp (nm, SDATA (filename)) != 0);
1612 #endif
1613 endp = nm + SBYTES (filename);
1615 /* If /~ or // appears, discard everything through first slash. */
1616 p = search_embedded_absfilename (nm, endp);
1617 if (p)
1618 /* Start over with the new string, so we check the file-name-handler
1619 again. Important with filenames like "/home/foo//:/hello///there"
1620 which whould substitute to "/:/hello///there" rather than "/there". */
1621 return Fsubstitute_in_file_name
1622 (make_specified_string (p, -1, endp - p, multibyte));
1624 /* See if any variables are substituted into the string
1625 and find the total length of their values in `total' */
1627 for (p = nm; p != endp;)
1628 if (*p != '$')
1629 p++;
1630 else
1632 p++;
1633 if (p == endp)
1634 goto badsubst;
1635 else if (*p == '$')
1637 /* "$$" means a single "$" */
1638 p++;
1639 total -= 1;
1640 substituted = 1;
1641 continue;
1643 else if (*p == '{')
1645 o = ++p;
1646 while (p != endp && *p != '}') p++;
1647 if (*p != '}') goto missingclose;
1648 s = p;
1650 else
1652 o = p;
1653 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1654 s = p;
1657 /* Copy out the variable name */
1658 target = (unsigned char *) alloca (s - o + 1);
1659 strncpy (target, o, s - o);
1660 target[s - o] = 0;
1661 #ifdef DOS_NT
1662 strupr (target); /* $home == $HOME etc. */
1663 #endif /* DOS_NT */
1665 /* Get variable value */
1666 o = (unsigned char *) egetenv (target);
1667 if (o)
1669 /* Don't try to guess a maximum length - UTF8 can use up to
1670 four bytes per character. This code is unlikely to run
1671 in a situation that requires performance, so decoding the
1672 env variables twice should be acceptable. Note that
1673 decoding may cause a garbage collect. */
1674 Lisp_Object orig, decoded;
1675 orig = make_unibyte_string (o, strlen (o));
1676 decoded = DECODE_FILE (orig);
1677 total += SBYTES (decoded);
1678 substituted = 1;
1680 else if (*p == '}')
1681 goto badvar;
1684 if (!substituted)
1685 return filename;
1687 /* If substitution required, recopy the string and do it */
1688 /* Make space in stack frame for the new copy */
1689 xnm = (unsigned char *) alloca (SBYTES (filename) + total + 1);
1690 x = xnm;
1692 /* Copy the rest of the name through, replacing $ constructs with values */
1693 for (p = nm; *p;)
1694 if (*p != '$')
1695 *x++ = *p++;
1696 else
1698 p++;
1699 if (p == endp)
1700 goto badsubst;
1701 else if (*p == '$')
1703 *x++ = *p++;
1704 continue;
1706 else if (*p == '{')
1708 o = ++p;
1709 while (p != endp && *p != '}') p++;
1710 if (*p != '}') goto missingclose;
1711 s = p++;
1713 else
1715 o = p;
1716 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1717 s = p;
1720 /* Copy out the variable name */
1721 target = (unsigned char *) alloca (s - o + 1);
1722 strncpy (target, o, s - o);
1723 target[s - o] = 0;
1724 #ifdef DOS_NT
1725 strupr (target); /* $home == $HOME etc. */
1726 #endif /* DOS_NT */
1728 /* Get variable value */
1729 o = (unsigned char *) egetenv (target);
1730 if (!o)
1732 *x++ = '$';
1733 strcpy (x, target); x+= strlen (target);
1735 else
1737 Lisp_Object orig, decoded;
1738 int orig_length, decoded_length;
1739 orig_length = strlen (o);
1740 orig = make_unibyte_string (o, orig_length);
1741 decoded = DECODE_FILE (orig);
1742 decoded_length = SBYTES (decoded);
1743 strncpy (x, SDATA (decoded), decoded_length);
1744 x += decoded_length;
1746 /* If environment variable needed decoding, return value
1747 needs to be multibyte. */
1748 if (decoded_length != orig_length
1749 || strncmp (SDATA (decoded), o, orig_length))
1750 multibyte = 1;
1754 *x = 0;
1756 /* If /~ or // appears, discard everything through first slash. */
1757 while ((p = search_embedded_absfilename (xnm, x)))
1758 /* This time we do not start over because we've already expanded envvars
1759 and replaced $$ with $. Maybe we should start over as well, but we'd
1760 need to quote some $ to $$ first. */
1761 xnm = p;
1763 return make_specified_string (xnm, -1, x - xnm, multibyte);
1765 badsubst:
1766 error ("Bad format environment-variable substitution");
1767 missingclose:
1768 error ("Missing \"}\" in environment-variable substitution");
1769 badvar:
1770 error ("Substituting nonexistent environment variable \"%s\"", target);
1772 /* NOTREACHED */
1773 return Qnil;
1776 /* A slightly faster and more convenient way to get
1777 (directory-file-name (expand-file-name FOO)). */
1779 Lisp_Object
1780 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1782 register Lisp_Object absname;
1784 absname = Fexpand_file_name (filename, defdir);
1786 /* Remove final slash, if any (unless this is the root dir).
1787 stat behaves differently depending! */
1788 if (SCHARS (absname) > 1
1789 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1790 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
1791 /* We cannot take shortcuts; they might be wrong for magic file names. */
1792 absname = Fdirectory_file_name (absname);
1793 return absname;
1796 /* Signal an error if the file ABSNAME already exists.
1797 If INTERACTIVE is nonzero, ask the user whether to proceed,
1798 and bypass the error if the user says to go ahead.
1799 QUERYSTRING is a name for the action that is being considered
1800 to alter the file.
1802 *STATPTR is used to store the stat information if the file exists.
1803 If the file does not exist, STATPTR->st_mode is set to 0.
1804 If STATPTR is null, we don't store into it.
1806 If QUICK is nonzero, we ask for y or n, not yes or no. */
1808 void
1809 barf_or_query_if_file_exists (Lisp_Object absname, const unsigned char *querystring, int interactive, struct stat *statptr, int quick)
1811 register Lisp_Object tem, encoded_filename;
1812 struct stat statbuf;
1813 struct gcpro gcpro1;
1815 encoded_filename = ENCODE_FILE (absname);
1817 /* stat is a good way to tell whether the file exists,
1818 regardless of what access permissions it has. */
1819 if (lstat (SDATA (encoded_filename), &statbuf) >= 0)
1821 if (! interactive)
1822 xsignal2 (Qfile_already_exists,
1823 build_string ("File already exists"), absname);
1824 GCPRO1 (absname);
1825 tem = format2 ("File %s already exists; %s anyway? ",
1826 absname, build_string (querystring));
1827 if (quick)
1828 tem = call1 (intern ("y-or-n-p"), tem);
1829 else
1830 tem = do_yes_or_no_p (tem);
1831 UNGCPRO;
1832 if (NILP (tem))
1833 xsignal2 (Qfile_already_exists,
1834 build_string ("File already exists"), absname);
1835 if (statptr)
1836 *statptr = statbuf;
1838 else
1840 if (statptr)
1841 statptr->st_mode = 0;
1843 return;
1846 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1847 "fCopy file: \nGCopy %s to file: \np\nP",
1848 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1849 If NEWNAME names a directory, copy FILE there.
1851 This function always sets the file modes of the output file to match
1852 the input file.
1854 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1855 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1856 signal a `file-already-exists' error without overwriting. If
1857 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1858 about overwriting; this is what happens in interactive use with M-x.
1859 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1860 existing file.
1862 Fourth arg KEEP-TIME non-nil means give the output file the same
1863 last-modified time as the old one. (This works on only some systems.)
1865 A prefix arg makes KEEP-TIME non-nil.
1867 If PRESERVE-UID-GID is non-nil, we try to transfer the
1868 uid and gid of FILE to NEWNAME.
1870 If PRESERVE-SELINUX-CONTEXT is non-nil and SELinux is enabled
1871 on the system, we copy the SELinux context of FILE to NEWNAME. */)
1872 (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)
1874 int ifd, ofd, n;
1875 char buf[16 * 1024];
1876 struct stat st, out_st;
1877 Lisp_Object handler;
1878 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1879 int count = SPECPDL_INDEX ();
1880 int input_file_statable_p;
1881 Lisp_Object encoded_file, encoded_newname;
1882 #if HAVE_LIBSELINUX
1883 security_context_t con;
1884 int fail, conlength = 0;
1885 #endif
1887 encoded_file = encoded_newname = Qnil;
1888 GCPRO4 (file, newname, encoded_file, encoded_newname);
1889 CHECK_STRING (file);
1890 CHECK_STRING (newname);
1892 if (!NILP (Ffile_directory_p (newname)))
1893 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1894 else
1895 newname = Fexpand_file_name (newname, Qnil);
1897 file = Fexpand_file_name (file, Qnil);
1899 /* If the input file name has special constructs in it,
1900 call the corresponding file handler. */
1901 handler = Ffind_file_name_handler (file, Qcopy_file);
1902 /* Likewise for output file name. */
1903 if (NILP (handler))
1904 handler = Ffind_file_name_handler (newname, Qcopy_file);
1905 if (!NILP (handler))
1906 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1907 ok_if_already_exists, keep_time, preserve_uid_gid,
1908 preserve_selinux_context));
1910 encoded_file = ENCODE_FILE (file);
1911 encoded_newname = ENCODE_FILE (newname);
1913 if (NILP (ok_if_already_exists)
1914 || INTEGERP (ok_if_already_exists))
1915 barf_or_query_if_file_exists (newname, "copy to it",
1916 INTEGERP (ok_if_already_exists), &out_st, 0);
1917 else if (stat (SDATA (encoded_newname), &out_st) < 0)
1918 out_st.st_mode = 0;
1920 #ifdef WINDOWSNT
1921 if (!CopyFile (SDATA (encoded_file),
1922 SDATA (encoded_newname),
1923 FALSE))
1924 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
1925 /* CopyFile retains the timestamp by default. */
1926 else if (NILP (keep_time))
1928 EMACS_TIME now;
1929 DWORD attributes;
1930 char * filename;
1932 EMACS_GET_TIME (now);
1933 filename = SDATA (encoded_newname);
1935 /* Ensure file is writable while its modified time is set. */
1936 attributes = GetFileAttributes (filename);
1937 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
1938 if (set_file_times (filename, now, now))
1940 /* Restore original attributes. */
1941 SetFileAttributes (filename, attributes);
1942 xsignal2 (Qfile_date_error,
1943 build_string ("Cannot set file date"), newname);
1945 /* Restore original attributes. */
1946 SetFileAttributes (filename, attributes);
1948 #else /* not WINDOWSNT */
1949 immediate_quit = 1;
1950 ifd = emacs_open (SDATA (encoded_file), O_RDONLY, 0);
1951 immediate_quit = 0;
1953 if (ifd < 0)
1954 report_file_error ("Opening input file", Fcons (file, Qnil));
1956 record_unwind_protect (close_file_unwind, make_number (ifd));
1958 /* We can only copy regular files and symbolic links. Other files are not
1959 copyable by us. */
1960 input_file_statable_p = (fstat (ifd, &st) >= 0);
1962 #if HAVE_LIBSELINUX
1963 if (!NILP (preserve_selinux_context) && is_selinux_enabled ())
1965 conlength = fgetfilecon (ifd, &con);
1966 if (conlength == -1)
1967 report_file_error ("Doing fgetfilecon", Fcons (file, Qnil));
1969 #endif
1971 if (out_st.st_mode != 0
1972 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1974 errno = 0;
1975 report_file_error ("Input and output files are the same",
1976 Fcons (file, Fcons (newname, Qnil)));
1979 #if defined (S_ISREG) && defined (S_ISLNK)
1980 if (input_file_statable_p)
1982 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
1984 #if defined (EISDIR)
1985 /* Get a better looking error message. */
1986 errno = EISDIR;
1987 #endif /* EISDIR */
1988 report_file_error ("Non-regular file", Fcons (file, Qnil));
1991 #endif /* S_ISREG && S_ISLNK */
1993 #ifdef MSDOS
1994 /* System's default file type was set to binary by _fmode in emacs.c. */
1995 ofd = emacs_open (SDATA (encoded_newname),
1996 O_WRONLY | O_TRUNC | O_CREAT
1997 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
1998 S_IREAD | S_IWRITE);
1999 #else /* not MSDOS */
2000 ofd = emacs_open (SDATA (encoded_newname),
2001 O_WRONLY | O_TRUNC | O_CREAT
2002 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2003 0666);
2004 #endif /* not MSDOS */
2005 if (ofd < 0)
2006 report_file_error ("Opening output file", Fcons (newname, Qnil));
2008 record_unwind_protect (close_file_unwind, make_number (ofd));
2010 immediate_quit = 1;
2011 QUIT;
2012 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2013 if (emacs_write (ofd, buf, n) != n)
2014 report_file_error ("I/O error", Fcons (newname, Qnil));
2015 immediate_quit = 0;
2017 #ifndef MSDOS
2018 /* Preserve the original file modes, and if requested, also its
2019 owner and group. */
2020 if (input_file_statable_p)
2022 if (! NILP (preserve_uid_gid))
2023 fchown (ofd, st.st_uid, st.st_gid);
2024 fchmod (ofd, st.st_mode & 07777);
2026 #endif /* not MSDOS */
2028 #if HAVE_LIBSELINUX
2029 if (conlength > 0)
2031 /* Set the modified context back to the file. */
2032 fail = fsetfilecon (ofd, con);
2033 if (fail)
2034 report_file_error ("Doing fsetfilecon", Fcons (newname, Qnil));
2036 freecon (con);
2038 #endif
2040 /* Closing the output clobbers the file times on some systems. */
2041 if (emacs_close (ofd) < 0)
2042 report_file_error ("I/O error", Fcons (newname, Qnil));
2044 if (input_file_statable_p)
2046 if (!NILP (keep_time))
2048 EMACS_TIME atime, mtime;
2049 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2050 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2051 if (set_file_times (SDATA (encoded_newname),
2052 atime, mtime))
2053 xsignal2 (Qfile_date_error,
2054 build_string ("Cannot set file date"), newname);
2058 emacs_close (ifd);
2060 #ifdef MSDOS
2061 if (input_file_statable_p)
2063 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2064 and if it can't, it tells so. Otherwise, under MSDOS we usually
2065 get only the READ bit, which will make the copied file read-only,
2066 so it's better not to chmod at all. */
2067 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2068 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2070 #endif /* MSDOS */
2071 #endif /* not WINDOWSNT */
2073 /* Discard the unwind protects. */
2074 specpdl_ptr = specpdl + count;
2076 UNGCPRO;
2077 return Qnil;
2080 DEFUN ("make-directory-internal", Fmake_directory_internal,
2081 Smake_directory_internal, 1, 1, 0,
2082 doc: /* Create a new directory named DIRECTORY. */)
2083 (Lisp_Object directory)
2085 const unsigned char *dir;
2086 Lisp_Object handler;
2087 Lisp_Object encoded_dir;
2089 CHECK_STRING (directory);
2090 directory = Fexpand_file_name (directory, Qnil);
2092 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2093 if (!NILP (handler))
2094 return call2 (handler, Qmake_directory_internal, directory);
2096 encoded_dir = ENCODE_FILE (directory);
2098 dir = SDATA (encoded_dir);
2100 #ifdef WINDOWSNT
2101 if (mkdir (dir) != 0)
2102 #else
2103 if (mkdir (dir, 0777) != 0)
2104 #endif
2105 report_file_error ("Creating directory", list1 (directory));
2107 return Qnil;
2110 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2111 Sdelete_directory_internal, 1, 1, 0,
2112 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2113 (Lisp_Object directory)
2115 const unsigned char *dir;
2116 Lisp_Object handler;
2117 Lisp_Object encoded_dir;
2119 CHECK_STRING (directory);
2120 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2121 encoded_dir = ENCODE_FILE (directory);
2122 dir = SDATA (encoded_dir);
2124 if (rmdir (dir) != 0)
2125 report_file_error ("Removing directory", list1 (directory));
2127 return Qnil;
2130 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2131 "(list (read-file-name \
2132 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2133 \"Move file to trash: \" \"Delete file: \") \
2134 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2135 (null current-prefix-arg))",
2136 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2137 If file has multiple names, it continues to exist with the other names.
2138 TRASH non-nil means to trash the file instead of deleting, provided
2139 `delete-by-moving-to-trash' is non-nil.
2141 When called interactively, TRASH is t if no prefix argument is given.
2142 With a prefix argument, TRASH is nil. */)
2143 (Lisp_Object filename, Lisp_Object trash)
2145 Lisp_Object handler;
2146 Lisp_Object encoded_file;
2147 struct gcpro gcpro1;
2149 GCPRO1 (filename);
2150 if (!NILP (Ffile_directory_p (filename))
2151 && NILP (Ffile_symlink_p (filename)))
2152 xsignal2 (Qfile_error,
2153 build_string ("Removing old name: is a directory"),
2154 filename);
2155 UNGCPRO;
2156 filename = Fexpand_file_name (filename, Qnil);
2158 handler = Ffind_file_name_handler (filename, Qdelete_file);
2159 if (!NILP (handler))
2160 return call3 (handler, Qdelete_file, filename, trash);
2162 if (delete_by_moving_to_trash && !NILP (trash))
2163 return call1 (Qmove_file_to_trash, filename);
2165 encoded_file = ENCODE_FILE (filename);
2167 if (0 > unlink (SDATA (encoded_file)))
2168 report_file_error ("Removing old name", list1 (filename));
2169 return Qnil;
2172 static Lisp_Object
2173 internal_delete_file_1 (Lisp_Object ignore)
2175 return Qt;
2178 /* Delete file FILENAME, returning 1 if successful and 0 if failed.
2179 This ignores `delete-by-moving-to-trash'. */
2182 internal_delete_file (Lisp_Object filename)
2184 Lisp_Object tem;
2186 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2187 Qt, internal_delete_file_1);
2188 return NILP (tem);
2191 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2192 "fRename file: \nGRename %s to file: \np",
2193 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2194 If file has names other than FILE, it continues to have those names.
2195 Signals a `file-already-exists' error if a file NEWNAME already exists
2196 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2197 A number as third arg means request confirmation if NEWNAME already exists.
2198 This is what happens in interactive use with M-x. */)
2199 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2201 Lisp_Object handler;
2202 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2203 Lisp_Object encoded_file, encoded_newname, symlink_target;
2205 symlink_target = encoded_file = encoded_newname = Qnil;
2206 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2207 CHECK_STRING (file);
2208 CHECK_STRING (newname);
2209 file = Fexpand_file_name (file, Qnil);
2211 if ((!NILP (Ffile_directory_p (newname)))
2212 #ifdef DOS_NT
2213 /* If the file names are identical but for the case,
2214 don't attempt to move directory to itself. */
2215 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2216 #endif
2219 Lisp_Object fname = NILP (Ffile_directory_p (file))
2220 ? file : Fdirectory_file_name (file);
2221 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2223 else
2224 newname = Fexpand_file_name (newname, Qnil);
2226 /* If the file name has special constructs in it,
2227 call the corresponding file handler. */
2228 handler = Ffind_file_name_handler (file, Qrename_file);
2229 if (NILP (handler))
2230 handler = Ffind_file_name_handler (newname, Qrename_file);
2231 if (!NILP (handler))
2232 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2233 file, newname, ok_if_already_exists));
2235 encoded_file = ENCODE_FILE (file);
2236 encoded_newname = ENCODE_FILE (newname);
2238 #ifdef DOS_NT
2239 /* If the file names are identical but for the case, don't ask for
2240 confirmation: they simply want to change the letter-case of the
2241 file name. */
2242 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2243 #endif
2244 if (NILP (ok_if_already_exists)
2245 || INTEGERP (ok_if_already_exists))
2246 barf_or_query_if_file_exists (newname, "rename to it",
2247 INTEGERP (ok_if_already_exists), 0, 0);
2248 if (0 > rename (SDATA (encoded_file), SDATA (encoded_newname)))
2250 if (errno == EXDEV)
2252 int count;
2253 #ifdef S_IFLNK
2254 symlink_target = Ffile_symlink_p (file);
2255 if (! NILP (symlink_target))
2256 Fmake_symbolic_link (symlink_target, newname,
2257 NILP (ok_if_already_exists) ? Qnil : Qt);
2258 else
2259 #endif
2260 if (!NILP (Ffile_directory_p (file)))
2261 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2262 else
2263 /* We have already prompted if it was an integer, so don't
2264 have copy-file prompt again. */
2265 Fcopy_file (file, newname,
2266 NILP (ok_if_already_exists) ? Qnil : Qt,
2267 Qt, Qt, Qt);
2269 count = SPECPDL_INDEX ();
2270 specbind (Qdelete_by_moving_to_trash, Qnil);
2272 if (!NILP (Ffile_directory_p (file))
2273 #ifdef S_IFLNK
2274 && NILP (symlink_target)
2275 #endif
2277 call2 (Qdelete_directory, file, Qt);
2278 else
2279 Fdelete_file (file, Qnil);
2280 unbind_to (count, Qnil);
2282 else
2283 report_file_error ("Renaming", list2 (file, newname));
2285 UNGCPRO;
2286 return Qnil;
2289 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2290 "fAdd name to file: \nGName to add to %s: \np",
2291 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2292 Signals a `file-already-exists' error if a file NEWNAME already exists
2293 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2294 A number as third arg means request confirmation if NEWNAME already exists.
2295 This is what happens in interactive use with M-x. */)
2296 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2298 Lisp_Object handler;
2299 Lisp_Object encoded_file, encoded_newname;
2300 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2302 GCPRO4 (file, newname, encoded_file, encoded_newname);
2303 encoded_file = encoded_newname = Qnil;
2304 CHECK_STRING (file);
2305 CHECK_STRING (newname);
2306 file = Fexpand_file_name (file, Qnil);
2308 if (!NILP (Ffile_directory_p (newname)))
2309 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2310 else
2311 newname = Fexpand_file_name (newname, Qnil);
2313 /* If the file name has special constructs in it,
2314 call the corresponding file handler. */
2315 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2316 if (!NILP (handler))
2317 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2318 newname, ok_if_already_exists));
2320 /* If the new name has special constructs in it,
2321 call the corresponding file handler. */
2322 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2323 if (!NILP (handler))
2324 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2325 newname, ok_if_already_exists));
2327 encoded_file = ENCODE_FILE (file);
2328 encoded_newname = ENCODE_FILE (newname);
2330 if (NILP (ok_if_already_exists)
2331 || INTEGERP (ok_if_already_exists))
2332 barf_or_query_if_file_exists (newname, "make it a new name",
2333 INTEGERP (ok_if_already_exists), 0, 0);
2335 unlink (SDATA (newname));
2336 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname)))
2337 report_file_error ("Adding new name", list2 (file, newname));
2339 UNGCPRO;
2340 return Qnil;
2343 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2344 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2345 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2346 Both args must be strings.
2347 Signals a `file-already-exists' error if a file LINKNAME already exists
2348 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2349 A number as third arg means request confirmation if LINKNAME already exists.
2350 This happens for interactive use with M-x. */)
2351 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2353 Lisp_Object handler;
2354 Lisp_Object encoded_filename, encoded_linkname;
2355 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2357 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2358 encoded_filename = encoded_linkname = Qnil;
2359 CHECK_STRING (filename);
2360 CHECK_STRING (linkname);
2361 /* If the link target has a ~, we must expand it to get
2362 a truly valid file name. Otherwise, do not expand;
2363 we want to permit links to relative file names. */
2364 if (SREF (filename, 0) == '~')
2365 filename = Fexpand_file_name (filename, Qnil);
2367 if (!NILP (Ffile_directory_p (linkname)))
2368 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2369 else
2370 linkname = Fexpand_file_name (linkname, Qnil);
2372 /* If the file name has special constructs in it,
2373 call the corresponding file handler. */
2374 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2375 if (!NILP (handler))
2376 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2377 linkname, ok_if_already_exists));
2379 /* If the new link name has special constructs in it,
2380 call the corresponding file handler. */
2381 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2382 if (!NILP (handler))
2383 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2384 linkname, ok_if_already_exists));
2386 #ifdef S_IFLNK
2387 encoded_filename = ENCODE_FILE (filename);
2388 encoded_linkname = ENCODE_FILE (linkname);
2390 if (NILP (ok_if_already_exists)
2391 || INTEGERP (ok_if_already_exists))
2392 barf_or_query_if_file_exists (linkname, "make it a link",
2393 INTEGERP (ok_if_already_exists), 0, 0);
2394 if (0 > symlink (SDATA (encoded_filename),
2395 SDATA (encoded_linkname)))
2397 /* If we didn't complain already, silently delete existing file. */
2398 if (errno == EEXIST)
2400 unlink (SDATA (encoded_linkname));
2401 if (0 <= symlink (SDATA (encoded_filename),
2402 SDATA (encoded_linkname)))
2404 UNGCPRO;
2405 return Qnil;
2409 report_file_error ("Making symbolic link", list2 (filename, linkname));
2411 UNGCPRO;
2412 return Qnil;
2414 #else
2415 UNGCPRO;
2416 xsignal1 (Qfile_error, build_string ("Symbolic links are not supported"));
2418 #endif /* S_IFLNK */
2422 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2423 1, 1, 0,
2424 doc: /* Return t if file FILENAME specifies an absolute file name.
2425 On Unix, this is a name starting with a `/' or a `~'. */)
2426 (Lisp_Object filename)
2428 CHECK_STRING (filename);
2429 return file_name_absolute_p (SDATA (filename)) ? Qt : Qnil;
2432 /* Return nonzero if file FILENAME exists and can be executed. */
2434 static int
2435 check_executable (char *filename)
2437 #ifdef DOS_NT
2438 int len = strlen (filename);
2439 char *suffix;
2440 struct stat st;
2441 if (stat (filename, &st) < 0)
2442 return 0;
2443 return ((st.st_mode & S_IEXEC) != 0);
2444 #else /* not DOS_NT */
2445 #ifdef HAVE_EUIDACCESS
2446 return (euidaccess (filename, 1) >= 0);
2447 #else
2448 /* Access isn't quite right because it uses the real uid
2449 and we really want to test with the effective uid.
2450 But Unix doesn't give us a right way to do it. */
2451 return (access (filename, 1) >= 0);
2452 #endif
2453 #endif /* not DOS_NT */
2456 /* Return nonzero if file FILENAME exists and can be written. */
2458 static int
2459 check_writable (const char *filename)
2461 #ifdef MSDOS
2462 struct stat st;
2463 if (stat (filename, &st) < 0)
2464 return 0;
2465 return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
2466 #else /* not MSDOS */
2467 #ifdef HAVE_EUIDACCESS
2468 return (euidaccess (filename, 2) >= 0);
2469 #else
2470 /* Access isn't quite right because it uses the real uid
2471 and we really want to test with the effective uid.
2472 But Unix doesn't give us a right way to do it.
2473 Opening with O_WRONLY could work for an ordinary file,
2474 but would lose for directories. */
2475 return (access (filename, 2) >= 0);
2476 #endif
2477 #endif /* not MSDOS */
2480 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2481 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2482 See also `file-readable-p' and `file-attributes'.
2483 This returns nil for a symlink to a nonexistent file.
2484 Use `file-symlink-p' to test for such links. */)
2485 (Lisp_Object filename)
2487 Lisp_Object absname;
2488 Lisp_Object handler;
2489 struct stat statbuf;
2491 CHECK_STRING (filename);
2492 absname = Fexpand_file_name (filename, Qnil);
2494 /* If the file name has special constructs in it,
2495 call the corresponding file handler. */
2496 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2497 if (!NILP (handler))
2498 return call2 (handler, Qfile_exists_p, absname);
2500 absname = ENCODE_FILE (absname);
2502 return (stat (SDATA (absname), &statbuf) >= 0) ? Qt : Qnil;
2505 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2506 doc: /* Return t if FILENAME can be executed by you.
2507 For a directory, this means you can access files in that directory. */)
2508 (Lisp_Object filename)
2510 Lisp_Object absname;
2511 Lisp_Object handler;
2513 CHECK_STRING (filename);
2514 absname = Fexpand_file_name (filename, Qnil);
2516 /* If the file name has special constructs in it,
2517 call the corresponding file handler. */
2518 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2519 if (!NILP (handler))
2520 return call2 (handler, Qfile_executable_p, absname);
2522 absname = ENCODE_FILE (absname);
2524 return (check_executable (SDATA (absname)) ? Qt : Qnil);
2527 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2528 doc: /* Return t if file FILENAME exists and you can read it.
2529 See also `file-exists-p' and `file-attributes'. */)
2530 (Lisp_Object filename)
2532 Lisp_Object absname;
2533 Lisp_Object handler;
2534 int desc;
2535 int flags;
2536 struct stat statbuf;
2538 CHECK_STRING (filename);
2539 absname = Fexpand_file_name (filename, Qnil);
2541 /* If the file name has special constructs in it,
2542 call the corresponding file handler. */
2543 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2544 if (!NILP (handler))
2545 return call2 (handler, Qfile_readable_p, absname);
2547 absname = ENCODE_FILE (absname);
2549 #if defined(DOS_NT) || defined(macintosh)
2550 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2551 directories. */
2552 if (access (SDATA (absname), 0) == 0)
2553 return Qt;
2554 return Qnil;
2555 #else /* not DOS_NT and not macintosh */
2556 flags = O_RDONLY;
2557 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
2558 /* Opening a fifo without O_NONBLOCK can wait.
2559 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2560 except in the case of a fifo, on a system which handles it. */
2561 desc = stat (SDATA (absname), &statbuf);
2562 if (desc < 0)
2563 return Qnil;
2564 if (S_ISFIFO (statbuf.st_mode))
2565 flags |= O_NONBLOCK;
2566 #endif
2567 desc = emacs_open (SDATA (absname), flags, 0);
2568 if (desc < 0)
2569 return Qnil;
2570 emacs_close (desc);
2571 return Qt;
2572 #endif /* not DOS_NT and not macintosh */
2575 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2576 on the RT/PC. */
2577 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2578 doc: /* Return t if file FILENAME can be written or created by you. */)
2579 (Lisp_Object filename)
2581 Lisp_Object absname, dir, encoded;
2582 Lisp_Object handler;
2583 struct stat statbuf;
2585 CHECK_STRING (filename);
2586 absname = Fexpand_file_name (filename, Qnil);
2588 /* If the file name has special constructs in it,
2589 call the corresponding file handler. */
2590 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2591 if (!NILP (handler))
2592 return call2 (handler, Qfile_writable_p, absname);
2594 encoded = ENCODE_FILE (absname);
2595 if (stat (SDATA (encoded), &statbuf) >= 0)
2596 return (check_writable (SDATA (encoded))
2597 ? Qt : Qnil);
2599 dir = Ffile_name_directory (absname);
2600 #ifdef MSDOS
2601 if (!NILP (dir))
2602 dir = Fdirectory_file_name (dir);
2603 #endif /* MSDOS */
2605 dir = ENCODE_FILE (dir);
2606 #ifdef WINDOWSNT
2607 /* The read-only attribute of the parent directory doesn't affect
2608 whether a file or directory can be created within it. Some day we
2609 should check ACLs though, which do affect this. */
2610 if (stat (SDATA (dir), &statbuf) < 0)
2611 return Qnil;
2612 return (statbuf.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2613 #else
2614 return (check_writable (!NILP (dir) ? (char *) SDATA (dir) : "")
2615 ? Qt : Qnil);
2616 #endif
2619 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2620 doc: /* Access file FILENAME, and get an error if that does not work.
2621 The second argument STRING is used in the error message.
2622 If there is no error, returns nil. */)
2623 (Lisp_Object filename, Lisp_Object string)
2625 Lisp_Object handler, encoded_filename, absname;
2626 int fd;
2628 CHECK_STRING (filename);
2629 absname = Fexpand_file_name (filename, Qnil);
2631 CHECK_STRING (string);
2633 /* If the file name has special constructs in it,
2634 call the corresponding file handler. */
2635 handler = Ffind_file_name_handler (absname, Qaccess_file);
2636 if (!NILP (handler))
2637 return call3 (handler, Qaccess_file, absname, string);
2639 encoded_filename = ENCODE_FILE (absname);
2641 fd = emacs_open (SDATA (encoded_filename), O_RDONLY, 0);
2642 if (fd < 0)
2643 report_file_error (SDATA (string), Fcons (filename, Qnil));
2644 emacs_close (fd);
2646 return Qnil;
2649 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2650 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2651 The value is the link target, as a string.
2652 Otherwise it returns nil.
2654 This function returns t when given the name of a symlink that
2655 points to a nonexistent file. */)
2656 (Lisp_Object filename)
2658 Lisp_Object handler;
2660 CHECK_STRING (filename);
2661 filename = Fexpand_file_name (filename, Qnil);
2663 /* If the file name has special constructs in it,
2664 call the corresponding file handler. */
2665 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2666 if (!NILP (handler))
2667 return call2 (handler, Qfile_symlink_p, filename);
2669 #ifdef S_IFLNK
2671 char *buf;
2672 int bufsize;
2673 int valsize;
2674 Lisp_Object val;
2676 filename = ENCODE_FILE (filename);
2678 bufsize = 50;
2679 buf = NULL;
2682 bufsize *= 2;
2683 buf = (char *) xrealloc (buf, bufsize);
2684 memset (buf, 0, bufsize);
2686 errno = 0;
2687 valsize = readlink (SDATA (filename), buf, bufsize);
2688 if (valsize == -1)
2690 #ifdef ERANGE
2691 /* HP-UX reports ERANGE if buffer is too small. */
2692 if (errno == ERANGE)
2693 valsize = bufsize;
2694 else
2695 #endif
2697 xfree (buf);
2698 return Qnil;
2702 while (valsize >= bufsize);
2704 val = make_string (buf, valsize);
2705 if (buf[0] == '/' && strchr (buf, ':'))
2706 val = concat2 (build_string ("/:"), val);
2707 xfree (buf);
2708 val = DECODE_FILE (val);
2709 return val;
2711 #else /* not S_IFLNK */
2712 return Qnil;
2713 #endif /* not S_IFLNK */
2716 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2717 doc: /* Return t if FILENAME names an existing directory.
2718 Symbolic links to directories count as directories.
2719 See `file-symlink-p' to distinguish symlinks. */)
2720 (Lisp_Object filename)
2722 register Lisp_Object absname;
2723 struct stat st;
2724 Lisp_Object handler;
2726 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2728 /* If the file name has special constructs in it,
2729 call the corresponding file handler. */
2730 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2731 if (!NILP (handler))
2732 return call2 (handler, Qfile_directory_p, absname);
2734 absname = ENCODE_FILE (absname);
2736 if (stat (SDATA (absname), &st) < 0)
2737 return Qnil;
2738 return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2741 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
2742 doc: /* Return t if file FILENAME names a directory you can open.
2743 For the value to be t, FILENAME must specify the name of a directory as a file,
2744 and the directory must allow you to open files in it. In order to use a
2745 directory as a buffer's current directory, this predicate must return true.
2746 A directory name spec may be given instead; then the value is t
2747 if the directory so specified exists and really is a readable and
2748 searchable directory. */)
2749 (Lisp_Object filename)
2751 Lisp_Object handler;
2752 int tem;
2753 struct gcpro gcpro1;
2755 /* If the file name has special constructs in it,
2756 call the corresponding file handler. */
2757 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
2758 if (!NILP (handler))
2759 return call2 (handler, Qfile_accessible_directory_p, filename);
2761 GCPRO1 (filename);
2762 tem = (NILP (Ffile_directory_p (filename))
2763 || NILP (Ffile_executable_p (filename)));
2764 UNGCPRO;
2765 return tem ? Qnil : Qt;
2768 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2769 doc: /* Return t if FILENAME names a regular file.
2770 This is the sort of file that holds an ordinary stream of data bytes.
2771 Symbolic links to regular files count as regular files.
2772 See `file-symlink-p' to distinguish symlinks. */)
2773 (Lisp_Object filename)
2775 register Lisp_Object absname;
2776 struct stat st;
2777 Lisp_Object handler;
2779 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2781 /* If the file name has special constructs in it,
2782 call the corresponding file handler. */
2783 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2784 if (!NILP (handler))
2785 return call2 (handler, Qfile_regular_p, absname);
2787 absname = ENCODE_FILE (absname);
2789 #ifdef WINDOWSNT
2791 int result;
2792 Lisp_Object tem = Vw32_get_true_file_attributes;
2794 /* Tell stat to use expensive method to get accurate info. */
2795 Vw32_get_true_file_attributes = Qt;
2796 result = stat (SDATA (absname), &st);
2797 Vw32_get_true_file_attributes = tem;
2799 if (result < 0)
2800 return Qnil;
2801 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2803 #else
2804 if (stat (SDATA (absname), &st) < 0)
2805 return Qnil;
2806 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2807 #endif
2810 DEFUN ("file-selinux-context", Ffile_selinux_context,
2811 Sfile_selinux_context, 1, 1, 0,
2812 doc: /* Return SELinux context of file named FILENAME,
2813 as a list ("user", "role", "type", "range"). Return (nil, nil, nil, nil)
2814 if file does not exist, is not accessible, or SELinux is disabled */)
2815 (Lisp_Object filename)
2817 Lisp_Object absname;
2818 Lisp_Object values[4];
2819 Lisp_Object handler;
2820 #if HAVE_LIBSELINUX
2821 security_context_t con;
2822 int conlength;
2823 context_t context;
2824 #endif
2826 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2828 /* If the file name has special constructs in it,
2829 call the corresponding file handler. */
2830 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2831 if (!NILP (handler))
2832 return call2 (handler, Qfile_selinux_context, absname);
2834 absname = ENCODE_FILE (absname);
2836 values[0] = Qnil;
2837 values[1] = Qnil;
2838 values[2] = Qnil;
2839 values[3] = Qnil;
2840 #if HAVE_LIBSELINUX
2841 if (is_selinux_enabled ())
2843 conlength = lgetfilecon (SDATA (absname), &con);
2844 if (conlength > 0)
2846 context = context_new (con);
2847 if (context_user_get (context))
2848 values[0] = build_string (context_user_get (context));
2849 if (context_role_get (context))
2850 values[1] = build_string (context_role_get (context));
2851 if (context_type_get (context))
2852 values[2] = build_string (context_type_get (context));
2853 if (context_range_get (context))
2854 values[3] = build_string (context_range_get (context));
2855 context_free (context);
2857 if (con)
2858 freecon (con);
2860 #endif
2862 return Flist (sizeof(values) / sizeof(values[0]), values);
2865 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2866 Sset_file_selinux_context, 2, 2, 0,
2867 doc: /* Set SELinux context of file named FILENAME to CONTEXT
2868 as a list ("user", "role", "type", "range"). Has no effect if SELinux
2869 is disabled. */)
2870 (Lisp_Object filename, Lisp_Object context)
2872 Lisp_Object absname, encoded_absname;
2873 Lisp_Object handler;
2874 Lisp_Object user = CAR_SAFE (context);
2875 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2876 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2877 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2878 #if HAVE_LIBSELINUX
2879 security_context_t con;
2880 int fail, conlength;
2881 context_t parsed_con;
2882 #endif
2884 absname = Fexpand_file_name (filename, current_buffer->directory);
2886 /* If the file name has special constructs in it,
2887 call the corresponding file handler. */
2888 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2889 if (!NILP (handler))
2890 return call3 (handler, Qset_file_selinux_context, absname, context);
2892 encoded_absname = ENCODE_FILE (absname);
2894 #if HAVE_LIBSELINUX
2895 if (is_selinux_enabled ())
2897 /* Get current file context. */
2898 conlength = lgetfilecon (SDATA (encoded_absname), &con);
2899 if (conlength > 0)
2901 parsed_con = context_new (con);
2902 /* Change the parts defined in the parameter.*/
2903 if (STRINGP (user))
2905 if (context_user_set (parsed_con, SDATA (user)))
2906 error ("Doing context_user_set");
2908 if (STRINGP (role))
2910 if (context_role_set (parsed_con, SDATA (role)))
2911 error ("Doing context_role_set");
2913 if (STRINGP (type))
2915 if (context_type_set (parsed_con, SDATA (type)))
2916 error ("Doing context_type_set");
2918 if (STRINGP (range))
2920 if (context_range_set (parsed_con, SDATA (range)))
2921 error ("Doing context_range_set");
2924 /* Set the modified context back to the file. */
2925 fail = lsetfilecon (SDATA (encoded_absname), context_str (parsed_con));
2926 if (fail)
2927 report_file_error ("Doing lsetfilecon", Fcons (absname, Qnil));
2929 context_free (parsed_con);
2931 else
2932 report_file_error("Doing lgetfilecon", Fcons (absname, Qnil));
2934 if (con)
2935 freecon (con);
2937 #endif
2939 return Qnil;
2942 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
2943 doc: /* Return mode bits of file named FILENAME, as an integer.
2944 Return nil, if file does not exist or is not accessible. */)
2945 (Lisp_Object filename)
2947 Lisp_Object absname;
2948 struct stat st;
2949 Lisp_Object handler;
2951 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2953 /* If the file name has special constructs in it,
2954 call the corresponding file handler. */
2955 handler = Ffind_file_name_handler (absname, Qfile_modes);
2956 if (!NILP (handler))
2957 return call2 (handler, Qfile_modes, absname);
2959 absname = ENCODE_FILE (absname);
2961 if (stat (SDATA (absname), &st) < 0)
2962 return Qnil;
2964 return make_number (st.st_mode & 07777);
2967 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
2968 "(let ((file (read-file-name \"File: \"))) \
2969 (list file (read-file-modes nil file)))",
2970 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
2971 Only the 12 low bits of MODE are used.
2973 Interactively, mode bits are read by `read-file-modes', which accepts
2974 symbolic notation, like the `chmod' command from GNU Coreutils. */)
2975 (Lisp_Object filename, Lisp_Object mode)
2977 Lisp_Object absname, encoded_absname;
2978 Lisp_Object handler;
2980 absname = Fexpand_file_name (filename, current_buffer->directory);
2981 CHECK_NUMBER (mode);
2983 /* If the file name has special constructs in it,
2984 call the corresponding file handler. */
2985 handler = Ffind_file_name_handler (absname, Qset_file_modes);
2986 if (!NILP (handler))
2987 return call3 (handler, Qset_file_modes, absname, mode);
2989 encoded_absname = ENCODE_FILE (absname);
2991 if (chmod (SDATA (encoded_absname), XINT (mode)) < 0)
2992 report_file_error ("Doing chmod", Fcons (absname, Qnil));
2994 return Qnil;
2997 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
2998 doc: /* Set the file permission bits for newly created files.
2999 The argument MODE should be an integer; only the low 9 bits are used.
3000 This setting is inherited by subprocesses. */)
3001 (Lisp_Object mode)
3003 CHECK_NUMBER (mode);
3005 umask ((~ XINT (mode)) & 0777);
3007 return Qnil;
3010 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3011 doc: /* Return the default file protection for created files.
3012 The value is an integer. */)
3013 (void)
3015 int realmask;
3016 Lisp_Object value;
3018 realmask = umask (0);
3019 umask (realmask);
3021 XSETINT (value, (~ realmask) & 0777);
3022 return value;
3026 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3027 doc: /* Set times of file FILENAME to TIME.
3028 Set both access and modification times.
3029 Return t on success, else nil.
3030 Use the current time if TIME is nil. TIME is in the format of
3031 `current-time'. */)
3032 (Lisp_Object filename, Lisp_Object time)
3034 Lisp_Object absname, encoded_absname;
3035 Lisp_Object handler;
3036 time_t sec;
3037 int usec;
3039 if (! lisp_time_argument (time, &sec, &usec))
3040 error ("Invalid time specification");
3042 absname = Fexpand_file_name (filename, current_buffer->directory);
3044 /* If the file name has special constructs in it,
3045 call the corresponding file handler. */
3046 handler = Ffind_file_name_handler (absname, Qset_file_times);
3047 if (!NILP (handler))
3048 return call3 (handler, Qset_file_times, absname, time);
3050 encoded_absname = ENCODE_FILE (absname);
3053 EMACS_TIME t;
3055 EMACS_SET_SECS (t, sec);
3056 EMACS_SET_USECS (t, usec);
3058 if (set_file_times (SDATA (encoded_absname), t, t))
3060 #ifdef DOS_NT
3061 struct stat st;
3063 /* Setting times on a directory always fails. */
3064 if (stat (SDATA (encoded_absname), &st) == 0
3065 && (st.st_mode & S_IFMT) == S_IFDIR)
3066 return Qnil;
3067 #endif
3068 report_file_error ("Setting file times", Fcons (absname, Qnil));
3069 return Qnil;
3073 return Qt;
3076 #ifdef HAVE_SYNC
3077 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3078 doc: /* Tell Unix to finish all pending disk updates. */)
3079 (void)
3081 sync ();
3082 return Qnil;
3085 #endif /* HAVE_SYNC */
3087 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3088 doc: /* Return t if file FILE1 is newer than file FILE2.
3089 If FILE1 does not exist, the answer is nil;
3090 otherwise, if FILE2 does not exist, the answer is t. */)
3091 (Lisp_Object file1, Lisp_Object file2)
3093 Lisp_Object absname1, absname2;
3094 struct stat st;
3095 int mtime1;
3096 Lisp_Object handler;
3097 struct gcpro gcpro1, gcpro2;
3099 CHECK_STRING (file1);
3100 CHECK_STRING (file2);
3102 absname1 = Qnil;
3103 GCPRO2 (absname1, file2);
3104 absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
3105 absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
3106 UNGCPRO;
3108 /* If the file name has special constructs in it,
3109 call the corresponding file handler. */
3110 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3111 if (NILP (handler))
3112 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3113 if (!NILP (handler))
3114 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3116 GCPRO2 (absname1, absname2);
3117 absname1 = ENCODE_FILE (absname1);
3118 absname2 = ENCODE_FILE (absname2);
3119 UNGCPRO;
3121 if (stat (SDATA (absname1), &st) < 0)
3122 return Qnil;
3124 mtime1 = st.st_mtime;
3126 if (stat (SDATA (absname2), &st) < 0)
3127 return Qt;
3129 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3132 #ifdef DOS_NT
3133 Lisp_Object Qfind_buffer_file_type;
3134 #endif /* DOS_NT */
3136 #ifndef READ_BUF_SIZE
3137 #define READ_BUF_SIZE (64 << 10)
3138 #endif
3140 /* This function is called after Lisp functions to decide a coding
3141 system are called, or when they cause an error. Before they are
3142 called, the current buffer is set unibyte and it contains only a
3143 newly inserted text (thus the buffer was empty before the
3144 insertion).
3146 The functions may set markers, overlays, text properties, or even
3147 alter the buffer contents, change the current buffer.
3149 Here, we reset all those changes by:
3150 o set back the current buffer.
3151 o move all markers and overlays to BEG.
3152 o remove all text properties.
3153 o set back the buffer multibyteness. */
3155 static Lisp_Object
3156 decide_coding_unwind (Lisp_Object unwind_data)
3158 Lisp_Object multibyte, undo_list, buffer;
3160 multibyte = XCAR (unwind_data);
3161 unwind_data = XCDR (unwind_data);
3162 undo_list = XCAR (unwind_data);
3163 buffer = XCDR (unwind_data);
3165 if (current_buffer != XBUFFER (buffer))
3166 set_buffer_internal (XBUFFER (buffer));
3167 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3168 adjust_overlays_for_delete (BEG, Z - BEG);
3169 BUF_INTERVALS (current_buffer) = 0;
3170 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3172 /* Now we are safe to change the buffer's multibyteness directly. */
3173 current_buffer->enable_multibyte_characters = multibyte;
3174 current_buffer->undo_list = undo_list;
3176 return Qnil;
3180 /* Used to pass values from insert-file-contents to read_non_regular. */
3182 static int non_regular_fd;
3183 static EMACS_INT non_regular_inserted;
3184 static EMACS_INT non_regular_nbytes;
3187 /* Read from a non-regular file.
3188 Read non_regular_nbytes bytes max from non_regular_fd.
3189 Non_regular_inserted specifies where to put the read bytes.
3190 Value is the number of bytes read. */
3192 static Lisp_Object
3193 read_non_regular (Lisp_Object ignore)
3195 EMACS_INT nbytes;
3197 immediate_quit = 1;
3198 QUIT;
3199 nbytes = emacs_read (non_regular_fd,
3200 BEG_ADDR + PT_BYTE - BEG_BYTE + non_regular_inserted,
3201 non_regular_nbytes);
3202 immediate_quit = 0;
3203 return make_number (nbytes);
3207 /* Condition-case handler used when reading from non-regular files
3208 in insert-file-contents. */
3210 static Lisp_Object
3211 read_non_regular_quit (Lisp_Object ignore)
3213 return Qnil;
3217 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3218 1, 5, 0,
3219 doc: /* Insert contents of file FILENAME after point.
3220 Returns list of absolute file name and number of characters inserted.
3221 If second argument VISIT is non-nil, the buffer's visited filename and
3222 last save file modtime are set, and it is marked unmodified. If
3223 visiting and the file does not exist, visiting is completed before the
3224 error is signaled.
3226 The optional third and fourth arguments BEG and END specify what portion
3227 of the file to insert. These arguments count bytes in the file, not
3228 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3230 If optional fifth argument REPLACE is non-nil, replace the current
3231 buffer contents (in the accessible portion) with the file contents.
3232 This is better than simply deleting and inserting the whole thing
3233 because (1) it preserves some marker positions and (2) it puts less data
3234 in the undo list. When REPLACE is non-nil, the second return value is
3235 the number of characters that replace previous buffer contents.
3237 This function does code conversion according to the value of
3238 `coding-system-for-read' or `file-coding-system-alist', and sets the
3239 variable `last-coding-system-used' to the coding system actually used. */)
3240 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3242 struct stat st;
3243 register int fd;
3244 EMACS_INT inserted = 0;
3245 int nochange = 0;
3246 register EMACS_INT how_much;
3247 register EMACS_INT unprocessed;
3248 int count = SPECPDL_INDEX ();
3249 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3250 Lisp_Object handler, val, insval, orig_filename, old_undo;
3251 Lisp_Object p;
3252 EMACS_INT total = 0;
3253 int not_regular = 0;
3254 unsigned char read_buf[READ_BUF_SIZE];
3255 struct coding_system coding;
3256 unsigned char buffer[1 << 14];
3257 int replace_handled = 0;
3258 int set_coding_system = 0;
3259 Lisp_Object coding_system;
3260 int read_quit = 0;
3261 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3262 int we_locked_file = 0;
3263 int deferred_remove_unwind_protect = 0;
3265 if (current_buffer->base_buffer && ! NILP (visit))
3266 error ("Cannot do file visiting in an indirect buffer");
3268 if (!NILP (current_buffer->read_only))
3269 Fbarf_if_buffer_read_only ();
3271 val = Qnil;
3272 p = Qnil;
3273 orig_filename = Qnil;
3274 old_undo = Qnil;
3276 GCPRO5 (filename, val, p, orig_filename, old_undo);
3278 CHECK_STRING (filename);
3279 filename = Fexpand_file_name (filename, Qnil);
3281 /* The value Qnil means that the coding system is not yet
3282 decided. */
3283 coding_system = Qnil;
3285 /* If the file name has special constructs in it,
3286 call the corresponding file handler. */
3287 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3288 if (!NILP (handler))
3290 val = call6 (handler, Qinsert_file_contents, filename,
3291 visit, beg, end, replace);
3292 if (CONSP (val) && CONSP (XCDR (val)))
3293 inserted = XINT (XCAR (XCDR (val)));
3294 goto handled;
3297 orig_filename = filename;
3298 filename = ENCODE_FILE (filename);
3300 fd = -1;
3302 #ifdef WINDOWSNT
3304 Lisp_Object tem = Vw32_get_true_file_attributes;
3306 /* Tell stat to use expensive method to get accurate info. */
3307 Vw32_get_true_file_attributes = Qt;
3308 total = stat (SDATA (filename), &st);
3309 Vw32_get_true_file_attributes = tem;
3311 if (total < 0)
3312 #else
3313 if (stat (SDATA (filename), &st) < 0)
3314 #endif /* WINDOWSNT */
3316 if (fd >= 0) emacs_close (fd);
3317 badopen:
3318 if (NILP (visit))
3319 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3320 st.st_mtime = -1;
3321 how_much = 0;
3322 if (!NILP (Vcoding_system_for_read))
3323 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3324 goto notfound;
3327 #ifdef S_IFREG
3328 /* This code will need to be changed in order to work on named
3329 pipes, and it's probably just not worth it. So we should at
3330 least signal an error. */
3331 if (!S_ISREG (st.st_mode))
3333 not_regular = 1;
3335 if (! NILP (visit))
3336 goto notfound;
3338 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3339 xsignal2 (Qfile_error,
3340 build_string ("not a regular file"), orig_filename);
3342 #endif
3344 if (fd < 0)
3345 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0)
3346 goto badopen;
3348 /* Replacement should preserve point as it preserves markers. */
3349 if (!NILP (replace))
3350 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3352 record_unwind_protect (close_file_unwind, make_number (fd));
3354 /* Can happen on any platform that uses long as type of off_t, but allows
3355 file sizes to exceed 2Gb, so give a suitable message. */
3356 if (! not_regular && st.st_size < 0)
3357 error ("Maximum buffer size exceeded");
3359 /* Prevent redisplay optimizations. */
3360 current_buffer->clip_changed = 1;
3362 if (!NILP (visit))
3364 if (!NILP (beg) || !NILP (end))
3365 error ("Attempt to visit less than an entire file");
3366 if (BEG < Z && NILP (replace))
3367 error ("Cannot do file visiting in a non-empty buffer");
3370 if (!NILP (beg))
3371 CHECK_NUMBER (beg);
3372 else
3373 XSETFASTINT (beg, 0);
3375 if (!NILP (end))
3376 CHECK_NUMBER (end);
3377 else
3379 if (! not_regular)
3381 XSETINT (end, st.st_size);
3383 /* Arithmetic overflow can occur if an Emacs integer cannot
3384 represent the file size, or if the calculations below
3385 overflow. The calculations below double the file size
3386 twice, so check that it can be multiplied by 4 safely. */
3387 if (XINT (end) != st.st_size
3388 /* Actually, it should test either INT_MAX or LONG_MAX
3389 depending on which one is used for EMACS_INT. But in
3390 any case, in practice, this test is redundant with the
3391 one above.
3392 || st.st_size > INT_MAX / 4 */)
3393 error ("Maximum buffer size exceeded");
3395 /* The file size returned from stat may be zero, but data
3396 may be readable nonetheless, for example when this is a
3397 file in the /proc filesystem. */
3398 if (st.st_size == 0)
3399 XSETINT (end, READ_BUF_SIZE);
3403 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3405 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3406 setup_coding_system (coding_system, &coding);
3407 /* Ensure we set Vlast_coding_system_used. */
3408 set_coding_system = 1;
3410 else if (BEG < Z)
3412 /* Decide the coding system to use for reading the file now
3413 because we can't use an optimized method for handling
3414 `coding:' tag if the current buffer is not empty. */
3415 if (!NILP (Vcoding_system_for_read))
3416 coding_system = Vcoding_system_for_read;
3417 else
3419 /* Don't try looking inside a file for a coding system
3420 specification if it is not seekable. */
3421 if (! not_regular && ! NILP (Vset_auto_coding_function))
3423 /* Find a coding system specified in the heading two
3424 lines or in the tailing several lines of the file.
3425 We assume that the 1K-byte and 3K-byte for heading
3426 and tailing respectively are sufficient for this
3427 purpose. */
3428 EMACS_INT nread;
3430 if (st.st_size <= (1024 * 4))
3431 nread = emacs_read (fd, read_buf, 1024 * 4);
3432 else
3434 nread = emacs_read (fd, read_buf, 1024);
3435 if (nread >= 0)
3437 if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
3438 report_file_error ("Setting file position",
3439 Fcons (orig_filename, Qnil));
3440 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3444 if (nread < 0)
3445 error ("IO error reading %s: %s",
3446 SDATA (orig_filename), emacs_strerror (errno));
3447 else if (nread > 0)
3449 struct buffer *prev = current_buffer;
3450 Lisp_Object buffer;
3451 struct buffer *buf;
3453 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3455 buffer = Fget_buffer_create (build_string (" *code-converting-work*"));
3456 buf = XBUFFER (buffer);
3458 delete_all_overlays (buf);
3459 buf->directory = current_buffer->directory;
3460 buf->read_only = Qnil;
3461 buf->filename = Qnil;
3462 buf->undo_list = Qt;
3463 eassert (buf->overlays_before == NULL);
3464 eassert (buf->overlays_after == NULL);
3466 set_buffer_internal (buf);
3467 Ferase_buffer ();
3468 buf->enable_multibyte_characters = Qnil;
3470 insert_1_both (read_buf, nread, nread, 0, 0, 0);
3471 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3472 coding_system = call2 (Vset_auto_coding_function,
3473 filename, make_number (nread));
3474 set_buffer_internal (prev);
3476 /* Discard the unwind protect for recovering the
3477 current buffer. */
3478 specpdl_ptr--;
3480 /* Rewind the file for the actual read done later. */
3481 if (lseek (fd, 0, 0) < 0)
3482 report_file_error ("Setting file position",
3483 Fcons (orig_filename, Qnil));
3487 if (NILP (coding_system))
3489 /* If we have not yet decided a coding system, check
3490 file-coding-system-alist. */
3491 Lisp_Object args[6];
3493 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3494 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3495 coding_system = Ffind_operation_coding_system (6, args);
3496 if (CONSP (coding_system))
3497 coding_system = XCAR (coding_system);
3501 if (NILP (coding_system))
3502 coding_system = Qundecided;
3503 else
3504 CHECK_CODING_SYSTEM (coding_system);
3506 if (NILP (current_buffer->enable_multibyte_characters))
3507 /* We must suppress all character code conversion except for
3508 end-of-line conversion. */
3509 coding_system = raw_text_coding_system (coding_system);
3511 setup_coding_system (coding_system, &coding);
3512 /* Ensure we set Vlast_coding_system_used. */
3513 set_coding_system = 1;
3516 /* If requested, replace the accessible part of the buffer
3517 with the file contents. Avoid replacing text at the
3518 beginning or end of the buffer that matches the file contents;
3519 that preserves markers pointing to the unchanged parts.
3521 Here we implement this feature in an optimized way
3522 for the case where code conversion is NOT needed.
3523 The following if-statement handles the case of conversion
3524 in a less optimal way.
3526 If the code conversion is "automatic" then we try using this
3527 method and hope for the best.
3528 But if we discover the need for conversion, we give up on this method
3529 and let the following if-statement handle the replace job. */
3530 if (!NILP (replace)
3531 && BEGV < ZV
3532 && (NILP (coding_system)
3533 || ! CODING_REQUIRE_DECODING (&coding)))
3535 /* same_at_start and same_at_end count bytes,
3536 because file access counts bytes
3537 and BEG and END count bytes. */
3538 EMACS_INT same_at_start = BEGV_BYTE;
3539 EMACS_INT same_at_end = ZV_BYTE;
3540 EMACS_INT overlap;
3541 /* There is still a possibility we will find the need to do code
3542 conversion. If that happens, we set this variable to 1 to
3543 give up on handling REPLACE in the optimized way. */
3544 int giveup_match_end = 0;
3546 if (XINT (beg) != 0)
3548 if (lseek (fd, XINT (beg), 0) < 0)
3549 report_file_error ("Setting file position",
3550 Fcons (orig_filename, Qnil));
3553 immediate_quit = 1;
3554 QUIT;
3555 /* Count how many chars at the start of the file
3556 match the text at the beginning of the buffer. */
3557 while (1)
3559 EMACS_INT nread, bufpos;
3561 nread = emacs_read (fd, buffer, sizeof buffer);
3562 if (nread < 0)
3563 error ("IO error reading %s: %s",
3564 SDATA (orig_filename), emacs_strerror (errno));
3565 else if (nread == 0)
3566 break;
3568 if (CODING_REQUIRE_DETECTION (&coding))
3570 coding_system = detect_coding_system (buffer, nread, nread, 1, 0,
3571 coding_system);
3572 setup_coding_system (coding_system, &coding);
3575 if (CODING_REQUIRE_DECODING (&coding))
3576 /* We found that the file should be decoded somehow.
3577 Let's give up here. */
3579 giveup_match_end = 1;
3580 break;
3583 bufpos = 0;
3584 while (bufpos < nread && same_at_start < ZV_BYTE
3585 && FETCH_BYTE (same_at_start) == buffer[bufpos])
3586 same_at_start++, bufpos++;
3587 /* If we found a discrepancy, stop the scan.
3588 Otherwise loop around and scan the next bufferful. */
3589 if (bufpos != nread)
3590 break;
3592 immediate_quit = 0;
3593 /* If the file matches the buffer completely,
3594 there's no need to replace anything. */
3595 if (same_at_start - BEGV_BYTE == XINT (end))
3597 emacs_close (fd);
3598 specpdl_ptr--;
3599 /* Truncate the buffer to the size of the file. */
3600 del_range_1 (same_at_start, same_at_end, 0, 0);
3601 goto handled;
3603 immediate_quit = 1;
3604 QUIT;
3605 /* Count how many chars at the end of the file
3606 match the text at the end of the buffer. But, if we have
3607 already found that decoding is necessary, don't waste time. */
3608 while (!giveup_match_end)
3610 EMACS_INT total_read, nread, bufpos, curpos, trial;
3612 /* At what file position are we now scanning? */
3613 curpos = XINT (end) - (ZV_BYTE - same_at_end);
3614 /* If the entire file matches the buffer tail, stop the scan. */
3615 if (curpos == 0)
3616 break;
3617 /* How much can we scan in the next step? */
3618 trial = min (curpos, sizeof buffer);
3619 if (lseek (fd, curpos - trial, 0) < 0)
3620 report_file_error ("Setting file position",
3621 Fcons (orig_filename, Qnil));
3623 total_read = nread = 0;
3624 while (total_read < trial)
3626 nread = emacs_read (fd, buffer + total_read, trial - total_read);
3627 if (nread < 0)
3628 error ("IO error reading %s: %s",
3629 SDATA (orig_filename), emacs_strerror (errno));
3630 else if (nread == 0)
3631 break;
3632 total_read += nread;
3635 /* Scan this bufferful from the end, comparing with
3636 the Emacs buffer. */
3637 bufpos = total_read;
3639 /* Compare with same_at_start to avoid counting some buffer text
3640 as matching both at the file's beginning and at the end. */
3641 while (bufpos > 0 && same_at_end > same_at_start
3642 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
3643 same_at_end--, bufpos--;
3645 /* If we found a discrepancy, stop the scan.
3646 Otherwise loop around and scan the preceding bufferful. */
3647 if (bufpos != 0)
3649 /* If this discrepancy is because of code conversion,
3650 we cannot use this method; giveup and try the other. */
3651 if (same_at_end > same_at_start
3652 && FETCH_BYTE (same_at_end - 1) >= 0200
3653 && ! NILP (current_buffer->enable_multibyte_characters)
3654 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3655 giveup_match_end = 1;
3656 break;
3659 if (nread == 0)
3660 break;
3662 immediate_quit = 0;
3664 if (! giveup_match_end)
3666 EMACS_INT temp;
3668 /* We win! We can handle REPLACE the optimized way. */
3670 /* Extend the start of non-matching text area to multibyte
3671 character boundary. */
3672 if (! NILP (current_buffer->enable_multibyte_characters))
3673 while (same_at_start > BEGV_BYTE
3674 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3675 same_at_start--;
3677 /* Extend the end of non-matching text area to multibyte
3678 character boundary. */
3679 if (! NILP (current_buffer->enable_multibyte_characters))
3680 while (same_at_end < ZV_BYTE
3681 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3682 same_at_end++;
3684 /* Don't try to reuse the same piece of text twice. */
3685 overlap = (same_at_start - BEGV_BYTE
3686 - (same_at_end + st.st_size - ZV));
3687 if (overlap > 0)
3688 same_at_end += overlap;
3690 /* Arrange to read only the nonmatching middle part of the file. */
3691 XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV_BYTE));
3692 XSETFASTINT (end, XINT (end) - (ZV_BYTE - same_at_end));
3694 del_range_byte (same_at_start, same_at_end, 0);
3695 /* Insert from the file at the proper position. */
3696 temp = BYTE_TO_CHAR (same_at_start);
3697 SET_PT_BOTH (temp, same_at_start);
3699 /* If display currently starts at beginning of line,
3700 keep it that way. */
3701 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3702 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3704 replace_handled = 1;
3708 /* If requested, replace the accessible part of the buffer
3709 with the file contents. Avoid replacing text at the
3710 beginning or end of the buffer that matches the file contents;
3711 that preserves markers pointing to the unchanged parts.
3713 Here we implement this feature for the case where code conversion
3714 is needed, in a simple way that needs a lot of memory.
3715 The preceding if-statement handles the case of no conversion
3716 in a more optimized way. */
3717 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3719 EMACS_INT same_at_start = BEGV_BYTE;
3720 EMACS_INT same_at_end = ZV_BYTE;
3721 EMACS_INT same_at_start_charpos;
3722 EMACS_INT inserted_chars;
3723 EMACS_INT overlap;
3724 EMACS_INT bufpos;
3725 unsigned char *decoded;
3726 EMACS_INT temp;
3727 int this_count = SPECPDL_INDEX ();
3728 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
3729 Lisp_Object conversion_buffer;
3731 conversion_buffer = code_conversion_save (1, multibyte);
3733 /* First read the whole file, performing code conversion into
3734 CONVERSION_BUFFER. */
3736 if (lseek (fd, XINT (beg), 0) < 0)
3737 report_file_error ("Setting file position",
3738 Fcons (orig_filename, Qnil));
3740 total = st.st_size; /* Total bytes in the file. */
3741 how_much = 0; /* Bytes read from file so far. */
3742 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3743 unprocessed = 0; /* Bytes not processed in previous loop. */
3745 GCPRO1 (conversion_buffer);
3746 while (how_much < total)
3748 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
3749 quitting while reading a huge while. */
3750 /* try is reserved in some compilers (Microsoft C) */
3751 EMACS_INT trytry = min (total - how_much,
3752 READ_BUF_SIZE - unprocessed);
3753 EMACS_INT this;
3755 /* Allow quitting out of the actual I/O. */
3756 immediate_quit = 1;
3757 QUIT;
3758 this = emacs_read (fd, read_buf + unprocessed, trytry);
3759 immediate_quit = 0;
3761 if (this <= 0)
3763 if (this < 0)
3764 how_much = this;
3765 break;
3768 how_much += this;
3770 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3771 BUF_Z (XBUFFER (conversion_buffer)));
3772 decode_coding_c_string (&coding, read_buf, unprocessed + this,
3773 conversion_buffer);
3774 unprocessed = coding.carryover_bytes;
3775 if (coding.carryover_bytes > 0)
3776 memcpy (read_buf, coding.carryover, unprocessed);
3778 UNGCPRO;
3779 emacs_close (fd);
3781 /* We should remove the unwind_protect calling
3782 close_file_unwind, but other stuff has been added the stack,
3783 so defer the removal till we reach the `handled' label. */
3784 deferred_remove_unwind_protect = 1;
3786 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
3787 if we couldn't read the file. */
3789 if (how_much < 0)
3790 error ("IO error reading %s: %s",
3791 SDATA (orig_filename), emacs_strerror (errno));
3793 if (unprocessed > 0)
3795 coding.mode |= CODING_MODE_LAST_BLOCK;
3796 decode_coding_c_string (&coding, read_buf, unprocessed,
3797 conversion_buffer);
3798 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3801 coding_system = CODING_ID_NAME (coding.id);
3802 set_coding_system = 1;
3803 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3804 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3805 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3807 /* Compare the beginning of the converted string with the buffer
3808 text. */
3810 bufpos = 0;
3811 while (bufpos < inserted && same_at_start < same_at_end
3812 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3813 same_at_start++, bufpos++;
3815 /* If the file matches the head of buffer completely,
3816 there's no need to replace anything. */
3818 if (bufpos == inserted)
3820 /* Truncate the buffer to the size of the file. */
3821 if (same_at_start == same_at_end)
3822 nochange = 1;
3823 else
3824 del_range_byte (same_at_start, same_at_end, 0);
3825 inserted = 0;
3827 unbind_to (this_count, Qnil);
3828 goto handled;
3831 /* Extend the start of non-matching text area to the previous
3832 multibyte character boundary. */
3833 if (! NILP (current_buffer->enable_multibyte_characters))
3834 while (same_at_start > BEGV_BYTE
3835 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3836 same_at_start--;
3838 /* Scan this bufferful from the end, comparing with
3839 the Emacs buffer. */
3840 bufpos = inserted;
3842 /* Compare with same_at_start to avoid counting some buffer text
3843 as matching both at the file's beginning and at the end. */
3844 while (bufpos > 0 && same_at_end > same_at_start
3845 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3846 same_at_end--, bufpos--;
3848 /* Extend the end of non-matching text area to the next
3849 multibyte character boundary. */
3850 if (! NILP (current_buffer->enable_multibyte_characters))
3851 while (same_at_end < ZV_BYTE
3852 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3853 same_at_end++;
3855 /* Don't try to reuse the same piece of text twice. */
3856 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3857 if (overlap > 0)
3858 same_at_end += overlap;
3860 /* If display currently starts at beginning of line,
3861 keep it that way. */
3862 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3863 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3865 /* Replace the chars that we need to replace,
3866 and update INSERTED to equal the number of bytes
3867 we are taking from the decoded string. */
3868 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3870 if (same_at_end != same_at_start)
3872 del_range_byte (same_at_start, same_at_end, 0);
3873 temp = GPT;
3874 same_at_start = GPT_BYTE;
3876 else
3878 temp = BYTE_TO_CHAR (same_at_start);
3880 /* Insert from the file at the proper position. */
3881 SET_PT_BOTH (temp, same_at_start);
3882 same_at_start_charpos
3883 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3884 same_at_start - BEGV_BYTE
3885 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3886 inserted_chars
3887 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3888 same_at_start + inserted - BEGV_BYTE
3889 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
3890 - same_at_start_charpos);
3891 /* This binding is to avoid ask-user-about-supersession-threat
3892 being called in insert_from_buffer (via in
3893 prepare_to_modify_buffer). */
3894 specbind (intern ("buffer-file-name"), Qnil);
3895 insert_from_buffer (XBUFFER (conversion_buffer),
3896 same_at_start_charpos, inserted_chars, 0);
3897 /* Set `inserted' to the number of inserted characters. */
3898 inserted = PT - temp;
3899 /* Set point before the inserted characters. */
3900 SET_PT_BOTH (temp, same_at_start);
3902 unbind_to (this_count, Qnil);
3904 goto handled;
3907 if (! not_regular)
3909 register Lisp_Object temp;
3911 total = XINT (end) - XINT (beg);
3913 /* Make sure point-max won't overflow after this insertion. */
3914 XSETINT (temp, total);
3915 if (total != XINT (temp))
3916 error ("Maximum buffer size exceeded");
3918 else
3919 /* For a special file, all we can do is guess. */
3920 total = READ_BUF_SIZE;
3922 if (NILP (visit) && inserted > 0)
3924 #ifdef CLASH_DETECTION
3925 if (!NILP (current_buffer->file_truename)
3926 /* Make binding buffer-file-name to nil effective. */
3927 && !NILP (current_buffer->filename)
3928 && SAVE_MODIFF >= MODIFF)
3929 we_locked_file = 1;
3930 #endif /* CLASH_DETECTION */
3931 prepare_to_modify_buffer (GPT, GPT, NULL);
3934 move_gap (PT);
3935 if (GAP_SIZE < total)
3936 make_gap (total - GAP_SIZE);
3938 if (XINT (beg) != 0 || !NILP (replace))
3940 if (lseek (fd, XINT (beg), 0) < 0)
3941 report_file_error ("Setting file position",
3942 Fcons (orig_filename, Qnil));
3945 /* In the following loop, HOW_MUCH contains the total bytes read so
3946 far for a regular file, and not changed for a special file. But,
3947 before exiting the loop, it is set to a negative value if I/O
3948 error occurs. */
3949 how_much = 0;
3951 /* Total bytes inserted. */
3952 inserted = 0;
3954 /* Here, we don't do code conversion in the loop. It is done by
3955 decode_coding_gap after all data are read into the buffer. */
3957 EMACS_INT gap_size = GAP_SIZE;
3959 while (how_much < total)
3961 /* try is reserved in some compilers (Microsoft C) */
3962 EMACS_INT trytry = min (total - how_much, READ_BUF_SIZE);
3963 EMACS_INT this;
3965 if (not_regular)
3967 Lisp_Object val;
3969 /* Maybe make more room. */
3970 if (gap_size < trytry)
3972 make_gap (total - gap_size);
3973 gap_size = GAP_SIZE;
3976 /* Read from the file, capturing `quit'. When an
3977 error occurs, end the loop, and arrange for a quit
3978 to be signaled after decoding the text we read. */
3979 non_regular_fd = fd;
3980 non_regular_inserted = inserted;
3981 non_regular_nbytes = trytry;
3982 val = internal_condition_case_1 (read_non_regular, Qnil, Qerror,
3983 read_non_regular_quit);
3984 if (NILP (val))
3986 read_quit = 1;
3987 break;
3990 this = XINT (val);
3992 else
3994 /* Allow quitting out of the actual I/O. We don't make text
3995 part of the buffer until all the reading is done, so a C-g
3996 here doesn't do any harm. */
3997 immediate_quit = 1;
3998 QUIT;
3999 this = emacs_read (fd, BEG_ADDR + PT_BYTE - BEG_BYTE + inserted, trytry);
4000 immediate_quit = 0;
4003 if (this <= 0)
4005 how_much = this;
4006 break;
4009 gap_size -= this;
4011 /* For a regular file, where TOTAL is the real size,
4012 count HOW_MUCH to compare with it.
4013 For a special file, where TOTAL is just a buffer size,
4014 so don't bother counting in HOW_MUCH.
4015 (INSERTED is where we count the number of characters inserted.) */
4016 if (! not_regular)
4017 how_much += this;
4018 inserted += this;
4022 /* Now we have read all the file data into the gap.
4023 If it was empty, undo marking the buffer modified. */
4025 if (inserted == 0)
4027 #ifdef CLASH_DETECTION
4028 if (we_locked_file)
4029 unlock_file (current_buffer->file_truename);
4030 #endif
4031 Vdeactivate_mark = old_Vdeactivate_mark;
4033 else
4034 Vdeactivate_mark = Qt;
4036 /* Make the text read part of the buffer. */
4037 GAP_SIZE -= inserted;
4038 GPT += inserted;
4039 GPT_BYTE += inserted;
4040 ZV += inserted;
4041 ZV_BYTE += inserted;
4042 Z += inserted;
4043 Z_BYTE += inserted;
4045 if (GAP_SIZE > 0)
4046 /* Put an anchor to ensure multi-byte form ends at gap. */
4047 *GPT_ADDR = 0;
4049 emacs_close (fd);
4051 /* Discard the unwind protect for closing the file. */
4052 specpdl_ptr--;
4054 if (how_much < 0)
4055 error ("IO error reading %s: %s",
4056 SDATA (orig_filename), emacs_strerror (errno));
4058 notfound:
4060 if (NILP (coding_system))
4062 /* The coding system is not yet decided. Decide it by an
4063 optimized method for handling `coding:' tag.
4065 Note that we can get here only if the buffer was empty
4066 before the insertion. */
4068 if (!NILP (Vcoding_system_for_read))
4069 coding_system = Vcoding_system_for_read;
4070 else
4072 /* Since we are sure that the current buffer was empty
4073 before the insertion, we can toggle
4074 enable-multibyte-characters directly here without taking
4075 care of marker adjustment. By this way, we can run Lisp
4076 program safely before decoding the inserted text. */
4077 Lisp_Object unwind_data;
4078 int count = SPECPDL_INDEX ();
4080 unwind_data = Fcons (current_buffer->enable_multibyte_characters,
4081 Fcons (current_buffer->undo_list,
4082 Fcurrent_buffer ()));
4083 current_buffer->enable_multibyte_characters = Qnil;
4084 current_buffer->undo_list = Qt;
4085 record_unwind_protect (decide_coding_unwind, unwind_data);
4087 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4089 coding_system = call2 (Vset_auto_coding_function,
4090 filename, make_number (inserted));
4093 if (NILP (coding_system))
4095 /* If the coding system is not yet decided, check
4096 file-coding-system-alist. */
4097 Lisp_Object args[6];
4099 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4100 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4101 coding_system = Ffind_operation_coding_system (6, args);
4102 if (CONSP (coding_system))
4103 coding_system = XCAR (coding_system);
4105 unbind_to (count, Qnil);
4106 inserted = Z_BYTE - BEG_BYTE;
4109 if (NILP (coding_system))
4110 coding_system = Qundecided;
4111 else
4112 CHECK_CODING_SYSTEM (coding_system);
4114 if (NILP (current_buffer->enable_multibyte_characters))
4115 /* We must suppress all character code conversion except for
4116 end-of-line conversion. */
4117 coding_system = raw_text_coding_system (coding_system);
4118 setup_coding_system (coding_system, &coding);
4119 /* Ensure we set Vlast_coding_system_used. */
4120 set_coding_system = 1;
4123 if (!NILP (visit))
4125 /* When we visit a file by raw-text, we change the buffer to
4126 unibyte. */
4127 if (CODING_FOR_UNIBYTE (&coding)
4128 /* Can't do this if part of the buffer might be preserved. */
4129 && NILP (replace))
4130 /* Visiting a file with these coding system makes the buffer
4131 unibyte. */
4132 current_buffer->enable_multibyte_characters = Qnil;
4135 coding.dst_multibyte = ! NILP (current_buffer->enable_multibyte_characters);
4136 if (CODING_MAY_REQUIRE_DECODING (&coding)
4137 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4139 move_gap_both (PT, PT_BYTE);
4140 GAP_SIZE += inserted;
4141 ZV_BYTE -= inserted;
4142 Z_BYTE -= inserted;
4143 ZV -= inserted;
4144 Z -= inserted;
4145 decode_coding_gap (&coding, inserted, inserted);
4146 inserted = coding.produced_char;
4147 coding_system = CODING_ID_NAME (coding.id);
4149 else if (inserted > 0)
4150 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4151 inserted);
4153 /* Now INSERTED is measured in characters. */
4155 #ifdef DOS_NT
4156 /* Use the conversion type to determine buffer-file-type
4157 (find-buffer-file-type is now used to help determine the
4158 conversion). */
4159 if ((VECTORP (CODING_ID_EOL_TYPE (coding.id))
4160 || EQ (CODING_ID_EOL_TYPE (coding.id), Qunix))
4161 && ! CODING_REQUIRE_DECODING (&coding))
4162 current_buffer->buffer_file_type = Qt;
4163 else
4164 current_buffer->buffer_file_type = Qnil;
4165 #endif
4167 handled:
4169 if (deferred_remove_unwind_protect)
4170 /* If requested above, discard the unwind protect for closing the
4171 file. */
4172 specpdl_ptr--;
4174 if (!NILP (visit))
4176 if (!EQ (current_buffer->undo_list, Qt) && !nochange)
4177 current_buffer->undo_list = Qnil;
4179 if (NILP (handler))
4181 current_buffer->modtime = st.st_mtime;
4182 current_buffer->modtime_size = st.st_size;
4183 current_buffer->filename = orig_filename;
4186 SAVE_MODIFF = MODIFF;
4187 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4188 XSETFASTINT (current_buffer->save_length, Z - BEG);
4189 #ifdef CLASH_DETECTION
4190 if (NILP (handler))
4192 if (!NILP (current_buffer->file_truename))
4193 unlock_file (current_buffer->file_truename);
4194 unlock_file (filename);
4196 #endif /* CLASH_DETECTION */
4197 if (not_regular)
4198 xsignal2 (Qfile_error,
4199 build_string ("not a regular file"), orig_filename);
4202 if (set_coding_system)
4203 Vlast_coding_system_used = coding_system;
4205 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4207 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4208 visit);
4209 if (! NILP (insval))
4211 CHECK_NUMBER (insval);
4212 inserted = XFASTINT (insval);
4216 /* Decode file format. */
4217 if (inserted > 0)
4219 /* Don't run point motion or modification hooks when decoding. */
4220 int count = SPECPDL_INDEX ();
4221 EMACS_INT old_inserted = inserted;
4222 specbind (Qinhibit_point_motion_hooks, Qt);
4223 specbind (Qinhibit_modification_hooks, Qt);
4225 /* Save old undo list and don't record undo for decoding. */
4226 old_undo = current_buffer->undo_list;
4227 current_buffer->undo_list = Qt;
4229 if (NILP (replace))
4231 insval = call3 (Qformat_decode,
4232 Qnil, make_number (inserted), visit);
4233 CHECK_NUMBER (insval);
4234 inserted = XFASTINT (insval);
4236 else
4238 /* If REPLACE is non-nil and we succeeded in not replacing the
4239 beginning or end of the buffer text with the file's contents,
4240 call format-decode with `point' positioned at the beginning
4241 of the buffer and `inserted' equalling the number of
4242 characters in the buffer. Otherwise, format-decode might
4243 fail to correctly analyze the beginning or end of the buffer.
4244 Hence we temporarily save `point' and `inserted' here and
4245 restore `point' iff format-decode did not insert or delete
4246 any text. Otherwise we leave `point' at point-min. */
4247 EMACS_INT opoint = PT;
4248 EMACS_INT opoint_byte = PT_BYTE;
4249 EMACS_INT oinserted = ZV - BEGV;
4250 int ochars_modiff = CHARS_MODIFF;
4252 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4253 insval = call3 (Qformat_decode,
4254 Qnil, make_number (oinserted), visit);
4255 CHECK_NUMBER (insval);
4256 if (ochars_modiff == CHARS_MODIFF)
4257 /* format_decode didn't modify buffer's characters => move
4258 point back to position before inserted text and leave
4259 value of inserted alone. */
4260 SET_PT_BOTH (opoint, opoint_byte);
4261 else
4262 /* format_decode modified buffer's characters => consider
4263 entire buffer changed and leave point at point-min. */
4264 inserted = XFASTINT (insval);
4267 /* For consistency with format-decode call these now iff inserted > 0
4268 (martin 2007-06-28). */
4269 p = Vafter_insert_file_functions;
4270 while (CONSP (p))
4272 if (NILP (replace))
4274 insval = call1 (XCAR (p), make_number (inserted));
4275 if (!NILP (insval))
4277 CHECK_NUMBER (insval);
4278 inserted = XFASTINT (insval);
4281 else
4283 /* For the rationale of this see the comment on
4284 format-decode above. */
4285 EMACS_INT opoint = PT;
4286 EMACS_INT opoint_byte = PT_BYTE;
4287 EMACS_INT oinserted = ZV - BEGV;
4288 int ochars_modiff = CHARS_MODIFF;
4290 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4291 insval = call1 (XCAR (p), make_number (oinserted));
4292 if (!NILP (insval))
4294 CHECK_NUMBER (insval);
4295 if (ochars_modiff == CHARS_MODIFF)
4296 /* after_insert_file_functions didn't modify
4297 buffer's characters => move point back to
4298 position before inserted text and leave value of
4299 inserted alone. */
4300 SET_PT_BOTH (opoint, opoint_byte);
4301 else
4302 /* after_insert_file_functions did modify buffer's
4303 characters => consider entire buffer changed and
4304 leave point at point-min. */
4305 inserted = XFASTINT (insval);
4309 QUIT;
4310 p = XCDR (p);
4313 if (NILP (visit))
4315 current_buffer->undo_list = old_undo;
4316 if (CONSP (old_undo) && inserted != old_inserted)
4318 /* Adjust the last undo record for the size change during
4319 the format conversion. */
4320 Lisp_Object tem = XCAR (old_undo);
4321 if (CONSP (tem) && INTEGERP (XCAR (tem))
4322 && INTEGERP (XCDR (tem))
4323 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4324 XSETCDR (tem, make_number (PT + inserted));
4327 else
4328 /* If undo_list was Qt before, keep it that way.
4329 Otherwise start with an empty undo_list. */
4330 current_buffer->undo_list = EQ (old_undo, Qt) ? Qt : Qnil;
4332 unbind_to (count, Qnil);
4335 /* Call after-change hooks for the inserted text, aside from the case
4336 of normal visiting (not with REPLACE), which is done in a new buffer
4337 "before" the buffer is changed. */
4338 if (inserted > 0 && total > 0
4339 && (NILP (visit) || !NILP (replace)))
4341 signal_after_change (PT, 0, inserted);
4342 update_compositions (PT, PT, CHECK_BORDER);
4345 if (!NILP (visit)
4346 && current_buffer->modtime == -1)
4348 /* If visiting nonexistent file, return nil. */
4349 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4352 if (read_quit)
4353 Fsignal (Qquit, Qnil);
4355 /* ??? Retval needs to be dealt with in all cases consistently. */
4356 if (NILP (val))
4357 val = Fcons (orig_filename,
4358 Fcons (make_number (inserted),
4359 Qnil));
4361 RETURN_UNGCPRO (unbind_to (count, val));
4364 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4366 static Lisp_Object
4367 build_annotations_unwind (Lisp_Object arg)
4369 Vwrite_region_annotation_buffers = arg;
4370 return Qnil;
4373 /* Decide the coding-system to encode the data with. */
4375 static Lisp_Object
4376 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4377 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4378 struct coding_system *coding)
4380 Lisp_Object val;
4381 Lisp_Object eol_parent = Qnil;
4383 if (auto_saving
4384 && NILP (Fstring_equal (current_buffer->filename,
4385 current_buffer->auto_save_file_name)))
4387 val = Qutf_8_emacs;
4388 eol_parent = Qunix;
4390 else if (!NILP (Vcoding_system_for_write))
4392 val = Vcoding_system_for_write;
4393 if (coding_system_require_warning
4394 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4395 /* Confirm that VAL can surely encode the current region. */
4396 val = call5 (Vselect_safe_coding_system_function,
4397 start, end, Fcons (Qt, Fcons (val, Qnil)),
4398 Qnil, filename);
4400 else
4402 /* If the variable `buffer-file-coding-system' is set locally,
4403 it means that the file was read with some kind of code
4404 conversion or the variable is explicitly set by users. We
4405 had better write it out with the same coding system even if
4406 `enable-multibyte-characters' is nil.
4408 If it is not set locally, we anyway have to convert EOL
4409 format if the default value of `buffer-file-coding-system'
4410 tells that it is not Unix-like (LF only) format. */
4411 int using_default_coding = 0;
4412 int force_raw_text = 0;
4414 val = current_buffer->buffer_file_coding_system;
4415 if (NILP (val)
4416 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4418 val = Qnil;
4419 if (NILP (current_buffer->enable_multibyte_characters))
4420 force_raw_text = 1;
4423 if (NILP (val))
4425 /* Check file-coding-system-alist. */
4426 Lisp_Object args[7], coding_systems;
4428 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4429 args[3] = filename; args[4] = append; args[5] = visit;
4430 args[6] = lockname;
4431 coding_systems = Ffind_operation_coding_system (7, args);
4432 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4433 val = XCDR (coding_systems);
4436 if (NILP (val))
4438 /* If we still have not decided a coding system, use the
4439 default value of buffer-file-coding-system. */
4440 val = current_buffer->buffer_file_coding_system;
4441 using_default_coding = 1;
4444 if (! NILP (val) && ! force_raw_text)
4446 Lisp_Object spec, attrs;
4448 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4449 attrs = AREF (spec, 0);
4450 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4451 force_raw_text = 1;
4454 if (!force_raw_text
4455 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4456 /* Confirm that VAL can surely encode the current region. */
4457 val = call5 (Vselect_safe_coding_system_function,
4458 start, end, val, Qnil, filename);
4460 /* If the decided coding-system doesn't specify end-of-line
4461 format, we use that of
4462 `default-buffer-file-coding-system'. */
4463 if (! using_default_coding
4464 && ! NILP (buffer_defaults.buffer_file_coding_system))
4465 val = (coding_inherit_eol_type
4466 (val, buffer_defaults.buffer_file_coding_system));
4468 /* If we decide not to encode text, use `raw-text' or one of its
4469 subsidiaries. */
4470 if (force_raw_text)
4471 val = raw_text_coding_system (val);
4474 val = coding_inherit_eol_type (val, eol_parent);
4475 setup_coding_system (val, coding);
4477 if (!STRINGP (start) && !NILP (current_buffer->selective_display))
4478 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4479 return val;
4482 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4483 "r\nFWrite region to file: \ni\ni\ni\np",
4484 doc: /* Write current region into specified file.
4485 When called from a program, requires three arguments:
4486 START, END and FILENAME. START and END are normally buffer positions
4487 specifying the part of the buffer to write.
4488 If START is nil, that means to use the entire buffer contents.
4489 If START is a string, then output that string to the file
4490 instead of any buffer contents; END is ignored.
4492 Optional fourth argument APPEND if non-nil means
4493 append to existing file contents (if any). If it is an integer,
4494 seek to that offset in the file before writing.
4495 Optional fifth argument VISIT, if t or a string, means
4496 set the last-save-file-modtime of buffer to this file's modtime
4497 and mark buffer not modified.
4498 If VISIT is a string, it is a second file name;
4499 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4500 VISIT is also the file name to lock and unlock for clash detection.
4501 If VISIT is neither t nor nil nor a string,
4502 that means do not display the \"Wrote file\" message.
4503 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4504 use for locking and unlocking, overriding FILENAME and VISIT.
4505 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4506 for an existing file with the same name. If MUSTBENEW is `excl',
4507 that means to get an error if the file already exists; never overwrite.
4508 If MUSTBENEW is neither nil nor `excl', that means ask for
4509 confirmation before overwriting, but do go ahead and overwrite the file
4510 if the user confirms.
4512 This does code conversion according to the value of
4513 `coding-system-for-write', `buffer-file-coding-system', or
4514 `file-coding-system-alist', and sets the variable
4515 `last-coding-system-used' to the coding system actually used.
4517 This calls `write-region-annotate-functions' at the start, and
4518 `write-region-post-annotation-function' at the end. */)
4519 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append, Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4521 register int desc;
4522 int failure;
4523 int save_errno = 0;
4524 const unsigned char *fn;
4525 struct stat st;
4526 int count = SPECPDL_INDEX ();
4527 int count1;
4528 Lisp_Object handler;
4529 Lisp_Object visit_file;
4530 Lisp_Object annotations;
4531 Lisp_Object encoded_filename;
4532 int visiting = (EQ (visit, Qt) || STRINGP (visit));
4533 int quietly = !NILP (visit);
4534 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4535 struct buffer *given_buffer;
4536 #ifdef DOS_NT
4537 int buffer_file_type = O_BINARY;
4538 #endif /* DOS_NT */
4539 struct coding_system coding;
4541 if (current_buffer->base_buffer && visiting)
4542 error ("Cannot do file visiting in an indirect buffer");
4544 if (!NILP (start) && !STRINGP (start))
4545 validate_region (&start, &end);
4547 visit_file = Qnil;
4548 GCPRO5 (start, filename, visit, visit_file, lockname);
4550 filename = Fexpand_file_name (filename, Qnil);
4552 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4553 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4555 if (STRINGP (visit))
4556 visit_file = Fexpand_file_name (visit, Qnil);
4557 else
4558 visit_file = filename;
4560 if (NILP (lockname))
4561 lockname = visit_file;
4563 annotations = Qnil;
4565 /* If the file name has special constructs in it,
4566 call the corresponding file handler. */
4567 handler = Ffind_file_name_handler (filename, Qwrite_region);
4568 /* If FILENAME has no handler, see if VISIT has one. */
4569 if (NILP (handler) && STRINGP (visit))
4570 handler = Ffind_file_name_handler (visit, Qwrite_region);
4572 if (!NILP (handler))
4574 Lisp_Object val;
4575 val = call6 (handler, Qwrite_region, start, end,
4576 filename, append, visit);
4578 if (visiting)
4580 SAVE_MODIFF = MODIFF;
4581 XSETFASTINT (current_buffer->save_length, Z - BEG);
4582 current_buffer->filename = visit_file;
4584 UNGCPRO;
4585 return val;
4588 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4590 /* Special kludge to simplify auto-saving. */
4591 if (NILP (start))
4593 /* Do it later, so write-region-annotate-function can work differently
4594 if we save "the buffer" vs "a region".
4595 This is useful in tar-mode. --Stef
4596 XSETFASTINT (start, BEG);
4597 XSETFASTINT (end, Z); */
4598 Fwiden ();
4601 record_unwind_protect (build_annotations_unwind,
4602 Vwrite_region_annotation_buffers);
4603 Vwrite_region_annotation_buffers = Fcons (Fcurrent_buffer (), Qnil);
4604 count1 = SPECPDL_INDEX ();
4606 given_buffer = current_buffer;
4608 if (!STRINGP (start))
4610 annotations = build_annotations (start, end);
4612 if (current_buffer != given_buffer)
4614 XSETFASTINT (start, BEGV);
4615 XSETFASTINT (end, ZV);
4619 if (NILP (start))
4621 XSETFASTINT (start, BEGV);
4622 XSETFASTINT (end, ZV);
4625 UNGCPRO;
4627 GCPRO5 (start, filename, annotations, visit_file, lockname);
4629 /* Decide the coding-system to encode the data with.
4630 We used to make this choice before calling build_annotations, but that
4631 leads to problems when a write-annotate-function takes care of
4632 unsavable chars (as was the case with X-Symbol). */
4633 Vlast_coding_system_used
4634 = choose_write_coding_system (start, end, filename,
4635 append, visit, lockname, &coding);
4637 #ifdef CLASH_DETECTION
4638 if (!auto_saving)
4639 lock_file (lockname);
4640 #endif /* CLASH_DETECTION */
4642 encoded_filename = ENCODE_FILE (filename);
4644 fn = SDATA (encoded_filename);
4645 desc = -1;
4646 if (!NILP (append))
4647 #ifdef DOS_NT
4648 desc = emacs_open (fn, O_WRONLY | buffer_file_type, 0);
4649 #else /* not DOS_NT */
4650 desc = emacs_open (fn, O_WRONLY, 0);
4651 #endif /* not DOS_NT */
4653 if (desc < 0 && (NILP (append) || errno == ENOENT))
4654 #ifdef DOS_NT
4655 desc = emacs_open (fn,
4656 O_WRONLY | O_CREAT | buffer_file_type
4657 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
4658 S_IREAD | S_IWRITE);
4659 #else /* not DOS_NT */
4660 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
4661 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
4662 auto_saving ? auto_save_mode_bits : 0666);
4663 #endif /* not DOS_NT */
4665 if (desc < 0)
4667 #ifdef CLASH_DETECTION
4668 save_errno = errno;
4669 if (!auto_saving) unlock_file (lockname);
4670 errno = save_errno;
4671 #endif /* CLASH_DETECTION */
4672 UNGCPRO;
4673 report_file_error ("Opening output file", Fcons (filename, Qnil));
4676 record_unwind_protect (close_file_unwind, make_number (desc));
4678 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
4680 long ret;
4682 if (NUMBERP (append))
4683 ret = lseek (desc, XINT (append), 1);
4684 else
4685 ret = lseek (desc, 0, 2);
4686 if (ret < 0)
4688 #ifdef CLASH_DETECTION
4689 if (!auto_saving) unlock_file (lockname);
4690 #endif /* CLASH_DETECTION */
4691 UNGCPRO;
4692 report_file_error ("Lseek error", Fcons (filename, Qnil));
4696 UNGCPRO;
4698 failure = 0;
4699 immediate_quit = 1;
4701 if (STRINGP (start))
4703 failure = 0 > a_write (desc, start, 0, SCHARS (start),
4704 &annotations, &coding);
4705 save_errno = errno;
4707 else if (XINT (start) != XINT (end))
4709 failure = 0 > a_write (desc, Qnil,
4710 XINT (start), XINT (end) - XINT (start),
4711 &annotations, &coding);
4712 save_errno = errno;
4714 else
4716 /* If file was empty, still need to write the annotations */
4717 coding.mode |= CODING_MODE_LAST_BLOCK;
4718 failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4719 save_errno = errno;
4722 if (CODING_REQUIRE_FLUSHING (&coding)
4723 && !(coding.mode & CODING_MODE_LAST_BLOCK)
4724 && ! failure)
4726 /* We have to flush out a data. */
4727 coding.mode |= CODING_MODE_LAST_BLOCK;
4728 failure = 0 > e_write (desc, Qnil, 1, 1, &coding);
4729 save_errno = errno;
4732 immediate_quit = 0;
4734 #ifdef HAVE_FSYNC
4735 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4736 Disk full in NFS may be reported here. */
4737 /* mib says that closing the file will try to write as fast as NFS can do
4738 it, and that means the fsync here is not crucial for autosave files. */
4739 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
4741 /* If fsync fails with EINTR, don't treat that as serious. Also
4742 ignore EINVAL which happens when fsync is not supported on this
4743 file. */
4744 if (errno != EINTR && errno != EINVAL)
4745 failure = 1, save_errno = errno;
4747 #endif
4749 /* NFS can report a write failure now. */
4750 if (emacs_close (desc) < 0)
4751 failure = 1, save_errno = errno;
4753 stat (fn, &st);
4755 /* Discard the unwind protect for close_file_unwind. */
4756 specpdl_ptr = specpdl + count1;
4758 /* Call write-region-post-annotation-function. */
4759 while (CONSP (Vwrite_region_annotation_buffers))
4761 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4762 if (!NILP (Fbuffer_live_p (buf)))
4764 Fset_buffer (buf);
4765 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4766 call0 (Vwrite_region_post_annotation_function);
4768 Vwrite_region_annotation_buffers
4769 = XCDR (Vwrite_region_annotation_buffers);
4772 unbind_to (count, Qnil);
4774 #ifdef CLASH_DETECTION
4775 if (!auto_saving)
4776 unlock_file (lockname);
4777 #endif /* CLASH_DETECTION */
4779 /* Do this before reporting IO error
4780 to avoid a "file has changed on disk" warning on
4781 next attempt to save. */
4782 if (visiting)
4784 current_buffer->modtime = st.st_mtime;
4785 current_buffer->modtime_size = st.st_size;
4788 if (failure)
4789 error ("IO error writing %s: %s", SDATA (filename),
4790 emacs_strerror (save_errno));
4792 if (visiting)
4794 SAVE_MODIFF = MODIFF;
4795 XSETFASTINT (current_buffer->save_length, Z - BEG);
4796 current_buffer->filename = visit_file;
4797 update_mode_lines++;
4799 else if (quietly)
4801 if (auto_saving
4802 && ! NILP (Fstring_equal (current_buffer->filename,
4803 current_buffer->auto_save_file_name)))
4804 SAVE_MODIFF = MODIFF;
4806 return Qnil;
4809 if (!auto_saving)
4810 message_with_string ((INTEGERP (append)
4811 ? "Updated %s"
4812 : ! NILP (append)
4813 ? "Added to %s"
4814 : "Wrote %s"),
4815 visit_file, 1);
4817 return Qnil;
4820 Lisp_Object merge (Lisp_Object, Lisp_Object, Lisp_Object);
4822 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4823 doc: /* Return t if (car A) is numerically less than (car B). */)
4824 (Lisp_Object a, Lisp_Object b)
4826 return Flss (Fcar (a), Fcar (b));
4829 /* Build the complete list of annotations appropriate for writing out
4830 the text between START and END, by calling all the functions in
4831 write-region-annotate-functions and merging the lists they return.
4832 If one of these functions switches to a different buffer, we assume
4833 that buffer contains altered text. Therefore, the caller must
4834 make sure to restore the current buffer in all cases,
4835 as save-excursion would do. */
4837 static Lisp_Object
4838 build_annotations (Lisp_Object start, Lisp_Object end)
4840 Lisp_Object annotations;
4841 Lisp_Object p, res;
4842 struct gcpro gcpro1, gcpro2;
4843 Lisp_Object original_buffer;
4844 int i, used_global = 0;
4846 XSETBUFFER (original_buffer, current_buffer);
4848 annotations = Qnil;
4849 p = Vwrite_region_annotate_functions;
4850 GCPRO2 (annotations, p);
4851 while (CONSP (p))
4853 struct buffer *given_buffer = current_buffer;
4854 if (EQ (Qt, XCAR (p)) && !used_global)
4855 { /* Use the global value of the hook. */
4856 Lisp_Object arg[2];
4857 used_global = 1;
4858 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
4859 arg[1] = XCDR (p);
4860 p = Fappend (2, arg);
4861 continue;
4863 Vwrite_region_annotations_so_far = annotations;
4864 res = call2 (XCAR (p), start, end);
4865 /* If the function makes a different buffer current,
4866 assume that means this buffer contains altered text to be output.
4867 Reset START and END from the buffer bounds
4868 and discard all previous annotations because they should have
4869 been dealt with by this function. */
4870 if (current_buffer != given_buffer)
4872 Vwrite_region_annotation_buffers
4873 = Fcons (Fcurrent_buffer (),
4874 Vwrite_region_annotation_buffers);
4875 XSETFASTINT (start, BEGV);
4876 XSETFASTINT (end, ZV);
4877 annotations = Qnil;
4879 Flength (res); /* Check basic validity of return value */
4880 annotations = merge (annotations, res, Qcar_less_than_car);
4881 p = XCDR (p);
4884 /* Now do the same for annotation functions implied by the file-format */
4885 if (auto_saving && (!EQ (current_buffer->auto_save_file_format, Qt)))
4886 p = current_buffer->auto_save_file_format;
4887 else
4888 p = current_buffer->file_format;
4889 for (i = 0; CONSP (p); p = XCDR (p), ++i)
4891 struct buffer *given_buffer = current_buffer;
4893 Vwrite_region_annotations_so_far = annotations;
4895 /* Value is either a list of annotations or nil if the function
4896 has written annotations to a temporary buffer, which is now
4897 current. */
4898 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
4899 original_buffer, make_number (i));
4900 if (current_buffer != given_buffer)
4902 XSETFASTINT (start, BEGV);
4903 XSETFASTINT (end, ZV);
4904 annotations = Qnil;
4907 if (CONSP (res))
4908 annotations = merge (annotations, res, Qcar_less_than_car);
4911 UNGCPRO;
4912 return annotations;
4916 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
4917 If STRING is nil, POS is the character position in the current buffer.
4918 Intersperse with them the annotations from *ANNOT
4919 which fall within the range of POS to POS + NCHARS,
4920 each at its appropriate position.
4922 We modify *ANNOT by discarding elements as we use them up.
4924 The return value is negative in case of system call failure. */
4926 static int
4927 a_write (int desc, Lisp_Object string, int pos, register int nchars, Lisp_Object *annot, struct coding_system *coding)
4929 Lisp_Object tem;
4930 int nextpos;
4931 int lastpos = pos + nchars;
4933 while (NILP (*annot) || CONSP (*annot))
4935 tem = Fcar_safe (Fcar (*annot));
4936 nextpos = pos - 1;
4937 if (INTEGERP (tem))
4938 nextpos = XFASTINT (tem);
4940 /* If there are no more annotations in this range,
4941 output the rest of the range all at once. */
4942 if (! (nextpos >= pos && nextpos <= lastpos))
4943 return e_write (desc, string, pos, lastpos, coding);
4945 /* Output buffer text up to the next annotation's position. */
4946 if (nextpos > pos)
4948 if (0 > e_write (desc, string, pos, nextpos, coding))
4949 return -1;
4950 pos = nextpos;
4952 /* Output the annotation. */
4953 tem = Fcdr (Fcar (*annot));
4954 if (STRINGP (tem))
4956 if (0 > e_write (desc, tem, 0, SCHARS (tem), coding))
4957 return -1;
4959 *annot = Fcdr (*annot);
4961 return 0;
4965 /* Write text in the range START and END into descriptor DESC,
4966 encoding them with coding system CODING. If STRING is nil, START
4967 and END are character positions of the current buffer, else they
4968 are indexes to the string STRING. */
4970 static int
4971 e_write (int desc, Lisp_Object string, int start, int end, struct coding_system *coding)
4973 if (STRINGP (string))
4975 start = 0;
4976 end = SCHARS (string);
4979 /* We used to have a code for handling selective display here. But,
4980 now it is handled within encode_coding. */
4982 while (start < end)
4984 if (STRINGP (string))
4986 coding->src_multibyte = SCHARS (string) < SBYTES (string);
4987 if (CODING_REQUIRE_ENCODING (coding))
4989 encode_coding_object (coding, string,
4990 start, string_char_to_byte (string, start),
4991 end, string_char_to_byte (string, end), Qt);
4993 else
4995 coding->dst_object = string;
4996 coding->consumed_char = SCHARS (string);
4997 coding->produced = SBYTES (string);
5000 else
5002 int start_byte = CHAR_TO_BYTE (start);
5003 int end_byte = CHAR_TO_BYTE (end);
5005 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5006 if (CODING_REQUIRE_ENCODING (coding))
5008 encode_coding_object (coding, Fcurrent_buffer (),
5009 start, start_byte, end, end_byte, Qt);
5011 else
5013 coding->dst_object = Qnil;
5014 coding->dst_pos_byte = start_byte;
5015 if (start >= GPT || end <= GPT)
5017 coding->consumed_char = end - start;
5018 coding->produced = end_byte - start_byte;
5020 else
5022 coding->consumed_char = GPT - start;
5023 coding->produced = GPT_BYTE - start_byte;
5028 if (coding->produced > 0)
5030 coding->produced -=
5031 emacs_write (desc,
5032 STRINGP (coding->dst_object)
5033 ? SDATA (coding->dst_object)
5034 : BYTE_POS_ADDR (coding->dst_pos_byte),
5035 coding->produced);
5037 if (coding->produced)
5038 return -1;
5040 start += coding->consumed_char;
5043 return 0;
5046 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5047 Sverify_visited_file_modtime, 1, 1, 0,
5048 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5049 This means that the file has not been changed since it was visited or saved.
5050 See Info node `(elisp)Modification Time' for more details. */)
5051 (Lisp_Object buf)
5053 struct buffer *b;
5054 struct stat st;
5055 Lisp_Object handler;
5056 Lisp_Object filename;
5058 CHECK_BUFFER (buf);
5059 b = XBUFFER (buf);
5061 if (!STRINGP (b->filename)) return Qt;
5062 if (b->modtime == 0) return Qt;
5064 /* If the file name has special constructs in it,
5065 call the corresponding file handler. */
5066 handler = Ffind_file_name_handler (b->filename,
5067 Qverify_visited_file_modtime);
5068 if (!NILP (handler))
5069 return call2 (handler, Qverify_visited_file_modtime, buf);
5071 filename = ENCODE_FILE (b->filename);
5073 if (stat (SDATA (filename), &st) < 0)
5075 /* If the file doesn't exist now and didn't exist before,
5076 we say that it isn't modified, provided the error is a tame one. */
5077 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
5078 st.st_mtime = -1;
5079 else
5080 st.st_mtime = 0;
5082 if ((st.st_mtime == b->modtime
5083 /* If both are positive, accept them if they are off by one second. */
5084 || (st.st_mtime > 0 && b->modtime > 0
5085 && (st.st_mtime == b->modtime + 1
5086 || st.st_mtime == b->modtime - 1)))
5087 && (st.st_size == b->modtime_size
5088 || b->modtime_size < 0))
5089 return Qt;
5090 return Qnil;
5093 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5094 Sclear_visited_file_modtime, 0, 0, 0,
5095 doc: /* Clear out records of last mod time of visited file.
5096 Next attempt to save will certainly not complain of a discrepancy. */)
5097 (void)
5099 current_buffer->modtime = 0;
5100 current_buffer->modtime_size = -1;
5101 return Qnil;
5104 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5105 Svisited_file_modtime, 0, 0, 0,
5106 doc: /* Return the current buffer's recorded visited file modification time.
5107 The value is a list of the form (HIGH LOW), like the time values
5108 that `file-attributes' returns. If the current buffer has no recorded
5109 file modification time, this function returns 0.
5110 See Info node `(elisp)Modification Time' for more details. */)
5111 (void)
5113 if (! current_buffer->modtime)
5114 return make_number (0);
5115 return make_time ((time_t) current_buffer->modtime);
5118 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5119 Sset_visited_file_modtime, 0, 1, 0,
5120 doc: /* Update buffer's recorded modification time from the visited file's time.
5121 Useful if the buffer was not read from the file normally
5122 or if the file itself has been changed for some known benign reason.
5123 An argument specifies the modification time value to use
5124 \(instead of that of the visited file), in the form of a list
5125 \(HIGH . LOW) or (HIGH LOW). */)
5126 (Lisp_Object time_list)
5128 if (!NILP (time_list))
5130 current_buffer->modtime = cons_to_long (time_list);
5131 current_buffer->modtime_size = -1;
5133 else
5135 register Lisp_Object filename;
5136 struct stat st;
5137 Lisp_Object handler;
5139 filename = Fexpand_file_name (current_buffer->filename, Qnil);
5141 /* If the file name has special constructs in it,
5142 call the corresponding file handler. */
5143 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5144 if (!NILP (handler))
5145 /* The handler can find the file name the same way we did. */
5146 return call2 (handler, Qset_visited_file_modtime, Qnil);
5148 filename = ENCODE_FILE (filename);
5150 if (stat (SDATA (filename), &st) >= 0)
5152 current_buffer->modtime = st.st_mtime;
5153 current_buffer->modtime_size = st.st_size;
5157 return Qnil;
5160 Lisp_Object
5161 auto_save_error (Lisp_Object error)
5163 Lisp_Object args[3], msg;
5164 int i, nbytes;
5165 struct gcpro gcpro1;
5166 char *msgbuf;
5167 USE_SAFE_ALLOCA;
5169 auto_save_error_occurred = 1;
5171 ring_bell (XFRAME (selected_frame));
5173 args[0] = build_string ("Auto-saving %s: %s");
5174 args[1] = current_buffer->name;
5175 args[2] = Ferror_message_string (error);
5176 msg = Fformat (3, args);
5177 GCPRO1 (msg);
5178 nbytes = SBYTES (msg);
5179 SAFE_ALLOCA (msgbuf, char *, nbytes);
5180 memcpy (msgbuf, SDATA (msg), nbytes);
5182 for (i = 0; i < 3; ++i)
5184 if (i == 0)
5185 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5186 else
5187 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5188 Fsleep_for (make_number (1), Qnil);
5191 SAFE_FREE ();
5192 UNGCPRO;
5193 return Qnil;
5196 Lisp_Object
5197 auto_save_1 (void)
5199 struct stat st;
5200 Lisp_Object modes;
5202 auto_save_mode_bits = 0666;
5204 /* Get visited file's mode to become the auto save file's mode. */
5205 if (! NILP (current_buffer->filename))
5207 if (stat (SDATA (current_buffer->filename), &st) >= 0)
5208 /* But make sure we can overwrite it later! */
5209 auto_save_mode_bits = st.st_mode | 0600;
5210 else if ((modes = Ffile_modes (current_buffer->filename),
5211 INTEGERP (modes)))
5212 /* Remote files don't cooperate with stat. */
5213 auto_save_mode_bits = XINT (modes) | 0600;
5216 return
5217 Fwrite_region (Qnil, Qnil, current_buffer->auto_save_file_name, Qnil,
5218 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5219 Qnil, Qnil);
5222 static Lisp_Object
5223 do_auto_save_unwind (Lisp_Object arg) /* used as unwind-protect function */
5226 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5227 auto_saving = 0;
5228 if (stream != NULL)
5230 BLOCK_INPUT;
5231 fclose (stream);
5232 UNBLOCK_INPUT;
5234 return Qnil;
5237 static Lisp_Object
5238 do_auto_save_unwind_1 (Lisp_Object value) /* used as unwind-protect function */
5241 minibuffer_auto_raise = XINT (value);
5242 return Qnil;
5245 static Lisp_Object
5246 do_auto_save_make_dir (Lisp_Object dir)
5248 Lisp_Object mode;
5250 call2 (Qmake_directory, dir, Qt);
5251 XSETFASTINT (mode, 0700);
5252 return Fset_file_modes (dir, mode);
5255 static Lisp_Object
5256 do_auto_save_eh (Lisp_Object ignore)
5258 return Qnil;
5261 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5262 doc: /* Auto-save all buffers that need it.
5263 This is all buffers that have auto-saving enabled
5264 and are changed since last auto-saved.
5265 Auto-saving writes the buffer into a file
5266 so that your editing is not lost if the system crashes.
5267 This file is not the file you visited; that changes only when you save.
5268 Normally we run the normal hook `auto-save-hook' before saving.
5270 A non-nil NO-MESSAGE argument means do not print any message if successful.
5271 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5272 (Lisp_Object no_message, Lisp_Object current_only)
5274 struct buffer *old = current_buffer, *b;
5275 Lisp_Object tail, buf;
5276 int auto_saved = 0;
5277 int do_handled_files;
5278 Lisp_Object oquit;
5279 FILE *stream = NULL;
5280 int count = SPECPDL_INDEX ();
5281 int orig_minibuffer_auto_raise = minibuffer_auto_raise;
5282 int old_message_p = 0;
5283 struct gcpro gcpro1, gcpro2;
5285 if (max_specpdl_size < specpdl_size + 40)
5286 max_specpdl_size = specpdl_size + 40;
5288 if (minibuf_level)
5289 no_message = Qt;
5291 if (NILP (no_message))
5293 old_message_p = push_message ();
5294 record_unwind_protect (pop_message_unwind, Qnil);
5297 /* Ordinarily don't quit within this function,
5298 but don't make it impossible to quit (in case we get hung in I/O). */
5299 oquit = Vquit_flag;
5300 Vquit_flag = Qnil;
5302 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5303 point to non-strings reached from Vbuffer_alist. */
5305 if (!NILP (Vrun_hooks))
5306 call1 (Vrun_hooks, intern ("auto-save-hook"));
5308 if (STRINGP (Vauto_save_list_file_name))
5310 Lisp_Object listfile;
5312 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5314 /* Don't try to create the directory when shutting down Emacs,
5315 because creating the directory might signal an error, and
5316 that would leave Emacs in a strange state. */
5317 if (!NILP (Vrun_hooks))
5319 Lisp_Object dir;
5320 dir = Qnil;
5321 GCPRO2 (dir, listfile);
5322 dir = Ffile_name_directory (listfile);
5323 if (NILP (Ffile_directory_p (dir)))
5324 internal_condition_case_1 (do_auto_save_make_dir,
5325 dir, Fcons (Fcons (Qfile_error, Qnil), Qnil),
5326 do_auto_save_eh);
5327 UNGCPRO;
5330 stream = fopen (SDATA (listfile), "w");
5333 record_unwind_protect (do_auto_save_unwind,
5334 make_save_value (stream, 0));
5335 record_unwind_protect (do_auto_save_unwind_1,
5336 make_number (minibuffer_auto_raise));
5337 minibuffer_auto_raise = 0;
5338 auto_saving = 1;
5339 auto_save_error_occurred = 0;
5341 /* On first pass, save all files that don't have handlers.
5342 On second pass, save all files that do have handlers.
5344 If Emacs is crashing, the handlers may tweak what is causing
5345 Emacs to crash in the first place, and it would be a shame if
5346 Emacs failed to autosave perfectly ordinary files because it
5347 couldn't handle some ange-ftp'd file. */
5349 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5350 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5352 buf = XCDR (XCAR (tail));
5353 b = XBUFFER (buf);
5355 /* Record all the buffers that have auto save mode
5356 in the special file that lists them. For each of these buffers,
5357 Record visited name (if any) and auto save name. */
5358 if (STRINGP (b->auto_save_file_name)
5359 && stream != NULL && do_handled_files == 0)
5361 BLOCK_INPUT;
5362 if (!NILP (b->filename))
5364 fwrite (SDATA (b->filename), 1,
5365 SBYTES (b->filename), stream);
5367 putc ('\n', stream);
5368 fwrite (SDATA (b->auto_save_file_name), 1,
5369 SBYTES (b->auto_save_file_name), stream);
5370 putc ('\n', stream);
5371 UNBLOCK_INPUT;
5374 if (!NILP (current_only)
5375 && b != current_buffer)
5376 continue;
5378 /* Don't auto-save indirect buffers.
5379 The base buffer takes care of it. */
5380 if (b->base_buffer)
5381 continue;
5383 /* Check for auto save enabled
5384 and file changed since last auto save
5385 and file changed since last real save. */
5386 if (STRINGP (b->auto_save_file_name)
5387 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5388 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5389 /* -1 means we've turned off autosaving for a while--see below. */
5390 && XINT (b->save_length) >= 0
5391 && (do_handled_files
5392 || NILP (Ffind_file_name_handler (b->auto_save_file_name,
5393 Qwrite_region))))
5395 EMACS_TIME before_time, after_time;
5397 EMACS_GET_TIME (before_time);
5399 /* If we had a failure, don't try again for 20 minutes. */
5400 if (b->auto_save_failure_time >= 0
5401 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5402 continue;
5404 set_buffer_internal (b);
5405 if (NILP (Vauto_save_include_big_deletions)
5406 && (XFASTINT (b->save_length) * 10
5407 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5408 /* A short file is likely to change a large fraction;
5409 spare the user annoying messages. */
5410 && XFASTINT (b->save_length) > 5000
5411 /* These messages are frequent and annoying for `*mail*'. */
5412 && !EQ (b->filename, Qnil)
5413 && NILP (no_message))
5415 /* It has shrunk too much; turn off auto-saving here. */
5416 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5417 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5418 b->name, 1);
5419 minibuffer_auto_raise = 0;
5420 /* Turn off auto-saving until there's a real save,
5421 and prevent any more warnings. */
5422 XSETINT (b->save_length, -1);
5423 Fsleep_for (make_number (1), Qnil);
5424 continue;
5426 if (!auto_saved && NILP (no_message))
5427 message1 ("Auto-saving...");
5428 internal_condition_case (auto_save_1, Qt, auto_save_error);
5429 auto_saved++;
5430 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5431 XSETFASTINT (current_buffer->save_length, Z - BEG);
5432 set_buffer_internal (old);
5434 EMACS_GET_TIME (after_time);
5436 /* If auto-save took more than 60 seconds,
5437 assume it was an NFS failure that got a timeout. */
5438 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5439 b->auto_save_failure_time = EMACS_SECS (after_time);
5443 /* Prevent another auto save till enough input events come in. */
5444 record_auto_save ();
5446 if (auto_saved && NILP (no_message))
5448 if (old_message_p)
5450 /* If we are going to restore an old message,
5451 give time to read ours. */
5452 sit_for (make_number (1), 0, 0);
5453 restore_message ();
5455 else if (!auto_save_error_occurred)
5456 /* Don't overwrite the error message if an error occurred.
5457 If we displayed a message and then restored a state
5458 with no message, leave a "done" message on the screen. */
5459 message1 ("Auto-saving...done");
5462 Vquit_flag = oquit;
5464 /* This restores the message-stack status. */
5465 unbind_to (count, Qnil);
5466 return Qnil;
5469 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5470 Sset_buffer_auto_saved, 0, 0, 0,
5471 doc: /* Mark current buffer as auto-saved with its current text.
5472 No auto-save file will be written until the buffer changes again. */)
5473 (void)
5475 /* FIXME: This should not be called in indirect buffers, since
5476 they're not autosaved. */
5477 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5478 XSETFASTINT (current_buffer->save_length, Z - BEG);
5479 current_buffer->auto_save_failure_time = -1;
5480 return Qnil;
5483 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5484 Sclear_buffer_auto_save_failure, 0, 0, 0,
5485 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5486 (void)
5488 current_buffer->auto_save_failure_time = -1;
5489 return Qnil;
5492 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5493 0, 0, 0,
5494 doc: /* Return t if current buffer has been auto-saved recently.
5495 More precisely, if it has been auto-saved since last read from or saved
5496 in the visited file. If the buffer has no visited file,
5497 then any auto-save counts as "recent". */)
5498 (void)
5500 /* FIXME: maybe we should return nil for indirect buffers since
5501 they're never autosaved. */
5502 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5505 /* Reading and completing file names */
5507 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5508 Snext_read_file_uses_dialog_p, 0, 0, 0,
5509 doc: /* Return t if a call to `read-file-name' will use a dialog.
5510 The return value is only relevant for a call to `read-file-name' that happens
5511 before any other event (mouse or keypress) is handled. */)
5512 (void)
5514 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK)
5515 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5516 && use_dialog_box
5517 && use_file_dialog
5518 && have_menus_p ())
5519 return Qt;
5520 #endif
5521 return Qnil;
5524 Lisp_Object
5525 Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
5527 struct gcpro gcpro1, gcpro2;
5528 Lisp_Object args[7];
5530 GCPRO1 (default_filename);
5531 args[0] = intern ("read-file-name");
5532 args[1] = prompt;
5533 args[2] = dir;
5534 args[3] = default_filename;
5535 args[4] = mustmatch;
5536 args[5] = initial;
5537 args[6] = predicate;
5538 RETURN_UNGCPRO (Ffuncall (7, args));
5542 void
5543 syms_of_fileio (void)
5545 Qoperations = intern_c_string ("operations");
5546 Qexpand_file_name = intern_c_string ("expand-file-name");
5547 Qsubstitute_in_file_name = intern_c_string ("substitute-in-file-name");
5548 Qdirectory_file_name = intern_c_string ("directory-file-name");
5549 Qfile_name_directory = intern_c_string ("file-name-directory");
5550 Qfile_name_nondirectory = intern_c_string ("file-name-nondirectory");
5551 Qunhandled_file_name_directory = intern_c_string ("unhandled-file-name-directory");
5552 Qfile_name_as_directory = intern_c_string ("file-name-as-directory");
5553 Qcopy_file = intern_c_string ("copy-file");
5554 Qmake_directory_internal = intern_c_string ("make-directory-internal");
5555 Qmake_directory = intern_c_string ("make-directory");
5556 Qdelete_directory_internal = intern_c_string ("delete-directory-internal");
5557 Qdelete_file = intern_c_string ("delete-file");
5558 Qrename_file = intern_c_string ("rename-file");
5559 Qadd_name_to_file = intern_c_string ("add-name-to-file");
5560 Qmake_symbolic_link = intern_c_string ("make-symbolic-link");
5561 Qfile_exists_p = intern_c_string ("file-exists-p");
5562 Qfile_executable_p = intern_c_string ("file-executable-p");
5563 Qfile_readable_p = intern_c_string ("file-readable-p");
5564 Qfile_writable_p = intern_c_string ("file-writable-p");
5565 Qfile_symlink_p = intern_c_string ("file-symlink-p");
5566 Qaccess_file = intern_c_string ("access-file");
5567 Qfile_directory_p = intern_c_string ("file-directory-p");
5568 Qfile_regular_p = intern_c_string ("file-regular-p");
5569 Qfile_accessible_directory_p = intern_c_string ("file-accessible-directory-p");
5570 Qfile_modes = intern_c_string ("file-modes");
5571 Qset_file_modes = intern_c_string ("set-file-modes");
5572 Qset_file_times = intern_c_string ("set-file-times");
5573 Qfile_selinux_context = intern_c_string("file-selinux-context");
5574 Qset_file_selinux_context = intern_c_string("set-file-selinux-context");
5575 Qfile_newer_than_file_p = intern_c_string ("file-newer-than-file-p");
5576 Qinsert_file_contents = intern_c_string ("insert-file-contents");
5577 Qwrite_region = intern_c_string ("write-region");
5578 Qverify_visited_file_modtime = intern_c_string ("verify-visited-file-modtime");
5579 Qset_visited_file_modtime = intern_c_string ("set-visited-file-modtime");
5580 Qauto_save_coding = intern_c_string ("auto-save-coding");
5582 staticpro (&Qoperations);
5583 staticpro (&Qexpand_file_name);
5584 staticpro (&Qsubstitute_in_file_name);
5585 staticpro (&Qdirectory_file_name);
5586 staticpro (&Qfile_name_directory);
5587 staticpro (&Qfile_name_nondirectory);
5588 staticpro (&Qunhandled_file_name_directory);
5589 staticpro (&Qfile_name_as_directory);
5590 staticpro (&Qcopy_file);
5591 staticpro (&Qmake_directory_internal);
5592 staticpro (&Qmake_directory);
5593 staticpro (&Qdelete_directory_internal);
5594 staticpro (&Qdelete_file);
5595 staticpro (&Qrename_file);
5596 staticpro (&Qadd_name_to_file);
5597 staticpro (&Qmake_symbolic_link);
5598 staticpro (&Qfile_exists_p);
5599 staticpro (&Qfile_executable_p);
5600 staticpro (&Qfile_readable_p);
5601 staticpro (&Qfile_writable_p);
5602 staticpro (&Qaccess_file);
5603 staticpro (&Qfile_symlink_p);
5604 staticpro (&Qfile_directory_p);
5605 staticpro (&Qfile_regular_p);
5606 staticpro (&Qfile_accessible_directory_p);
5607 staticpro (&Qfile_modes);
5608 staticpro (&Qset_file_modes);
5609 staticpro (&Qset_file_times);
5610 staticpro (&Qfile_selinux_context);
5611 staticpro (&Qset_file_selinux_context);
5612 staticpro (&Qfile_newer_than_file_p);
5613 staticpro (&Qinsert_file_contents);
5614 staticpro (&Qwrite_region);
5615 staticpro (&Qverify_visited_file_modtime);
5616 staticpro (&Qset_visited_file_modtime);
5617 staticpro (&Qauto_save_coding);
5619 Qfile_name_history = intern_c_string ("file-name-history");
5620 Fset (Qfile_name_history, Qnil);
5621 staticpro (&Qfile_name_history);
5623 Qfile_error = intern_c_string ("file-error");
5624 staticpro (&Qfile_error);
5625 Qfile_already_exists = intern_c_string ("file-already-exists");
5626 staticpro (&Qfile_already_exists);
5627 Qfile_date_error = intern_c_string ("file-date-error");
5628 staticpro (&Qfile_date_error);
5629 Qexcl = intern_c_string ("excl");
5630 staticpro (&Qexcl);
5632 #ifdef DOS_NT
5633 Qfind_buffer_file_type = intern_c_string ("find-buffer-file-type");
5634 staticpro (&Qfind_buffer_file_type);
5635 #endif /* DOS_NT */
5637 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system,
5638 doc: /* *Coding system for encoding file names.
5639 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5640 Vfile_name_coding_system = Qnil;
5642 DEFVAR_LISP ("default-file-name-coding-system",
5643 &Vdefault_file_name_coding_system,
5644 doc: /* Default coding system for encoding file names.
5645 This variable is used only when `file-name-coding-system' is nil.
5647 This variable is set/changed by the command `set-language-environment'.
5648 User should not set this variable manually,
5649 instead use `file-name-coding-system' to get a constant encoding
5650 of file names regardless of the current language environment. */);
5651 Vdefault_file_name_coding_system = Qnil;
5653 Qformat_decode = intern_c_string ("format-decode");
5654 staticpro (&Qformat_decode);
5655 Qformat_annotate_function = intern_c_string ("format-annotate-function");
5656 staticpro (&Qformat_annotate_function);
5657 Qafter_insert_file_set_coding = intern_c_string ("after-insert-file-set-coding");
5658 staticpro (&Qafter_insert_file_set_coding);
5660 Qcar_less_than_car = intern_c_string ("car-less-than-car");
5661 staticpro (&Qcar_less_than_car);
5663 Fput (Qfile_error, Qerror_conditions,
5664 Fpurecopy (list2 (Qfile_error, Qerror)));
5665 Fput (Qfile_error, Qerror_message,
5666 make_pure_c_string ("File error"));
5668 Fput (Qfile_already_exists, Qerror_conditions,
5669 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5670 Fput (Qfile_already_exists, Qerror_message,
5671 make_pure_c_string ("File already exists"));
5673 Fput (Qfile_date_error, Qerror_conditions,
5674 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5675 Fput (Qfile_date_error, Qerror_message,
5676 make_pure_c_string ("Cannot set file date"));
5678 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
5679 doc: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
5680 If a file name matches REGEXP, then all I/O on that file is done by calling
5681 HANDLER.
5683 The first argument given to HANDLER is the name of the I/O primitive
5684 to be handled; the remaining arguments are the arguments that were
5685 passed to that primitive. For example, if you do
5686 (file-exists-p FILENAME)
5687 and FILENAME is handled by HANDLER, then HANDLER is called like this:
5688 (funcall HANDLER 'file-exists-p FILENAME)
5689 The function `find-file-name-handler' checks this list for a handler
5690 for its argument. */);
5691 Vfile_name_handler_alist = Qnil;
5693 DEFVAR_LISP ("set-auto-coding-function",
5694 &Vset_auto_coding_function,
5695 doc: /* If non-nil, a function to call to decide a coding system of file.
5696 Two arguments are passed to this function: the file name
5697 and the length of a file contents following the point.
5698 This function should return a coding system to decode the file contents.
5699 It should check the file name against `auto-coding-alist'.
5700 If no coding system is decided, it should check a coding system
5701 specified in the heading lines with the format:
5702 -*- ... coding: CODING-SYSTEM; ... -*-
5703 or local variable spec of the tailing lines with `coding:' tag. */);
5704 Vset_auto_coding_function = Qnil;
5706 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
5707 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5708 Each is passed one argument, the number of characters inserted,
5709 with point at the start of the inserted text. Each function
5710 should leave point the same, and return the new character count.
5711 If `insert-file-contents' is intercepted by a handler from
5712 `file-name-handler-alist', that handler is responsible for calling the
5713 functions in `after-insert-file-functions' if appropriate. */);
5714 Vafter_insert_file_functions = Qnil;
5716 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
5717 doc: /* A list of functions to be called at the start of `write-region'.
5718 Each is passed two arguments, START and END as for `write-region'.
5719 These are usually two numbers but not always; see the documentation
5720 for `write-region'. The function should return a list of pairs
5721 of the form (POSITION . STRING), consisting of strings to be effectively
5722 inserted at the specified positions of the file being written (1 means to
5723 insert before the first byte written). The POSITIONs must be sorted into
5724 increasing order.
5726 If there are several annotation functions, the lists returned by these
5727 functions are merged destructively. As each annotation function runs,
5728 the variable `write-region-annotations-so-far' contains a list of all
5729 annotations returned by previous annotation functions.
5731 An annotation function can return with a different buffer current.
5732 Doing so removes the annotations returned by previous functions, and
5733 resets START and END to `point-min' and `point-max' of the new buffer.
5735 After `write-region' completes, Emacs calls the function stored in
5736 `write-region-post-annotation-function', once for each buffer that was
5737 current when building the annotations (i.e., at least once), with that
5738 buffer current. */);
5739 Vwrite_region_annotate_functions = Qnil;
5740 staticpro (&Qwrite_region_annotate_functions);
5741 Qwrite_region_annotate_functions
5742 = intern_c_string ("write-region-annotate-functions");
5744 DEFVAR_LISP ("write-region-post-annotation-function",
5745 &Vwrite_region_post_annotation_function,
5746 doc: /* Function to call after `write-region' completes.
5747 The function is called with no arguments. If one or more of the
5748 annotation functions in `write-region-annotate-functions' changed the
5749 current buffer, the function stored in this variable is called for
5750 each of those additional buffers as well, in addition to the original
5751 buffer. The relevant buffer is current during each function call. */);
5752 Vwrite_region_post_annotation_function = Qnil;
5753 staticpro (&Vwrite_region_annotation_buffers);
5755 DEFVAR_LISP ("write-region-annotations-so-far",
5756 &Vwrite_region_annotations_so_far,
5757 doc: /* When an annotation function is called, this holds the previous annotations.
5758 These are the annotations made by other annotation functions
5759 that were already called. See also `write-region-annotate-functions'. */);
5760 Vwrite_region_annotations_so_far = Qnil;
5762 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
5763 doc: /* A list of file name handlers that temporarily should not be used.
5764 This applies only to the operation `inhibit-file-name-operation'. */);
5765 Vinhibit_file_name_handlers = Qnil;
5767 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
5768 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5769 Vinhibit_file_name_operation = Qnil;
5771 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
5772 doc: /* File name in which we write a list of all auto save file names.
5773 This variable is initialized automatically from `auto-save-list-file-prefix'
5774 shortly after Emacs reads your `.emacs' file, if you have not yet given it
5775 a non-nil value. */);
5776 Vauto_save_list_file_name = Qnil;
5778 DEFVAR_LISP ("auto-save-visited-file-name", &Vauto_save_visited_file_name,
5779 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5780 Normally auto-save files are written under other names. */);
5781 Vauto_save_visited_file_name = Qnil;
5783 DEFVAR_LISP ("auto-save-include-big-deletions", &Vauto_save_include_big_deletions,
5784 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5785 If nil, deleting a substantial portion of the text disables auto-save
5786 in the buffer; this is the default behavior, because the auto-save
5787 file is usually more useful if it contains the deleted text. */);
5788 Vauto_save_include_big_deletions = Qnil;
5790 #ifdef HAVE_FSYNC
5791 DEFVAR_BOOL ("write-region-inhibit-fsync", &write_region_inhibit_fsync,
5792 doc: /* *Non-nil means don't call fsync in `write-region'.
5793 This variable affects calls to `write-region' as well as save commands.
5794 A non-nil value may result in data loss! */);
5795 write_region_inhibit_fsync = 0;
5796 #endif
5798 DEFVAR_BOOL ("delete-by-moving-to-trash", &delete_by_moving_to_trash,
5799 doc: /* Specifies whether to use the system's trash can.
5800 When non-nil, certain file deletion commands use the function
5801 `move-file-to-trash' instead of deleting files outright.
5802 This includes interactive calls to `delete-file' and
5803 `delete-directory' and the Dired deletion commands. */);
5804 delete_by_moving_to_trash = 0;
5805 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
5806 Qmove_file_to_trash = intern_c_string ("move-file-to-trash");
5807 staticpro (&Qmove_file_to_trash);
5808 Qcopy_directory = intern_c_string ("copy-directory");
5809 staticpro (&Qcopy_directory);
5810 Qdelete_directory = intern_c_string ("delete-directory");
5811 staticpro (&Qdelete_directory);
5813 defsubr (&Sfind_file_name_handler);
5814 defsubr (&Sfile_name_directory);
5815 defsubr (&Sfile_name_nondirectory);
5816 defsubr (&Sunhandled_file_name_directory);
5817 defsubr (&Sfile_name_as_directory);
5818 defsubr (&Sdirectory_file_name);
5819 defsubr (&Smake_temp_name);
5820 defsubr (&Sexpand_file_name);
5821 defsubr (&Ssubstitute_in_file_name);
5822 defsubr (&Scopy_file);
5823 defsubr (&Smake_directory_internal);
5824 defsubr (&Sdelete_directory_internal);
5825 defsubr (&Sdelete_file);
5826 defsubr (&Srename_file);
5827 defsubr (&Sadd_name_to_file);
5828 defsubr (&Smake_symbolic_link);
5829 defsubr (&Sfile_name_absolute_p);
5830 defsubr (&Sfile_exists_p);
5831 defsubr (&Sfile_executable_p);
5832 defsubr (&Sfile_readable_p);
5833 defsubr (&Sfile_writable_p);
5834 defsubr (&Saccess_file);
5835 defsubr (&Sfile_symlink_p);
5836 defsubr (&Sfile_directory_p);
5837 defsubr (&Sfile_accessible_directory_p);
5838 defsubr (&Sfile_regular_p);
5839 defsubr (&Sfile_modes);
5840 defsubr (&Sset_file_modes);
5841 defsubr (&Sset_file_times);
5842 defsubr (&Sfile_selinux_context);
5843 defsubr (&Sset_file_selinux_context);
5844 defsubr (&Sset_default_file_modes);
5845 defsubr (&Sdefault_file_modes);
5846 defsubr (&Sfile_newer_than_file_p);
5847 defsubr (&Sinsert_file_contents);
5848 defsubr (&Swrite_region);
5849 defsubr (&Scar_less_than_car);
5850 defsubr (&Sverify_visited_file_modtime);
5851 defsubr (&Sclear_visited_file_modtime);
5852 defsubr (&Svisited_file_modtime);
5853 defsubr (&Sset_visited_file_modtime);
5854 defsubr (&Sdo_auto_save);
5855 defsubr (&Sset_buffer_auto_saved);
5856 defsubr (&Sclear_buffer_auto_save_failure);
5857 defsubr (&Srecent_auto_save_p);
5859 defsubr (&Snext_read_file_uses_dialog_p);
5861 #ifdef HAVE_SYNC
5862 defsubr (&Sunix_sync);
5863 #endif
5866 /* arch-tag: 64ba3fd7-f844-4fb2-ba4b-427eb928786c
5867 (do not change this comment) */