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