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