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