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