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