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