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