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