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