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