Refill some copyright headers.
[bpt/emacs.git] / src / fileio.c
1 /* File IO for GNU Emacs.
2
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, 2011 Free Software Foundation, Inc.
6
7 This file is part of GNU Emacs.
8
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.
13
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.
18
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/>. */
21
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>
29
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33
34 #if !defined (S_ISLNK) && defined (S_IFLNK)
35 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
36 #endif
37
38 #if !defined (S_ISFIFO) && defined (S_IFIFO)
39 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
40 #endif
41
42 #if !defined (S_ISREG) && defined (S_IFREG)
43 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
44 #endif
45
46 #ifdef HAVE_PWD_H
47 #include <pwd.h>
48 #endif
49
50 #include <ctype.h>
51 #include <errno.h>
52
53 #ifdef HAVE_LIBSELINUX
54 #include <selinux/selinux.h>
55 #include <selinux/context.h>
56 #endif
57
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"
67
68 #ifdef WINDOWSNT
69 #define NOMINMAX 1
70 #include <windows.h>
71 #include <fcntl.h>
72 #endif /* not WINDOWSNT */
73
74 #ifdef MSDOS
75 #include "msdos.h"
76 #include <sys/param.h>
77 #include <fcntl.h>
78 #endif
79
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
94
95 #include "systime.h"
96
97 #ifdef HPUX
98 #include <netio.h>
99 #endif
100
101 #include "commands.h"
102
103 #ifndef S_ISLNK
104 # define lstat stat
105 #endif
106
107 #ifndef FILE_SYSTEM_CASE
108 #define FILE_SYSTEM_CASE(filename) (filename)
109 #endif
110
111 /* Nonzero during writing of auto-save files */
112 int auto_saving;
113
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;
117
118 /* Set by auto_save_1 if an error occurred during the last auto-save. */
119 int auto_save_error_occurred;
120
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;
127
128 /* Coding system for file names, or nil if none. */
129 Lisp_Object Vfile_name_coding_system;
130
131 /* Coding system for file names used only when
132 Vfile_name_coding_system is nil. */
133 Lisp_Object Vdefault_file_name_coding_system;
134
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;
138
139 /* Property name of a file name handler,
140 which gives a list of operations it handles.. */
141 Lisp_Object Qoperations;
142
143 /* Lisp functions for translating file formats */
144 Lisp_Object Qformat_decode, Qformat_annotate_function;
145
146 /* Function to be called to decide a coding system of a reading file. */
147 Lisp_Object Vset_auto_coding_function;
148
149 /* Functions to be called to process text properties in inserted file. */
150 Lisp_Object Vafter_insert_file_functions;
151
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;
155
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;
160
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;
164
165 /* Each time an annotation function changes the buffer, the new buffer
166 is added here. */
167 Lisp_Object Vwrite_region_annotation_buffers;
168
169 /* File name in which we write a list of all our auto save files. */
170 Lisp_Object Vauto_save_list_file_name;
171
172 /* Whether or not files are auto-saved into themselves. */
173 Lisp_Object Vauto_save_visited_file_name;
174
175 /* Whether or not to continue auto-saving after a large deletion. */
176 Lisp_Object Vauto_save_include_big_deletions;
177
178 #ifdef HAVE_FSYNC
179 /* Nonzero means skip the call to fsync in Fwrite-region. */
180 int write_region_inhibit_fsync;
181 #endif
182
183 /* Non-zero means call move-file-to-trash in Fdelete_file or
184 Fdelete_directory_internal. */
185 int delete_by_moving_to_trash;
186
187 Lisp_Object Qdelete_by_moving_to_trash;
188
189 /* Lisp function for moving files to trash. */
190 Lisp_Object Qmove_file_to_trash;
191
192 /* Lisp function for recursively copying directories. */
193 Lisp_Object Qcopy_directory;
194
195 /* Lisp function for recursively deleting directories. */
196 Lisp_Object Qdelete_directory;
197
198 #ifdef WINDOWSNT
199 extern Lisp_Object Vw32_get_true_file_attributes;
200 #endif
201
202 /* These variables describe handlers that have "already" had a chance
203 to handle the current operation.
204
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. */
208
209 static Lisp_Object Vinhibit_file_name_handlers;
210 static Lisp_Object Vinhibit_file_name_operation;
211
212 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
213 Lisp_Object Qexcl;
214 Lisp_Object Qfile_name_history;
215
216 Lisp_Object Qcar_less_than_car;
217
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 *);
221
222 \f
223 void
224 report_file_error (const char *string, Lisp_Object data)
225 {
226 Lisp_Object errstring;
227 int errorno = errno;
228 char *str;
229
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);
235
236 while (1)
237 switch (errorno)
238 {
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 ('/')))
248 {
249 int c;
250
251 str = (char *) SDATA (errstring);
252 c = STRING_CHAR (str);
253 Faset (errstring, make_number (0), make_number (DOWNCASE (c)));
254 }
255
256 xsignal (Qfile_error,
257 Fcons (build_string (string), Fcons (errstring, data)));
258 }
259 }
260
261 Lisp_Object
262 close_file_unwind (Lisp_Object fd)
263 {
264 emacs_close (XFASTINT (fd));
265 return Qnil;
266 }
267
268 /* Restore point, having saved it as a marker. */
269
270 Lisp_Object
271 restore_point_unwind (Lisp_Object location)
272 {
273 Fgoto_char (location);
274 Fset_marker (location, Qnil, Qnil);
275 return Qnil;
276 }
277
278 \f
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;
313
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.
319
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)
325 {
326 /* This function must not munge the match data. */
327 Lisp_Object chain, inhibited_handlers, result;
328 int pos = -1;
329
330 result = Qnil;
331 CHECK_STRING (filename);
332
333 if (EQ (operation, Vinhibit_file_name_operation))
334 inhibited_handlers = Vinhibit_file_name_handlers;
335 else
336 inhibited_handlers = Qnil;
337
338 for (chain = Vfile_name_handler_alist; CONSP (chain);
339 chain = XCDR (chain))
340 {
341 Lisp_Object elt;
342 elt = XCAR (chain);
343 if (CONSP (elt))
344 {
345 Lisp_Object string = XCAR (elt);
346 int match_pos;
347 Lisp_Object handler = XCDR (elt);
348 Lisp_Object operations = Qnil;
349
350 if (SYMBOLP (handler))
351 operations = Fget (handler, Qoperations);
352
353 if (STRINGP (string)
354 && (match_pos = fast_string_match (string, filename)) > pos
355 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
356 {
357 Lisp_Object tem;
358
359 handler = XCDR (elt);
360 tem = Fmemq (handler, inhibited_handlers);
361 if (NILP (tem))
362 {
363 result = handler;
364 pos = match_pos;
365 }
366 }
367 }
368
369 QUIT;
370 }
371 return result;
372 }
373 \f
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)
381 {
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;
389
390 CHECK_STRING (filename);
391
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);
397
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);
406
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--;
416
417 if (p == beg)
418 return Qnil;
419 #ifdef DOS_NT
420 /* Expansion of "c:" to drive and default directory. */
421 if (p[-1] == ':')
422 {
423 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
424 unsigned char *res = alloca (MAXPATHLEN + 1);
425 unsigned char *r = res;
426
427 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
428 {
429 strncpy (res, beg, 2);
430 beg += 2;
431 r += 2;
432 }
433
434 if (getdefdir (toupper (*beg) - 'A' + 1, r))
435 {
436 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
437 strcat (res, "/");
438 beg = res;
439 p = beg + strlen (beg);
440 }
441 }
442 dostounix_filename (beg);
443 #endif /* DOS_NT */
444
445 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
446 }
447
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)
455 {
456 register const unsigned char *beg, *p, *end;
457 Lisp_Object handler;
458
459 CHECK_STRING (filename);
460
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);
466
467 beg = SDATA (filename);
468 end = p = beg + SBYTES (filename);
469
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
477 )
478 p--;
479
480 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
481 }
482
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)
495 {
496 Lisp_Object handler;
497
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);
503
504 return Ffile_name_directory (filename);
505 }
506
507 \f
508 char *
509 file_name_as_directory (char *out, char *in)
510 {
511 int size = strlen (in) - 1;
512
513 strcpy (out, in);
514
515 if (size < 0)
516 {
517 out[0] = '.';
518 out[1] = '/';
519 out[2] = 0;
520 return out;
521 }
522
523 /* For Unix syntax, Append a slash if necessary */
524 if (!IS_DIRECTORY_SEP (out[size]))
525 {
526 out[size + 1] = DIRECTORY_SEP;
527 out[size + 2] = '\0';
528 }
529 #ifdef DOS_NT
530 dostounix_filename (out);
531 #endif
532 return out;
533 }
534
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)
544 {
545 char *buf;
546 Lisp_Object handler;
547
548 CHECK_STRING (file);
549 if (NILP (file))
550 return Qnil;
551
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);
557
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));
562 }
563 \f
564 /*
565 * Convert from directory name to filename.
566 * On UNIX, it's simple: just make sure there isn't a terminating /
567
568 * Value is nonzero if the string output is different from the input.
569 */
570
571 int
572 directory_file_name (char *src, char *dst)
573 {
574 long slen;
575
576 slen = strlen (src);
577
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
586 )
587 dst[slen - 1] = 0;
588 #ifdef DOS_NT
589 dostounix_filename (dst);
590 #endif
591 return 1;
592 }
593
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)
602 {
603 char *buf;
604 Lisp_Object handler;
605
606 CHECK_STRING (directory);
607
608 if (NILP (directory))
609 return Qnil;
610
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);
616
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));
621 }
622
623 static const char make_temp_name_tbl[64] =
624 {
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','-','_'
633 };
634
635 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
636
637 /* Value is a temporary file name starting with PREFIX, a string.
638
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.
644
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.
649
650 This function signals an error if no unique file name could be
651 generated. */
652
653 Lisp_Object
654 make_temp_name (Lisp_Object prefix, int base64_p)
655 {
656 Lisp_Object val;
657 int len, clen;
658 int pid;
659 unsigned char *p, *data;
660 char pidbuf[20];
661 int pidlen;
662
663 CHECK_STRING (prefix);
664
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. */
669
670 pid = (int) getpid ();
671
672 if (base64_p)
673 {
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;
678 }
679 else
680 {
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
690 }
691
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;
699
700 memcpy (p, pidbuf, pidlen);
701 p += pidlen;
702
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.
707
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. */
711
712 if (!make_temp_name_count_initialized_p)
713 {
714 make_temp_name_count = (unsigned) time (NULL);
715 make_temp_name_count_initialized_p = 1;
716 }
717
718 while (1)
719 {
720 struct stat ignored;
721 unsigned num = make_temp_name_count;
722
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;
726
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;
731
732 if (stat (data, &ignored) < 0)
733 {
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 */
748 }
749 }
750
751 error ("Cannot create temporary name for prefix `%s'",
752 SDATA (prefix));
753 return Qnil;
754 }
755
756
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.
761
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.
765
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:
769
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)
774 {
775 return make_temp_name (prefix, 0);
776 }
777
778
779 \f
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 NAME should be a string that is a valid file name for the underlying
786 filesystem.
787 File name components that are `.' are removed, and
788 so are file name components followed by `..', along with the `..' itself;
789 note that these simplifications are done without checking the resulting
790 file names in the file system.
791 Multiple consecutive slashes are collapsed into a single slash,
792 except at the beginning of the file name when they are significant (e.g.,
793 UNC file names on MS-Windows.)
794 An initial `~/' expands to your home directory.
795 An initial `~USER/' expands to USER's home directory.
796 See also the function `substitute-in-file-name'.
797
798 For technical reasons, this function can return correct but
799 non-intuitive results for the root directory; for instance,
800 \(expand-file-name ".." "/") returns "/..". For this reason, use
801 \(directory-file-name (file-name-directory dirname)) to traverse a
802 filesystem tree, not (expand-file-name ".." dirname). */)
803 (Lisp_Object name, Lisp_Object default_directory)
804 {
805 /* These point to SDATA and need to be careful with string-relocation
806 during GC (via DECODE_FILE). */
807 unsigned char *nm, *newdir;
808 /* This should only point to alloca'd data. */
809 unsigned char *target;
810
811 int tlen;
812 struct passwd *pw;
813 #ifdef DOS_NT
814 int drive = 0;
815 int collapse_newdir = 1;
816 int is_escaped = 0;
817 #endif /* DOS_NT */
818 int length;
819 Lisp_Object handler, result;
820 int multibyte;
821 Lisp_Object hdir;
822
823 CHECK_STRING (name);
824
825 /* If the file name has special constructs in it,
826 call the corresponding file handler. */
827 handler = Ffind_file_name_handler (name, Qexpand_file_name);
828 if (!NILP (handler))
829 return call3 (handler, Qexpand_file_name, name, default_directory);
830
831 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
832 if (NILP (default_directory))
833 default_directory = current_buffer->directory;
834 if (! STRINGP (default_directory))
835 {
836 #ifdef DOS_NT
837 /* "/" is not considered a root directory on DOS_NT, so using "/"
838 here causes an infinite recursion in, e.g., the following:
839
840 (let (default-directory)
841 (expand-file-name "a"))
842
843 To avoid this, we set default_directory to the root of the
844 current drive. */
845 default_directory = build_string (emacs_root_dir ());
846 #else
847 default_directory = build_string ("/");
848 #endif
849 }
850
851 if (!NILP (default_directory))
852 {
853 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
854 if (!NILP (handler))
855 return call3 (handler, Qexpand_file_name, name, default_directory);
856 }
857
858 {
859 unsigned char *o = SDATA (default_directory);
860
861 /* Make sure DEFAULT_DIRECTORY is properly expanded.
862 It would be better to do this down below where we actually use
863 default_directory. Unfortunately, calling Fexpand_file_name recursively
864 could invoke GC, and the strings might be relocated. This would
865 be annoying because we have pointers into strings lying around
866 that would need adjusting, and people would add new pointers to
867 the code and forget to adjust them, resulting in intermittent bugs.
868 Putting this call here avoids all that crud.
869
870 The EQ test avoids infinite recursion. */
871 if (! NILP (default_directory) && !EQ (default_directory, name)
872 /* Save time in some common cases - as long as default_directory
873 is not relative, it can be canonicalized with name below (if it
874 is needed at all) without requiring it to be expanded now. */
875 #ifdef DOS_NT
876 /* Detect MSDOS file names with drive specifiers. */
877 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
878 && IS_DIRECTORY_SEP (o[2]))
879 #ifdef WINDOWSNT
880 /* Detect Windows file names in UNC format. */
881 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
882 #endif
883 #else /* not DOS_NT */
884 /* Detect Unix absolute file names (/... alone is not absolute on
885 DOS or Windows). */
886 && ! (IS_DIRECTORY_SEP (o[0]))
887 #endif /* not DOS_NT */
888 )
889 {
890 struct gcpro gcpro1;
891
892 GCPRO1 (name);
893 default_directory = Fexpand_file_name (default_directory, Qnil);
894 UNGCPRO;
895 }
896 }
897 name = FILE_SYSTEM_CASE (name);
898 multibyte = STRING_MULTIBYTE (name);
899 if (multibyte != STRING_MULTIBYTE (default_directory))
900 {
901 if (multibyte)
902 default_directory = string_to_multibyte (default_directory);
903 else
904 {
905 name = string_to_multibyte (name);
906 multibyte = 1;
907 }
908 }
909
910 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
911 nm = (unsigned char *) alloca (SBYTES (name) + 1);
912 memcpy (nm, SDATA (name), SBYTES (name) + 1);
913
914 #ifdef DOS_NT
915 /* Note if special escape prefix is present, but remove for now. */
916 if (nm[0] == '/' && nm[1] == ':')
917 {
918 is_escaped = 1;
919 nm += 2;
920 }
921
922 /* Find and remove drive specifier if present; this makes nm absolute
923 even if the rest of the name appears to be relative. Only look for
924 drive specifier at the beginning. */
925 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
926 {
927 drive = nm[0];
928 nm += 2;
929 }
930
931 #ifdef WINDOWSNT
932 /* If we see "c://somedir", we want to strip the first slash after the
933 colon when stripping the drive letter. Otherwise, this expands to
934 "//somedir". */
935 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
936 nm++;
937
938 /* Discard any previous drive specifier if nm is now in UNC format. */
939 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
940 {
941 drive = 0;
942 }
943 #endif /* WINDOWSNT */
944 #endif /* DOS_NT */
945
946 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
947 none are found, we can probably return right away. We will avoid
948 allocating a new string if name is already fully expanded. */
949 if (
950 IS_DIRECTORY_SEP (nm[0])
951 #ifdef MSDOS
952 && drive && !is_escaped
953 #endif
954 #ifdef WINDOWSNT
955 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
956 #endif
957 )
958 {
959 /* If it turns out that the filename we want to return is just a
960 suffix of FILENAME, we don't need to go through and edit
961 things; we just need to construct a new string using data
962 starting at the middle of FILENAME. If we set lose to a
963 non-zero value, that means we've discovered that we can't do
964 that cool trick. */
965 int lose = 0;
966 unsigned char *p = nm;
967
968 while (*p)
969 {
970 /* Since we know the name is absolute, we can assume that each
971 element starts with a "/". */
972
973 /* "." and ".." are hairy. */
974 if (IS_DIRECTORY_SEP (p[0])
975 && p[1] == '.'
976 && (IS_DIRECTORY_SEP (p[2])
977 || p[2] == 0
978 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
979 || p[3] == 0))))
980 lose = 1;
981 /* We want to replace multiple `/' in a row with a single
982 slash. */
983 else if (p > nm
984 && IS_DIRECTORY_SEP (p[0])
985 && IS_DIRECTORY_SEP (p[1]))
986 lose = 1;
987 p++;
988 }
989 if (!lose)
990 {
991 #ifdef DOS_NT
992 /* Make sure directories are all separated with /, but
993 avoid allocation of a new string when not required. */
994 dostounix_filename (nm);
995 #ifdef WINDOWSNT
996 if (IS_DIRECTORY_SEP (nm[1]))
997 {
998 if (strcmp (nm, SDATA (name)) != 0)
999 name = make_specified_string (nm, -1, strlen (nm), multibyte);
1000 }
1001 else
1002 #endif
1003 /* drive must be set, so this is okay */
1004 if (strcmp (nm - 2, SDATA (name)) != 0)
1005 {
1006 char temp[] = " :";
1007
1008 name = make_specified_string (nm, -1, p - nm, multibyte);
1009 temp[0] = DRIVE_LETTER (drive);
1010 name = concat2 (build_string (temp), name);
1011 }
1012 return name;
1013 #else /* not DOS_NT */
1014 if (strcmp (nm, SDATA (name)) == 0)
1015 return name;
1016 return make_specified_string (nm, -1, strlen (nm), multibyte);
1017 #endif /* not DOS_NT */
1018 }
1019 }
1020
1021 /* At this point, nm might or might not be an absolute file name. We
1022 need to expand ~ or ~user if present, otherwise prefix nm with
1023 default_directory if nm is not absolute, and finally collapse /./
1024 and /foo/../ sequences.
1025
1026 We set newdir to be the appropriate prefix if one is needed:
1027 - the relevant user directory if nm starts with ~ or ~user
1028 - the specified drive's working dir (DOS/NT only) if nm does not
1029 start with /
1030 - the value of default_directory.
1031
1032 Note that these prefixes are not guaranteed to be absolute (except
1033 for the working dir of a drive). Therefore, to ensure we always
1034 return an absolute name, if the final prefix is not absolute we
1035 append it to the current working directory. */
1036
1037 newdir = 0;
1038
1039 if (nm[0] == '~') /* prefix ~ */
1040 {
1041 if (IS_DIRECTORY_SEP (nm[1])
1042 || nm[1] == 0) /* ~ by itself */
1043 {
1044 Lisp_Object tem;
1045
1046 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1047 newdir = (unsigned char *) "";
1048 nm++;
1049 /* egetenv may return a unibyte string, which will bite us since
1050 we expect the directory to be multibyte. */
1051 tem = build_string (newdir);
1052 if (!STRING_MULTIBYTE (tem))
1053 {
1054 hdir = DECODE_FILE (tem);
1055 newdir = SDATA (hdir);
1056 }
1057 #ifdef DOS_NT
1058 collapse_newdir = 0;
1059 #endif
1060 }
1061 else /* ~user/filename */
1062 {
1063 unsigned char *o, *p;
1064 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
1065 o = alloca (p - nm + 1);
1066 memcpy (o, nm, p - nm);
1067 o [p - nm] = 0;
1068
1069 BLOCK_INPUT;
1070 pw = (struct passwd *) getpwnam (o + 1);
1071 UNBLOCK_INPUT;
1072 if (pw)
1073 {
1074 newdir = (unsigned char *) pw -> pw_dir;
1075 nm = p;
1076 #ifdef DOS_NT
1077 collapse_newdir = 0;
1078 #endif
1079 }
1080
1081 /* If we don't find a user of that name, leave the name
1082 unchanged; don't move nm forward to p. */
1083 }
1084 }
1085
1086 #ifdef DOS_NT
1087 /* On DOS and Windows, nm is absolute if a drive name was specified;
1088 use the drive's current directory as the prefix if needed. */
1089 if (!newdir && drive)
1090 {
1091 /* Get default directory if needed to make nm absolute. */
1092 if (!IS_DIRECTORY_SEP (nm[0]))
1093 {
1094 newdir = alloca (MAXPATHLEN + 1);
1095 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1096 newdir = NULL;
1097 }
1098 if (!newdir)
1099 {
1100 /* Either nm starts with /, or drive isn't mounted. */
1101 newdir = alloca (4);
1102 newdir[0] = DRIVE_LETTER (drive);
1103 newdir[1] = ':';
1104 newdir[2] = '/';
1105 newdir[3] = 0;
1106 }
1107 }
1108 #endif /* DOS_NT */
1109
1110 /* Finally, if no prefix has been specified and nm is not absolute,
1111 then it must be expanded relative to default_directory. */
1112
1113 if (1
1114 #ifndef DOS_NT
1115 /* /... alone is not absolute on DOS and Windows. */
1116 && !IS_DIRECTORY_SEP (nm[0])
1117 #endif
1118 #ifdef WINDOWSNT
1119 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1120 #endif
1121 && !newdir)
1122 {
1123 newdir = SDATA (default_directory);
1124 #ifdef DOS_NT
1125 /* Note if special escape prefix is present, but remove for now. */
1126 if (newdir[0] == '/' && newdir[1] == ':')
1127 {
1128 is_escaped = 1;
1129 newdir += 2;
1130 }
1131 #endif
1132 }
1133
1134 #ifdef DOS_NT
1135 if (newdir)
1136 {
1137 /* First ensure newdir is an absolute name. */
1138 if (
1139 /* Detect MSDOS file names with drive specifiers. */
1140 ! (IS_DRIVE (newdir[0])
1141 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1142 #ifdef WINDOWSNT
1143 /* Detect Windows file names in UNC format. */
1144 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1145 #endif
1146 )
1147 {
1148 /* Effectively, let newdir be (expand-file-name newdir cwd).
1149 Because of the admonition against calling expand-file-name
1150 when we have pointers into lisp strings, we accomplish this
1151 indirectly by prepending newdir to nm if necessary, and using
1152 cwd (or the wd of newdir's drive) as the new newdir. */
1153
1154 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1155 {
1156 drive = newdir[0];
1157 newdir += 2;
1158 }
1159 if (!IS_DIRECTORY_SEP (nm[0]))
1160 {
1161 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1162 file_name_as_directory (tmp, newdir);
1163 strcat (tmp, nm);
1164 nm = tmp;
1165 }
1166 newdir = alloca (MAXPATHLEN + 1);
1167 if (drive)
1168 {
1169 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1170 newdir = "/";
1171 }
1172 else
1173 getwd (newdir);
1174 }
1175
1176 /* Strip off drive name from prefix, if present. */
1177 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1178 {
1179 drive = newdir[0];
1180 newdir += 2;
1181 }
1182
1183 /* Keep only a prefix from newdir if nm starts with slash
1184 (//server/share for UNC, nothing otherwise). */
1185 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1186 {
1187 #ifdef WINDOWSNT
1188 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1189 {
1190 unsigned char *p;
1191 newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
1192 p = newdir + 2;
1193 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1194 p++;
1195 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1196 *p = 0;
1197 }
1198 else
1199 #endif
1200 newdir = "";
1201 }
1202 }
1203 #endif /* DOS_NT */
1204
1205 if (newdir)
1206 {
1207 /* Get rid of any slash at the end of newdir, unless newdir is
1208 just / or // (an incomplete UNC name). */
1209 length = strlen (newdir);
1210 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1211 #ifdef WINDOWSNT
1212 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1213 #endif
1214 )
1215 {
1216 unsigned char *temp = (unsigned char *) alloca (length);
1217 memcpy (temp, newdir, length - 1);
1218 temp[length - 1] = 0;
1219 newdir = temp;
1220 }
1221 tlen = length + 1;
1222 }
1223 else
1224 tlen = 0;
1225
1226 /* Now concatenate the directory and name to new space in the stack frame */
1227 tlen += strlen (nm) + 1;
1228 #ifdef DOS_NT
1229 /* Reserve space for drive specifier and escape prefix, since either
1230 or both may need to be inserted. (The Microsoft x86 compiler
1231 produces incorrect code if the following two lines are combined.) */
1232 target = (unsigned char *) alloca (tlen + 4);
1233 target += 4;
1234 #else /* not DOS_NT */
1235 target = (unsigned char *) alloca (tlen);
1236 #endif /* not DOS_NT */
1237 *target = 0;
1238
1239 if (newdir)
1240 {
1241 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1242 {
1243 #ifdef DOS_NT
1244 /* If newdir is effectively "C:/", then the drive letter will have
1245 been stripped and newdir will be "/". Concatenating with an
1246 absolute directory in nm produces "//", which will then be
1247 incorrectly treated as a network share. Ignore newdir in
1248 this case (keeping the drive letter). */
1249 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1250 && newdir[1] == '\0'))
1251 #endif
1252 strcpy (target, newdir);
1253 }
1254 else
1255 file_name_as_directory (target, newdir);
1256 }
1257
1258 strcat (target, nm);
1259
1260 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1261 appear. */
1262 {
1263 unsigned char *p = target;
1264 unsigned char *o = target;
1265
1266 while (*p)
1267 {
1268 if (!IS_DIRECTORY_SEP (*p))
1269 {
1270 *o++ = *p++;
1271 }
1272 else if (p[1] == '.'
1273 && (IS_DIRECTORY_SEP (p[2])
1274 || p[2] == 0))
1275 {
1276 /* If "/." is the entire filename, keep the "/". Otherwise,
1277 just delete the whole "/.". */
1278 if (o == target && p[2] == '\0')
1279 *o++ = *p;
1280 p += 2;
1281 }
1282 else if (p[1] == '.' && p[2] == '.'
1283 /* `/../' is the "superroot" on certain file systems.
1284 Turned off on DOS_NT systems because they have no
1285 "superroot" and because this causes us to produce
1286 file names like "d:/../foo" which fail file-related
1287 functions of the underlying OS. (To reproduce, try a
1288 long series of "../../" in default_directory, longer
1289 than the number of levels from the root.) */
1290 #ifndef DOS_NT
1291 && o != target
1292 #endif
1293 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1294 {
1295 #ifdef WINDOWSNT
1296 unsigned char *prev_o = o;
1297 #endif
1298 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1299 ;
1300 #ifdef WINDOWSNT
1301 /* Don't go below server level in UNC filenames. */
1302 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1303 && IS_DIRECTORY_SEP (*target))
1304 o = prev_o;
1305 else
1306 #endif
1307 /* Keep initial / only if this is the whole name. */
1308 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1309 ++o;
1310 p += 3;
1311 }
1312 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1313 /* Collapse multiple `/' in a row. */
1314 p++;
1315 else
1316 {
1317 *o++ = *p++;
1318 }
1319 }
1320
1321 #ifdef DOS_NT
1322 /* At last, set drive name. */
1323 #ifdef WINDOWSNT
1324 /* Except for network file name. */
1325 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1326 #endif /* WINDOWSNT */
1327 {
1328 if (!drive) abort ();
1329 target -= 2;
1330 target[0] = DRIVE_LETTER (drive);
1331 target[1] = ':';
1332 }
1333 /* Reinsert the escape prefix if required. */
1334 if (is_escaped)
1335 {
1336 target -= 2;
1337 target[0] = '/';
1338 target[1] = ':';
1339 }
1340 dostounix_filename (target);
1341 #endif /* DOS_NT */
1342
1343 result = make_specified_string (target, -1, o - target, multibyte);
1344 }
1345
1346 /* Again look to see if the file name has special constructs in it
1347 and perhaps call the corresponding file handler. This is needed
1348 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1349 the ".." component gives us "/user@host:/bar/../baz" which needs
1350 to be expanded again. */
1351 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1352 if (!NILP (handler))
1353 return call3 (handler, Qexpand_file_name, result, default_directory);
1354
1355 return result;
1356 }
1357
1358 #if 0
1359 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1360 This is the old version of expand-file-name, before it was thoroughly
1361 rewritten for Emacs 10.31. We leave this version here commented-out,
1362 because the code is very complex and likely to have subtle bugs. If
1363 bugs _are_ found, it might be of interest to look at the old code and
1364 see what did it do in the relevant situation.
1365
1366 Don't remove this code: it's true that it will be accessible
1367 from the repository, but a few years from deletion, people will
1368 forget it is there. */
1369
1370 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1371 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1372 "Convert FILENAME to absolute, and canonicalize it.\n\
1373 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1374 \(does not start with slash); if DEFAULT is nil or missing,\n\
1375 the current buffer's value of default-directory is used.\n\
1376 Filenames containing `.' or `..' as components are simplified;\n\
1377 initial `~/' expands to your home directory.\n\
1378 See also the function `substitute-in-file-name'.")
1379 (name, defalt)
1380 Lisp_Object name, defalt;
1381 {
1382 unsigned char *nm;
1383
1384 register unsigned char *newdir, *p, *o;
1385 int tlen;
1386 unsigned char *target;
1387 struct passwd *pw;
1388 int lose;
1389
1390 CHECK_STRING (name);
1391 nm = SDATA (name);
1392
1393 /* If nm is absolute, flush ...// and detect /./ and /../.
1394 If no /./ or /../ we can return right away. */
1395 if (nm[0] == '/')
1396 {
1397 p = nm;
1398 lose = 0;
1399 while (*p)
1400 {
1401 if (p[0] == '/' && p[1] == '/'
1402 )
1403 nm = p + 1;
1404 if (p[0] == '/' && p[1] == '~')
1405 nm = p + 1, lose = 1;
1406 if (p[0] == '/' && p[1] == '.'
1407 && (p[2] == '/' || p[2] == 0
1408 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1409 lose = 1;
1410 p++;
1411 }
1412 if (!lose)
1413 {
1414 if (nm == SDATA (name))
1415 return name;
1416 return build_string (nm);
1417 }
1418 }
1419
1420 /* Now determine directory to start with and put it in NEWDIR */
1421
1422 newdir = 0;
1423
1424 if (nm[0] == '~') /* prefix ~ */
1425 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1426 {
1427 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1428 newdir = (unsigned char *) "";
1429 nm++;
1430 }
1431 else /* ~user/filename */
1432 {
1433 /* Get past ~ to user */
1434 unsigned char *user = nm + 1;
1435 /* Find end of name. */
1436 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1437 int len = ptr ? ptr - user : strlen (user);
1438 /* Copy the user name into temp storage. */
1439 o = (unsigned char *) alloca (len + 1);
1440 memcpy (o, user, len);
1441 o[len] = 0;
1442
1443 /* Look up the user name. */
1444 BLOCK_INPUT;
1445 pw = (struct passwd *) getpwnam (o + 1);
1446 UNBLOCK_INPUT;
1447 if (!pw)
1448 error ("\"%s\" isn't a registered user", o + 1);
1449
1450 newdir = (unsigned char *) pw->pw_dir;
1451
1452 /* Discard the user name from NM. */
1453 nm += len;
1454 }
1455
1456 if (nm[0] != '/' && !newdir)
1457 {
1458 if (NILP (defalt))
1459 defalt = current_buffer->directory;
1460 CHECK_STRING (defalt);
1461 newdir = SDATA (defalt);
1462 }
1463
1464 /* Now concatenate the directory and name to new space in the stack frame */
1465
1466 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1467 target = (unsigned char *) alloca (tlen);
1468 *target = 0;
1469
1470 if (newdir)
1471 {
1472 if (nm[0] == 0 || nm[0] == '/')
1473 strcpy (target, newdir);
1474 else
1475 file_name_as_directory (target, newdir);
1476 }
1477
1478 strcat (target, nm);
1479
1480 /* Now canonicalize by removing /. and /foo/.. if they appear */
1481
1482 p = target;
1483 o = target;
1484
1485 while (*p)
1486 {
1487 if (*p != '/')
1488 {
1489 *o++ = *p++;
1490 }
1491 else if (!strncmp (p, "//", 2)
1492 )
1493 {
1494 o = target;
1495 p++;
1496 }
1497 else if (p[0] == '/' && p[1] == '.'
1498 && (p[2] == '/' || p[2] == 0))
1499 p += 2;
1500 else if (!strncmp (p, "/..", 3)
1501 /* `/../' is the "superroot" on certain file systems. */
1502 && o != target
1503 && (p[3] == '/' || p[3] == 0))
1504 {
1505 while (o != target && *--o != '/')
1506 ;
1507 if (o == target && *o == '/')
1508 ++o;
1509 p += 3;
1510 }
1511 else
1512 {
1513 *o++ = *p++;
1514 }
1515 }
1516
1517 return make_string (target, o - target);
1518 }
1519 #endif
1520 \f
1521 /* If /~ or // appears, discard everything through first slash. */
1522 static int
1523 file_name_absolute_p (const unsigned char *filename)
1524 {
1525 return
1526 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1527 #ifdef DOS_NT
1528 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1529 && IS_DIRECTORY_SEP (filename[2]))
1530 #endif
1531 );
1532 }
1533
1534 static unsigned char *
1535 search_embedded_absfilename (unsigned char *nm, unsigned char *endp)
1536 {
1537 unsigned char *p, *s;
1538
1539 for (p = nm + 1; p < endp; p++)
1540 {
1541 if ((0
1542 || IS_DIRECTORY_SEP (p[-1]))
1543 && file_name_absolute_p (p)
1544 #if defined (WINDOWSNT) || defined(CYGWIN)
1545 /* // at start of file name is meaningful in Apollo,
1546 WindowsNT and Cygwin systems. */
1547 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1548 #endif /* not (WINDOWSNT || CYGWIN) */
1549 )
1550 {
1551 for (s = p; *s && (!IS_DIRECTORY_SEP (*s)); s++);
1552 if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
1553 {
1554 unsigned char *o = alloca (s - p + 1);
1555 struct passwd *pw;
1556 memcpy (o, p, s - p);
1557 o [s - p] = 0;
1558
1559 /* If we have ~user and `user' exists, discard
1560 everything up to ~. But if `user' does not exist, leave
1561 ~user alone, it might be a literal file name. */
1562 BLOCK_INPUT;
1563 pw = getpwnam (o + 1);
1564 UNBLOCK_INPUT;
1565 if (pw)
1566 return p;
1567 }
1568 else
1569 return p;
1570 }
1571 }
1572 return NULL;
1573 }
1574
1575 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1576 Ssubstitute_in_file_name, 1, 1, 0,
1577 doc: /* Substitute environment variables referred to in FILENAME.
1578 `$FOO' where FOO is an environment variable name means to substitute
1579 the value of that variable. The variable name should be terminated
1580 with a character not a letter, digit or underscore; otherwise, enclose
1581 the entire variable name in braces.
1582
1583 If `/~' appears, all of FILENAME through that `/' is discarded.
1584 If `//' appears, everything up to and including the first of
1585 those `/' is discarded. */)
1586 (Lisp_Object filename)
1587 {
1588 unsigned char *nm;
1589
1590 register unsigned char *s, *p, *o, *x, *endp;
1591 unsigned char *target = NULL;
1592 int total = 0;
1593 int substituted = 0;
1594 int multibyte;
1595 unsigned char *xnm;
1596 Lisp_Object handler;
1597
1598 CHECK_STRING (filename);
1599
1600 multibyte = STRING_MULTIBYTE (filename);
1601
1602 /* If the file name has special constructs in it,
1603 call the corresponding file handler. */
1604 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1605 if (!NILP (handler))
1606 return call2 (handler, Qsubstitute_in_file_name, filename);
1607
1608 /* Always work on a copy of the string, in case GC happens during
1609 decode of environment variables, causing the original Lisp_String
1610 data to be relocated. */
1611 nm = (unsigned char *) alloca (SBYTES (filename) + 1);
1612 memcpy (nm, SDATA (filename), SBYTES (filename) + 1);
1613
1614 #ifdef DOS_NT
1615 dostounix_filename (nm);
1616 substituted = (strcmp (nm, SDATA (filename)) != 0);
1617 #endif
1618 endp = nm + SBYTES (filename);
1619
1620 /* If /~ or // appears, discard everything through first slash. */
1621 p = search_embedded_absfilename (nm, endp);
1622 if (p)
1623 /* Start over with the new string, so we check the file-name-handler
1624 again. Important with filenames like "/home/foo//:/hello///there"
1625 which whould substitute to "/:/hello///there" rather than "/there". */
1626 return Fsubstitute_in_file_name
1627 (make_specified_string (p, -1, endp - p, multibyte));
1628
1629 /* See if any variables are substituted into the string
1630 and find the total length of their values in `total' */
1631
1632 for (p = nm; p != endp;)
1633 if (*p != '$')
1634 p++;
1635 else
1636 {
1637 p++;
1638 if (p == endp)
1639 goto badsubst;
1640 else if (*p == '$')
1641 {
1642 /* "$$" means a single "$" */
1643 p++;
1644 total -= 1;
1645 substituted = 1;
1646 continue;
1647 }
1648 else if (*p == '{')
1649 {
1650 o = ++p;
1651 while (p != endp && *p != '}') p++;
1652 if (*p != '}') goto missingclose;
1653 s = p;
1654 }
1655 else
1656 {
1657 o = p;
1658 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1659 s = p;
1660 }
1661
1662 /* Copy out the variable name */
1663 target = (unsigned char *) alloca (s - o + 1);
1664 strncpy (target, o, s - o);
1665 target[s - o] = 0;
1666 #ifdef DOS_NT
1667 strupr (target); /* $home == $HOME etc. */
1668 #endif /* DOS_NT */
1669
1670 /* Get variable value */
1671 o = (unsigned char *) egetenv (target);
1672 if (o)
1673 {
1674 /* Don't try to guess a maximum length - UTF8 can use up to
1675 four bytes per character. This code is unlikely to run
1676 in a situation that requires performance, so decoding the
1677 env variables twice should be acceptable. Note that
1678 decoding may cause a garbage collect. */
1679 Lisp_Object orig, decoded;
1680 orig = make_unibyte_string (o, strlen (o));
1681 decoded = DECODE_FILE (orig);
1682 total += SBYTES (decoded);
1683 substituted = 1;
1684 }
1685 else if (*p == '}')
1686 goto badvar;
1687 }
1688
1689 if (!substituted)
1690 return filename;
1691
1692 /* If substitution required, recopy the string and do it */
1693 /* Make space in stack frame for the new copy */
1694 xnm = (unsigned char *) alloca (SBYTES (filename) + total + 1);
1695 x = xnm;
1696
1697 /* Copy the rest of the name through, replacing $ constructs with values */
1698 for (p = nm; *p;)
1699 if (*p != '$')
1700 *x++ = *p++;
1701 else
1702 {
1703 p++;
1704 if (p == endp)
1705 goto badsubst;
1706 else if (*p == '$')
1707 {
1708 *x++ = *p++;
1709 continue;
1710 }
1711 else if (*p == '{')
1712 {
1713 o = ++p;
1714 while (p != endp && *p != '}') p++;
1715 if (*p != '}') goto missingclose;
1716 s = p++;
1717 }
1718 else
1719 {
1720 o = p;
1721 while (p != endp && (isalnum (*p) || *p == '_')) p++;
1722 s = p;
1723 }
1724
1725 /* Copy out the variable name */
1726 target = (unsigned char *) alloca (s - o + 1);
1727 strncpy (target, o, s - o);
1728 target[s - o] = 0;
1729 #ifdef DOS_NT
1730 strupr (target); /* $home == $HOME etc. */
1731 #endif /* DOS_NT */
1732
1733 /* Get variable value */
1734 o = (unsigned char *) egetenv (target);
1735 if (!o)
1736 {
1737 *x++ = '$';
1738 strcpy (x, target); x+= strlen (target);
1739 }
1740 else
1741 {
1742 Lisp_Object orig, decoded;
1743 int orig_length, decoded_length;
1744 orig_length = strlen (o);
1745 orig = make_unibyte_string (o, orig_length);
1746 decoded = DECODE_FILE (orig);
1747 decoded_length = SBYTES (decoded);
1748 strncpy (x, SDATA (decoded), decoded_length);
1749 x += decoded_length;
1750
1751 /* If environment variable needed decoding, return value
1752 needs to be multibyte. */
1753 if (decoded_length != orig_length
1754 || strncmp (SDATA (decoded), o, orig_length))
1755 multibyte = 1;
1756 }
1757 }
1758
1759 *x = 0;
1760
1761 /* If /~ or // appears, discard everything through first slash. */
1762 while ((p = search_embedded_absfilename (xnm, x)))
1763 /* This time we do not start over because we've already expanded envvars
1764 and replaced $$ with $. Maybe we should start over as well, but we'd
1765 need to quote some $ to $$ first. */
1766 xnm = p;
1767
1768 return make_specified_string (xnm, -1, x - xnm, multibyte);
1769
1770 badsubst:
1771 error ("Bad format environment-variable substitution");
1772 missingclose:
1773 error ("Missing \"}\" in environment-variable substitution");
1774 badvar:
1775 error ("Substituting nonexistent environment variable \"%s\"", target);
1776
1777 /* NOTREACHED */
1778 return Qnil;
1779 }
1780 \f
1781 /* A slightly faster and more convenient way to get
1782 (directory-file-name (expand-file-name FOO)). */
1783
1784 Lisp_Object
1785 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1786 {
1787 register Lisp_Object absname;
1788
1789 absname = Fexpand_file_name (filename, defdir);
1790
1791 /* Remove final slash, if any (unless this is the root dir).
1792 stat behaves differently depending! */
1793 if (SCHARS (absname) > 1
1794 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1795 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
1796 /* We cannot take shortcuts; they might be wrong for magic file names. */
1797 absname = Fdirectory_file_name (absname);
1798 return absname;
1799 }
1800 \f
1801 /* Signal an error if the file ABSNAME already exists.
1802 If INTERACTIVE is nonzero, ask the user whether to proceed,
1803 and bypass the error if the user says to go ahead.
1804 QUERYSTRING is a name for the action that is being considered
1805 to alter the file.
1806
1807 *STATPTR is used to store the stat information if the file exists.
1808 If the file does not exist, STATPTR->st_mode is set to 0.
1809 If STATPTR is null, we don't store into it.
1810
1811 If QUICK is nonzero, we ask for y or n, not yes or no. */
1812
1813 void
1814 barf_or_query_if_file_exists (Lisp_Object absname, const unsigned char *querystring, int interactive, struct stat *statptr, int quick)
1815 {
1816 register Lisp_Object tem, encoded_filename;
1817 struct stat statbuf;
1818 struct gcpro gcpro1;
1819
1820 encoded_filename = ENCODE_FILE (absname);
1821
1822 /* stat is a good way to tell whether the file exists,
1823 regardless of what access permissions it has. */
1824 if (lstat (SDATA (encoded_filename), &statbuf) >= 0)
1825 {
1826 if (! interactive)
1827 xsignal2 (Qfile_already_exists,
1828 build_string ("File already exists"), absname);
1829 GCPRO1 (absname);
1830 tem = format2 ("File %s already exists; %s anyway? ",
1831 absname, build_string (querystring));
1832 if (quick)
1833 tem = call1 (intern ("y-or-n-p"), tem);
1834 else
1835 tem = do_yes_or_no_p (tem);
1836 UNGCPRO;
1837 if (NILP (tem))
1838 xsignal2 (Qfile_already_exists,
1839 build_string ("File already exists"), absname);
1840 if (statptr)
1841 *statptr = statbuf;
1842 }
1843 else
1844 {
1845 if (statptr)
1846 statptr->st_mode = 0;
1847 }
1848 return;
1849 }
1850
1851 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1852 "fCopy file: \nGCopy %s to file: \np\nP",
1853 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1854 If NEWNAME names a directory, copy FILE there.
1855
1856 This function always sets the file modes of the output file to match
1857 the input file.
1858
1859 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1860 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1861 signal a `file-already-exists' error without overwriting. If
1862 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1863 about overwriting; this is what happens in interactive use with M-x.
1864 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1865 existing file.
1866
1867 Fourth arg KEEP-TIME non-nil means give the output file the same
1868 last-modified time as the old one. (This works on only some systems.)
1869
1870 A prefix arg makes KEEP-TIME non-nil.
1871
1872 If PRESERVE-UID-GID is non-nil, we try to transfer the
1873 uid and gid of FILE to NEWNAME.
1874
1875 If PRESERVE-SELINUX-CONTEXT is non-nil and SELinux is enabled
1876 on the system, we copy the SELinux context of FILE to NEWNAME. */)
1877 (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)
1878 {
1879 int ifd, ofd, n;
1880 char buf[16 * 1024];
1881 struct stat st, out_st;
1882 Lisp_Object handler;
1883 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1884 int count = SPECPDL_INDEX ();
1885 int input_file_statable_p;
1886 Lisp_Object encoded_file, encoded_newname;
1887 #if HAVE_LIBSELINUX
1888 security_context_t con;
1889 int fail, conlength = 0;
1890 #endif
1891
1892 encoded_file = encoded_newname = Qnil;
1893 GCPRO4 (file, newname, encoded_file, encoded_newname);
1894 CHECK_STRING (file);
1895 CHECK_STRING (newname);
1896
1897 if (!NILP (Ffile_directory_p (newname)))
1898 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1899 else
1900 newname = Fexpand_file_name (newname, Qnil);
1901
1902 file = Fexpand_file_name (file, Qnil);
1903
1904 /* If the input file name has special constructs in it,
1905 call the corresponding file handler. */
1906 handler = Ffind_file_name_handler (file, Qcopy_file);
1907 /* Likewise for output file name. */
1908 if (NILP (handler))
1909 handler = Ffind_file_name_handler (newname, Qcopy_file);
1910 if (!NILP (handler))
1911 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1912 ok_if_already_exists, keep_time, preserve_uid_gid,
1913 preserve_selinux_context));
1914
1915 encoded_file = ENCODE_FILE (file);
1916 encoded_newname = ENCODE_FILE (newname);
1917
1918 if (NILP (ok_if_already_exists)
1919 || INTEGERP (ok_if_already_exists))
1920 barf_or_query_if_file_exists (newname, "copy to it",
1921 INTEGERP (ok_if_already_exists), &out_st, 0);
1922 else if (stat (SDATA (encoded_newname), &out_st) < 0)
1923 out_st.st_mode = 0;
1924
1925 #ifdef WINDOWSNT
1926 if (!CopyFile (SDATA (encoded_file),
1927 SDATA (encoded_newname),
1928 FALSE))
1929 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
1930 /* CopyFile retains the timestamp by default. */
1931 else if (NILP (keep_time))
1932 {
1933 EMACS_TIME now;
1934 DWORD attributes;
1935 char * filename;
1936
1937 EMACS_GET_TIME (now);
1938 filename = SDATA (encoded_newname);
1939
1940 /* Ensure file is writable while its modified time is set. */
1941 attributes = GetFileAttributes (filename);
1942 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
1943 if (set_file_times (filename, now, now))
1944 {
1945 /* Restore original attributes. */
1946 SetFileAttributes (filename, attributes);
1947 xsignal2 (Qfile_date_error,
1948 build_string ("Cannot set file date"), newname);
1949 }
1950 /* Restore original attributes. */
1951 SetFileAttributes (filename, attributes);
1952 }
1953 #else /* not WINDOWSNT */
1954 immediate_quit = 1;
1955 ifd = emacs_open (SDATA (encoded_file), O_RDONLY, 0);
1956 immediate_quit = 0;
1957
1958 if (ifd < 0)
1959 report_file_error ("Opening input file", Fcons (file, Qnil));
1960
1961 record_unwind_protect (close_file_unwind, make_number (ifd));
1962
1963 /* We can only copy regular files and symbolic links. Other files are not
1964 copyable by us. */
1965 input_file_statable_p = (fstat (ifd, &st) >= 0);
1966
1967 #if HAVE_LIBSELINUX
1968 if (!NILP (preserve_selinux_context) && is_selinux_enabled ())
1969 {
1970 conlength = fgetfilecon (ifd, &con);
1971 if (conlength == -1)
1972 report_file_error ("Doing fgetfilecon", Fcons (file, Qnil));
1973 }
1974 #endif
1975
1976 if (out_st.st_mode != 0
1977 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1978 {
1979 errno = 0;
1980 report_file_error ("Input and output files are the same",
1981 Fcons (file, Fcons (newname, Qnil)));
1982 }
1983
1984 #if defined (S_ISREG) && defined (S_ISLNK)
1985 if (input_file_statable_p)
1986 {
1987 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
1988 {
1989 #if defined (EISDIR)
1990 /* Get a better looking error message. */
1991 errno = EISDIR;
1992 #endif /* EISDIR */
1993 report_file_error ("Non-regular file", Fcons (file, Qnil));
1994 }
1995 }
1996 #endif /* S_ISREG && S_ISLNK */
1997
1998 #ifdef MSDOS
1999 /* System's default file type was set to binary by _fmode in emacs.c. */
2000 ofd = emacs_open (SDATA (encoded_newname),
2001 O_WRONLY | O_TRUNC | O_CREAT
2002 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2003 S_IREAD | S_IWRITE);
2004 #else /* not MSDOS */
2005 ofd = emacs_open (SDATA (encoded_newname),
2006 O_WRONLY | O_TRUNC | O_CREAT
2007 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2008 0666);
2009 #endif /* not MSDOS */
2010 if (ofd < 0)
2011 report_file_error ("Opening output file", Fcons (newname, Qnil));
2012
2013 record_unwind_protect (close_file_unwind, make_number (ofd));
2014
2015 immediate_quit = 1;
2016 QUIT;
2017 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2018 if (emacs_write (ofd, buf, n) != n)
2019 report_file_error ("I/O error", Fcons (newname, Qnil));
2020 immediate_quit = 0;
2021
2022 #ifndef MSDOS
2023 /* Preserve the original file modes, and if requested, also its
2024 owner and group. */
2025 if (input_file_statable_p)
2026 {
2027 if (! NILP (preserve_uid_gid))
2028 fchown (ofd, st.st_uid, st.st_gid);
2029 fchmod (ofd, st.st_mode & 07777);
2030 }
2031 #endif /* not MSDOS */
2032
2033 #if HAVE_LIBSELINUX
2034 if (conlength > 0)
2035 {
2036 /* Set the modified context back to the file. */
2037 fail = fsetfilecon (ofd, con);
2038 if (fail)
2039 report_file_error ("Doing fsetfilecon", Fcons (newname, Qnil));
2040
2041 freecon (con);
2042 }
2043 #endif
2044
2045 /* Closing the output clobbers the file times on some systems. */
2046 if (emacs_close (ofd) < 0)
2047 report_file_error ("I/O error", Fcons (newname, Qnil));
2048
2049 if (input_file_statable_p)
2050 {
2051 if (!NILP (keep_time))
2052 {
2053 EMACS_TIME atime, mtime;
2054 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2055 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2056 if (set_file_times (SDATA (encoded_newname),
2057 atime, mtime))
2058 xsignal2 (Qfile_date_error,
2059 build_string ("Cannot set file date"), newname);
2060 }
2061 }
2062
2063 emacs_close (ifd);
2064
2065 #ifdef MSDOS
2066 if (input_file_statable_p)
2067 {
2068 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2069 and if it can't, it tells so. Otherwise, under MSDOS we usually
2070 get only the READ bit, which will make the copied file read-only,
2071 so it's better not to chmod at all. */
2072 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2073 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2074 }
2075 #endif /* MSDOS */
2076 #endif /* not WINDOWSNT */
2077
2078 /* Discard the unwind protects. */
2079 specpdl_ptr = specpdl + count;
2080
2081 UNGCPRO;
2082 return Qnil;
2083 }
2084 \f
2085 DEFUN ("make-directory-internal", Fmake_directory_internal,
2086 Smake_directory_internal, 1, 1, 0,
2087 doc: /* Create a new directory named DIRECTORY. */)
2088 (Lisp_Object directory)
2089 {
2090 const unsigned char *dir;
2091 Lisp_Object handler;
2092 Lisp_Object encoded_dir;
2093
2094 CHECK_STRING (directory);
2095 directory = Fexpand_file_name (directory, Qnil);
2096
2097 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2098 if (!NILP (handler))
2099 return call2 (handler, Qmake_directory_internal, directory);
2100
2101 encoded_dir = ENCODE_FILE (directory);
2102
2103 dir = SDATA (encoded_dir);
2104
2105 #ifdef WINDOWSNT
2106 if (mkdir (dir) != 0)
2107 #else
2108 if (mkdir (dir, 0777) != 0)
2109 #endif
2110 report_file_error ("Creating directory", list1 (directory));
2111
2112 return Qnil;
2113 }
2114
2115 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2116 Sdelete_directory_internal, 1, 1, 0,
2117 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2118 (Lisp_Object directory)
2119 {
2120 const unsigned char *dir;
2121 Lisp_Object handler;
2122 Lisp_Object encoded_dir;
2123
2124 CHECK_STRING (directory);
2125 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2126 encoded_dir = ENCODE_FILE (directory);
2127 dir = SDATA (encoded_dir);
2128
2129 if (rmdir (dir) != 0)
2130 report_file_error ("Removing directory", list1 (directory));
2131
2132 return Qnil;
2133 }
2134
2135 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2136 "(list (read-file-name \
2137 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2138 \"Move file to trash: \" \"Delete file: \") \
2139 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2140 (null current-prefix-arg))",
2141 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2142 If file has multiple names, it continues to exist with the other names.
2143 TRASH non-nil means to trash the file instead of deleting, provided
2144 `delete-by-moving-to-trash' is non-nil.
2145
2146 When called interactively, TRASH is t if no prefix argument is given.
2147 With a prefix argument, TRASH is nil. */)
2148 (Lisp_Object filename, Lisp_Object trash)
2149 {
2150 Lisp_Object handler;
2151 Lisp_Object encoded_file;
2152 struct gcpro gcpro1;
2153
2154 GCPRO1 (filename);
2155 if (!NILP (Ffile_directory_p (filename))
2156 && NILP (Ffile_symlink_p (filename)))
2157 xsignal2 (Qfile_error,
2158 build_string ("Removing old name: is a directory"),
2159 filename);
2160 UNGCPRO;
2161 filename = Fexpand_file_name (filename, Qnil);
2162
2163 handler = Ffind_file_name_handler (filename, Qdelete_file);
2164 if (!NILP (handler))
2165 return call3 (handler, Qdelete_file, filename, trash);
2166
2167 if (delete_by_moving_to_trash && !NILP (trash))
2168 return call1 (Qmove_file_to_trash, filename);
2169
2170 encoded_file = ENCODE_FILE (filename);
2171
2172 if (0 > unlink (SDATA (encoded_file)))
2173 report_file_error ("Removing old name", list1 (filename));
2174 return Qnil;
2175 }
2176
2177 static Lisp_Object
2178 internal_delete_file_1 (Lisp_Object ignore)
2179 {
2180 return Qt;
2181 }
2182
2183 /* Delete file FILENAME, returning 1 if successful and 0 if failed.
2184 This ignores `delete-by-moving-to-trash'. */
2185
2186 int
2187 internal_delete_file (Lisp_Object filename)
2188 {
2189 Lisp_Object tem;
2190
2191 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2192 Qt, internal_delete_file_1);
2193 return NILP (tem);
2194 }
2195 \f
2196 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2197 "fRename file: \nGRename %s to file: \np",
2198 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2199 If file has names other than FILE, it continues to have those names.
2200 Signals a `file-already-exists' error if a file NEWNAME already exists
2201 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2202 A number as third arg means request confirmation if NEWNAME already exists.
2203 This is what happens in interactive use with M-x. */)
2204 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2205 {
2206 Lisp_Object handler;
2207 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2208 Lisp_Object encoded_file, encoded_newname, symlink_target;
2209
2210 symlink_target = encoded_file = encoded_newname = Qnil;
2211 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2212 CHECK_STRING (file);
2213 CHECK_STRING (newname);
2214 file = Fexpand_file_name (file, Qnil);
2215
2216 if ((!NILP (Ffile_directory_p (newname)))
2217 #ifdef DOS_NT
2218 /* If the file names are identical but for the case,
2219 don't attempt to move directory to itself. */
2220 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2221 #endif
2222 )
2223 {
2224 Lisp_Object fname = NILP (Ffile_directory_p (file))
2225 ? file : Fdirectory_file_name (file);
2226 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2227 }
2228 else
2229 newname = Fexpand_file_name (newname, Qnil);
2230
2231 /* If the file name has special constructs in it,
2232 call the corresponding file handler. */
2233 handler = Ffind_file_name_handler (file, Qrename_file);
2234 if (NILP (handler))
2235 handler = Ffind_file_name_handler (newname, Qrename_file);
2236 if (!NILP (handler))
2237 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2238 file, newname, ok_if_already_exists));
2239
2240 encoded_file = ENCODE_FILE (file);
2241 encoded_newname = ENCODE_FILE (newname);
2242
2243 #ifdef DOS_NT
2244 /* If the file names are identical but for the case, don't ask for
2245 confirmation: they simply want to change the letter-case of the
2246 file name. */
2247 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2248 #endif
2249 if (NILP (ok_if_already_exists)
2250 || INTEGERP (ok_if_already_exists))
2251 barf_or_query_if_file_exists (newname, "rename to it",
2252 INTEGERP (ok_if_already_exists), 0, 0);
2253 if (0 > rename (SDATA (encoded_file), SDATA (encoded_newname)))
2254 {
2255 if (errno == EXDEV)
2256 {
2257 int count;
2258 #ifdef S_IFLNK
2259 symlink_target = Ffile_symlink_p (file);
2260 if (! NILP (symlink_target))
2261 Fmake_symbolic_link (symlink_target, newname,
2262 NILP (ok_if_already_exists) ? Qnil : Qt);
2263 else
2264 #endif
2265 if (!NILP (Ffile_directory_p (file)))
2266 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2267 else
2268 /* We have already prompted if it was an integer, so don't
2269 have copy-file prompt again. */
2270 Fcopy_file (file, newname,
2271 NILP (ok_if_already_exists) ? Qnil : Qt,
2272 Qt, Qt, Qt);
2273
2274 count = SPECPDL_INDEX ();
2275 specbind (Qdelete_by_moving_to_trash, Qnil);
2276
2277 if (!NILP (Ffile_directory_p (file))
2278 #ifdef S_IFLNK
2279 && NILP (symlink_target)
2280 #endif
2281 )
2282 call2 (Qdelete_directory, file, Qt);
2283 else
2284 Fdelete_file (file, Qnil);
2285 unbind_to (count, Qnil);
2286 }
2287 else
2288 report_file_error ("Renaming", list2 (file, newname));
2289 }
2290 UNGCPRO;
2291 return Qnil;
2292 }
2293
2294 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2295 "fAdd name to file: \nGName to add to %s: \np",
2296 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2297 Signals a `file-already-exists' error if a file NEWNAME already exists
2298 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2299 A number as third arg means request confirmation if NEWNAME already exists.
2300 This is what happens in interactive use with M-x. */)
2301 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2302 {
2303 Lisp_Object handler;
2304 Lisp_Object encoded_file, encoded_newname;
2305 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2306
2307 GCPRO4 (file, newname, encoded_file, encoded_newname);
2308 encoded_file = encoded_newname = Qnil;
2309 CHECK_STRING (file);
2310 CHECK_STRING (newname);
2311 file = Fexpand_file_name (file, Qnil);
2312
2313 if (!NILP (Ffile_directory_p (newname)))
2314 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2315 else
2316 newname = Fexpand_file_name (newname, Qnil);
2317
2318 /* If the file name has special constructs in it,
2319 call the corresponding file handler. */
2320 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2321 if (!NILP (handler))
2322 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2323 newname, ok_if_already_exists));
2324
2325 /* If the new name has special constructs in it,
2326 call the corresponding file handler. */
2327 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2328 if (!NILP (handler))
2329 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2330 newname, ok_if_already_exists));
2331
2332 encoded_file = ENCODE_FILE (file);
2333 encoded_newname = ENCODE_FILE (newname);
2334
2335 if (NILP (ok_if_already_exists)
2336 || INTEGERP (ok_if_already_exists))
2337 barf_or_query_if_file_exists (newname, "make it a new name",
2338 INTEGERP (ok_if_already_exists), 0, 0);
2339
2340 unlink (SDATA (newname));
2341 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname)))
2342 report_file_error ("Adding new name", list2 (file, newname));
2343
2344 UNGCPRO;
2345 return Qnil;
2346 }
2347
2348 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2349 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2350 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2351 Both args must be strings.
2352 Signals a `file-already-exists' error if a file LINKNAME already exists
2353 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2354 A number as third arg means request confirmation if LINKNAME already exists.
2355 This happens for interactive use with M-x. */)
2356 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2357 {
2358 Lisp_Object handler;
2359 Lisp_Object encoded_filename, encoded_linkname;
2360 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2361
2362 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2363 encoded_filename = encoded_linkname = Qnil;
2364 CHECK_STRING (filename);
2365 CHECK_STRING (linkname);
2366 /* If the link target has a ~, we must expand it to get
2367 a truly valid file name. Otherwise, do not expand;
2368 we want to permit links to relative file names. */
2369 if (SREF (filename, 0) == '~')
2370 filename = Fexpand_file_name (filename, Qnil);
2371
2372 if (!NILP (Ffile_directory_p (linkname)))
2373 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2374 else
2375 linkname = Fexpand_file_name (linkname, Qnil);
2376
2377 /* If the file name has special constructs in it,
2378 call the corresponding file handler. */
2379 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2380 if (!NILP (handler))
2381 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2382 linkname, ok_if_already_exists));
2383
2384 /* If the new link name has special constructs in it,
2385 call the corresponding file handler. */
2386 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2387 if (!NILP (handler))
2388 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2389 linkname, ok_if_already_exists));
2390
2391 #ifdef S_IFLNK
2392 encoded_filename = ENCODE_FILE (filename);
2393 encoded_linkname = ENCODE_FILE (linkname);
2394
2395 if (NILP (ok_if_already_exists)
2396 || INTEGERP (ok_if_already_exists))
2397 barf_or_query_if_file_exists (linkname, "make it a link",
2398 INTEGERP (ok_if_already_exists), 0, 0);
2399 if (0 > symlink (SDATA (encoded_filename),
2400 SDATA (encoded_linkname)))
2401 {
2402 /* If we didn't complain already, silently delete existing file. */
2403 if (errno == EEXIST)
2404 {
2405 unlink (SDATA (encoded_linkname));
2406 if (0 <= symlink (SDATA (encoded_filename),
2407 SDATA (encoded_linkname)))
2408 {
2409 UNGCPRO;
2410 return Qnil;
2411 }
2412 }
2413
2414 report_file_error ("Making symbolic link", list2 (filename, linkname));
2415 }
2416 UNGCPRO;
2417 return Qnil;
2418
2419 #else
2420 UNGCPRO;
2421 xsignal1 (Qfile_error, build_string ("Symbolic links are not supported"));
2422
2423 #endif /* S_IFLNK */
2424 }
2425
2426 \f
2427 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2428 1, 1, 0,
2429 doc: /* Return t if file FILENAME specifies an absolute file name.
2430 On Unix, this is a name starting with a `/' or a `~'. */)
2431 (Lisp_Object filename)
2432 {
2433 CHECK_STRING (filename);
2434 return file_name_absolute_p (SDATA (filename)) ? Qt : Qnil;
2435 }
2436 \f
2437 /* Return nonzero if file FILENAME exists and can be executed. */
2438
2439 static int
2440 check_executable (char *filename)
2441 {
2442 #ifdef DOS_NT
2443 int len = strlen (filename);
2444 char *suffix;
2445 struct stat st;
2446 if (stat (filename, &st) < 0)
2447 return 0;
2448 return ((st.st_mode & S_IEXEC) != 0);
2449 #else /* not DOS_NT */
2450 #ifdef HAVE_EUIDACCESS
2451 return (euidaccess (filename, 1) >= 0);
2452 #else
2453 /* Access isn't quite right because it uses the real uid
2454 and we really want to test with the effective uid.
2455 But Unix doesn't give us a right way to do it. */
2456 return (access (filename, 1) >= 0);
2457 #endif
2458 #endif /* not DOS_NT */
2459 }
2460
2461 /* Return nonzero if file FILENAME exists and can be written. */
2462
2463 static int
2464 check_writable (const char *filename)
2465 {
2466 #ifdef MSDOS
2467 struct stat st;
2468 if (stat (filename, &st) < 0)
2469 return 0;
2470 return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
2471 #else /* not MSDOS */
2472 #ifdef HAVE_EUIDACCESS
2473 return (euidaccess (filename, 2) >= 0);
2474 #else
2475 /* Access isn't quite right because it uses the real uid
2476 and we really want to test with the effective uid.
2477 But Unix doesn't give us a right way to do it.
2478 Opening with O_WRONLY could work for an ordinary file,
2479 but would lose for directories. */
2480 return (access (filename, 2) >= 0);
2481 #endif
2482 #endif /* not MSDOS */
2483 }
2484
2485 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2486 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2487 See also `file-readable-p' and `file-attributes'.
2488 This returns nil for a symlink to a nonexistent file.
2489 Use `file-symlink-p' to test for such links. */)
2490 (Lisp_Object filename)
2491 {
2492 Lisp_Object absname;
2493 Lisp_Object handler;
2494 struct stat statbuf;
2495
2496 CHECK_STRING (filename);
2497 absname = Fexpand_file_name (filename, Qnil);
2498
2499 /* If the file name has special constructs in it,
2500 call the corresponding file handler. */
2501 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2502 if (!NILP (handler))
2503 return call2 (handler, Qfile_exists_p, absname);
2504
2505 absname = ENCODE_FILE (absname);
2506
2507 return (stat (SDATA (absname), &statbuf) >= 0) ? Qt : Qnil;
2508 }
2509
2510 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2511 doc: /* Return t if FILENAME can be executed by you.
2512 For a directory, this means you can access files in that directory. */)
2513 (Lisp_Object filename)
2514 {
2515 Lisp_Object absname;
2516 Lisp_Object handler;
2517
2518 CHECK_STRING (filename);
2519 absname = Fexpand_file_name (filename, Qnil);
2520
2521 /* If the file name has special constructs in it,
2522 call the corresponding file handler. */
2523 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2524 if (!NILP (handler))
2525 return call2 (handler, Qfile_executable_p, absname);
2526
2527 absname = ENCODE_FILE (absname);
2528
2529 return (check_executable (SDATA (absname)) ? Qt : Qnil);
2530 }
2531
2532 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2533 doc: /* Return t if file FILENAME exists and you can read it.
2534 See also `file-exists-p' and `file-attributes'. */)
2535 (Lisp_Object filename)
2536 {
2537 Lisp_Object absname;
2538 Lisp_Object handler;
2539 int desc;
2540 int flags;
2541 struct stat statbuf;
2542
2543 CHECK_STRING (filename);
2544 absname = Fexpand_file_name (filename, Qnil);
2545
2546 /* If the file name has special constructs in it,
2547 call the corresponding file handler. */
2548 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2549 if (!NILP (handler))
2550 return call2 (handler, Qfile_readable_p, absname);
2551
2552 absname = ENCODE_FILE (absname);
2553
2554 #if defined(DOS_NT) || defined(macintosh)
2555 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2556 directories. */
2557 if (access (SDATA (absname), 0) == 0)
2558 return Qt;
2559 return Qnil;
2560 #else /* not DOS_NT and not macintosh */
2561 flags = O_RDONLY;
2562 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
2563 /* Opening a fifo without O_NONBLOCK can wait.
2564 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2565 except in the case of a fifo, on a system which handles it. */
2566 desc = stat (SDATA (absname), &statbuf);
2567 if (desc < 0)
2568 return Qnil;
2569 if (S_ISFIFO (statbuf.st_mode))
2570 flags |= O_NONBLOCK;
2571 #endif
2572 desc = emacs_open (SDATA (absname), flags, 0);
2573 if (desc < 0)
2574 return Qnil;
2575 emacs_close (desc);
2576 return Qt;
2577 #endif /* not DOS_NT and not macintosh */
2578 }
2579
2580 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2581 on the RT/PC. */
2582 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2583 doc: /* Return t if file FILENAME can be written or created by you. */)
2584 (Lisp_Object filename)
2585 {
2586 Lisp_Object absname, dir, encoded;
2587 Lisp_Object handler;
2588 struct stat statbuf;
2589
2590 CHECK_STRING (filename);
2591 absname = Fexpand_file_name (filename, Qnil);
2592
2593 /* If the file name has special constructs in it,
2594 call the corresponding file handler. */
2595 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2596 if (!NILP (handler))
2597 return call2 (handler, Qfile_writable_p, absname);
2598
2599 encoded = ENCODE_FILE (absname);
2600 if (stat (SDATA (encoded), &statbuf) >= 0)
2601 return (check_writable (SDATA (encoded))
2602 ? Qt : Qnil);
2603
2604 dir = Ffile_name_directory (absname);
2605 #ifdef MSDOS
2606 if (!NILP (dir))
2607 dir = Fdirectory_file_name (dir);
2608 #endif /* MSDOS */
2609
2610 dir = ENCODE_FILE (dir);
2611 #ifdef WINDOWSNT
2612 /* The read-only attribute of the parent directory doesn't affect
2613 whether a file or directory can be created within it. Some day we
2614 should check ACLs though, which do affect this. */
2615 if (stat (SDATA (dir), &statbuf) < 0)
2616 return Qnil;
2617 return (statbuf.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2618 #else
2619 return (check_writable (!NILP (dir) ? (char *) SDATA (dir) : "")
2620 ? Qt : Qnil);
2621 #endif
2622 }
2623 \f
2624 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2625 doc: /* Access file FILENAME, and get an error if that does not work.
2626 The second argument STRING is used in the error message.
2627 If there is no error, returns nil. */)
2628 (Lisp_Object filename, Lisp_Object string)
2629 {
2630 Lisp_Object handler, encoded_filename, absname;
2631 int fd;
2632
2633 CHECK_STRING (filename);
2634 absname = Fexpand_file_name (filename, Qnil);
2635
2636 CHECK_STRING (string);
2637
2638 /* If the file name has special constructs in it,
2639 call the corresponding file handler. */
2640 handler = Ffind_file_name_handler (absname, Qaccess_file);
2641 if (!NILP (handler))
2642 return call3 (handler, Qaccess_file, absname, string);
2643
2644 encoded_filename = ENCODE_FILE (absname);
2645
2646 fd = emacs_open (SDATA (encoded_filename), O_RDONLY, 0);
2647 if (fd < 0)
2648 report_file_error (SDATA (string), Fcons (filename, Qnil));
2649 emacs_close (fd);
2650
2651 return Qnil;
2652 }
2653 \f
2654 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2655 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2656 The value is the link target, as a string.
2657 Otherwise it returns nil.
2658
2659 This function returns t when given the name of a symlink that
2660 points to a nonexistent file. */)
2661 (Lisp_Object filename)
2662 {
2663 Lisp_Object handler;
2664
2665 CHECK_STRING (filename);
2666 filename = Fexpand_file_name (filename, Qnil);
2667
2668 /* If the file name has special constructs in it,
2669 call the corresponding file handler. */
2670 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2671 if (!NILP (handler))
2672 return call2 (handler, Qfile_symlink_p, filename);
2673
2674 #ifdef S_IFLNK
2675 {
2676 char *buf;
2677 int bufsize;
2678 int valsize;
2679 Lisp_Object val;
2680
2681 filename = ENCODE_FILE (filename);
2682
2683 bufsize = 50;
2684 buf = NULL;
2685 do
2686 {
2687 bufsize *= 2;
2688 buf = (char *) xrealloc (buf, bufsize);
2689 memset (buf, 0, bufsize);
2690
2691 errno = 0;
2692 valsize = readlink (SDATA (filename), buf, bufsize);
2693 if (valsize == -1)
2694 {
2695 #ifdef ERANGE
2696 /* HP-UX reports ERANGE if buffer is too small. */
2697 if (errno == ERANGE)
2698 valsize = bufsize;
2699 else
2700 #endif
2701 {
2702 xfree (buf);
2703 return Qnil;
2704 }
2705 }
2706 }
2707 while (valsize >= bufsize);
2708
2709 val = make_string (buf, valsize);
2710 if (buf[0] == '/' && strchr (buf, ':'))
2711 val = concat2 (build_string ("/:"), val);
2712 xfree (buf);
2713 val = DECODE_FILE (val);
2714 return val;
2715 }
2716 #else /* not S_IFLNK */
2717 return Qnil;
2718 #endif /* not S_IFLNK */
2719 }
2720
2721 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2722 doc: /* Return t if FILENAME names an existing directory.
2723 Symbolic links to directories count as directories.
2724 See `file-symlink-p' to distinguish symlinks. */)
2725 (Lisp_Object filename)
2726 {
2727 register Lisp_Object absname;
2728 struct stat st;
2729 Lisp_Object handler;
2730
2731 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2732
2733 /* If the file name has special constructs in it,
2734 call the corresponding file handler. */
2735 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2736 if (!NILP (handler))
2737 return call2 (handler, Qfile_directory_p, absname);
2738
2739 absname = ENCODE_FILE (absname);
2740
2741 if (stat (SDATA (absname), &st) < 0)
2742 return Qnil;
2743 return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
2744 }
2745
2746 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
2747 doc: /* Return t if file FILENAME names a directory you can open.
2748 For the value to be t, FILENAME must specify the name of a directory as a file,
2749 and the directory must allow you to open files in it. In order to use a
2750 directory as a buffer's current directory, this predicate must return true.
2751 A directory name spec may be given instead; then the value is t
2752 if the directory so specified exists and really is a readable and
2753 searchable directory. */)
2754 (Lisp_Object filename)
2755 {
2756 Lisp_Object handler;
2757 int tem;
2758 struct gcpro gcpro1;
2759
2760 /* If the file name has special constructs in it,
2761 call the corresponding file handler. */
2762 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
2763 if (!NILP (handler))
2764 return call2 (handler, Qfile_accessible_directory_p, filename);
2765
2766 GCPRO1 (filename);
2767 tem = (NILP (Ffile_directory_p (filename))
2768 || NILP (Ffile_executable_p (filename)));
2769 UNGCPRO;
2770 return tem ? Qnil : Qt;
2771 }
2772
2773 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2774 doc: /* Return t if FILENAME names a regular file.
2775 This is the sort of file that holds an ordinary stream of data bytes.
2776 Symbolic links to regular files count as regular files.
2777 See `file-symlink-p' to distinguish symlinks. */)
2778 (Lisp_Object filename)
2779 {
2780 register Lisp_Object absname;
2781 struct stat st;
2782 Lisp_Object handler;
2783
2784 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2785
2786 /* If the file name has special constructs in it,
2787 call the corresponding file handler. */
2788 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2789 if (!NILP (handler))
2790 return call2 (handler, Qfile_regular_p, absname);
2791
2792 absname = ENCODE_FILE (absname);
2793
2794 #ifdef WINDOWSNT
2795 {
2796 int result;
2797 Lisp_Object tem = Vw32_get_true_file_attributes;
2798
2799 /* Tell stat to use expensive method to get accurate info. */
2800 Vw32_get_true_file_attributes = Qt;
2801 result = stat (SDATA (absname), &st);
2802 Vw32_get_true_file_attributes = tem;
2803
2804 if (result < 0)
2805 return Qnil;
2806 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2807 }
2808 #else
2809 if (stat (SDATA (absname), &st) < 0)
2810 return Qnil;
2811 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
2812 #endif
2813 }
2814 \f
2815 DEFUN ("file-selinux-context", Ffile_selinux_context,
2816 Sfile_selinux_context, 1, 1, 0,
2817 doc: /* Return SELinux context of file named FILENAME,
2818 as a list ("user", "role", "type", "range"). Return (nil, nil, nil, nil)
2819 if file does not exist, is not accessible, or SELinux is disabled */)
2820 (Lisp_Object filename)
2821 {
2822 Lisp_Object absname;
2823 Lisp_Object values[4];
2824 Lisp_Object handler;
2825 #if HAVE_LIBSELINUX
2826 security_context_t con;
2827 int conlength;
2828 context_t context;
2829 #endif
2830
2831 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2832
2833 /* If the file name has special constructs in it,
2834 call the corresponding file handler. */
2835 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2836 if (!NILP (handler))
2837 return call2 (handler, Qfile_selinux_context, absname);
2838
2839 absname = ENCODE_FILE (absname);
2840
2841 values[0] = Qnil;
2842 values[1] = Qnil;
2843 values[2] = Qnil;
2844 values[3] = Qnil;
2845 #if HAVE_LIBSELINUX
2846 if (is_selinux_enabled ())
2847 {
2848 conlength = lgetfilecon (SDATA (absname), &con);
2849 if (conlength > 0)
2850 {
2851 context = context_new (con);
2852 if (context_user_get (context))
2853 values[0] = build_string (context_user_get (context));
2854 if (context_role_get (context))
2855 values[1] = build_string (context_role_get (context));
2856 if (context_type_get (context))
2857 values[2] = build_string (context_type_get (context));
2858 if (context_range_get (context))
2859 values[3] = build_string (context_range_get (context));
2860 context_free (context);
2861 }
2862 if (con)
2863 freecon (con);
2864 }
2865 #endif
2866
2867 return Flist (sizeof(values) / sizeof(values[0]), values);
2868 }
2869 \f
2870 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2871 Sset_file_selinux_context, 2, 2, 0,
2872 doc: /* Set SELinux context of file named FILENAME to CONTEXT
2873 as a list ("user", "role", "type", "range"). Has no effect if SELinux
2874 is disabled. */)
2875 (Lisp_Object filename, Lisp_Object context)
2876 {
2877 Lisp_Object absname, encoded_absname;
2878 Lisp_Object handler;
2879 Lisp_Object user = CAR_SAFE (context);
2880 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2881 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2882 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2883 #if HAVE_LIBSELINUX
2884 security_context_t con;
2885 int fail, conlength;
2886 context_t parsed_con;
2887 #endif
2888
2889 absname = Fexpand_file_name (filename, current_buffer->directory);
2890
2891 /* If the file name has special constructs in it,
2892 call the corresponding file handler. */
2893 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2894 if (!NILP (handler))
2895 return call3 (handler, Qset_file_selinux_context, absname, context);
2896
2897 encoded_absname = ENCODE_FILE (absname);
2898
2899 #if HAVE_LIBSELINUX
2900 if (is_selinux_enabled ())
2901 {
2902 /* Get current file context. */
2903 conlength = lgetfilecon (SDATA (encoded_absname), &con);
2904 if (conlength > 0)
2905 {
2906 parsed_con = context_new (con);
2907 /* Change the parts defined in the parameter.*/
2908 if (STRINGP (user))
2909 {
2910 if (context_user_set (parsed_con, SDATA (user)))
2911 error ("Doing context_user_set");
2912 }
2913 if (STRINGP (role))
2914 {
2915 if (context_role_set (parsed_con, SDATA (role)))
2916 error ("Doing context_role_set");
2917 }
2918 if (STRINGP (type))
2919 {
2920 if (context_type_set (parsed_con, SDATA (type)))
2921 error ("Doing context_type_set");
2922 }
2923 if (STRINGP (range))
2924 {
2925 if (context_range_set (parsed_con, SDATA (range)))
2926 error ("Doing context_range_set");
2927 }
2928
2929 /* Set the modified context back to the file. */
2930 fail = lsetfilecon (SDATA (encoded_absname), context_str (parsed_con));
2931 if (fail)
2932 report_file_error ("Doing lsetfilecon", Fcons (absname, Qnil));
2933
2934 context_free (parsed_con);
2935 }
2936 else
2937 report_file_error("Doing lgetfilecon", Fcons (absname, Qnil));
2938
2939 if (con)
2940 freecon (con);
2941 }
2942 #endif
2943
2944 return Qnil;
2945 }
2946 \f
2947 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
2948 doc: /* Return mode bits of file named FILENAME, as an integer.
2949 Return nil, if file does not exist or is not accessible. */)
2950 (Lisp_Object filename)
2951 {
2952 Lisp_Object absname;
2953 struct stat st;
2954 Lisp_Object handler;
2955
2956 absname = expand_and_dir_to_file (filename, current_buffer->directory);
2957
2958 /* If the file name has special constructs in it,
2959 call the corresponding file handler. */
2960 handler = Ffind_file_name_handler (absname, Qfile_modes);
2961 if (!NILP (handler))
2962 return call2 (handler, Qfile_modes, absname);
2963
2964 absname = ENCODE_FILE (absname);
2965
2966 if (stat (SDATA (absname), &st) < 0)
2967 return Qnil;
2968
2969 return make_number (st.st_mode & 07777);
2970 }
2971
2972 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
2973 "(let ((file (read-file-name \"File: \"))) \
2974 (list file (read-file-modes nil file)))",
2975 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
2976 Only the 12 low bits of MODE are used.
2977
2978 Interactively, mode bits are read by `read-file-modes', which accepts
2979 symbolic notation, like the `chmod' command from GNU Coreutils. */)
2980 (Lisp_Object filename, Lisp_Object mode)
2981 {
2982 Lisp_Object absname, encoded_absname;
2983 Lisp_Object handler;
2984
2985 absname = Fexpand_file_name (filename, current_buffer->directory);
2986 CHECK_NUMBER (mode);
2987
2988 /* If the file name has special constructs in it,
2989 call the corresponding file handler. */
2990 handler = Ffind_file_name_handler (absname, Qset_file_modes);
2991 if (!NILP (handler))
2992 return call3 (handler, Qset_file_modes, absname, mode);
2993
2994 encoded_absname = ENCODE_FILE (absname);
2995
2996 if (chmod (SDATA (encoded_absname), XINT (mode)) < 0)
2997 report_file_error ("Doing chmod", Fcons (absname, Qnil));
2998
2999 return Qnil;
3000 }
3001
3002 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3003 doc: /* Set the file permission bits for newly created files.
3004 The argument MODE should be an integer; only the low 9 bits are used.
3005 This setting is inherited by subprocesses. */)
3006 (Lisp_Object mode)
3007 {
3008 CHECK_NUMBER (mode);
3009
3010 umask ((~ XINT (mode)) & 0777);
3011
3012 return Qnil;
3013 }
3014
3015 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3016 doc: /* Return the default file protection for created files.
3017 The value is an integer. */)
3018 (void)
3019 {
3020 int realmask;
3021 Lisp_Object value;
3022
3023 realmask = umask (0);
3024 umask (realmask);
3025
3026 XSETINT (value, (~ realmask) & 0777);
3027 return value;
3028 }
3029 \f
3030
3031 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3032 doc: /* Set times of file FILENAME to TIME.
3033 Set both access and modification times.
3034 Return t on success, else nil.
3035 Use the current time if TIME is nil. TIME is in the format of
3036 `current-time'. */)
3037 (Lisp_Object filename, Lisp_Object time)
3038 {
3039 Lisp_Object absname, encoded_absname;
3040 Lisp_Object handler;
3041 time_t sec;
3042 int usec;
3043
3044 if (! lisp_time_argument (time, &sec, &usec))
3045 error ("Invalid time specification");
3046
3047 absname = Fexpand_file_name (filename, current_buffer->directory);
3048
3049 /* If the file name has special constructs in it,
3050 call the corresponding file handler. */
3051 handler = Ffind_file_name_handler (absname, Qset_file_times);
3052 if (!NILP (handler))
3053 return call3 (handler, Qset_file_times, absname, time);
3054
3055 encoded_absname = ENCODE_FILE (absname);
3056
3057 {
3058 EMACS_TIME t;
3059
3060 EMACS_SET_SECS (t, sec);
3061 EMACS_SET_USECS (t, usec);
3062
3063 if (set_file_times (SDATA (encoded_absname), t, t))
3064 {
3065 #ifdef DOS_NT
3066 struct stat st;
3067
3068 /* Setting times on a directory always fails. */
3069 if (stat (SDATA (encoded_absname), &st) == 0
3070 && (st.st_mode & S_IFMT) == S_IFDIR)
3071 return Qnil;
3072 #endif
3073 report_file_error ("Setting file times", Fcons (absname, Qnil));
3074 return Qnil;
3075 }
3076 }
3077
3078 return Qt;
3079 }
3080 \f
3081 #ifdef HAVE_SYNC
3082 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3083 doc: /* Tell Unix to finish all pending disk updates. */)
3084 (void)
3085 {
3086 sync ();
3087 return Qnil;
3088 }
3089
3090 #endif /* HAVE_SYNC */
3091
3092 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3093 doc: /* Return t if file FILE1 is newer than file FILE2.
3094 If FILE1 does not exist, the answer is nil;
3095 otherwise, if FILE2 does not exist, the answer is t. */)
3096 (Lisp_Object file1, Lisp_Object file2)
3097 {
3098 Lisp_Object absname1, absname2;
3099 struct stat st;
3100 int mtime1;
3101 Lisp_Object handler;
3102 struct gcpro gcpro1, gcpro2;
3103
3104 CHECK_STRING (file1);
3105 CHECK_STRING (file2);
3106
3107 absname1 = Qnil;
3108 GCPRO2 (absname1, file2);
3109 absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
3110 absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
3111 UNGCPRO;
3112
3113 /* If the file name has special constructs in it,
3114 call the corresponding file handler. */
3115 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3116 if (NILP (handler))
3117 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3118 if (!NILP (handler))
3119 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3120
3121 GCPRO2 (absname1, absname2);
3122 absname1 = ENCODE_FILE (absname1);
3123 absname2 = ENCODE_FILE (absname2);
3124 UNGCPRO;
3125
3126 if (stat (SDATA (absname1), &st) < 0)
3127 return Qnil;
3128
3129 mtime1 = st.st_mtime;
3130
3131 if (stat (SDATA (absname2), &st) < 0)
3132 return Qt;
3133
3134 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3135 }
3136 \f
3137 #ifdef DOS_NT
3138 Lisp_Object Qfind_buffer_file_type;
3139 #endif /* DOS_NT */
3140
3141 #ifndef READ_BUF_SIZE
3142 #define READ_BUF_SIZE (64 << 10)
3143 #endif
3144
3145 /* This function is called after Lisp functions to decide a coding
3146 system are called, or when they cause an error. Before they are
3147 called, the current buffer is set unibyte and it contains only a
3148 newly inserted text (thus the buffer was empty before the
3149 insertion).
3150
3151 The functions may set markers, overlays, text properties, or even
3152 alter the buffer contents, change the current buffer.
3153
3154 Here, we reset all those changes by:
3155 o set back the current buffer.
3156 o move all markers and overlays to BEG.
3157 o remove all text properties.
3158 o set back the buffer multibyteness. */
3159
3160 static Lisp_Object
3161 decide_coding_unwind (Lisp_Object unwind_data)
3162 {
3163 Lisp_Object multibyte, undo_list, buffer;
3164
3165 multibyte = XCAR (unwind_data);
3166 unwind_data = XCDR (unwind_data);
3167 undo_list = XCAR (unwind_data);
3168 buffer = XCDR (unwind_data);
3169
3170 if (current_buffer != XBUFFER (buffer))
3171 set_buffer_internal (XBUFFER (buffer));
3172 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3173 adjust_overlays_for_delete (BEG, Z - BEG);
3174 BUF_INTERVALS (current_buffer) = 0;
3175 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3176
3177 /* Now we are safe to change the buffer's multibyteness directly. */
3178 current_buffer->enable_multibyte_characters = multibyte;
3179 current_buffer->undo_list = undo_list;
3180
3181 return Qnil;
3182 }
3183
3184
3185 /* Used to pass values from insert-file-contents to read_non_regular. */
3186
3187 static int non_regular_fd;
3188 static EMACS_INT non_regular_inserted;
3189 static EMACS_INT non_regular_nbytes;
3190
3191
3192 /* Read from a non-regular file.
3193 Read non_regular_nbytes bytes max from non_regular_fd.
3194 Non_regular_inserted specifies where to put the read bytes.
3195 Value is the number of bytes read. */
3196
3197 static Lisp_Object
3198 read_non_regular (Lisp_Object ignore)
3199 {
3200 EMACS_INT nbytes;
3201
3202 immediate_quit = 1;
3203 QUIT;
3204 nbytes = emacs_read (non_regular_fd,
3205 BEG_ADDR + PT_BYTE - BEG_BYTE + non_regular_inserted,
3206 non_regular_nbytes);
3207 immediate_quit = 0;
3208 return make_number (nbytes);
3209 }
3210
3211
3212 /* Condition-case handler used when reading from non-regular files
3213 in insert-file-contents. */
3214
3215 static Lisp_Object
3216 read_non_regular_quit (Lisp_Object ignore)
3217 {
3218 return Qnil;
3219 }
3220
3221
3222 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3223 1, 5, 0,
3224 doc: /* Insert contents of file FILENAME after point.
3225 Returns list of absolute file name and number of characters inserted.
3226 If second argument VISIT is non-nil, the buffer's visited filename and
3227 last save file modtime are set, and it is marked unmodified. If
3228 visiting and the file does not exist, visiting is completed before the
3229 error is signaled.
3230
3231 The optional third and fourth arguments BEG and END specify what portion
3232 of the file to insert. These arguments count bytes in the file, not
3233 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3234
3235 If optional fifth argument REPLACE is non-nil, replace the current
3236 buffer contents (in the accessible portion) with the file contents.
3237 This is better than simply deleting and inserting the whole thing
3238 because (1) it preserves some marker positions and (2) it puts less data
3239 in the undo list. When REPLACE is non-nil, the second return value is
3240 the number of characters that replace previous buffer contents.
3241
3242 This function does code conversion according to the value of
3243 `coding-system-for-read' or `file-coding-system-alist', and sets the
3244 variable `last-coding-system-used' to the coding system actually used. */)
3245 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3246 {
3247 struct stat st;
3248 register int fd;
3249 EMACS_INT inserted = 0;
3250 int nochange = 0;
3251 register EMACS_INT how_much;
3252 register EMACS_INT unprocessed;
3253 int count = SPECPDL_INDEX ();
3254 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3255 Lisp_Object handler, val, insval, orig_filename, old_undo;
3256 Lisp_Object p;
3257 EMACS_INT total = 0;
3258 int not_regular = 0;
3259 unsigned char read_buf[READ_BUF_SIZE];
3260 struct coding_system coding;
3261 unsigned char buffer[1 << 14];
3262 int replace_handled = 0;
3263 int set_coding_system = 0;
3264 Lisp_Object coding_system;
3265 int read_quit = 0;
3266 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3267 int we_locked_file = 0;
3268 int deferred_remove_unwind_protect = 0;
3269
3270 if (current_buffer->base_buffer && ! NILP (visit))
3271 error ("Cannot do file visiting in an indirect buffer");
3272
3273 if (!NILP (current_buffer->read_only))
3274 Fbarf_if_buffer_read_only ();
3275
3276 val = Qnil;
3277 p = Qnil;
3278 orig_filename = Qnil;
3279 old_undo = Qnil;
3280
3281 GCPRO5 (filename, val, p, orig_filename, old_undo);
3282
3283 CHECK_STRING (filename);
3284 filename = Fexpand_file_name (filename, Qnil);
3285
3286 /* The value Qnil means that the coding system is not yet
3287 decided. */
3288 coding_system = Qnil;
3289
3290 /* If the file name has special constructs in it,
3291 call the corresponding file handler. */
3292 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3293 if (!NILP (handler))
3294 {
3295 val = call6 (handler, Qinsert_file_contents, filename,
3296 visit, beg, end, replace);
3297 if (CONSP (val) && CONSP (XCDR (val)))
3298 inserted = XINT (XCAR (XCDR (val)));
3299 goto handled;
3300 }
3301
3302 orig_filename = filename;
3303 filename = ENCODE_FILE (filename);
3304
3305 fd = -1;
3306
3307 #ifdef WINDOWSNT
3308 {
3309 Lisp_Object tem = Vw32_get_true_file_attributes;
3310
3311 /* Tell stat to use expensive method to get accurate info. */
3312 Vw32_get_true_file_attributes = Qt;
3313 total = stat (SDATA (filename), &st);
3314 Vw32_get_true_file_attributes = tem;
3315 }
3316 if (total < 0)
3317 #else
3318 if (stat (SDATA (filename), &st) < 0)
3319 #endif /* WINDOWSNT */
3320 {
3321 if (fd >= 0) emacs_close (fd);
3322 badopen:
3323 if (NILP (visit))
3324 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3325 st.st_mtime = -1;
3326 how_much = 0;
3327 if (!NILP (Vcoding_system_for_read))
3328 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3329 goto notfound;
3330 }
3331
3332 #ifdef S_IFREG
3333 /* This code will need to be changed in order to work on named
3334 pipes, and it's probably just not worth it. So we should at
3335 least signal an error. */
3336 if (!S_ISREG (st.st_mode))
3337 {
3338 not_regular = 1;
3339
3340 if (! NILP (visit))
3341 goto notfound;
3342
3343 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3344 xsignal2 (Qfile_error,
3345 build_string ("not a regular file"), orig_filename);
3346 }
3347 #endif
3348
3349 if (fd < 0)
3350 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0)
3351 goto badopen;
3352
3353 /* Replacement should preserve point as it preserves markers. */
3354 if (!NILP (replace))
3355 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3356
3357 record_unwind_protect (close_file_unwind, make_number (fd));
3358
3359 /* Can happen on any platform that uses long as type of off_t, but allows
3360 file sizes to exceed 2Gb, so give a suitable message. */
3361 if (! not_regular && st.st_size < 0)
3362 error ("Maximum buffer size exceeded");
3363
3364 /* Prevent redisplay optimizations. */
3365 current_buffer->clip_changed = 1;
3366
3367 if (!NILP (visit))
3368 {
3369 if (!NILP (beg) || !NILP (end))
3370 error ("Attempt to visit less than an entire file");
3371 if (BEG < Z && NILP (replace))
3372 error ("Cannot do file visiting in a non-empty buffer");
3373 }
3374
3375 if (!NILP (beg))
3376 CHECK_NUMBER (beg);
3377 else
3378 XSETFASTINT (beg, 0);
3379
3380 if (!NILP (end))
3381 CHECK_NUMBER (end);
3382 else
3383 {
3384 if (! not_regular)
3385 {
3386 XSETINT (end, st.st_size);
3387
3388 /* Arithmetic overflow can occur if an Emacs integer cannot
3389 represent the file size, or if the calculations below
3390 overflow. The calculations below double the file size
3391 twice, so check that it can be multiplied by 4 safely. */
3392 if (XINT (end) != st.st_size
3393 /* Actually, it should test either INT_MAX or LONG_MAX
3394 depending on which one is used for EMACS_INT. But in
3395 any case, in practice, this test is redundant with the
3396 one above.
3397 || st.st_size > INT_MAX / 4 */)
3398 error ("Maximum buffer size exceeded");
3399
3400 /* The file size returned from stat may be zero, but data
3401 may be readable nonetheless, for example when this is a
3402 file in the /proc filesystem. */
3403 if (st.st_size == 0)
3404 XSETINT (end, READ_BUF_SIZE);
3405 }
3406 }
3407
3408 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3409 {
3410 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3411 setup_coding_system (coding_system, &coding);
3412 /* Ensure we set Vlast_coding_system_used. */
3413 set_coding_system = 1;
3414 }
3415 else if (BEG < Z)
3416 {
3417 /* Decide the coding system to use for reading the file now
3418 because we can't use an optimized method for handling
3419 `coding:' tag if the current buffer is not empty. */
3420 if (!NILP (Vcoding_system_for_read))
3421 coding_system = Vcoding_system_for_read;
3422 else
3423 {
3424 /* Don't try looking inside a file for a coding system
3425 specification if it is not seekable. */
3426 if (! not_regular && ! NILP (Vset_auto_coding_function))
3427 {
3428 /* Find a coding system specified in the heading two
3429 lines or in the tailing several lines of the file.
3430 We assume that the 1K-byte and 3K-byte for heading
3431 and tailing respectively are sufficient for this
3432 purpose. */
3433 EMACS_INT nread;
3434
3435 if (st.st_size <= (1024 * 4))
3436 nread = emacs_read (fd, read_buf, 1024 * 4);
3437 else
3438 {
3439 nread = emacs_read (fd, read_buf, 1024);
3440 if (nread >= 0)
3441 {
3442 if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
3443 report_file_error ("Setting file position",
3444 Fcons (orig_filename, Qnil));
3445 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3446 }
3447 }
3448
3449 if (nread < 0)
3450 error ("IO error reading %s: %s",
3451 SDATA (orig_filename), emacs_strerror (errno));
3452 else if (nread > 0)
3453 {
3454 struct buffer *prev = current_buffer;
3455 Lisp_Object buffer;
3456 struct buffer *buf;
3457
3458 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3459
3460 buffer = Fget_buffer_create (build_string (" *code-converting-work*"));
3461 buf = XBUFFER (buffer);
3462
3463 delete_all_overlays (buf);
3464 buf->directory = current_buffer->directory;
3465 buf->read_only = Qnil;
3466 buf->filename = Qnil;
3467 buf->undo_list = Qt;
3468 eassert (buf->overlays_before == NULL);
3469 eassert (buf->overlays_after == NULL);
3470
3471 set_buffer_internal (buf);
3472 Ferase_buffer ();
3473 buf->enable_multibyte_characters = Qnil;
3474
3475 insert_1_both (read_buf, nread, nread, 0, 0, 0);
3476 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3477 coding_system = call2 (Vset_auto_coding_function,
3478 filename, make_number (nread));
3479 set_buffer_internal (prev);
3480
3481 /* Discard the unwind protect for recovering the
3482 current buffer. */
3483 specpdl_ptr--;
3484
3485 /* Rewind the file for the actual read done later. */
3486 if (lseek (fd, 0, 0) < 0)
3487 report_file_error ("Setting file position",
3488 Fcons (orig_filename, Qnil));
3489 }
3490 }
3491
3492 if (NILP (coding_system))
3493 {
3494 /* If we have not yet decided a coding system, check
3495 file-coding-system-alist. */
3496 Lisp_Object args[6];
3497
3498 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3499 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3500 coding_system = Ffind_operation_coding_system (6, args);
3501 if (CONSP (coding_system))
3502 coding_system = XCAR (coding_system);
3503 }
3504 }
3505
3506 if (NILP (coding_system))
3507 coding_system = Qundecided;
3508 else
3509 CHECK_CODING_SYSTEM (coding_system);
3510
3511 if (NILP (current_buffer->enable_multibyte_characters))
3512 /* We must suppress all character code conversion except for
3513 end-of-line conversion. */
3514 coding_system = raw_text_coding_system (coding_system);
3515
3516 setup_coding_system (coding_system, &coding);
3517 /* Ensure we set Vlast_coding_system_used. */
3518 set_coding_system = 1;
3519 }
3520
3521 /* If requested, replace the accessible part of the buffer
3522 with the file contents. Avoid replacing text at the
3523 beginning or end of the buffer that matches the file contents;
3524 that preserves markers pointing to the unchanged parts.
3525
3526 Here we implement this feature in an optimized way
3527 for the case where code conversion is NOT needed.
3528 The following if-statement handles the case of conversion
3529 in a less optimal way.
3530
3531 If the code conversion is "automatic" then we try using this
3532 method and hope for the best.
3533 But if we discover the need for conversion, we give up on this method
3534 and let the following if-statement handle the replace job. */
3535 if (!NILP (replace)
3536 && BEGV < ZV
3537 && (NILP (coding_system)
3538 || ! CODING_REQUIRE_DECODING (&coding)))
3539 {
3540 /* same_at_start and same_at_end count bytes,
3541 because file access counts bytes
3542 and BEG and END count bytes. */
3543 EMACS_INT same_at_start = BEGV_BYTE;
3544 EMACS_INT same_at_end = ZV_BYTE;
3545 EMACS_INT overlap;
3546 /* There is still a possibility we will find the need to do code
3547 conversion. If that happens, we set this variable to 1 to
3548 give up on handling REPLACE in the optimized way. */
3549 int giveup_match_end = 0;
3550
3551 if (XINT (beg) != 0)
3552 {
3553 if (lseek (fd, XINT (beg), 0) < 0)
3554 report_file_error ("Setting file position",
3555 Fcons (orig_filename, Qnil));
3556 }
3557
3558 immediate_quit = 1;
3559 QUIT;
3560 /* Count how many chars at the start of the file
3561 match the text at the beginning of the buffer. */
3562 while (1)
3563 {
3564 EMACS_INT nread, bufpos;
3565
3566 nread = emacs_read (fd, buffer, sizeof buffer);
3567 if (nread < 0)
3568 error ("IO error reading %s: %s",
3569 SDATA (orig_filename), emacs_strerror (errno));
3570 else if (nread == 0)
3571 break;
3572
3573 if (CODING_REQUIRE_DETECTION (&coding))
3574 {
3575 coding_system = detect_coding_system (buffer, nread, nread, 1, 0,
3576 coding_system);
3577 setup_coding_system (coding_system, &coding);
3578 }
3579
3580 if (CODING_REQUIRE_DECODING (&coding))
3581 /* We found that the file should be decoded somehow.
3582 Let's give up here. */
3583 {
3584 giveup_match_end = 1;
3585 break;
3586 }
3587
3588 bufpos = 0;
3589 while (bufpos < nread && same_at_start < ZV_BYTE
3590 && FETCH_BYTE (same_at_start) == buffer[bufpos])
3591 same_at_start++, bufpos++;
3592 /* If we found a discrepancy, stop the scan.
3593 Otherwise loop around and scan the next bufferful. */
3594 if (bufpos != nread)
3595 break;
3596 }
3597 immediate_quit = 0;
3598 /* If the file matches the buffer completely,
3599 there's no need to replace anything. */
3600 if (same_at_start - BEGV_BYTE == XINT (end))
3601 {
3602 emacs_close (fd);
3603 specpdl_ptr--;
3604 /* Truncate the buffer to the size of the file. */
3605 del_range_1 (same_at_start, same_at_end, 0, 0);
3606 goto handled;
3607 }
3608 immediate_quit = 1;
3609 QUIT;
3610 /* Count how many chars at the end of the file
3611 match the text at the end of the buffer. But, if we have
3612 already found that decoding is necessary, don't waste time. */
3613 while (!giveup_match_end)
3614 {
3615 EMACS_INT total_read, nread, bufpos, curpos, trial;
3616
3617 /* At what file position are we now scanning? */
3618 curpos = XINT (end) - (ZV_BYTE - same_at_end);
3619 /* If the entire file matches the buffer tail, stop the scan. */
3620 if (curpos == 0)
3621 break;
3622 /* How much can we scan in the next step? */
3623 trial = min (curpos, sizeof buffer);
3624 if (lseek (fd, curpos - trial, 0) < 0)
3625 report_file_error ("Setting file position",
3626 Fcons (orig_filename, Qnil));
3627
3628 total_read = nread = 0;
3629 while (total_read < trial)
3630 {
3631 nread = emacs_read (fd, buffer + total_read, trial - total_read);
3632 if (nread < 0)
3633 error ("IO error reading %s: %s",
3634 SDATA (orig_filename), emacs_strerror (errno));
3635 else if (nread == 0)
3636 break;
3637 total_read += nread;
3638 }
3639
3640 /* Scan this bufferful from the end, comparing with
3641 the Emacs buffer. */
3642 bufpos = total_read;
3643
3644 /* Compare with same_at_start to avoid counting some buffer text
3645 as matching both at the file's beginning and at the end. */
3646 while (bufpos > 0 && same_at_end > same_at_start
3647 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
3648 same_at_end--, bufpos--;
3649
3650 /* If we found a discrepancy, stop the scan.
3651 Otherwise loop around and scan the preceding bufferful. */
3652 if (bufpos != 0)
3653 {
3654 /* If this discrepancy is because of code conversion,
3655 we cannot use this method; giveup and try the other. */
3656 if (same_at_end > same_at_start
3657 && FETCH_BYTE (same_at_end - 1) >= 0200
3658 && ! NILP (current_buffer->enable_multibyte_characters)
3659 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3660 giveup_match_end = 1;
3661 break;
3662 }
3663
3664 if (nread == 0)
3665 break;
3666 }
3667 immediate_quit = 0;
3668
3669 if (! giveup_match_end)
3670 {
3671 EMACS_INT temp;
3672
3673 /* We win! We can handle REPLACE the optimized way. */
3674
3675 /* Extend the start of non-matching text area to multibyte
3676 character boundary. */
3677 if (! NILP (current_buffer->enable_multibyte_characters))
3678 while (same_at_start > BEGV_BYTE
3679 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3680 same_at_start--;
3681
3682 /* Extend the end of non-matching text area to multibyte
3683 character boundary. */
3684 if (! NILP (current_buffer->enable_multibyte_characters))
3685 while (same_at_end < ZV_BYTE
3686 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3687 same_at_end++;
3688
3689 /* Don't try to reuse the same piece of text twice. */
3690 overlap = (same_at_start - BEGV_BYTE
3691 - (same_at_end + st.st_size - ZV));
3692 if (overlap > 0)
3693 same_at_end += overlap;
3694
3695 /* Arrange to read only the nonmatching middle part of the file. */
3696 XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV_BYTE));
3697 XSETFASTINT (end, XINT (end) - (ZV_BYTE - same_at_end));
3698
3699 del_range_byte (same_at_start, same_at_end, 0);
3700 /* Insert from the file at the proper position. */
3701 temp = BYTE_TO_CHAR (same_at_start);
3702 SET_PT_BOTH (temp, same_at_start);
3703
3704 /* If display currently starts at beginning of line,
3705 keep it that way. */
3706 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3707 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3708
3709 replace_handled = 1;
3710 }
3711 }
3712
3713 /* If requested, replace the accessible part of the buffer
3714 with the file contents. Avoid replacing text at the
3715 beginning or end of the buffer that matches the file contents;
3716 that preserves markers pointing to the unchanged parts.
3717
3718 Here we implement this feature for the case where code conversion
3719 is needed, in a simple way that needs a lot of memory.
3720 The preceding if-statement handles the case of no conversion
3721 in a more optimized way. */
3722 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3723 {
3724 EMACS_INT same_at_start = BEGV_BYTE;
3725 EMACS_INT same_at_end = ZV_BYTE;
3726 EMACS_INT same_at_start_charpos;
3727 EMACS_INT inserted_chars;
3728 EMACS_INT overlap;
3729 EMACS_INT bufpos;
3730 unsigned char *decoded;
3731 EMACS_INT temp;
3732 int this_count = SPECPDL_INDEX ();
3733 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
3734 Lisp_Object conversion_buffer;
3735
3736 conversion_buffer = code_conversion_save (1, multibyte);
3737
3738 /* First read the whole file, performing code conversion into
3739 CONVERSION_BUFFER. */
3740
3741 if (lseek (fd, XINT (beg), 0) < 0)
3742 report_file_error ("Setting file position",
3743 Fcons (orig_filename, Qnil));
3744
3745 total = st.st_size; /* Total bytes in the file. */
3746 how_much = 0; /* Bytes read from file so far. */
3747 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3748 unprocessed = 0; /* Bytes not processed in previous loop. */
3749
3750 GCPRO1 (conversion_buffer);
3751 while (how_much < total)
3752 {
3753 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
3754 quitting while reading a huge while. */
3755 /* try is reserved in some compilers (Microsoft C) */
3756 EMACS_INT trytry = min (total - how_much,
3757 READ_BUF_SIZE - unprocessed);
3758 EMACS_INT this;
3759
3760 /* Allow quitting out of the actual I/O. */
3761 immediate_quit = 1;
3762 QUIT;
3763 this = emacs_read (fd, read_buf + unprocessed, trytry);
3764 immediate_quit = 0;
3765
3766 if (this <= 0)
3767 {
3768 if (this < 0)
3769 how_much = this;
3770 break;
3771 }
3772
3773 how_much += this;
3774
3775 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3776 BUF_Z (XBUFFER (conversion_buffer)));
3777 decode_coding_c_string (&coding, read_buf, unprocessed + this,
3778 conversion_buffer);
3779 unprocessed = coding.carryover_bytes;
3780 if (coding.carryover_bytes > 0)
3781 memcpy (read_buf, coding.carryover, unprocessed);
3782 }
3783 UNGCPRO;
3784 emacs_close (fd);
3785
3786 /* We should remove the unwind_protect calling
3787 close_file_unwind, but other stuff has been added the stack,
3788 so defer the removal till we reach the `handled' label. */
3789 deferred_remove_unwind_protect = 1;
3790
3791 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
3792 if we couldn't read the file. */
3793
3794 if (how_much < 0)
3795 error ("IO error reading %s: %s",
3796 SDATA (orig_filename), emacs_strerror (errno));
3797
3798 if (unprocessed > 0)
3799 {
3800 coding.mode |= CODING_MODE_LAST_BLOCK;
3801 decode_coding_c_string (&coding, read_buf, unprocessed,
3802 conversion_buffer);
3803 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3804 }
3805
3806 coding_system = CODING_ID_NAME (coding.id);
3807 set_coding_system = 1;
3808 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3809 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3810 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3811
3812 /* Compare the beginning of the converted string with the buffer
3813 text. */
3814
3815 bufpos = 0;
3816 while (bufpos < inserted && same_at_start < same_at_end
3817 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3818 same_at_start++, bufpos++;
3819
3820 /* If the file matches the head of buffer completely,
3821 there's no need to replace anything. */
3822
3823 if (bufpos == inserted)
3824 {
3825 /* Truncate the buffer to the size of the file. */
3826 if (same_at_start == same_at_end)
3827 nochange = 1;
3828 else
3829 del_range_byte (same_at_start, same_at_end, 0);
3830 inserted = 0;
3831
3832 unbind_to (this_count, Qnil);
3833 goto handled;
3834 }
3835
3836 /* Extend the start of non-matching text area to the previous
3837 multibyte character boundary. */
3838 if (! NILP (current_buffer->enable_multibyte_characters))
3839 while (same_at_start > BEGV_BYTE
3840 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3841 same_at_start--;
3842
3843 /* Scan this bufferful from the end, comparing with
3844 the Emacs buffer. */
3845 bufpos = inserted;
3846
3847 /* Compare with same_at_start to avoid counting some buffer text
3848 as matching both at the file's beginning and at the end. */
3849 while (bufpos > 0 && same_at_end > same_at_start
3850 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3851 same_at_end--, bufpos--;
3852
3853 /* Extend the end of non-matching text area to the next
3854 multibyte character boundary. */
3855 if (! NILP (current_buffer->enable_multibyte_characters))
3856 while (same_at_end < ZV_BYTE
3857 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3858 same_at_end++;
3859
3860 /* Don't try to reuse the same piece of text twice. */
3861 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3862 if (overlap > 0)
3863 same_at_end += overlap;
3864
3865 /* If display currently starts at beginning of line,
3866 keep it that way. */
3867 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3868 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3869
3870 /* Replace the chars that we need to replace,
3871 and update INSERTED to equal the number of bytes
3872 we are taking from the decoded string. */
3873 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3874
3875 if (same_at_end != same_at_start)
3876 {
3877 del_range_byte (same_at_start, same_at_end, 0);
3878 temp = GPT;
3879 same_at_start = GPT_BYTE;
3880 }
3881 else
3882 {
3883 temp = BYTE_TO_CHAR (same_at_start);
3884 }
3885 /* Insert from the file at the proper position. */
3886 SET_PT_BOTH (temp, same_at_start);
3887 same_at_start_charpos
3888 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3889 same_at_start - BEGV_BYTE
3890 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3891 inserted_chars
3892 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
3893 same_at_start + inserted - BEGV_BYTE
3894 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
3895 - same_at_start_charpos);
3896 /* This binding is to avoid ask-user-about-supersession-threat
3897 being called in insert_from_buffer (via in
3898 prepare_to_modify_buffer). */
3899 specbind (intern ("buffer-file-name"), Qnil);
3900 insert_from_buffer (XBUFFER (conversion_buffer),
3901 same_at_start_charpos, inserted_chars, 0);
3902 /* Set `inserted' to the number of inserted characters. */
3903 inserted = PT - temp;
3904 /* Set point before the inserted characters. */
3905 SET_PT_BOTH (temp, same_at_start);
3906
3907 unbind_to (this_count, Qnil);
3908
3909 goto handled;
3910 }
3911
3912 if (! not_regular)
3913 {
3914 register Lisp_Object temp;
3915
3916 total = XINT (end) - XINT (beg);
3917
3918 /* Make sure point-max won't overflow after this insertion. */
3919 XSETINT (temp, total);
3920 if (total != XINT (temp))
3921 error ("Maximum buffer size exceeded");
3922 }
3923 else
3924 /* For a special file, all we can do is guess. */
3925 total = READ_BUF_SIZE;
3926
3927 if (NILP (visit) && inserted > 0)
3928 {
3929 #ifdef CLASH_DETECTION
3930 if (!NILP (current_buffer->file_truename)
3931 /* Make binding buffer-file-name to nil effective. */
3932 && !NILP (current_buffer->filename)
3933 && SAVE_MODIFF >= MODIFF)
3934 we_locked_file = 1;
3935 #endif /* CLASH_DETECTION */
3936 prepare_to_modify_buffer (GPT, GPT, NULL);
3937 }
3938
3939 move_gap (PT);
3940 if (GAP_SIZE < total)
3941 make_gap (total - GAP_SIZE);
3942
3943 if (XINT (beg) != 0 || !NILP (replace))
3944 {
3945 if (lseek (fd, XINT (beg), 0) < 0)
3946 report_file_error ("Setting file position",
3947 Fcons (orig_filename, Qnil));
3948 }
3949
3950 /* In the following loop, HOW_MUCH contains the total bytes read so
3951 far for a regular file, and not changed for a special file. But,
3952 before exiting the loop, it is set to a negative value if I/O
3953 error occurs. */
3954 how_much = 0;
3955
3956 /* Total bytes inserted. */
3957 inserted = 0;
3958
3959 /* Here, we don't do code conversion in the loop. It is done by
3960 decode_coding_gap after all data are read into the buffer. */
3961 {
3962 EMACS_INT gap_size = GAP_SIZE;
3963
3964 while (how_much < total)
3965 {
3966 /* try is reserved in some compilers (Microsoft C) */
3967 EMACS_INT trytry = min (total - how_much, READ_BUF_SIZE);
3968 EMACS_INT this;
3969
3970 if (not_regular)
3971 {
3972 Lisp_Object val;
3973
3974 /* Maybe make more room. */
3975 if (gap_size < trytry)
3976 {
3977 make_gap (total - gap_size);
3978 gap_size = GAP_SIZE;
3979 }
3980
3981 /* Read from the file, capturing `quit'. When an
3982 error occurs, end the loop, and arrange for a quit
3983 to be signaled after decoding the text we read. */
3984 non_regular_fd = fd;
3985 non_regular_inserted = inserted;
3986 non_regular_nbytes = trytry;
3987 val = internal_condition_case_1 (read_non_regular, Qnil, Qerror,
3988 read_non_regular_quit);
3989 if (NILP (val))
3990 {
3991 read_quit = 1;
3992 break;
3993 }
3994
3995 this = XINT (val);
3996 }
3997 else
3998 {
3999 /* Allow quitting out of the actual I/O. We don't make text
4000 part of the buffer until all the reading is done, so a C-g
4001 here doesn't do any harm. */
4002 immediate_quit = 1;
4003 QUIT;
4004 this = emacs_read (fd, BEG_ADDR + PT_BYTE - BEG_BYTE + inserted, trytry);
4005 immediate_quit = 0;
4006 }
4007
4008 if (this <= 0)
4009 {
4010 how_much = this;
4011 break;
4012 }
4013
4014 gap_size -= this;
4015
4016 /* For a regular file, where TOTAL is the real size,
4017 count HOW_MUCH to compare with it.
4018 For a special file, where TOTAL is just a buffer size,
4019 so don't bother counting in HOW_MUCH.
4020 (INSERTED is where we count the number of characters inserted.) */
4021 if (! not_regular)
4022 how_much += this;
4023 inserted += this;
4024 }
4025 }
4026
4027 /* Now we have read all the file data into the gap.
4028 If it was empty, undo marking the buffer modified. */
4029
4030 if (inserted == 0)
4031 {
4032 #ifdef CLASH_DETECTION
4033 if (we_locked_file)
4034 unlock_file (current_buffer->file_truename);
4035 #endif
4036 Vdeactivate_mark = old_Vdeactivate_mark;
4037 }
4038 else
4039 Vdeactivate_mark = Qt;
4040
4041 /* Make the text read part of the buffer. */
4042 GAP_SIZE -= inserted;
4043 GPT += inserted;
4044 GPT_BYTE += inserted;
4045 ZV += inserted;
4046 ZV_BYTE += inserted;
4047 Z += inserted;
4048 Z_BYTE += inserted;
4049
4050 if (GAP_SIZE > 0)
4051 /* Put an anchor to ensure multi-byte form ends at gap. */
4052 *GPT_ADDR = 0;
4053
4054 emacs_close (fd);
4055
4056 /* Discard the unwind protect for closing the file. */
4057 specpdl_ptr--;
4058
4059 if (how_much < 0)
4060 error ("IO error reading %s: %s",
4061 SDATA (orig_filename), emacs_strerror (errno));
4062
4063 notfound:
4064
4065 if (NILP (coding_system))
4066 {
4067 /* The coding system is not yet decided. Decide it by an
4068 optimized method for handling `coding:' tag.
4069
4070 Note that we can get here only if the buffer was empty
4071 before the insertion. */
4072
4073 if (!NILP (Vcoding_system_for_read))
4074 coding_system = Vcoding_system_for_read;
4075 else
4076 {
4077 /* Since we are sure that the current buffer was empty
4078 before the insertion, we can toggle
4079 enable-multibyte-characters directly here without taking
4080 care of marker adjustment. By this way, we can run Lisp
4081 program safely before decoding the inserted text. */
4082 Lisp_Object unwind_data;
4083 int count = SPECPDL_INDEX ();
4084
4085 unwind_data = Fcons (current_buffer->enable_multibyte_characters,
4086 Fcons (current_buffer->undo_list,
4087 Fcurrent_buffer ()));
4088 current_buffer->enable_multibyte_characters = Qnil;
4089 current_buffer->undo_list = Qt;
4090 record_unwind_protect (decide_coding_unwind, unwind_data);
4091
4092 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4093 {
4094 coding_system = call2 (Vset_auto_coding_function,
4095 filename, make_number (inserted));
4096 }
4097
4098 if (NILP (coding_system))
4099 {
4100 /* If the coding system is not yet decided, check
4101 file-coding-system-alist. */
4102 Lisp_Object args[6];
4103
4104 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4105 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4106 coding_system = Ffind_operation_coding_system (6, args);
4107 if (CONSP (coding_system))
4108 coding_system = XCAR (coding_system);
4109 }
4110 unbind_to (count, Qnil);
4111 inserted = Z_BYTE - BEG_BYTE;
4112 }
4113
4114 if (NILP (coding_system))
4115 coding_system = Qundecided;
4116 else
4117 CHECK_CODING_SYSTEM (coding_system);
4118
4119 if (NILP (current_buffer->enable_multibyte_characters))
4120 /* We must suppress all character code conversion except for
4121 end-of-line conversion. */
4122 coding_system = raw_text_coding_system (coding_system);
4123 setup_coding_system (coding_system, &coding);
4124 /* Ensure we set Vlast_coding_system_used. */
4125 set_coding_system = 1;
4126 }
4127
4128 if (!NILP (visit))
4129 {
4130 /* When we visit a file by raw-text, we change the buffer to
4131 unibyte. */
4132 if (CODING_FOR_UNIBYTE (&coding)
4133 /* Can't do this if part of the buffer might be preserved. */
4134 && NILP (replace))
4135 /* Visiting a file with these coding system makes the buffer
4136 unibyte. */
4137 current_buffer->enable_multibyte_characters = Qnil;
4138 }
4139
4140 coding.dst_multibyte = ! NILP (current_buffer->enable_multibyte_characters);
4141 if (CODING_MAY_REQUIRE_DECODING (&coding)
4142 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4143 {
4144 move_gap_both (PT, PT_BYTE);
4145 GAP_SIZE += inserted;
4146 ZV_BYTE -= inserted;
4147 Z_BYTE -= inserted;
4148 ZV -= inserted;
4149 Z -= inserted;
4150 decode_coding_gap (&coding, inserted, inserted);
4151 inserted = coding.produced_char;
4152 coding_system = CODING_ID_NAME (coding.id);
4153 }
4154 else if (inserted > 0)
4155 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4156 inserted);
4157
4158 /* Now INSERTED is measured in characters. */
4159
4160 #ifdef DOS_NT
4161 /* Use the conversion type to determine buffer-file-type
4162 (find-buffer-file-type is now used to help determine the
4163 conversion). */
4164 if ((VECTORP (CODING_ID_EOL_TYPE (coding.id))
4165 || EQ (CODING_ID_EOL_TYPE (coding.id), Qunix))
4166 && ! CODING_REQUIRE_DECODING (&coding))
4167 current_buffer->buffer_file_type = Qt;
4168 else
4169 current_buffer->buffer_file_type = Qnil;
4170 #endif
4171
4172 handled:
4173
4174 if (deferred_remove_unwind_protect)
4175 /* If requested above, discard the unwind protect for closing the
4176 file. */
4177 specpdl_ptr--;
4178
4179 if (!NILP (visit))
4180 {
4181 if (!EQ (current_buffer->undo_list, Qt) && !nochange)
4182 current_buffer->undo_list = Qnil;
4183
4184 if (NILP (handler))
4185 {
4186 current_buffer->modtime = st.st_mtime;
4187 current_buffer->modtime_size = st.st_size;
4188 current_buffer->filename = orig_filename;
4189 }
4190
4191 SAVE_MODIFF = MODIFF;
4192 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4193 XSETFASTINT (current_buffer->save_length, Z - BEG);
4194 #ifdef CLASH_DETECTION
4195 if (NILP (handler))
4196 {
4197 if (!NILP (current_buffer->file_truename))
4198 unlock_file (current_buffer->file_truename);
4199 unlock_file (filename);
4200 }
4201 #endif /* CLASH_DETECTION */
4202 if (not_regular)
4203 xsignal2 (Qfile_error,
4204 build_string ("not a regular file"), orig_filename);
4205 }
4206
4207 if (set_coding_system)
4208 Vlast_coding_system_used = coding_system;
4209
4210 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4211 {
4212 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4213 visit);
4214 if (! NILP (insval))
4215 {
4216 CHECK_NUMBER (insval);
4217 inserted = XFASTINT (insval);
4218 }
4219 }
4220
4221 /* Decode file format. */
4222 if (inserted > 0)
4223 {
4224 /* Don't run point motion or modification hooks when decoding. */
4225 int count = SPECPDL_INDEX ();
4226 EMACS_INT old_inserted = inserted;
4227 specbind (Qinhibit_point_motion_hooks, Qt);
4228 specbind (Qinhibit_modification_hooks, Qt);
4229
4230 /* Save old undo list and don't record undo for decoding. */
4231 old_undo = current_buffer->undo_list;
4232 current_buffer->undo_list = Qt;
4233
4234 if (NILP (replace))
4235 {
4236 insval = call3 (Qformat_decode,
4237 Qnil, make_number (inserted), visit);
4238 CHECK_NUMBER (insval);
4239 inserted = XFASTINT (insval);
4240 }
4241 else
4242 {
4243 /* If REPLACE is non-nil and we succeeded in not replacing the
4244 beginning or end of the buffer text with the file's contents,
4245 call format-decode with `point' positioned at the beginning
4246 of the buffer and `inserted' equalling the number of
4247 characters in the buffer. Otherwise, format-decode might
4248 fail to correctly analyze the beginning or end of the buffer.
4249 Hence we temporarily save `point' and `inserted' here and
4250 restore `point' iff format-decode did not insert or delete
4251 any text. Otherwise we leave `point' at point-min. */
4252 EMACS_INT opoint = PT;
4253 EMACS_INT opoint_byte = PT_BYTE;
4254 EMACS_INT oinserted = ZV - BEGV;
4255 int ochars_modiff = CHARS_MODIFF;
4256
4257 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4258 insval = call3 (Qformat_decode,
4259 Qnil, make_number (oinserted), visit);
4260 CHECK_NUMBER (insval);
4261 if (ochars_modiff == CHARS_MODIFF)
4262 /* format_decode didn't modify buffer's characters => move
4263 point back to position before inserted text and leave
4264 value of inserted alone. */
4265 SET_PT_BOTH (opoint, opoint_byte);
4266 else
4267 /* format_decode modified buffer's characters => consider
4268 entire buffer changed and leave point at point-min. */
4269 inserted = XFASTINT (insval);
4270 }
4271
4272 /* For consistency with format-decode call these now iff inserted > 0
4273 (martin 2007-06-28). */
4274 p = Vafter_insert_file_functions;
4275 while (CONSP (p))
4276 {
4277 if (NILP (replace))
4278 {
4279 insval = call1 (XCAR (p), make_number (inserted));
4280 if (!NILP (insval))
4281 {
4282 CHECK_NUMBER (insval);
4283 inserted = XFASTINT (insval);
4284 }
4285 }
4286 else
4287 {
4288 /* For the rationale of this see the comment on
4289 format-decode above. */
4290 EMACS_INT opoint = PT;
4291 EMACS_INT opoint_byte = PT_BYTE;
4292 EMACS_INT oinserted = ZV - BEGV;
4293 int ochars_modiff = CHARS_MODIFF;
4294
4295 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4296 insval = call1 (XCAR (p), make_number (oinserted));
4297 if (!NILP (insval))
4298 {
4299 CHECK_NUMBER (insval);
4300 if (ochars_modiff == CHARS_MODIFF)
4301 /* after_insert_file_functions didn't modify
4302 buffer's characters => move point back to
4303 position before inserted text and leave value of
4304 inserted alone. */
4305 SET_PT_BOTH (opoint, opoint_byte);
4306 else
4307 /* after_insert_file_functions did modify buffer's
4308 characters => consider entire buffer changed and
4309 leave point at point-min. */
4310 inserted = XFASTINT (insval);
4311 }
4312 }
4313
4314 QUIT;
4315 p = XCDR (p);
4316 }
4317
4318 if (NILP (visit))
4319 {
4320 current_buffer->undo_list = old_undo;
4321 if (CONSP (old_undo) && inserted != old_inserted)
4322 {
4323 /* Adjust the last undo record for the size change during
4324 the format conversion. */
4325 Lisp_Object tem = XCAR (old_undo);
4326 if (CONSP (tem) && INTEGERP (XCAR (tem))
4327 && INTEGERP (XCDR (tem))
4328 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4329 XSETCDR (tem, make_number (PT + inserted));
4330 }
4331 }
4332 else
4333 /* If undo_list was Qt before, keep it that way.
4334 Otherwise start with an empty undo_list. */
4335 current_buffer->undo_list = EQ (old_undo, Qt) ? Qt : Qnil;
4336
4337 unbind_to (count, Qnil);
4338 }
4339
4340 /* Call after-change hooks for the inserted text, aside from the case
4341 of normal visiting (not with REPLACE), which is done in a new buffer
4342 "before" the buffer is changed. */
4343 if (inserted > 0 && total > 0
4344 && (NILP (visit) || !NILP (replace)))
4345 {
4346 signal_after_change (PT, 0, inserted);
4347 update_compositions (PT, PT, CHECK_BORDER);
4348 }
4349
4350 if (!NILP (visit)
4351 && current_buffer->modtime == -1)
4352 {
4353 /* If visiting nonexistent file, return nil. */
4354 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4355 }
4356
4357 if (read_quit)
4358 Fsignal (Qquit, Qnil);
4359
4360 /* ??? Retval needs to be dealt with in all cases consistently. */
4361 if (NILP (val))
4362 val = Fcons (orig_filename,
4363 Fcons (make_number (inserted),
4364 Qnil));
4365
4366 RETURN_UNGCPRO (unbind_to (count, val));
4367 }
4368 \f
4369 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4370
4371 static Lisp_Object
4372 build_annotations_unwind (Lisp_Object arg)
4373 {
4374 Vwrite_region_annotation_buffers = arg;
4375 return Qnil;
4376 }
4377
4378 /* Decide the coding-system to encode the data with. */
4379
4380 static Lisp_Object
4381 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4382 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4383 struct coding_system *coding)
4384 {
4385 Lisp_Object val;
4386 Lisp_Object eol_parent = Qnil;
4387
4388 if (auto_saving
4389 && NILP (Fstring_equal (current_buffer->filename,
4390 current_buffer->auto_save_file_name)))
4391 {
4392 val = Qutf_8_emacs;
4393 eol_parent = Qunix;
4394 }
4395 else if (!NILP (Vcoding_system_for_write))
4396 {
4397 val = Vcoding_system_for_write;
4398 if (coding_system_require_warning
4399 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4400 /* Confirm that VAL can surely encode the current region. */
4401 val = call5 (Vselect_safe_coding_system_function,
4402 start, end, Fcons (Qt, Fcons (val, Qnil)),
4403 Qnil, filename);
4404 }
4405 else
4406 {
4407 /* If the variable `buffer-file-coding-system' is set locally,
4408 it means that the file was read with some kind of code
4409 conversion or the variable is explicitly set by users. We
4410 had better write it out with the same coding system even if
4411 `enable-multibyte-characters' is nil.
4412
4413 If it is not set locally, we anyway have to convert EOL
4414 format if the default value of `buffer-file-coding-system'
4415 tells that it is not Unix-like (LF only) format. */
4416 int using_default_coding = 0;
4417 int force_raw_text = 0;
4418
4419 val = current_buffer->buffer_file_coding_system;
4420 if (NILP (val)
4421 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4422 {
4423 val = Qnil;
4424 if (NILP (current_buffer->enable_multibyte_characters))
4425 force_raw_text = 1;
4426 }
4427
4428 if (NILP (val))
4429 {
4430 /* Check file-coding-system-alist. */
4431 Lisp_Object args[7], coding_systems;
4432
4433 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4434 args[3] = filename; args[4] = append; args[5] = visit;
4435 args[6] = lockname;
4436 coding_systems = Ffind_operation_coding_system (7, args);
4437 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4438 val = XCDR (coding_systems);
4439 }
4440
4441 if (NILP (val))
4442 {
4443 /* If we still have not decided a coding system, use the
4444 default value of buffer-file-coding-system. */
4445 val = current_buffer->buffer_file_coding_system;
4446 using_default_coding = 1;
4447 }
4448
4449 if (! NILP (val) && ! force_raw_text)
4450 {
4451 Lisp_Object spec, attrs;
4452
4453 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4454 attrs = AREF (spec, 0);
4455 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4456 force_raw_text = 1;
4457 }
4458
4459 if (!force_raw_text
4460 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4461 /* Confirm that VAL can surely encode the current region. */
4462 val = call5 (Vselect_safe_coding_system_function,
4463 start, end, val, Qnil, filename);
4464
4465 /* If the decided coding-system doesn't specify end-of-line
4466 format, we use that of
4467 `default-buffer-file-coding-system'. */
4468 if (! using_default_coding
4469 && ! NILP (buffer_defaults.buffer_file_coding_system))
4470 val = (coding_inherit_eol_type
4471 (val, buffer_defaults.buffer_file_coding_system));
4472
4473 /* If we decide not to encode text, use `raw-text' or one of its
4474 subsidiaries. */
4475 if (force_raw_text)
4476 val = raw_text_coding_system (val);
4477 }
4478
4479 val = coding_inherit_eol_type (val, eol_parent);
4480 setup_coding_system (val, coding);
4481
4482 if (!STRINGP (start) && !NILP (current_buffer->selective_display))
4483 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4484 return val;
4485 }
4486
4487 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4488 "r\nFWrite region to file: \ni\ni\ni\np",
4489 doc: /* Write current region into specified file.
4490 When called from a program, requires three arguments:
4491 START, END and FILENAME. START and END are normally buffer positions
4492 specifying the part of the buffer to write.
4493 If START is nil, that means to use the entire buffer contents.
4494 If START is a string, then output that string to the file
4495 instead of any buffer contents; END is ignored.
4496
4497 Optional fourth argument APPEND if non-nil means
4498 append to existing file contents (if any). If it is an integer,
4499 seek to that offset in the file before writing.
4500 Optional fifth argument VISIT, if t or a string, means
4501 set the last-save-file-modtime of buffer to this file's modtime
4502 and mark buffer not modified.
4503 If VISIT is a string, it is a second file name;
4504 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4505 VISIT is also the file name to lock and unlock for clash detection.
4506 If VISIT is neither t nor nil nor a string,
4507 that means do not display the \"Wrote file\" message.
4508 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4509 use for locking and unlocking, overriding FILENAME and VISIT.
4510 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4511 for an existing file with the same name. If MUSTBENEW is `excl',
4512 that means to get an error if the file already exists; never overwrite.
4513 If MUSTBENEW is neither nil nor `excl', that means ask for
4514 confirmation before overwriting, but do go ahead and overwrite the file
4515 if the user confirms.
4516
4517 This does code conversion according to the value of
4518 `coding-system-for-write', `buffer-file-coding-system', or
4519 `file-coding-system-alist', and sets the variable
4520 `last-coding-system-used' to the coding system actually used.
4521
4522 This calls `write-region-annotate-functions' at the start, and
4523 `write-region-post-annotation-function' at the end. */)
4524 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append, Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4525 {
4526 register int desc;
4527 int failure;
4528 int save_errno = 0;
4529 const unsigned char *fn;
4530 struct stat st;
4531 int count = SPECPDL_INDEX ();
4532 int count1;
4533 Lisp_Object handler;
4534 Lisp_Object visit_file;
4535 Lisp_Object annotations;
4536 Lisp_Object encoded_filename;
4537 int visiting = (EQ (visit, Qt) || STRINGP (visit));
4538 int quietly = !NILP (visit);
4539 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4540 struct buffer *given_buffer;
4541 #ifdef DOS_NT
4542 int buffer_file_type = O_BINARY;
4543 #endif /* DOS_NT */
4544 struct coding_system coding;
4545
4546 if (current_buffer->base_buffer && visiting)
4547 error ("Cannot do file visiting in an indirect buffer");
4548
4549 if (!NILP (start) && !STRINGP (start))
4550 validate_region (&start, &end);
4551
4552 visit_file = Qnil;
4553 GCPRO5 (start, filename, visit, visit_file, lockname);
4554
4555 filename = Fexpand_file_name (filename, Qnil);
4556
4557 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4558 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4559
4560 if (STRINGP (visit))
4561 visit_file = Fexpand_file_name (visit, Qnil);
4562 else
4563 visit_file = filename;
4564
4565 if (NILP (lockname))
4566 lockname = visit_file;
4567
4568 annotations = Qnil;
4569
4570 /* If the file name has special constructs in it,
4571 call the corresponding file handler. */
4572 handler = Ffind_file_name_handler (filename, Qwrite_region);
4573 /* If FILENAME has no handler, see if VISIT has one. */
4574 if (NILP (handler) && STRINGP (visit))
4575 handler = Ffind_file_name_handler (visit, Qwrite_region);
4576
4577 if (!NILP (handler))
4578 {
4579 Lisp_Object val;
4580 val = call6 (handler, Qwrite_region, start, end,
4581 filename, append, visit);
4582
4583 if (visiting)
4584 {
4585 SAVE_MODIFF = MODIFF;
4586 XSETFASTINT (current_buffer->save_length, Z - BEG);
4587 current_buffer->filename = visit_file;
4588 }
4589 UNGCPRO;
4590 return val;
4591 }
4592
4593 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4594
4595 /* Special kludge to simplify auto-saving. */
4596 if (NILP (start))
4597 {
4598 /* Do it later, so write-region-annotate-function can work differently
4599 if we save "the buffer" vs "a region".
4600 This is useful in tar-mode. --Stef
4601 XSETFASTINT (start, BEG);
4602 XSETFASTINT (end, Z); */
4603 Fwiden ();
4604 }
4605
4606 record_unwind_protect (build_annotations_unwind,
4607 Vwrite_region_annotation_buffers);
4608 Vwrite_region_annotation_buffers = Fcons (Fcurrent_buffer (), Qnil);
4609 count1 = SPECPDL_INDEX ();
4610
4611 given_buffer = current_buffer;
4612
4613 if (!STRINGP (start))
4614 {
4615 annotations = build_annotations (start, end);
4616
4617 if (current_buffer != given_buffer)
4618 {
4619 XSETFASTINT (start, BEGV);
4620 XSETFASTINT (end, ZV);
4621 }
4622 }
4623
4624 if (NILP (start))
4625 {
4626 XSETFASTINT (start, BEGV);
4627 XSETFASTINT (end, ZV);
4628 }
4629
4630 UNGCPRO;
4631
4632 GCPRO5 (start, filename, annotations, visit_file, lockname);
4633
4634 /* Decide the coding-system to encode the data with.
4635 We used to make this choice before calling build_annotations, but that
4636 leads to problems when a write-annotate-function takes care of
4637 unsavable chars (as was the case with X-Symbol). */
4638 Vlast_coding_system_used
4639 = choose_write_coding_system (start, end, filename,
4640 append, visit, lockname, &coding);
4641
4642 #ifdef CLASH_DETECTION
4643 if (!auto_saving)
4644 lock_file (lockname);
4645 #endif /* CLASH_DETECTION */
4646
4647 encoded_filename = ENCODE_FILE (filename);
4648
4649 fn = SDATA (encoded_filename);
4650 desc = -1;
4651 if (!NILP (append))
4652 #ifdef DOS_NT
4653 desc = emacs_open (fn, O_WRONLY | buffer_file_type, 0);
4654 #else /* not DOS_NT */
4655 desc = emacs_open (fn, O_WRONLY, 0);
4656 #endif /* not DOS_NT */
4657
4658 if (desc < 0 && (NILP (append) || errno == ENOENT))
4659 #ifdef DOS_NT
4660 desc = emacs_open (fn,
4661 O_WRONLY | O_CREAT | buffer_file_type
4662 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
4663 S_IREAD | S_IWRITE);
4664 #else /* not DOS_NT */
4665 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
4666 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
4667 auto_saving ? auto_save_mode_bits : 0666);
4668 #endif /* not DOS_NT */
4669
4670 if (desc < 0)
4671 {
4672 #ifdef CLASH_DETECTION
4673 save_errno = errno;
4674 if (!auto_saving) unlock_file (lockname);
4675 errno = save_errno;
4676 #endif /* CLASH_DETECTION */
4677 UNGCPRO;
4678 report_file_error ("Opening output file", Fcons (filename, Qnil));
4679 }
4680
4681 record_unwind_protect (close_file_unwind, make_number (desc));
4682
4683 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
4684 {
4685 long ret;
4686
4687 if (NUMBERP (append))
4688 ret = lseek (desc, XINT (append), 1);
4689 else
4690 ret = lseek (desc, 0, 2);
4691 if (ret < 0)
4692 {
4693 #ifdef CLASH_DETECTION
4694 if (!auto_saving) unlock_file (lockname);
4695 #endif /* CLASH_DETECTION */
4696 UNGCPRO;
4697 report_file_error ("Lseek error", Fcons (filename, Qnil));
4698 }
4699 }
4700
4701 UNGCPRO;
4702
4703 failure = 0;
4704 immediate_quit = 1;
4705
4706 if (STRINGP (start))
4707 {
4708 failure = 0 > a_write (desc, start, 0, SCHARS (start),
4709 &annotations, &coding);
4710 save_errno = errno;
4711 }
4712 else if (XINT (start) != XINT (end))
4713 {
4714 failure = 0 > a_write (desc, Qnil,
4715 XINT (start), XINT (end) - XINT (start),
4716 &annotations, &coding);
4717 save_errno = errno;
4718 }
4719 else
4720 {
4721 /* If file was empty, still need to write the annotations */
4722 coding.mode |= CODING_MODE_LAST_BLOCK;
4723 failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4724 save_errno = errno;
4725 }
4726
4727 if (CODING_REQUIRE_FLUSHING (&coding)
4728 && !(coding.mode & CODING_MODE_LAST_BLOCK)
4729 && ! failure)
4730 {
4731 /* We have to flush out a data. */
4732 coding.mode |= CODING_MODE_LAST_BLOCK;
4733 failure = 0 > e_write (desc, Qnil, 1, 1, &coding);
4734 save_errno = errno;
4735 }
4736
4737 immediate_quit = 0;
4738
4739 #ifdef HAVE_FSYNC
4740 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4741 Disk full in NFS may be reported here. */
4742 /* mib says that closing the file will try to write as fast as NFS can do
4743 it, and that means the fsync here is not crucial for autosave files. */
4744 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
4745 {
4746 /* If fsync fails with EINTR, don't treat that as serious. Also
4747 ignore EINVAL which happens when fsync is not supported on this
4748 file. */
4749 if (errno != EINTR && errno != EINVAL)
4750 failure = 1, save_errno = errno;
4751 }
4752 #endif
4753
4754 /* NFS can report a write failure now. */
4755 if (emacs_close (desc) < 0)
4756 failure = 1, save_errno = errno;
4757
4758 stat (fn, &st);
4759
4760 /* Discard the unwind protect for close_file_unwind. */
4761 specpdl_ptr = specpdl + count1;
4762
4763 /* Call write-region-post-annotation-function. */
4764 while (CONSP (Vwrite_region_annotation_buffers))
4765 {
4766 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4767 if (!NILP (Fbuffer_live_p (buf)))
4768 {
4769 Fset_buffer (buf);
4770 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4771 call0 (Vwrite_region_post_annotation_function);
4772 }
4773 Vwrite_region_annotation_buffers
4774 = XCDR (Vwrite_region_annotation_buffers);
4775 }
4776
4777 unbind_to (count, Qnil);
4778
4779 #ifdef CLASH_DETECTION
4780 if (!auto_saving)
4781 unlock_file (lockname);
4782 #endif /* CLASH_DETECTION */
4783
4784 /* Do this before reporting IO error
4785 to avoid a "file has changed on disk" warning on
4786 next attempt to save. */
4787 if (visiting)
4788 {
4789 current_buffer->modtime = st.st_mtime;
4790 current_buffer->modtime_size = st.st_size;
4791 }
4792
4793 if (failure)
4794 error ("IO error writing %s: %s", SDATA (filename),
4795 emacs_strerror (save_errno));
4796
4797 if (visiting)
4798 {
4799 SAVE_MODIFF = MODIFF;
4800 XSETFASTINT (current_buffer->save_length, Z - BEG);
4801 current_buffer->filename = visit_file;
4802 update_mode_lines++;
4803 }
4804 else if (quietly)
4805 {
4806 if (auto_saving
4807 && ! NILP (Fstring_equal (current_buffer->filename,
4808 current_buffer->auto_save_file_name)))
4809 SAVE_MODIFF = MODIFF;
4810
4811 return Qnil;
4812 }
4813
4814 if (!auto_saving)
4815 message_with_string ((INTEGERP (append)
4816 ? "Updated %s"
4817 : ! NILP (append)
4818 ? "Added to %s"
4819 : "Wrote %s"),
4820 visit_file, 1);
4821
4822 return Qnil;
4823 }
4824 \f
4825 Lisp_Object merge (Lisp_Object, Lisp_Object, Lisp_Object);
4826
4827 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4828 doc: /* Return t if (car A) is numerically less than (car B). */)
4829 (Lisp_Object a, Lisp_Object b)
4830 {
4831 return Flss (Fcar (a), Fcar (b));
4832 }
4833
4834 /* Build the complete list of annotations appropriate for writing out
4835 the text between START and END, by calling all the functions in
4836 write-region-annotate-functions and merging the lists they return.
4837 If one of these functions switches to a different buffer, we assume
4838 that buffer contains altered text. Therefore, the caller must
4839 make sure to restore the current buffer in all cases,
4840 as save-excursion would do. */
4841
4842 static Lisp_Object
4843 build_annotations (Lisp_Object start, Lisp_Object end)
4844 {
4845 Lisp_Object annotations;
4846 Lisp_Object p, res;
4847 struct gcpro gcpro1, gcpro2;
4848 Lisp_Object original_buffer;
4849 int i, used_global = 0;
4850
4851 XSETBUFFER (original_buffer, current_buffer);
4852
4853 annotations = Qnil;
4854 p = Vwrite_region_annotate_functions;
4855 GCPRO2 (annotations, p);
4856 while (CONSP (p))
4857 {
4858 struct buffer *given_buffer = current_buffer;
4859 if (EQ (Qt, XCAR (p)) && !used_global)
4860 { /* Use the global value of the hook. */
4861 Lisp_Object arg[2];
4862 used_global = 1;
4863 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
4864 arg[1] = XCDR (p);
4865 p = Fappend (2, arg);
4866 continue;
4867 }
4868 Vwrite_region_annotations_so_far = annotations;
4869 res = call2 (XCAR (p), start, end);
4870 /* If the function makes a different buffer current,
4871 assume that means this buffer contains altered text to be output.
4872 Reset START and END from the buffer bounds
4873 and discard all previous annotations because they should have
4874 been dealt with by this function. */
4875 if (current_buffer != given_buffer)
4876 {
4877 Vwrite_region_annotation_buffers
4878 = Fcons (Fcurrent_buffer (),
4879 Vwrite_region_annotation_buffers);
4880 XSETFASTINT (start, BEGV);
4881 XSETFASTINT (end, ZV);
4882 annotations = Qnil;
4883 }
4884 Flength (res); /* Check basic validity of return value */
4885 annotations = merge (annotations, res, Qcar_less_than_car);
4886 p = XCDR (p);
4887 }
4888
4889 /* Now do the same for annotation functions implied by the file-format */
4890 if (auto_saving && (!EQ (current_buffer->auto_save_file_format, Qt)))
4891 p = current_buffer->auto_save_file_format;
4892 else
4893 p = current_buffer->file_format;
4894 for (i = 0; CONSP (p); p = XCDR (p), ++i)
4895 {
4896 struct buffer *given_buffer = current_buffer;
4897
4898 Vwrite_region_annotations_so_far = annotations;
4899
4900 /* Value is either a list of annotations or nil if the function
4901 has written annotations to a temporary buffer, which is now
4902 current. */
4903 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
4904 original_buffer, make_number (i));
4905 if (current_buffer != given_buffer)
4906 {
4907 XSETFASTINT (start, BEGV);
4908 XSETFASTINT (end, ZV);
4909 annotations = Qnil;
4910 }
4911
4912 if (CONSP (res))
4913 annotations = merge (annotations, res, Qcar_less_than_car);
4914 }
4915
4916 UNGCPRO;
4917 return annotations;
4918 }
4919
4920 \f
4921 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
4922 If STRING is nil, POS is the character position in the current buffer.
4923 Intersperse with them the annotations from *ANNOT
4924 which fall within the range of POS to POS + NCHARS,
4925 each at its appropriate position.
4926
4927 We modify *ANNOT by discarding elements as we use them up.
4928
4929 The return value is negative in case of system call failure. */
4930
4931 static int
4932 a_write (int desc, Lisp_Object string, int pos, register int nchars, Lisp_Object *annot, struct coding_system *coding)
4933 {
4934 Lisp_Object tem;
4935 int nextpos;
4936 int lastpos = pos + nchars;
4937
4938 while (NILP (*annot) || CONSP (*annot))
4939 {
4940 tem = Fcar_safe (Fcar (*annot));
4941 nextpos = pos - 1;
4942 if (INTEGERP (tem))
4943 nextpos = XFASTINT (tem);
4944
4945 /* If there are no more annotations in this range,
4946 output the rest of the range all at once. */
4947 if (! (nextpos >= pos && nextpos <= lastpos))
4948 return e_write (desc, string, pos, lastpos, coding);
4949
4950 /* Output buffer text up to the next annotation's position. */
4951 if (nextpos > pos)
4952 {
4953 if (0 > e_write (desc, string, pos, nextpos, coding))
4954 return -1;
4955 pos = nextpos;
4956 }
4957 /* Output the annotation. */
4958 tem = Fcdr (Fcar (*annot));
4959 if (STRINGP (tem))
4960 {
4961 if (0 > e_write (desc, tem, 0, SCHARS (tem), coding))
4962 return -1;
4963 }
4964 *annot = Fcdr (*annot);
4965 }
4966 return 0;
4967 }
4968
4969
4970 /* Write text in the range START and END into descriptor DESC,
4971 encoding them with coding system CODING. If STRING is nil, START
4972 and END are character positions of the current buffer, else they
4973 are indexes to the string STRING. */
4974
4975 static int
4976 e_write (int desc, Lisp_Object string, int start, int end, struct coding_system *coding)
4977 {
4978 if (STRINGP (string))
4979 {
4980 start = 0;
4981 end = SCHARS (string);
4982 }
4983
4984 /* We used to have a code for handling selective display here. But,
4985 now it is handled within encode_coding. */
4986
4987 while (start < end)
4988 {
4989 if (STRINGP (string))
4990 {
4991 coding->src_multibyte = SCHARS (string) < SBYTES (string);
4992 if (CODING_REQUIRE_ENCODING (coding))
4993 {
4994 encode_coding_object (coding, string,
4995 start, string_char_to_byte (string, start),
4996 end, string_char_to_byte (string, end), Qt);
4997 }
4998 else
4999 {
5000 coding->dst_object = string;
5001 coding->consumed_char = SCHARS (string);
5002 coding->produced = SBYTES (string);
5003 }
5004 }
5005 else
5006 {
5007 int start_byte = CHAR_TO_BYTE (start);
5008 int end_byte = CHAR_TO_BYTE (end);
5009
5010 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5011 if (CODING_REQUIRE_ENCODING (coding))
5012 {
5013 encode_coding_object (coding, Fcurrent_buffer (),
5014 start, start_byte, end, end_byte, Qt);
5015 }
5016 else
5017 {
5018 coding->dst_object = Qnil;
5019 coding->dst_pos_byte = start_byte;
5020 if (start >= GPT || end <= GPT)
5021 {
5022 coding->consumed_char = end - start;
5023 coding->produced = end_byte - start_byte;
5024 }
5025 else
5026 {
5027 coding->consumed_char = GPT - start;
5028 coding->produced = GPT_BYTE - start_byte;
5029 }
5030 }
5031 }
5032
5033 if (coding->produced > 0)
5034 {
5035 coding->produced -=
5036 emacs_write (desc,
5037 STRINGP (coding->dst_object)
5038 ? SDATA (coding->dst_object)
5039 : BYTE_POS_ADDR (coding->dst_pos_byte),
5040 coding->produced);
5041
5042 if (coding->produced)
5043 return -1;
5044 }
5045 start += coding->consumed_char;
5046 }
5047
5048 return 0;
5049 }
5050 \f
5051 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5052 Sverify_visited_file_modtime, 0, 1, 0,
5053 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5054 This means that the file has not been changed since it was visited or saved.
5055 If BUF is omitted or nil, it defaults to the current buffer.
5056 See Info node `(elisp)Modification Time' for more details. */)
5057 (Lisp_Object buf)
5058 {
5059 struct buffer *b;
5060 struct stat st;
5061 Lisp_Object handler;
5062 Lisp_Object filename;
5063
5064 if (NILP (buf))
5065 b = current_buffer;
5066 else
5067 {
5068 CHECK_BUFFER (buf);
5069 b = XBUFFER (buf);
5070 }
5071
5072 if (!STRINGP (b->filename)) return Qt;
5073 if (b->modtime == 0) return Qt;
5074
5075 /* If the file name has special constructs in it,
5076 call the corresponding file handler. */
5077 handler = Ffind_file_name_handler (b->filename,
5078 Qverify_visited_file_modtime);
5079 if (!NILP (handler))
5080 return call2 (handler, Qverify_visited_file_modtime, buf);
5081
5082 filename = ENCODE_FILE (b->filename);
5083
5084 if (stat (SDATA (filename), &st) < 0)
5085 {
5086 /* If the file doesn't exist now and didn't exist before,
5087 we say that it isn't modified, provided the error is a tame one. */
5088 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
5089 st.st_mtime = -1;
5090 else
5091 st.st_mtime = 0;
5092 }
5093 if ((st.st_mtime == b->modtime
5094 /* If both are positive, accept them if they are off by one second. */
5095 || (st.st_mtime > 0 && b->modtime > 0
5096 && (st.st_mtime == b->modtime + 1
5097 || st.st_mtime == b->modtime - 1)))
5098 && (st.st_size == b->modtime_size
5099 || b->modtime_size < 0))
5100 return Qt;
5101 return Qnil;
5102 }
5103
5104 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5105 Sclear_visited_file_modtime, 0, 0, 0,
5106 doc: /* Clear out records of last mod time of visited file.
5107 Next attempt to save will certainly not complain of a discrepancy. */)
5108 (void)
5109 {
5110 current_buffer->modtime = 0;
5111 current_buffer->modtime_size = -1;
5112 return Qnil;
5113 }
5114
5115 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5116 Svisited_file_modtime, 0, 0, 0,
5117 doc: /* Return the current buffer's recorded visited file modification time.
5118 The value is a list of the form (HIGH LOW), like the time values
5119 that `file-attributes' returns. If the current buffer has no recorded
5120 file modification time, this function returns 0.
5121 See Info node `(elisp)Modification Time' for more details. */)
5122 (void)
5123 {
5124 if (! current_buffer->modtime)
5125 return make_number (0);
5126 return make_time ((time_t) current_buffer->modtime);
5127 }
5128
5129 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5130 Sset_visited_file_modtime, 0, 1, 0,
5131 doc: /* Update buffer's recorded modification time from the visited file's time.
5132 Useful if the buffer was not read from the file normally
5133 or if the file itself has been changed for some known benign reason.
5134 An argument specifies the modification time value to use
5135 \(instead of that of the visited file), in the form of a list
5136 \(HIGH . LOW) or (HIGH LOW). */)
5137 (Lisp_Object time_list)
5138 {
5139 if (!NILP (time_list))
5140 {
5141 current_buffer->modtime = cons_to_long (time_list);
5142 current_buffer->modtime_size = -1;
5143 }
5144 else
5145 {
5146 register Lisp_Object filename;
5147 struct stat st;
5148 Lisp_Object handler;
5149
5150 filename = Fexpand_file_name (current_buffer->filename, Qnil);
5151
5152 /* If the file name has special constructs in it,
5153 call the corresponding file handler. */
5154 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5155 if (!NILP (handler))
5156 /* The handler can find the file name the same way we did. */
5157 return call2 (handler, Qset_visited_file_modtime, Qnil);
5158
5159 filename = ENCODE_FILE (filename);
5160
5161 if (stat (SDATA (filename), &st) >= 0)
5162 {
5163 current_buffer->modtime = st.st_mtime;
5164 current_buffer->modtime_size = st.st_size;
5165 }
5166 }
5167
5168 return Qnil;
5169 }
5170 \f
5171 Lisp_Object
5172 auto_save_error (Lisp_Object error)
5173 {
5174 Lisp_Object args[3], msg;
5175 int i, nbytes;
5176 struct gcpro gcpro1;
5177 char *msgbuf;
5178 USE_SAFE_ALLOCA;
5179
5180 auto_save_error_occurred = 1;
5181
5182 ring_bell (XFRAME (selected_frame));
5183
5184 args[0] = build_string ("Auto-saving %s: %s");
5185 args[1] = current_buffer->name;
5186 args[2] = Ferror_message_string (error);
5187 msg = Fformat (3, args);
5188 GCPRO1 (msg);
5189 nbytes = SBYTES (msg);
5190 SAFE_ALLOCA (msgbuf, char *, nbytes);
5191 memcpy (msgbuf, SDATA (msg), nbytes);
5192
5193 for (i = 0; i < 3; ++i)
5194 {
5195 if (i == 0)
5196 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5197 else
5198 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5199 Fsleep_for (make_number (1), Qnil);
5200 }
5201
5202 SAFE_FREE ();
5203 UNGCPRO;
5204 return Qnil;
5205 }
5206
5207 Lisp_Object
5208 auto_save_1 (void)
5209 {
5210 struct stat st;
5211 Lisp_Object modes;
5212
5213 auto_save_mode_bits = 0666;
5214
5215 /* Get visited file's mode to become the auto save file's mode. */
5216 if (! NILP (current_buffer->filename))
5217 {
5218 if (stat (SDATA (current_buffer->filename), &st) >= 0)
5219 /* But make sure we can overwrite it later! */
5220 auto_save_mode_bits = st.st_mode | 0600;
5221 else if ((modes = Ffile_modes (current_buffer->filename),
5222 INTEGERP (modes)))
5223 /* Remote files don't cooperate with stat. */
5224 auto_save_mode_bits = XINT (modes) | 0600;
5225 }
5226
5227 return
5228 Fwrite_region (Qnil, Qnil, current_buffer->auto_save_file_name, Qnil,
5229 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5230 Qnil, Qnil);
5231 }
5232
5233 static Lisp_Object
5234 do_auto_save_unwind (Lisp_Object arg) /* used as unwind-protect function */
5235
5236 {
5237 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5238 auto_saving = 0;
5239 if (stream != NULL)
5240 {
5241 BLOCK_INPUT;
5242 fclose (stream);
5243 UNBLOCK_INPUT;
5244 }
5245 return Qnil;
5246 }
5247
5248 static Lisp_Object
5249 do_auto_save_unwind_1 (Lisp_Object value) /* used as unwind-protect function */
5250
5251 {
5252 minibuffer_auto_raise = XINT (value);
5253 return Qnil;
5254 }
5255
5256 static Lisp_Object
5257 do_auto_save_make_dir (Lisp_Object dir)
5258 {
5259 Lisp_Object mode;
5260
5261 call2 (Qmake_directory, dir, Qt);
5262 XSETFASTINT (mode, 0700);
5263 return Fset_file_modes (dir, mode);
5264 }
5265
5266 static Lisp_Object
5267 do_auto_save_eh (Lisp_Object ignore)
5268 {
5269 return Qnil;
5270 }
5271
5272 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5273 doc: /* Auto-save all buffers that need it.
5274 This is all buffers that have auto-saving enabled
5275 and are changed since last auto-saved.
5276 Auto-saving writes the buffer into a file
5277 so that your editing is not lost if the system crashes.
5278 This file is not the file you visited; that changes only when you save.
5279 Normally we run the normal hook `auto-save-hook' before saving.
5280
5281 A non-nil NO-MESSAGE argument means do not print any message if successful.
5282 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5283 (Lisp_Object no_message, Lisp_Object current_only)
5284 {
5285 struct buffer *old = current_buffer, *b;
5286 Lisp_Object tail, buf;
5287 int auto_saved = 0;
5288 int do_handled_files;
5289 Lisp_Object oquit;
5290 FILE *stream = NULL;
5291 int count = SPECPDL_INDEX ();
5292 int orig_minibuffer_auto_raise = minibuffer_auto_raise;
5293 int old_message_p = 0;
5294 struct gcpro gcpro1, gcpro2;
5295
5296 if (max_specpdl_size < specpdl_size + 40)
5297 max_specpdl_size = specpdl_size + 40;
5298
5299 if (minibuf_level)
5300 no_message = Qt;
5301
5302 if (NILP (no_message))
5303 {
5304 old_message_p = push_message ();
5305 record_unwind_protect (pop_message_unwind, Qnil);
5306 }
5307
5308 /* Ordinarily don't quit within this function,
5309 but don't make it impossible to quit (in case we get hung in I/O). */
5310 oquit = Vquit_flag;
5311 Vquit_flag = Qnil;
5312
5313 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5314 point to non-strings reached from Vbuffer_alist. */
5315
5316 if (!NILP (Vrun_hooks))
5317 call1 (Vrun_hooks, intern ("auto-save-hook"));
5318
5319 if (STRINGP (Vauto_save_list_file_name))
5320 {
5321 Lisp_Object listfile;
5322
5323 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5324
5325 /* Don't try to create the directory when shutting down Emacs,
5326 because creating the directory might signal an error, and
5327 that would leave Emacs in a strange state. */
5328 if (!NILP (Vrun_hooks))
5329 {
5330 Lisp_Object dir;
5331 dir = Qnil;
5332 GCPRO2 (dir, listfile);
5333 dir = Ffile_name_directory (listfile);
5334 if (NILP (Ffile_directory_p (dir)))
5335 internal_condition_case_1 (do_auto_save_make_dir,
5336 dir, Fcons (Fcons (Qfile_error, Qnil), Qnil),
5337 do_auto_save_eh);
5338 UNGCPRO;
5339 }
5340
5341 stream = fopen (SDATA (listfile), "w");
5342 }
5343
5344 record_unwind_protect (do_auto_save_unwind,
5345 make_save_value (stream, 0));
5346 record_unwind_protect (do_auto_save_unwind_1,
5347 make_number (minibuffer_auto_raise));
5348 minibuffer_auto_raise = 0;
5349 auto_saving = 1;
5350 auto_save_error_occurred = 0;
5351
5352 /* On first pass, save all files that don't have handlers.
5353 On second pass, save all files that do have handlers.
5354
5355 If Emacs is crashing, the handlers may tweak what is causing
5356 Emacs to crash in the first place, and it would be a shame if
5357 Emacs failed to autosave perfectly ordinary files because it
5358 couldn't handle some ange-ftp'd file. */
5359
5360 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5361 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5362 {
5363 buf = XCDR (XCAR (tail));
5364 b = XBUFFER (buf);
5365
5366 /* Record all the buffers that have auto save mode
5367 in the special file that lists them. For each of these buffers,
5368 Record visited name (if any) and auto save name. */
5369 if (STRINGP (b->auto_save_file_name)
5370 && stream != NULL && do_handled_files == 0)
5371 {
5372 BLOCK_INPUT;
5373 if (!NILP (b->filename))
5374 {
5375 fwrite (SDATA (b->filename), 1,
5376 SBYTES (b->filename), stream);
5377 }
5378 putc ('\n', stream);
5379 fwrite (SDATA (b->auto_save_file_name), 1,
5380 SBYTES (b->auto_save_file_name), stream);
5381 putc ('\n', stream);
5382 UNBLOCK_INPUT;
5383 }
5384
5385 if (!NILP (current_only)
5386 && b != current_buffer)
5387 continue;
5388
5389 /* Don't auto-save indirect buffers.
5390 The base buffer takes care of it. */
5391 if (b->base_buffer)
5392 continue;
5393
5394 /* Check for auto save enabled
5395 and file changed since last auto save
5396 and file changed since last real save. */
5397 if (STRINGP (b->auto_save_file_name)
5398 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5399 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5400 /* -1 means we've turned off autosaving for a while--see below. */
5401 && XINT (b->save_length) >= 0
5402 && (do_handled_files
5403 || NILP (Ffind_file_name_handler (b->auto_save_file_name,
5404 Qwrite_region))))
5405 {
5406 EMACS_TIME before_time, after_time;
5407
5408 EMACS_GET_TIME (before_time);
5409
5410 /* If we had a failure, don't try again for 20 minutes. */
5411 if (b->auto_save_failure_time >= 0
5412 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5413 continue;
5414
5415 set_buffer_internal (b);
5416 if (NILP (Vauto_save_include_big_deletions)
5417 && (XFASTINT (b->save_length) * 10
5418 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5419 /* A short file is likely to change a large fraction;
5420 spare the user annoying messages. */
5421 && XFASTINT (b->save_length) > 5000
5422 /* These messages are frequent and annoying for `*mail*'. */
5423 && !EQ (b->filename, Qnil)
5424 && NILP (no_message))
5425 {
5426 /* It has shrunk too much; turn off auto-saving here. */
5427 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5428 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5429 b->name, 1);
5430 minibuffer_auto_raise = 0;
5431 /* Turn off auto-saving until there's a real save,
5432 and prevent any more warnings. */
5433 XSETINT (b->save_length, -1);
5434 Fsleep_for (make_number (1), Qnil);
5435 continue;
5436 }
5437 if (!auto_saved && NILP (no_message))
5438 message1 ("Auto-saving...");
5439 internal_condition_case (auto_save_1, Qt, auto_save_error);
5440 auto_saved++;
5441 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5442 XSETFASTINT (current_buffer->save_length, Z - BEG);
5443 set_buffer_internal (old);
5444
5445 EMACS_GET_TIME (after_time);
5446
5447 /* If auto-save took more than 60 seconds,
5448 assume it was an NFS failure that got a timeout. */
5449 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5450 b->auto_save_failure_time = EMACS_SECS (after_time);
5451 }
5452 }
5453
5454 /* Prevent another auto save till enough input events come in. */
5455 record_auto_save ();
5456
5457 if (auto_saved && NILP (no_message))
5458 {
5459 if (old_message_p)
5460 {
5461 /* If we are going to restore an old message,
5462 give time to read ours. */
5463 sit_for (make_number (1), 0, 0);
5464 restore_message ();
5465 }
5466 else if (!auto_save_error_occurred)
5467 /* Don't overwrite the error message if an error occurred.
5468 If we displayed a message and then restored a state
5469 with no message, leave a "done" message on the screen. */
5470 message1 ("Auto-saving...done");
5471 }
5472
5473 Vquit_flag = oquit;
5474
5475 /* This restores the message-stack status. */
5476 unbind_to (count, Qnil);
5477 return Qnil;
5478 }
5479
5480 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5481 Sset_buffer_auto_saved, 0, 0, 0,
5482 doc: /* Mark current buffer as auto-saved with its current text.
5483 No auto-save file will be written until the buffer changes again. */)
5484 (void)
5485 {
5486 /* FIXME: This should not be called in indirect buffers, since
5487 they're not autosaved. */
5488 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5489 XSETFASTINT (current_buffer->save_length, Z - BEG);
5490 current_buffer->auto_save_failure_time = -1;
5491 return Qnil;
5492 }
5493
5494 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5495 Sclear_buffer_auto_save_failure, 0, 0, 0,
5496 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5497 (void)
5498 {
5499 current_buffer->auto_save_failure_time = -1;
5500 return Qnil;
5501 }
5502
5503 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5504 0, 0, 0,
5505 doc: /* Return t if current buffer has been auto-saved recently.
5506 More precisely, if it has been auto-saved since last read from or saved
5507 in the visited file. If the buffer has no visited file,
5508 then any auto-save counts as "recent". */)
5509 (void)
5510 {
5511 /* FIXME: maybe we should return nil for indirect buffers since
5512 they're never autosaved. */
5513 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5514 }
5515 \f
5516 /* Reading and completing file names */
5517
5518 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5519 Snext_read_file_uses_dialog_p, 0, 0, 0,
5520 doc: /* Return t if a call to `read-file-name' will use a dialog.
5521 The return value is only relevant for a call to `read-file-name' that happens
5522 before any other event (mouse or keypress) is handled. */)
5523 (void)
5524 {
5525 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK)
5526 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5527 && use_dialog_box
5528 && use_file_dialog
5529 && have_menus_p ())
5530 return Qt;
5531 #endif
5532 return Qnil;
5533 }
5534
5535 Lisp_Object
5536 Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
5537 {
5538 struct gcpro gcpro1, gcpro2;
5539 Lisp_Object args[7];
5540
5541 GCPRO1 (default_filename);
5542 args[0] = intern ("read-file-name");
5543 args[1] = prompt;
5544 args[2] = dir;
5545 args[3] = default_filename;
5546 args[4] = mustmatch;
5547 args[5] = initial;
5548 args[6] = predicate;
5549 RETURN_UNGCPRO (Ffuncall (7, args));
5550 }
5551
5552 \f
5553 void
5554 syms_of_fileio (void)
5555 {
5556 Qoperations = intern_c_string ("operations");
5557 Qexpand_file_name = intern_c_string ("expand-file-name");
5558 Qsubstitute_in_file_name = intern_c_string ("substitute-in-file-name");
5559 Qdirectory_file_name = intern_c_string ("directory-file-name");
5560 Qfile_name_directory = intern_c_string ("file-name-directory");
5561 Qfile_name_nondirectory = intern_c_string ("file-name-nondirectory");
5562 Qunhandled_file_name_directory = intern_c_string ("unhandled-file-name-directory");
5563 Qfile_name_as_directory = intern_c_string ("file-name-as-directory");
5564 Qcopy_file = intern_c_string ("copy-file");
5565 Qmake_directory_internal = intern_c_string ("make-directory-internal");
5566 Qmake_directory = intern_c_string ("make-directory");
5567 Qdelete_directory_internal = intern_c_string ("delete-directory-internal");
5568 Qdelete_file = intern_c_string ("delete-file");
5569 Qrename_file = intern_c_string ("rename-file");
5570 Qadd_name_to_file = intern_c_string ("add-name-to-file");
5571 Qmake_symbolic_link = intern_c_string ("make-symbolic-link");
5572 Qfile_exists_p = intern_c_string ("file-exists-p");
5573 Qfile_executable_p = intern_c_string ("file-executable-p");
5574 Qfile_readable_p = intern_c_string ("file-readable-p");
5575 Qfile_writable_p = intern_c_string ("file-writable-p");
5576 Qfile_symlink_p = intern_c_string ("file-symlink-p");
5577 Qaccess_file = intern_c_string ("access-file");
5578 Qfile_directory_p = intern_c_string ("file-directory-p");
5579 Qfile_regular_p = intern_c_string ("file-regular-p");
5580 Qfile_accessible_directory_p = intern_c_string ("file-accessible-directory-p");
5581 Qfile_modes = intern_c_string ("file-modes");
5582 Qset_file_modes = intern_c_string ("set-file-modes");
5583 Qset_file_times = intern_c_string ("set-file-times");
5584 Qfile_selinux_context = intern_c_string("file-selinux-context");
5585 Qset_file_selinux_context = intern_c_string("set-file-selinux-context");
5586 Qfile_newer_than_file_p = intern_c_string ("file-newer-than-file-p");
5587 Qinsert_file_contents = intern_c_string ("insert-file-contents");
5588 Qwrite_region = intern_c_string ("write-region");
5589 Qverify_visited_file_modtime = intern_c_string ("verify-visited-file-modtime");
5590 Qset_visited_file_modtime = intern_c_string ("set-visited-file-modtime");
5591 Qauto_save_coding = intern_c_string ("auto-save-coding");
5592
5593 staticpro (&Qoperations);
5594 staticpro (&Qexpand_file_name);
5595 staticpro (&Qsubstitute_in_file_name);
5596 staticpro (&Qdirectory_file_name);
5597 staticpro (&Qfile_name_directory);
5598 staticpro (&Qfile_name_nondirectory);
5599 staticpro (&Qunhandled_file_name_directory);
5600 staticpro (&Qfile_name_as_directory);
5601 staticpro (&Qcopy_file);
5602 staticpro (&Qmake_directory_internal);
5603 staticpro (&Qmake_directory);
5604 staticpro (&Qdelete_directory_internal);
5605 staticpro (&Qdelete_file);
5606 staticpro (&Qrename_file);
5607 staticpro (&Qadd_name_to_file);
5608 staticpro (&Qmake_symbolic_link);
5609 staticpro (&Qfile_exists_p);
5610 staticpro (&Qfile_executable_p);
5611 staticpro (&Qfile_readable_p);
5612 staticpro (&Qfile_writable_p);
5613 staticpro (&Qaccess_file);
5614 staticpro (&Qfile_symlink_p);
5615 staticpro (&Qfile_directory_p);
5616 staticpro (&Qfile_regular_p);
5617 staticpro (&Qfile_accessible_directory_p);
5618 staticpro (&Qfile_modes);
5619 staticpro (&Qset_file_modes);
5620 staticpro (&Qset_file_times);
5621 staticpro (&Qfile_selinux_context);
5622 staticpro (&Qset_file_selinux_context);
5623 staticpro (&Qfile_newer_than_file_p);
5624 staticpro (&Qinsert_file_contents);
5625 staticpro (&Qwrite_region);
5626 staticpro (&Qverify_visited_file_modtime);
5627 staticpro (&Qset_visited_file_modtime);
5628 staticpro (&Qauto_save_coding);
5629
5630 Qfile_name_history = intern_c_string ("file-name-history");
5631 Fset (Qfile_name_history, Qnil);
5632 staticpro (&Qfile_name_history);
5633
5634 Qfile_error = intern_c_string ("file-error");
5635 staticpro (&Qfile_error);
5636 Qfile_already_exists = intern_c_string ("file-already-exists");
5637 staticpro (&Qfile_already_exists);
5638 Qfile_date_error = intern_c_string ("file-date-error");
5639 staticpro (&Qfile_date_error);
5640 Qexcl = intern_c_string ("excl");
5641 staticpro (&Qexcl);
5642
5643 #ifdef DOS_NT
5644 Qfind_buffer_file_type = intern_c_string ("find-buffer-file-type");
5645 staticpro (&Qfind_buffer_file_type);
5646 #endif /* DOS_NT */
5647
5648 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system,
5649 doc: /* *Coding system for encoding file names.
5650 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5651 Vfile_name_coding_system = Qnil;
5652
5653 DEFVAR_LISP ("default-file-name-coding-system",
5654 &Vdefault_file_name_coding_system,
5655 doc: /* Default coding system for encoding file names.
5656 This variable is used only when `file-name-coding-system' is nil.
5657
5658 This variable is set/changed by the command `set-language-environment'.
5659 User should not set this variable manually,
5660 instead use `file-name-coding-system' to get a constant encoding
5661 of file names regardless of the current language environment. */);
5662 Vdefault_file_name_coding_system = Qnil;
5663
5664 Qformat_decode = intern_c_string ("format-decode");
5665 staticpro (&Qformat_decode);
5666 Qformat_annotate_function = intern_c_string ("format-annotate-function");
5667 staticpro (&Qformat_annotate_function);
5668 Qafter_insert_file_set_coding = intern_c_string ("after-insert-file-set-coding");
5669 staticpro (&Qafter_insert_file_set_coding);
5670
5671 Qcar_less_than_car = intern_c_string ("car-less-than-car");
5672 staticpro (&Qcar_less_than_car);
5673
5674 Fput (Qfile_error, Qerror_conditions,
5675 Fpurecopy (list2 (Qfile_error, Qerror)));
5676 Fput (Qfile_error, Qerror_message,
5677 make_pure_c_string ("File error"));
5678
5679 Fput (Qfile_already_exists, Qerror_conditions,
5680 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5681 Fput (Qfile_already_exists, Qerror_message,
5682 make_pure_c_string ("File already exists"));
5683
5684 Fput (Qfile_date_error, Qerror_conditions,
5685 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5686 Fput (Qfile_date_error, Qerror_message,
5687 make_pure_c_string ("Cannot set file date"));
5688
5689 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
5690 doc: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
5691 If a file name matches REGEXP, then all I/O on that file is done by calling
5692 HANDLER.
5693
5694 The first argument given to HANDLER is the name of the I/O primitive
5695 to be handled; the remaining arguments are the arguments that were
5696 passed to that primitive. For example, if you do
5697 (file-exists-p FILENAME)
5698 and FILENAME is handled by HANDLER, then HANDLER is called like this:
5699 (funcall HANDLER 'file-exists-p FILENAME)
5700 The function `find-file-name-handler' checks this list for a handler
5701 for its argument. */);
5702 Vfile_name_handler_alist = Qnil;
5703
5704 DEFVAR_LISP ("set-auto-coding-function",
5705 &Vset_auto_coding_function,
5706 doc: /* If non-nil, a function to call to decide a coding system of file.
5707 Two arguments are passed to this function: the file name
5708 and the length of a file contents following the point.
5709 This function should return a coding system to decode the file contents.
5710 It should check the file name against `auto-coding-alist'.
5711 If no coding system is decided, it should check a coding system
5712 specified in the heading lines with the format:
5713 -*- ... coding: CODING-SYSTEM; ... -*-
5714 or local variable spec of the tailing lines with `coding:' tag. */);
5715 Vset_auto_coding_function = Qnil;
5716
5717 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
5718 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5719 Each is passed one argument, the number of characters inserted,
5720 with point at the start of the inserted text. Each function
5721 should leave point the same, and return the new character count.
5722 If `insert-file-contents' is intercepted by a handler from
5723 `file-name-handler-alist', that handler is responsible for calling the
5724 functions in `after-insert-file-functions' if appropriate. */);
5725 Vafter_insert_file_functions = Qnil;
5726
5727 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
5728 doc: /* A list of functions to be called at the start of `write-region'.
5729 Each is passed two arguments, START and END as for `write-region'.
5730 These are usually two numbers but not always; see the documentation
5731 for `write-region'. The function should return a list of pairs
5732 of the form (POSITION . STRING), consisting of strings to be effectively
5733 inserted at the specified positions of the file being written (1 means to
5734 insert before the first byte written). The POSITIONs must be sorted into
5735 increasing order.
5736
5737 If there are several annotation functions, the lists returned by these
5738 functions are merged destructively. As each annotation function runs,
5739 the variable `write-region-annotations-so-far' contains a list of all
5740 annotations returned by previous annotation functions.
5741
5742 An annotation function can return with a different buffer current.
5743 Doing so removes the annotations returned by previous functions, and
5744 resets START and END to `point-min' and `point-max' of the new buffer.
5745
5746 After `write-region' completes, Emacs calls the function stored in
5747 `write-region-post-annotation-function', once for each buffer that was
5748 current when building the annotations (i.e., at least once), with that
5749 buffer current. */);
5750 Vwrite_region_annotate_functions = Qnil;
5751 staticpro (&Qwrite_region_annotate_functions);
5752 Qwrite_region_annotate_functions
5753 = intern_c_string ("write-region-annotate-functions");
5754
5755 DEFVAR_LISP ("write-region-post-annotation-function",
5756 &Vwrite_region_post_annotation_function,
5757 doc: /* Function to call after `write-region' completes.
5758 The function is called with no arguments. If one or more of the
5759 annotation functions in `write-region-annotate-functions' changed the
5760 current buffer, the function stored in this variable is called for
5761 each of those additional buffers as well, in addition to the original
5762 buffer. The relevant buffer is current during each function call. */);
5763 Vwrite_region_post_annotation_function = Qnil;
5764 staticpro (&Vwrite_region_annotation_buffers);
5765
5766 DEFVAR_LISP ("write-region-annotations-so-far",
5767 &Vwrite_region_annotations_so_far,
5768 doc: /* When an annotation function is called, this holds the previous annotations.
5769 These are the annotations made by other annotation functions
5770 that were already called. See also `write-region-annotate-functions'. */);
5771 Vwrite_region_annotations_so_far = Qnil;
5772
5773 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
5774 doc: /* A list of file name handlers that temporarily should not be used.
5775 This applies only to the operation `inhibit-file-name-operation'. */);
5776 Vinhibit_file_name_handlers = Qnil;
5777
5778 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
5779 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5780 Vinhibit_file_name_operation = Qnil;
5781
5782 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
5783 doc: /* File name in which we write a list of all auto save file names.
5784 This variable is initialized automatically from `auto-save-list-file-prefix'
5785 shortly after Emacs reads your `.emacs' file, if you have not yet given it
5786 a non-nil value. */);
5787 Vauto_save_list_file_name = Qnil;
5788
5789 DEFVAR_LISP ("auto-save-visited-file-name", &Vauto_save_visited_file_name,
5790 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5791 Normally auto-save files are written under other names. */);
5792 Vauto_save_visited_file_name = Qnil;
5793
5794 DEFVAR_LISP ("auto-save-include-big-deletions", &Vauto_save_include_big_deletions,
5795 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5796 If nil, deleting a substantial portion of the text disables auto-save
5797 in the buffer; this is the default behavior, because the auto-save
5798 file is usually more useful if it contains the deleted text. */);
5799 Vauto_save_include_big_deletions = Qnil;
5800
5801 #ifdef HAVE_FSYNC
5802 DEFVAR_BOOL ("write-region-inhibit-fsync", &write_region_inhibit_fsync,
5803 doc: /* *Non-nil means don't call fsync in `write-region'.
5804 This variable affects calls to `write-region' as well as save commands.
5805 A non-nil value may result in data loss! */);
5806 write_region_inhibit_fsync = 0;
5807 #endif
5808
5809 DEFVAR_BOOL ("delete-by-moving-to-trash", &delete_by_moving_to_trash,
5810 doc: /* Specifies whether to use the system's trash can.
5811 When non-nil, certain file deletion commands use the function
5812 `move-file-to-trash' instead of deleting files outright.
5813 This includes interactive calls to `delete-file' and
5814 `delete-directory' and the Dired deletion commands. */);
5815 delete_by_moving_to_trash = 0;
5816 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
5817 Qmove_file_to_trash = intern_c_string ("move-file-to-trash");
5818 staticpro (&Qmove_file_to_trash);
5819 Qcopy_directory = intern_c_string ("copy-directory");
5820 staticpro (&Qcopy_directory);
5821 Qdelete_directory = intern_c_string ("delete-directory");
5822 staticpro (&Qdelete_directory);
5823
5824 defsubr (&Sfind_file_name_handler);
5825 defsubr (&Sfile_name_directory);
5826 defsubr (&Sfile_name_nondirectory);
5827 defsubr (&Sunhandled_file_name_directory);
5828 defsubr (&Sfile_name_as_directory);
5829 defsubr (&Sdirectory_file_name);
5830 defsubr (&Smake_temp_name);
5831 defsubr (&Sexpand_file_name);
5832 defsubr (&Ssubstitute_in_file_name);
5833 defsubr (&Scopy_file);
5834 defsubr (&Smake_directory_internal);
5835 defsubr (&Sdelete_directory_internal);
5836 defsubr (&Sdelete_file);
5837 defsubr (&Srename_file);
5838 defsubr (&Sadd_name_to_file);
5839 defsubr (&Smake_symbolic_link);
5840 defsubr (&Sfile_name_absolute_p);
5841 defsubr (&Sfile_exists_p);
5842 defsubr (&Sfile_executable_p);
5843 defsubr (&Sfile_readable_p);
5844 defsubr (&Sfile_writable_p);
5845 defsubr (&Saccess_file);
5846 defsubr (&Sfile_symlink_p);
5847 defsubr (&Sfile_directory_p);
5848 defsubr (&Sfile_accessible_directory_p);
5849 defsubr (&Sfile_regular_p);
5850 defsubr (&Sfile_modes);
5851 defsubr (&Sset_file_modes);
5852 defsubr (&Sset_file_times);
5853 defsubr (&Sfile_selinux_context);
5854 defsubr (&Sset_file_selinux_context);
5855 defsubr (&Sset_default_file_modes);
5856 defsubr (&Sdefault_file_modes);
5857 defsubr (&Sfile_newer_than_file_p);
5858 defsubr (&Sinsert_file_contents);
5859 defsubr (&Swrite_region);
5860 defsubr (&Scar_less_than_car);
5861 defsubr (&Sverify_visited_file_modtime);
5862 defsubr (&Sclear_visited_file_modtime);
5863 defsubr (&Svisited_file_modtime);
5864 defsubr (&Sset_visited_file_modtime);
5865 defsubr (&Sdo_auto_save);
5866 defsubr (&Sset_buffer_auto_saved);
5867 defsubr (&Sclear_buffer_auto_save_failure);
5868 defsubr (&Srecent_auto_save_p);
5869
5870 defsubr (&Snext_read_file_uses_dialog_p);
5871
5872 #ifdef HAVE_SYNC
5873 defsubr (&Sunix_sync);
5874 #endif
5875 }
5876