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