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