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