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