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