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