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