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