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