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