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