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