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