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