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