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