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