]> code.delx.au - gnu-emacs/blob - lisp/files.el
(feature-symbols, file-provides, file-requires): Use mapc.
[gnu-emacs] / lisp / files.el
1 ;;; files.el --- file input and output commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 92, 93,
4 ;; 94, 95, 96, 97, 98, 99, 2000 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Defines most of Emacs's file- and directory-handling functions,
28 ;; including basic file visiting, backup generation, link handling,
29 ;; ITS-id version control, load- and write-hook handling, and the like.
30
31 ;;; Code:
32
33 (defgroup backup nil
34 "Backups of edited data files."
35 :group 'files)
36
37 (defgroup find-file nil
38 "Finding files."
39 :group 'files)
40
41
42 (defcustom delete-auto-save-files t
43 "*Non-nil means delete auto-save file when a buffer is saved or killed.
44
45 Note that auto-save file will not be deleted if the buffer is killed
46 when it has unsaved changes."
47 :type 'boolean
48 :group 'auto-save)
49
50 (defcustom directory-abbrev-alist
51 nil
52 "*Alist of abbreviations for file directories.
53 A list of elements of the form (FROM . TO), each meaning to replace
54 FROM with TO when it appears in a directory name. This replacement is
55 done when setting up the default directory of a newly visited file.
56 *Every* FROM string should start with `^'.
57
58 Do not use `~' in the TO strings.
59 They should be ordinary absolute directory names.
60
61 Use this feature when you have directories which you normally refer to
62 via absolute symbolic links. Make TO the name of the link, and FROM
63 the name it is linked to."
64 :type '(repeat (cons :format "%v"
65 :value ("" . "")
66 (regexp :tag "From")
67 (regexp :tag "To")))
68 :group 'abbrev
69 :group 'find-file)
70
71 ;;; Turn off backup files on VMS since it has version numbers.
72 (defcustom make-backup-files (not (eq system-type 'vax-vms))
73 "*Non-nil means make a backup of a file the first time it is saved.
74 This can be done by renaming the file or by copying.
75
76 Renaming means that Emacs renames the existing file so that it is a
77 backup file, then writes the buffer into a new file. Any other names
78 that the old file had will now refer to the backup file. The new file
79 is owned by you and its group is defaulted.
80
81 Copying means that Emacs copies the existing file into the backup
82 file, then writes the buffer on top of the existing file. Any other
83 names that the old file had will now refer to the new (edited) file.
84 The file's owner and group are unchanged.
85
86 The choice of renaming or copying is controlled by the variables
87 `backup-by-copying', `backup-by-copying-when-linked',
88 `backup-by-copying-when-mismatch' and
89 `backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
90 :type 'boolean
91 :group 'backup)
92
93 ;; Do this so that local variables based on the file name
94 ;; are not overridden by the major mode.
95 (defvar backup-inhibited nil
96 "Non-nil means don't make a backup, regardless of the other parameters.
97 This variable is intended for use by making it local to a buffer.
98 But it is local only if you make it local.")
99 (put 'backup-inhibited 'permanent-local t)
100
101 (defcustom backup-by-copying nil
102 "*Non-nil means always use copying to create backup files.
103 See documentation of variable `make-backup-files'."
104 :type 'boolean
105 :group 'backup)
106
107 (defcustom backup-by-copying-when-linked nil
108 "*Non-nil means use copying to create backups for files with multiple names.
109 This causes the alternate names to refer to the latest version as edited.
110 This variable is relevant only if `backup-by-copying' is nil."
111 :type 'boolean
112 :group 'backup)
113
114 (defcustom backup-by-copying-when-mismatch nil
115 "*Non-nil means create backups by copying if this preserves owner or group.
116 Renaming may still be used (subject to control of other variables)
117 when it would not result in changing the owner or group of the file;
118 that is, for files which are owned by you and whose group matches
119 the default for a new file created there by you.
120 This variable is relevant only if `backup-by-copying' is nil."
121 :type 'boolean
122 :group 'backup)
123
124 (defcustom backup-by-copying-when-privileged-mismatch 200
125 "*Non-nil means create backups by copying to preserve a privileged owner.
126 Renaming may still be used (subject to control of other variables)
127 when it would not result in changing the owner of the file or if the owner
128 has a user id greater than the value of this variable. This is useful
129 when low-numbered uid's are used for special system users (such as root)
130 that must maintain ownership of certain files.
131 This variable is relevant only if `backup-by-copying' and
132 `backup-by-copying-when-mismatch' are nil."
133 :type '(choice (const nil) integer)
134 :group 'backup)
135
136 (defvar backup-enable-predicate
137 (lambda (name)
138 (not (or (let ((comp (compare-strings temporary-file-directory 0 nil
139 name 0 nil)))
140 ;; Directory is under temporary-file-directory.
141 (and (not (eq comp t))
142 (< comp -1)))
143 (if small-temporary-file-directory
144 (let ((comp (compare-strings small-temporary-file-directory
145 0 nil
146 name 0 nil)))
147 ;; Directory is under small-temporary-file-directory.
148 (and (not (eq comp t))
149 (< comp -1)))))))
150 "Predicate that looks at a file name and decides whether to make backups.
151 Called with an absolute file name as argument, it returns t to enable backup.
152 The default version checks for files in `temporary-file-directory' or
153 `small-temporary-file-directory'.")
154
155 (defcustom buffer-offer-save nil
156 "*Non-nil in a buffer means always offer to save buffer on exit.
157 Do so even if the buffer is not visiting a file.
158 Automatically local in all buffers."
159 :type 'boolean
160 :group 'backup)
161 (make-variable-buffer-local 'buffer-offer-save)
162
163 (defcustom find-file-existing-other-name t
164 "*Non-nil means find a file under alternative names, in existing buffers.
165 This means if any existing buffer is visiting the file you want
166 under another name, you get the existing buffer instead of a new buffer."
167 :type 'boolean
168 :group 'find-file)
169
170 (defcustom find-file-visit-truename nil
171 "*Non-nil means visit a file under its truename.
172 The truename of a file is found by chasing all links
173 both at the file level and at the levels of the containing directories."
174 :type 'boolean
175 :group 'find-file)
176
177 (defcustom revert-without-query
178 nil
179 "*Specify which files should be reverted without query.
180 The value is a list of regular expressions.
181 If the file name matches one of these regular expressions,
182 then `revert-buffer' reverts the file without querying
183 if the file has changed on disk and you have not edited the buffer."
184 :type '(repeat regexp)
185 :group 'find-file)
186
187 (defvar buffer-file-number nil
188 "The device number and file number of the file visited in the current buffer.
189 The value is a list of the form (FILENUM DEVNUM).
190 This pair of numbers uniquely identifies the file.
191 If the buffer is visiting a new file, the value is nil.")
192 (make-variable-buffer-local 'buffer-file-number)
193 (put 'buffer-file-number 'permanent-local t)
194
195 (defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
196 "Non-nil means that buffer-file-number uniquely identifies files.")
197
198 (defvar file-name-invalid-regexp
199 (cond ((and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
200 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
201 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
202 "[\000-\031]\\|" ; control characters
203 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
204 "\\(/[^/.]+\\.[^/.]*\\.\\)")) ; more than a single dot
205 ((memq system-type '(ms-dos windows-nt))
206 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
207 "[|<>\"?*\000-\031]")) ; invalid characters
208 (t "[\000]"))
209 "Regexp recognizing file names which aren't allowed by the filesystem.")
210
211 (defcustom file-precious-flag nil
212 "*Non-nil means protect against I/O errors while saving files.
213 Some modes set this non-nil in particular buffers.
214
215 This feature works by writing the new contents into a temporary file
216 and then renaming the temporary file to replace the original.
217 In this way, any I/O error in writing leaves the original untouched,
218 and there is never any instant where the file is nonexistent.
219
220 Note that this feature forces backups to be made by copying.
221 Yet, at the same time, saving a precious file
222 breaks any hard links between it and other files."
223 :type 'boolean
224 :group 'backup)
225
226 (defcustom version-control nil
227 "*Control use of version numbers for backup files.
228 t means make numeric backup versions unconditionally.
229 nil means make them for files that have some already.
230 `never' means do not make them."
231 :type '(choice (const :tag "Never" never)
232 (const :tag "If existing" nil)
233 (other :tag "Always" t))
234 :group 'backup
235 :group 'vc)
236
237 (defcustom dired-kept-versions 2
238 "*When cleaning directory, number of versions to keep."
239 :type 'integer
240 :group 'backup
241 :group 'dired)
242
243 (defcustom delete-old-versions nil
244 "*If t, delete excess backup versions silently.
245 If nil, ask confirmation. Any other value prevents any trimming."
246 :type '(choice (const :tag "Delete" t)
247 (const :tag "Ask" nil)
248 (other :tag "Leave" other))
249 :group 'backup)
250
251 (defcustom kept-old-versions 2
252 "*Number of oldest versions to keep when a new numbered backup is made."
253 :type 'integer
254 :group 'backup)
255
256 (defcustom kept-new-versions 2
257 "*Number of newest versions to keep when a new numbered backup is made.
258 Includes the new backup. Must be > 0"
259 :type 'integer
260 :group 'backup)
261
262 (defcustom require-final-newline nil
263 "*Value of t says silently ensure a file ends in a newline when it is saved.
264 Non-nil but not t says ask user whether to add a newline when there isn't one.
265 nil means don't add newlines."
266 :type '(choice (const :tag "Off" nil)
267 (const :tag "Add" t)
268 (other :tag "Ask" ask))
269 :group 'editing-basics)
270
271 (defcustom auto-save-default t
272 "*Non-nil says by default do auto-saving of every file-visiting buffer."
273 :type 'boolean
274 :group 'auto-save)
275
276 (defcustom auto-save-visited-file-name nil
277 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
278 Normally auto-save files are written under other names."
279 :type 'boolean
280 :group 'auto-save)
281
282 (defcustom auto-save-file-name-transforms
283 '(("\\`/[^/]*:\\(.+/\\)*\\(.*\\)" "/tmp/\\2"))
284 "*Transforms to apply to buffer file name before making auto-save file name.
285 Each transform is a list (REGEXP REPLACEMENT):
286 REGEXP is a regular expression to match against the file name.
287 If it matches, `replace-match' is used to replace the
288 matching part with REPLACEMENT.
289 All the transforms in the list are tried, in the order they are listed.
290 When one transform applies, its result is final;
291 no further transforms are tried.
292
293 The default value is set up to put the auto-save file into `/tmp'
294 for editing a remote file."
295 :group 'auto-save
296 :type '(repeat (list (string :tag "Regexp") (string :tag "Replacement")))
297 :version "21.1")
298
299 (defcustom save-abbrevs nil
300 "*Non-nil means save word abbrevs too when files are saved.
301 Loading an abbrev file sets this to t."
302 :type 'boolean
303 :group 'abbrev)
304
305 (defcustom find-file-run-dired t
306 "*Non-nil means allow `find-file' to visit directories.
307 To visit the directory, `find-file' runs `find-directory-functions'."
308 :type 'boolean
309 :group 'find-file)
310
311 (defcustom find-directory-functions '(cvs-dired-noselect dired-noselect)
312 "*List of functions to try in sequence to visit a directory.
313 Each function is called with the directory name as the sole argument
314 and should return either a buffer or nil."
315 :type '(hook :options (cvs-dired-noselect dired-noselect))
316 :group 'find-file)
317
318 ;;;It is not useful to make this a local variable.
319 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
320 (defvar find-file-not-found-hooks nil
321 "List of functions to be called for `find-file' on nonexistent file.
322 These functions are called as soon as the error is detected.
323 Variable `buffer-file-name' is already set up.
324 The functions are called in the order given until one of them returns non-nil.")
325
326 ;;;It is not useful to make this a local variable.
327 ;;;(put 'find-file-hooks 'permanent-local t)
328 (defvar find-file-hooks nil
329 "List of functions to be called after a buffer is loaded from a file.
330 The buffer's local variables (if any) will have been processed before the
331 functions are called.")
332
333 (defvar write-file-hooks nil
334 "List of functions to be called before writing out a buffer to a file.
335 If one of them returns non-nil, the file is considered already written
336 and the rest are not called.
337 These hooks are considered to pertain to the visited file.
338 So any buffer-local binding of `write-file-hooks' is
339 discarded if you change the visited file name with \\[set-visited-file-name].
340
341 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
342 See also `write-contents-hooks'.")
343 ;;; However, in case someone does make it local...
344 (put 'write-file-hooks 'permanent-local t)
345
346 (defvar local-write-file-hooks nil
347 "Just like `write-file-hooks', except intended for per-buffer use.
348 The functions in this list are called before the ones in
349 `write-file-hooks'.
350
351 This variable is meant to be used for hooks that have to do with a
352 particular visited file. Therefore, it is a permanent local, so that
353 changing the major mode does not clear it. However, calling
354 `set-visited-file-name' does clear it.")
355 (make-variable-buffer-local 'local-write-file-hooks)
356 (put 'local-write-file-hooks 'permanent-local t)
357
358 (defvar write-contents-hooks nil
359 "List of functions to be called before writing out a buffer to a file.
360 If one of them returns non-nil, the file is considered already written
361 and the rest are not called.
362
363 This variable is meant to be used for hooks that pertain to the
364 buffer's contents, not to the particular visited file; thus,
365 `set-visited-file-name' does not clear this variable; but changing the
366 major mode does clear it.
367
368 This variable automatically becomes buffer-local whenever it is set.
369 If you use `add-hook' to add elements to the list, use nil for the
370 LOCAL argument.
371
372 See also `write-file-hooks'.")
373 (make-variable-buffer-local 'write-contents-hooks)
374
375 (defcustom enable-local-variables t
376 "*Control use of local variables in files you visit.
377 The value can be t, nil or something else.
378 A value of t means file local variables specifications are obeyed;
379 nil means they are ignored; anything else means query.
380 This variable also controls use of major modes specified in
381 a -*- line.
382
383 The command \\[normal-mode], when used interactively,
384 always obeys file local variable specifications and the -*- line,
385 and ignores this variable."
386 :type '(choice (const :tag "Obey" t)
387 (const :tag "Ignore" nil)
388 (other :tag "Query" other))
389 :group 'find-file)
390
391 (defvar local-enable-local-variables t
392 "Like `enable-local-variables' but meant for buffer-local bindings.
393 The meaningful values are nil and non-nil. The default is non-nil.
394 If a major mode sets this to nil, buffer-locally, then any local
395 variables list in the file will be ignored.
396
397 This variable does not affect the use of major modes
398 specified in a -*- line.")
399
400 (defcustom enable-local-eval 'maybe
401 "*Control processing of the \"variable\" `eval' in a file's local variables.
402 The value can be t, nil or something else.
403 A value of t means obey `eval' variables;
404 nil means ignore them; anything else means query.
405
406 The command \\[normal-mode] always obeys local-variables lists
407 and ignores this variable."
408 :type '(choice (const :tag "Obey" t)
409 (const :tag "Ignore" nil)
410 (other :tag "Query" other))
411 :group 'find-file)
412
413 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
414 (or (fboundp 'lock-buffer)
415 (defalias 'lock-buffer 'ignore))
416 (or (fboundp 'unlock-buffer)
417 (defalias 'unlock-buffer 'ignore))
418 (or (fboundp 'file-locked-p)
419 (defalias 'file-locked-p 'ignore))
420
421 (defvar view-read-only nil
422 "*Non-nil means buffers visiting files read-only, do it in view mode.")
423
424 (defvar temporary-file-directory
425 (file-name-as-directory
426 (cond ((memq system-type '(ms-dos windows-nt))
427 (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
428 ((memq system-type '(vax-vms axp-vms))
429 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
430 (t
431 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
432 "The directory for writing temporary files.")
433
434 (defvar small-temporary-file-directory
435 (if (eq system-type 'ms-dos) (getenv "TMPDIR"))
436 "The directory for writing small temporary files.
437 If non-nil, this directory is used instead of `temporary-file-directory'
438 by programs that create small temporary files. This is for systems that
439 have fast storage with limited space, such as a RAM disk.")
440
441 ;; The system null device. (Should reference NULL_DEVICE from C.)
442 (defvar null-device "/dev/null" "The system null device.")
443
444 (defun ange-ftp-completion-hook-function (op &rest args)
445 "Provides support for ange-ftp host name completion.
446 Runs the usual ange-ftp hook, but only for completion operations."
447 ;; Having this here avoids the need to load ange-ftp when it's not
448 ;; really in use.
449 (if (memq op '(file-name-completion file-name-all-completions))
450 (apply 'ange-ftp-hook-function op args)
451 (let ((inhibit-file-name-handlers
452 (cons 'ange-ftp-completion-hook-function
453 (and (eq inhibit-file-name-operation op)
454 inhibit-file-name-handlers)))
455 (inhibit-file-name-operation op))
456 (apply op args))))
457
458 (defun convert-standard-filename (filename)
459 "Convert a standard file's name to something suitable for the current OS.
460 This function's standard definition is trivial; it just returns the argument.
461 However, on some systems, the function is redefined
462 with a definition that really does change some file names."
463 filename)
464 \f
465 (defun pwd ()
466 "Show the current default directory."
467 (interactive nil)
468 (message "Directory %s" default-directory))
469
470 (defvar cd-path nil
471 "Value of the CDPATH environment variable, as a list.
472 Not actually set up until the first time you you use it.")
473
474 (defun parse-colon-path (cd-path)
475 "Explode a colon-separated search path into a list of directory names.
476 \(For values of `colon' equal to `path-separator'.)"
477 ;; We could use split-string here.
478 (and cd-path
479 (let (cd-prefix cd-list (cd-start 0) cd-colon)
480 (setq cd-path (concat cd-path path-separator))
481 (while (setq cd-colon (string-match path-separator cd-path cd-start))
482 (setq cd-list
483 (nconc cd-list
484 (list (if (= cd-start cd-colon)
485 nil
486 (substitute-in-file-name
487 (file-name-as-directory
488 (substring cd-path cd-start cd-colon)))))))
489 (setq cd-start (+ cd-colon 1)))
490 cd-list)))
491
492 (defun cd-absolute (dir)
493 "Change current directory to given absolute file name DIR."
494 ;; Put the name into directory syntax now,
495 ;; because otherwise expand-file-name may give some bad results.
496 (if (not (eq system-type 'vax-vms))
497 (setq dir (file-name-as-directory dir)))
498 (setq dir (abbreviate-file-name (expand-file-name dir)))
499 (if (not (file-directory-p dir))
500 (if (file-exists-p dir)
501 (error "%s is not a directory" dir)
502 (error "%s: no such directory" dir))
503 (if (file-executable-p dir)
504 (setq default-directory dir)
505 (error "Cannot cd to %s: Permission denied" dir))))
506
507 (defun cd (dir)
508 "Make DIR become the current buffer's default directory.
509 If your environment includes a `CDPATH' variable, try each one of that
510 colon-separated list of directories when resolving a relative directory name."
511 (interactive
512 (list (read-file-name "Change default directory: "
513 default-directory default-directory
514 (and (member cd-path '(nil ("./")))
515 (null (getenv "CDPATH"))))))
516 (if (file-name-absolute-p dir)
517 (cd-absolute (expand-file-name dir))
518 (if (null cd-path)
519 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
520 (setq cd-path (or trypath (list "./")))))
521 (if (not (catch 'found
522 (mapcar
523 (function (lambda (x)
524 (let ((f (expand-file-name (concat x dir))))
525 (if (file-directory-p f)
526 (progn
527 (cd-absolute f)
528 (throw 'found t))))))
529 cd-path)
530 nil))
531 (error "No such directory found via CDPATH environment variable"))))
532
533 (defun load-file (file)
534 "Load the Lisp file named FILE."
535 (interactive "fLoad file: ")
536 (let ((completion-ignored-extensions
537 (delete ".elc" completion-ignored-extensions)))
538 (load (expand-file-name file) nil nil t)))
539
540 (defun load-library (library)
541 "Load the library named LIBRARY.
542 This is an interface to the function `load'."
543 (interactive "sLoad library: ")
544 (load library))
545
546 (defun file-local-copy (file)
547 "Copy the file FILE into a temporary file on this machine.
548 Returns the name of the local copy, or nil, if FILE is directly
549 accessible."
550 ;; This formerly had an optional BUFFER argument that wasn't used by
551 ;; anything.
552 (let ((handler (find-file-name-handler file 'file-local-copy)))
553 (if handler
554 (funcall handler 'file-local-copy file)
555 nil)))
556
557 (defun file-truename (filename &optional counter prev-dirs)
558 "Return the truename of FILENAME, which should be absolute.
559 The truename of a file name is found by chasing symbolic links
560 both at the level of the file and at the level of the directories
561 containing it, until no links are left at any level.
562
563 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
564 Do not specify them in other calls."
565 ;; COUNTER can be a cons cell whose car is the count of how many more links
566 ;; to chase before getting an error.
567 ;; PREV-DIRS can be a cons cell whose car is an alist
568 ;; of truenames we've just recently computed.
569
570 ;; The last test looks dubious, maybe `+' is meant here? --simon.
571 (if (or (string= filename "") (string= filename "~")
572 (and (string= (substring filename 0 1) "~")
573 (string-match "~[^/]*" filename)))
574 (progn
575 (setq filename (expand-file-name filename))
576 (if (string= filename "")
577 (setq filename "/"))))
578 (or counter (setq counter (list 100)))
579 (let (done
580 ;; For speed, remove the ange-ftp completion handler from the list.
581 ;; We know it's not needed here.
582 ;; For even more speed, do this only on the outermost call.
583 (file-name-handler-alist
584 (if prev-dirs file-name-handler-alist
585 (let ((tem (copy-sequence file-name-handler-alist)))
586 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
587 (or prev-dirs (setq prev-dirs (list nil)))
588
589 ;; andrewi@harlequin.co.uk - none of the following code (except for
590 ;; invoking the file-name handler) currently applies on Windows
591 ;; (ie. there are no native symlinks), but there is an issue with
592 ;; case differences being ignored by the OS, and short "8.3 DOS"
593 ;; name aliases existing for all files. (The short names are not
594 ;; reported by directory-files, but can be used to refer to files.)
595 ;; It seems appropriate for file-truename to resolve these issues in
596 ;; the most natural way, which on Windows is to call the function
597 ;; `w32-long-file-name' - this returns the exact name of a file as
598 ;; it is stored on disk (expanding short name aliases with the full
599 ;; name in the process).
600 (if (eq system-type 'windows-nt)
601 (let ((handler (find-file-name-handler filename 'file-truename))
602 newname)
603 ;; For file name that has a special handler, call handler.
604 ;; This is so that ange-ftp can save time by doing a no-op.
605 (if handler
606 (setq filename (funcall handler 'file-truename filename))
607 ;; If filename contains a wildcard, newname will be the old name.
608 (if (string-match "[[*?]" filename)
609 (setq newname filename)
610 ;; If filename doesn't exist, newname will be nil.
611 (setq newname (w32-long-file-name filename)))
612 (setq filename (or newname filename)))
613 (setq done t)))
614
615 ;; If this file directly leads to a link, process that iteratively
616 ;; so that we don't use lots of stack.
617 (while (not done)
618 (setcar counter (1- (car counter)))
619 (if (< (car counter) 0)
620 (error "Apparent cycle of symbolic links for %s" filename))
621 (let ((handler (find-file-name-handler filename 'file-truename)))
622 ;; For file name that has a special handler, call handler.
623 ;; This is so that ange-ftp can save time by doing a no-op.
624 (if handler
625 (setq filename (funcall handler 'file-truename filename)
626 done t)
627 (let ((dir (or (file-name-directory filename) default-directory))
628 target dirfile)
629 ;; Get the truename of the directory.
630 (setq dirfile (directory-file-name dir))
631 ;; If these are equal, we have the (or a) root directory.
632 (or (string= dir dirfile)
633 ;; If this is the same dir we last got the truename for,
634 ;; save time--don't recalculate.
635 (if (assoc dir (car prev-dirs))
636 (setq dir (cdr (assoc dir (car prev-dirs))))
637 (let ((old dir)
638 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
639 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
640 (setq dir new))))
641 (if (equal ".." (file-name-nondirectory filename))
642 (setq filename
643 (directory-file-name (file-name-directory (directory-file-name dir)))
644 done t)
645 (if (equal "." (file-name-nondirectory filename))
646 (setq filename (directory-file-name dir)
647 done t)
648 ;; Put it back on the file name.
649 (setq filename (concat dir (file-name-nondirectory filename)))
650 ;; Is the file name the name of a link?
651 (setq target (file-symlink-p filename))
652 (if target
653 ;; Yes => chase that link, then start all over
654 ;; since the link may point to a directory name that uses links.
655 ;; We can't safely use expand-file-name here
656 ;; since target might look like foo/../bar where foo
657 ;; is itself a link. Instead, we handle . and .. above.
658 (setq filename
659 (if (file-name-absolute-p target)
660 target
661 (concat dir target))
662 done nil)
663 ;; No, we are done!
664 (setq done t))))))))
665 filename))
666
667 (defun file-chase-links (filename)
668 "Chase links in FILENAME until a name that is not a link.
669 Does not examine containing directories for links,
670 unlike `file-truename'."
671 (let (tem (count 100) (newname filename))
672 (while (setq tem (file-symlink-p newname))
673 (save-match-data
674 (if (= count 0)
675 (error "Apparent cycle of symbolic links for %s" filename))
676 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
677 (while (string-match "//+" tem)
678 (setq tem (replace-match "/" nil nil tem)))
679 ;; Handle `..' by hand, since it needs to work in the
680 ;; target of any directory symlink.
681 ;; This code is not quite complete; it does not handle
682 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
683 (while (string-match "\\`\\.\\./" tem)
684 (setq tem (substring tem 3))
685 (setq newname (expand-file-name newname))
686 ;; Chase links in the default dir of the symlink.
687 (setq newname
688 (file-chase-links
689 (directory-file-name (file-name-directory newname))))
690 ;; Now find the parent of that dir.
691 (setq newname (file-name-directory newname)))
692 (setq newname (expand-file-name tem (file-name-directory newname)))
693 (setq count (1- count))))
694 newname))
695 \f
696 (defun switch-to-buffer-other-window (buffer &optional norecord)
697 "Select buffer BUFFER in another window.
698 Optional second arg NORECORD non-nil means
699 do not put this buffer at the front of the list of recently selected ones."
700 (interactive "BSwitch to buffer in other window: ")
701 (let ((pop-up-windows t))
702 (pop-to-buffer buffer t norecord)))
703
704 (defun switch-to-buffer-other-frame (buffer &optional norecord)
705 "Switch to buffer BUFFER in another frame.
706 Optional second arg NORECORD non-nil means
707 do not put this buffer at the front of the list of recently selected ones."
708 (interactive "BSwitch to buffer in other frame: ")
709 (let ((pop-up-frames t))
710 (pop-to-buffer buffer t norecord)
711 (raise-frame (window-frame (selected-window)))))
712
713 (defun find-file (filename &optional wildcards)
714 "Edit file FILENAME.
715 Switch to a buffer visiting file FILENAME,
716 creating one if none already exists.
717 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
718 expand wildcards (if any) and visit multiple files. Wildcard expansion
719 can be suppressed by setting `find-file-wildcards'."
720 (interactive "FFind file: \np")
721 (let ((value (find-file-noselect filename nil nil wildcards)))
722 (if (listp value)
723 (mapcar 'switch-to-buffer (nreverse value))
724 (switch-to-buffer value))))
725
726 (defun find-file-other-window (filename &optional wildcards)
727 "Edit file FILENAME, in another window.
728 May create a new window, or reuse an existing one.
729 See the function `display-buffer'.
730 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
731 expand wildcards (if any) and visit multiple files."
732 (interactive "FFind file in other window: \np")
733 (let ((value (find-file-noselect filename nil nil wildcards)))
734 (if (listp value)
735 (progn
736 (setq value (nreverse value))
737 (switch-to-buffer-other-window (car value))
738 (mapcar 'switch-to-buffer (cdr value)))
739 (switch-to-buffer-other-window value))))
740
741 (defun find-file-other-frame (filename &optional wildcards)
742 "Edit file FILENAME, in another frame.
743 May create a new frame, or reuse an existing one.
744 See the function `display-buffer'.
745 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
746 expand wildcards (if any) and visit multiple files."
747 (interactive "FFind file in other frame: \np")
748 (let ((value (find-file-noselect filename nil nil wildcards)))
749 (if (listp value)
750 (progn
751 (setq value (nreverse value))
752 (switch-to-buffer-other-frame (car value))
753 (mapcar 'switch-to-buffer (cdr value)))
754 (switch-to-buffer-other-frame value))))
755
756 (defun find-file-read-only (filename &optional wildcards)
757 "Edit file FILENAME but don't allow changes.
758 Like `find-file' but marks buffer as read-only.
759 Use \\[toggle-read-only] to permit editing."
760 (interactive "fFind file read-only: \np")
761 (find-file filename wildcards)
762 (toggle-read-only 1)
763 (current-buffer))
764
765 (defun find-file-read-only-other-window (filename &optional wildcards)
766 "Edit file FILENAME in another window but don't allow changes.
767 Like \\[find-file-other-window] but marks buffer as read-only.
768 Use \\[toggle-read-only] to permit editing."
769 (interactive "fFind file read-only other window: \np")
770 (find-file-other-window filename wildcards)
771 (toggle-read-only 1)
772 (current-buffer))
773
774 (defun find-file-read-only-other-frame (filename &optional wildcards)
775 "Edit file FILENAME in another frame but don't allow changes.
776 Like \\[find-file-other-frame] but marks buffer as read-only.
777 Use \\[toggle-read-only] to permit editing."
778 (interactive "fFind file read-only other frame: \np")
779 (find-file-other-frame filename wildcards)
780 (toggle-read-only 1)
781 (current-buffer))
782
783 (defun find-alternate-file-other-window (filename)
784 "Find file FILENAME as a replacement for the file in the next window.
785 This command does not select that window."
786 (interactive
787 (save-selected-window
788 (other-window 1)
789 (let ((file buffer-file-name)
790 (file-name nil)
791 (file-dir nil))
792 (and file
793 (setq file-name (file-name-nondirectory file)
794 file-dir (file-name-directory file)))
795 (list (read-file-name
796 "Find alternate file: " file-dir nil nil file-name)))))
797 (if (one-window-p)
798 (find-file-other-window filename)
799 (save-selected-window
800 (other-window 1)
801 (find-alternate-file filename))))
802
803 (defun find-alternate-file (filename)
804 "Find file FILENAME, select its buffer, kill previous buffer.
805 If the current buffer now contains an empty file that you just visited
806 \(presumably by mistake), use this command to visit the file you really want."
807 (interactive
808 (let ((file buffer-file-name)
809 (file-name nil)
810 (file-dir nil))
811 (and file
812 (setq file-name (file-name-nondirectory file)
813 file-dir (file-name-directory file)))
814 (list (read-file-name
815 "Find alternate file: " file-dir nil nil file-name))))
816 (and (buffer-modified-p) (buffer-file-name)
817 ;; (not buffer-read-only)
818 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
819 (buffer-name))))
820 (error "Aborted"))
821 (let ((obuf (current-buffer))
822 (ofile buffer-file-name)
823 (onum buffer-file-number)
824 (otrue buffer-file-truename)
825 (oname (buffer-name)))
826 (if (get-buffer " **lose**")
827 (kill-buffer " **lose**"))
828 (rename-buffer " **lose**")
829 (unwind-protect
830 (progn
831 (unlock-buffer)
832 (setq buffer-file-name nil)
833 (setq buffer-file-number nil)
834 (setq buffer-file-truename nil)
835 (find-file filename))
836 (cond ((eq obuf (current-buffer))
837 (setq buffer-file-name ofile)
838 (setq buffer-file-number onum)
839 (setq buffer-file-truename otrue)
840 (lock-buffer)
841 (rename-buffer oname))))
842 (or (eq (current-buffer) obuf)
843 (kill-buffer obuf))))
844 \f
845 (defun create-file-buffer (filename)
846 "Create a suitably named buffer for visiting FILENAME, and return it.
847 FILENAME (sans directory) is used unchanged if that name is free;
848 otherwise a string <2> or <3> or ... is appended to get an unused name."
849 (let ((lastname (file-name-nondirectory filename)))
850 (if (string= lastname "")
851 (setq lastname filename))
852 (generate-new-buffer lastname)))
853
854 (defun generate-new-buffer (name)
855 "Create and return a buffer with a name based on NAME.
856 Choose the buffer's name using `generate-new-buffer-name'."
857 (get-buffer-create (generate-new-buffer-name name)))
858
859 (defcustom automount-dir-prefix "^/tmp_mnt/"
860 "Regexp to match the automounter prefix in a directory name."
861 :group 'files
862 :type 'regexp)
863
864 (defvar abbreviated-home-dir nil
865 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
866
867 (defun abbreviate-file-name (filename)
868 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
869 This also substitutes \"~\" for the user's home directory.
870 Type \\[describe-variable] directory-abbrev-alist RET for more information."
871 ;; Get rid of the prefixes added by the automounter.
872 (if (and automount-dir-prefix
873 (string-match automount-dir-prefix filename)
874 (file-exists-p (file-name-directory
875 (substring filename (1- (match-end 0))))))
876 (setq filename (substring filename (1- (match-end 0)))))
877 (let ((tail directory-abbrev-alist))
878 ;; If any elt of directory-abbrev-alist matches this name,
879 ;; abbreviate accordingly.
880 (while tail
881 (if (string-match (car (car tail)) filename)
882 (setq filename
883 (concat (cdr (car tail)) (substring filename (match-end 0)))))
884 (setq tail (cdr tail)))
885 ;; Compute and save the abbreviated homedir name.
886 ;; We defer computing this until the first time it's needed, to
887 ;; give time for directory-abbrev-alist to be set properly.
888 ;; We include a slash at the end, to avoid spurious matches
889 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
890 (or abbreviated-home-dir
891 (setq abbreviated-home-dir
892 (let ((abbreviated-home-dir "$foo"))
893 (concat "^" (abbreviate-file-name (expand-file-name "~"))
894 "\\(/\\|$\\)"))))
895
896 ;; If FILENAME starts with the abbreviated homedir,
897 ;; make it start with `~' instead.
898 (if (and (string-match abbreviated-home-dir filename)
899 ;; If the home dir is just /, don't change it.
900 (not (and (= (match-end 0) 1)
901 (= (aref filename 0) ?/)))
902 ;; MS-DOS root directories can come with a drive letter;
903 ;; Novell Netware allows drive letters beyond `Z:'.
904 (not (and (or (eq system-type 'ms-dos)
905 (eq system-type 'windows-nt))
906 (save-match-data
907 (string-match "^[a-zA-`]:/$" filename)))))
908 (setq filename
909 (concat "~"
910 (substring filename (match-beginning 1) (match-end 1))
911 (substring filename (match-end 0)))))
912 filename))
913
914 (defcustom find-file-not-true-dirname-list nil
915 "*List of logical names for which visiting shouldn't save the true dirname.
916 On VMS, when you visit a file using a logical name that searches a path,
917 you may or may not want the visited file name to record the specific
918 directory where the file was found. If you *do not* want that, add the logical
919 name to this list as a string."
920 :type '(repeat (string :tag "Name"))
921 :group 'find-file)
922
923 (defun find-buffer-visiting (filename)
924 "Return the buffer visiting file FILENAME (a string).
925 This is like `get-file-buffer', except that it checks for any buffer
926 visiting the same file, possibly under a different name.
927 If there is no such live buffer, return nil."
928 (let ((buf (get-file-buffer filename))
929 (truename (abbreviate-file-name (file-truename filename))))
930 (or buf
931 (let ((list (buffer-list)) found)
932 (while (and (not found) list)
933 (save-excursion
934 (set-buffer (car list))
935 (if (and buffer-file-name
936 (string= buffer-file-truename truename))
937 (setq found (car list))))
938 (setq list (cdr list)))
939 found)
940 (let ((number (nthcdr 10 (file-attributes truename)))
941 (list (buffer-list)) found)
942 (and buffer-file-numbers-unique
943 number
944 (while (and (not found) list)
945 (save-excursion
946 (set-buffer (car list))
947 (if (and buffer-file-name
948 (equal buffer-file-number number)
949 ;; Verify this buffer's file number
950 ;; still belongs to its file.
951 (file-exists-p buffer-file-name)
952 (equal (nthcdr 10 (file-attributes buffer-file-name))
953 number))
954 (setq found (car list))))
955 (setq list (cdr list))))
956 found))))
957 \f
958 (defcustom find-file-wildcards t
959 "*Non-nil means file-visiting commands should handle wildcards.
960 For example, if you specify `*.c', that would visit all the files
961 whose names match the pattern."
962 :group 'files
963 :version "20.4"
964 :type 'boolean)
965
966 (defun find-file-noselect (filename &optional nowarn rawfile wildcards)
967 "Read file FILENAME into a buffer and return the buffer.
968 If a buffer exists visiting FILENAME, return that one, but
969 verify that the file has not changed since visited or saved.
970 The buffer is not selected, just returned to the caller.
971 Optional first arg NOWARN non-nil means suppress any warning messages.
972 Optional second arg RAWFILE non-nil means the file is read literally.
973 Optional third arg WILDCARDS non-nil means do wildcard processing
974 and visit all the matching files. When wildcards are actually
975 used and expanded, the value is a list of buffers
976 that are visiting the various files."
977 (setq filename
978 (abbreviate-file-name
979 (expand-file-name filename)))
980 (if (file-directory-p filename)
981 (or (and find-file-run-dired
982 (run-hook-with-args-until-success
983 'find-directory-functions
984 (if find-file-visit-truename
985 (abbreviate-file-name (file-truename filename))
986 filename)))
987 (error "%s is a directory" filename))
988 (if (and wildcards
989 find-file-wildcards
990 (not (string-match "\\`/:" filename))
991 (string-match "[[*?]" filename))
992 (let ((files (condition-case nil
993 (file-expand-wildcards filename t)
994 (error (list filename))))
995 (find-file-wildcards nil))
996 (if (null files)
997 (find-file-noselect filename)
998 (car (mapcar #'find-file-noselect files))))
999 (let* ((buf (get-file-buffer filename))
1000 (truename (abbreviate-file-name (file-truename filename)))
1001 (number (nthcdr 10 (file-attributes truename)))
1002 ;; Find any buffer for a file which has same truename.
1003 (other (and (not buf) (find-buffer-visiting filename))))
1004 ;; Let user know if there is a buffer with the same truename.
1005 (if other
1006 (progn
1007 (or nowarn
1008 (string-equal filename (buffer-file-name other))
1009 (message "%s and %s are the same file"
1010 filename (buffer-file-name other)))
1011 ;; Optionally also find that buffer.
1012 (if (or find-file-existing-other-name find-file-visit-truename)
1013 (setq buf other))))
1014 (if buf
1015 ;; We are using an existing buffer.
1016 (progn
1017 (or nowarn
1018 (verify-visited-file-modtime buf)
1019 (cond ((not (file-exists-p filename))
1020 (error "File %s no longer exists!" filename))
1021 ;; Certain files should be reverted automatically
1022 ;; if they have changed on disk and not in the buffer.
1023 ((and (not (buffer-modified-p buf))
1024 (let ((tail revert-without-query)
1025 (found nil))
1026 (while tail
1027 (if (string-match (car tail) filename)
1028 (setq found t))
1029 (setq tail (cdr tail)))
1030 found))
1031 (with-current-buffer buf
1032 (message "Reverting file %s..." filename)
1033 (revert-buffer t t)
1034 (message "Reverting file %s...done" filename)))
1035 ((yes-or-no-p
1036 (if (string= (file-name-nondirectory filename)
1037 (buffer-name buf))
1038 (format
1039 (if (buffer-modified-p buf)
1040 "File %s changed on disk. Discard your edits? "
1041 "File %s changed on disk. Reread from disk? ")
1042 (file-name-nondirectory filename))
1043 (format
1044 (if (buffer-modified-p buf)
1045 "File %s changed on disk. Discard your edits in %s? "
1046 "File %s changed on disk. Reread from disk into %s? ")
1047 (file-name-nondirectory filename)
1048 (buffer-name buf))))
1049 (with-current-buffer buf
1050 (revert-buffer t t)))))
1051 (with-current-buffer buf
1052 (when (not (eq (not (null rawfile))
1053 (not (null find-file-literally))))
1054 (if (buffer-modified-p)
1055 (if (y-or-n-p (if rawfile
1056 "Save file and revisit literally? "
1057 "Save file and revisit non-literally? "))
1058 (progn
1059 (save-buffer)
1060 (find-file-noselect-1 buf filename nowarn
1061 rawfile truename number))
1062 (if (y-or-n-p (if rawfile
1063 "Discard your edits and revisit file literally? "
1064 "Discard your edits and revisit file non-literally? "))
1065 (find-file-noselect-1 buf filename nowarn
1066 rawfile truename number)
1067 (error (if rawfile "File already visited non-literally"
1068 "File already visited literally"))))
1069 (if (y-or-n-p (if rawfile
1070 "Revisit file literally? "
1071 "Revisit file non-literally? "))
1072 (find-file-noselect-1 buf filename nowarn
1073 rawfile truename number)
1074 (error (if rawfile "File already visited non-literally"
1075 "File already visited literally"))))))
1076 ;; Return the buffer we are using.
1077 buf)
1078 ;; Create a new buffer.
1079 (setq buf (create-file-buffer filename))
1080 (set-buffer-major-mode buf)
1081 ;; find-file-noselect-1 may use a different buffer.
1082 (find-file-noselect-1 buf filename nowarn
1083 rawfile truename number))))))
1084
1085 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
1086 (let ((inhibit-read-only t)
1087 error)
1088 (with-current-buffer buf
1089 (kill-local-variable 'find-file-literally)
1090 ;; Needed in case we are re-visiting the file with a different
1091 ;; text representation.
1092 (kill-local-variable 'buffer-file-coding-system)
1093 (erase-buffer)
1094 (and (default-value 'enable-multibyte-characters)
1095 (not rawfile)
1096 (set-buffer-multibyte t))
1097 (if rawfile
1098 (condition-case ()
1099 (insert-file-contents-literally filename t)
1100 (file-error
1101 (when (and (file-exists-p filename)
1102 (not (file-readable-p filename)))
1103 (kill-buffer buf)
1104 (signal 'file-error (list "File is not readable"
1105 filename)))
1106 ;; Unconditionally set error
1107 (setq error t)))
1108 (condition-case ()
1109 (insert-file-contents filename t)
1110 (file-error
1111 (when (and (file-exists-p filename)
1112 (not (file-readable-p filename)))
1113 (kill-buffer buf)
1114 (signal 'file-error (list "File is not readable"
1115 filename)))
1116 ;; Run find-file-not-found-hooks until one returns non-nil.
1117 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
1118 ;; If they fail too, set error.
1119 (setq error t)))))
1120 ;; Record the file's truename, and maybe use that as visited name.
1121 (if (equal filename buffer-file-name)
1122 (setq buffer-file-truename truename)
1123 (setq buffer-file-truename
1124 (abbreviate-file-name (file-truename buffer-file-name))))
1125 (setq buffer-file-number number)
1126 ;; On VMS, we may want to remember which directory in a search list
1127 ;; the file was found in.
1128 (and (eq system-type 'vax-vms)
1129 (let (logical)
1130 (if (string-match ":" (file-name-directory filename))
1131 (setq logical (substring (file-name-directory filename)
1132 0 (match-beginning 0))))
1133 (not (member logical find-file-not-true-dirname-list)))
1134 (setq buffer-file-name buffer-file-truename))
1135 (if find-file-visit-truename
1136 (setq buffer-file-name
1137 (setq filename
1138 (expand-file-name buffer-file-truename))))
1139 ;; Set buffer's default directory to that of the file.
1140 (setq default-directory (file-name-directory buffer-file-name))
1141 ;; Turn off backup files for certain file names. Since
1142 ;; this is a permanent local, the major mode won't eliminate it.
1143 (and (not (funcall backup-enable-predicate buffer-file-name))
1144 (progn
1145 (make-local-variable 'backup-inhibited)
1146 (setq backup-inhibited t)))
1147 (if rawfile
1148 (progn
1149 (set-buffer-multibyte nil)
1150 (setq buffer-file-coding-system 'no-conversion)
1151 (make-local-variable 'find-file-literally)
1152 (setq find-file-literally t))
1153 (after-find-file error (not nowarn)))
1154 (current-buffer))))
1155 \f
1156 (defun insert-file-contents-literally (filename &optional visit beg end replace)
1157 "Like `insert-file-contents', but only reads in the file literally.
1158 A buffer may be modified in several ways after reading into the buffer,
1159 to Emacs features such as format decoding, character code
1160 conversion, find-file-hooks, automatic uncompression, etc.
1161
1162 This function ensures that none of these modifications will take place."
1163 (let ((format-alist nil)
1164 (after-insert-file-functions nil)
1165 (coding-system-for-read 'no-conversion)
1166 (coding-system-for-write 'no-conversion)
1167 (jka-compr-compression-info-list nil)
1168 (find-buffer-file-type-function
1169 (if (fboundp 'find-buffer-file-type)
1170 (symbol-function 'find-buffer-file-type)
1171 nil)))
1172 (unwind-protect
1173 (progn
1174 (fset 'find-buffer-file-type (lambda (filename) t))
1175 (insert-file-contents filename visit beg end replace))
1176 (if find-buffer-file-type-function
1177 (fset 'find-buffer-file-type find-buffer-file-type-function)
1178 (fmakunbound 'find-buffer-file-type)))))
1179
1180 (defun insert-file-literally (filename)
1181 "Insert contents of file FILENAME into buffer after point with no conversion.
1182
1183 This function is meant for the user to run interactively.
1184 Don't call it from programs! Use `insert-file-contents-literally' instead.
1185 \(Its calling sequence is different; see its documentation)."
1186 (interactive "*fInsert file literally: ")
1187 (if (file-directory-p filename)
1188 (signal 'file-error (list "Opening input file" "file is a directory"
1189 filename)))
1190 (let ((tem (insert-file-contents-literally filename)))
1191 (push-mark (+ (point) (car (cdr tem))))))
1192
1193 (defvar find-file-literally nil
1194 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1195 This is a permanent local.")
1196 (put 'find-file-literally 'permanent-local t)
1197
1198 (defun find-file-literally (filename)
1199 "Visit file FILENAME with no conversion of any kind.
1200 Format conversion and character code conversion are both disabled,
1201 and multibyte characters are disabled in the resulting buffer.
1202 The major mode used is Fundamental mode regardless of the file name,
1203 and local variable specifications in the file are ignored.
1204 Automatic uncompression is also disabled.
1205
1206 You cannot absolutely rely on this function to result in
1207 visiting the file literally. If Emacs already has a buffer
1208 which is visiting the file, you get the existing buffer,
1209 regardless of whether it was created literally or not.
1210
1211 In a Lisp program, if you want to be sure of accessing a file's
1212 contents literally, you should create a temporary buffer and then read
1213 the file contents into it using `insert-file-contents-literally'."
1214 (interactive "FFind file literally: ")
1215 (switch-to-buffer (find-file-noselect filename nil t)))
1216 \f
1217 (defvar after-find-file-from-revert-buffer nil)
1218
1219 (defun after-find-file (&optional error warn noauto
1220 after-find-file-from-revert-buffer
1221 nomodes)
1222 "Called after finding a file and by the default revert function.
1223 Sets buffer mode, parses local variables.
1224 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
1225 error in reading the file. WARN non-nil means warn if there
1226 exists an auto-save file more recent than the visited file.
1227 NOAUTO means don't mess with auto-save mode.
1228 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1229 means this call was from `revert-buffer'.
1230 Fifth arg NOMODES non-nil means don't alter the file's modes.
1231 Finishes by calling the functions in `find-file-hooks'
1232 unless NOMODES is non-nil."
1233 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1234 (if noninteractive
1235 nil
1236 (let* (not-serious
1237 (msg
1238 (cond ((and error (file-attributes buffer-file-name))
1239 (setq buffer-read-only t)
1240 "File exists, but cannot be read")
1241 ((not buffer-read-only)
1242 (if (and warn
1243 ;; No need to warn if buffer is auto-saved
1244 ;; under the name of the visited file.
1245 (not (and buffer-file-name
1246 auto-save-visited-file-name))
1247 (file-newer-than-file-p (or buffer-auto-save-file-name
1248 (make-auto-save-file-name))
1249 buffer-file-name))
1250 (format "%s has auto save data; consider M-x recover-file"
1251 (file-name-nondirectory buffer-file-name))
1252 (setq not-serious t)
1253 (if error "(New file)" nil)))
1254 ((not error)
1255 (setq not-serious t)
1256 "Note: file is write protected")
1257 ((file-attributes (directory-file-name default-directory))
1258 "File not found and directory write-protected")
1259 ((file-exists-p (file-name-directory buffer-file-name))
1260 (setq buffer-read-only nil))
1261 (t
1262 (setq buffer-read-only nil)
1263 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1264 "Use M-x make-directory RET RET to create the directory"
1265 "Use C-u M-x make-directory RET RET to create directory and its parents")))))
1266 (if msg
1267 (progn
1268 (message msg)
1269 (or not-serious (sit-for 1 nil t)))))
1270 (if (and auto-save-default (not noauto))
1271 (auto-save-mode t)))
1272 ;; Make people do a little extra work (C-x C-q)
1273 ;; before altering a backup file.
1274 (if (backup-file-name-p buffer-file-name)
1275 (setq buffer-read-only t))
1276 (if nomodes
1277 nil
1278 (and view-read-only view-mode
1279 (view-mode-disable))
1280 (normal-mode t)
1281 (if (and buffer-read-only view-read-only
1282 (not (eq (get major-mode 'mode-class) 'special)))
1283 (view-mode-enter))
1284 (run-hooks 'find-file-hooks)))
1285
1286 (defun normal-mode (&optional find-file)
1287 "Choose the major mode for this buffer automatically.
1288 Also sets up any specified local variables of the file.
1289 Uses the visited file name, the -*- line, and the local variables spec.
1290
1291 This function is called automatically from `find-file'. In that case,
1292 we may set up the file-specified mode and local variables,
1293 depending on the value of `enable-local-variables': if it is t, we do;
1294 if it is nil, we don't; otherwise, we query.
1295 In addition, if `local-enable-local-variables' is nil, we do
1296 not set local variables (though we do notice a mode specified with -*-.)
1297
1298 `enable-local-variables' is ignored if you run `normal-mode' interactively,
1299 or from Lisp without specifying the optional argument FIND-FILE;
1300 in that case, this function acts as if `enable-local-variables' were t."
1301 (interactive)
1302 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1303 (condition-case err
1304 (set-auto-mode)
1305 (error (message "File mode specification error: %s"
1306 (prin1-to-string err))))
1307 (condition-case err
1308 (let ((enable-local-variables (or (not find-file)
1309 enable-local-variables)))
1310 (hack-local-variables))
1311 (error (message "File local-variables error: %s"
1312 (prin1-to-string err)))))
1313
1314 (defvar auto-mode-alist
1315 (mapc
1316 (lambda (elt)
1317 (cons (purecopy (car elt)) (cdr elt)))
1318 '(("\\.te?xt\\'" . text-mode)
1319 ("\\.c\\'" . c-mode)
1320 ("\\.h\\'" . c-mode)
1321 ("\\.tex\\'" . tex-mode)
1322 ("\\.ltx\\'" . latex-mode)
1323 ("\\.el\\'" . emacs-lisp-mode)
1324 ("\\.scm\\'" . scheme-mode)
1325 ("\\.l\\'" . lisp-mode)
1326 ("\\.lisp\\'" . lisp-mode)
1327 ("\\.f\\'" . fortran-mode)
1328 ("\\.F\\'" . fortran-mode)
1329 ("\\.for\\'" . fortran-mode)
1330 ("\\.p\\'" . pascal-mode)
1331 ("\\.pas\\'" . pascal-mode)
1332 ("\\.ad[abs]\\'" . ada-mode)
1333 ("\\.\\([pP][Llm]\\|al\\)\\'" . perl-mode)
1334 ("\\.s?html?\\'" . html-mode)
1335 ("\\.cc\\'" . c++-mode)
1336 ("\\.hh\\'" . c++-mode)
1337 ("\\.hpp\\'" . c++-mode)
1338 ("\\.C\\'" . c++-mode)
1339 ("\\.H\\'" . c++-mode)
1340 ("\\.cpp\\'" . c++-mode)
1341 ("\\.cxx\\'" . c++-mode)
1342 ("\\.hxx\\'" . c++-mode)
1343 ("\\.c\\+\\+\\'" . c++-mode)
1344 ("\\.h\\+\\+\\'" . c++-mode)
1345 ("\\.m\\'" . objc-mode)
1346 ("\\.java\\'" . java-mode)
1347 ("\\.mk\\'" . makefile-mode)
1348 ("\\(M\\|m\\|GNUm\\)akefile\\(\\.in\\)?\\'" . makefile-mode)
1349 ("\\.am\\'" . makefile-mode) ;For Automake.
1350 ;;; Less common extensions come here
1351 ;;; so more common ones above are found faster.
1352 ("\\.texinfo\\'" . texinfo-mode)
1353 ("\\.te?xi\\'" . texinfo-mode)
1354 ("\\.s\\'" . asm-mode)
1355 ("\\.S\\'" . asm-mode)
1356 ("\\.asm\\'" . asm-mode)
1357 ("ChangeLog\\'" . change-log-mode)
1358 ("change\\.log\\'" . change-log-mode)
1359 ("changelo\\'" . change-log-mode)
1360 ("ChangeLog\\.[0-9]+\\'" . change-log-mode)
1361 ;; for MSDOS and MS-Windows (which are case-insensitive)
1362 ("changelog\\'" . change-log-mode)
1363 ("changelog\\.[0-9]+\\'" . change-log-mode)
1364 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1365 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
1366 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
1367 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1368 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1369 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
1370 ("\\.m?spec$" . sh-mode)
1371 ("\\.mm\\'" . nroff-mode)
1372 ("\\.me\\'" . nroff-mode)
1373 ("\\.ms\\'" . nroff-mode)
1374 ("\\.man\\'" . nroff-mode)
1375 ("\\.\\(u?lpc\\|pike\\|pmod\\)\\'" . pike-mode)
1376 ;;; The following should come after the ChangeLog pattern
1377 ;;; for the sake of ChangeLog.1, etc.
1378 ;;; and after the .scm.[0-9] pattern too.
1379 ("\\.[12345678]\\'" . nroff-mode)
1380 ("\\.TeX\\'" . tex-mode)
1381 ("\\.sty\\'" . latex-mode)
1382 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
1383 ("\\.clo\\'" . latex-mode) ;LaTeX 2e class option
1384 ("\\.bbl\\'" . latex-mode)
1385 ("\\.bib\\'" . bibtex-mode)
1386 ("\\.sql\\'" . sql-mode)
1387 ("\\.m4\\'" . m4-mode)
1388 ("\\.mc\\'" . m4-mode)
1389 ("\\.mf\\'" . metafont-mode)
1390 ("\\.mp\\'" . metapost-mode)
1391 ("\\.vhdl?\\'" . vhdl-mode)
1392 ("\\.article\\'" . text-mode)
1393 ("\\.letter\\'" . text-mode)
1394 ("\\.tcl\\'" . tcl-mode)
1395 ("\\.exp\\'" . tcl-mode)
1396 ("\\.itcl\\'" . tcl-mode)
1397 ("\\.itk\\'" . tcl-mode)
1398 ("\\.icn\\'" . icon-mode)
1399 ("\\.sim\\'" . simula-mode)
1400 ("\\.mss\\'" . scribe-mode)
1401 ("\\.f90\\'" . f90-mode)
1402 ("\\.pro\\'" . idlwave-mode)
1403 ("\\.lsp\\'" . lisp-mode)
1404 ("\\.awk\\'" . awk-mode)
1405 ("\\.prolog\\'" . prolog-mode)
1406 ("\\.tar\\'" . tar-mode)
1407 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|jar\\)\\'" . archive-mode)
1408 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|JAR\\)\\'" . archive-mode)
1409 ;; Mailer puts message to be edited in
1410 ;; /tmp/Re.... or Message
1411 ("\\`/tmp/Re" . text-mode)
1412 ("/Message[0-9]*\\'" . text-mode)
1413 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1414 ("\\.zone\\'" . zone-mode)
1415 ;; some news reader is reported to use this
1416 ("\\`/tmp/fol/" . text-mode)
1417 ("\\.y\\'" . c-mode)
1418 ("\\.lex\\'" . c-mode)
1419 ("\\.oak\\'" . scheme-mode)
1420 ("\\.sgml?\\'" . sgml-mode)
1421 ("\\.xml\\'" . sgml-mode)
1422 ("\\.dtd\\'" . sgml-mode)
1423 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
1424 ("\\.idl\\'" . idl-mode)
1425 ;; .emacs following a directory delimiter
1426 ;; in Unix, MSDOG or VMS syntax.
1427 ("[]>:/\\]\\..*emacs\\'" . emacs-lisp-mode)
1428 ("\\`\\..*emacs\\'" . emacs-lisp-mode)
1429 ;; _emacs following a directory delimiter
1430 ;; in MsDos syntax
1431 ("[:/]_emacs\\'" . emacs-lisp-mode)
1432 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode)
1433 ("\\.ml\\'" . lisp-mode)
1434 ("\\.asn$" . snmp-mode)
1435 ("\\.mib$" . snmp-mode)
1436 ("\\.smi$" . snmp-mode)
1437 ("\\.as2$" . snmpv2-mode)
1438 ("\\.mi2$" . snmpv2-mode)
1439 ("\\.sm2$" . snmpv2-mode)
1440 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode)
1441 ("\\.[eE]?[pP][sS]$" . ps-mode)
1442 ("configure\\.in\\'" . autoconf-mode)
1443 ("BROWSE\\'" . ebrowse-tree-mode)
1444 ("\\.ebrowse\\'" . ebrowse-tree-mode)))
1445 "Alist of filename patterns vs corresponding major mode functions.
1446 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1447 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1448 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1449 mode function to use. FUNCTION will be called, unless it is nil.
1450
1451 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1452 calling FUNCTION (if it's not nil), we delete the suffix that matched
1453 REGEXP and search the list again for another match.")
1454
1455
1456 (defvar interpreter-mode-alist
1457 (mapc
1458 (lambda (l)
1459 (cons (purecopy (car l)) (cdr l)))
1460 '(("perl" . perl-mode)
1461 ("perl5" . perl-mode)
1462 ("miniperl" . perl-mode)
1463 ("wish" . tcl-mode)
1464 ("wishx" . tcl-mode)
1465 ("tcl" . tcl-mode)
1466 ("tclsh" . tcl-mode)
1467 ("awk" . awk-mode)
1468 ("mawk" . awk-mode)
1469 ("nawk" . awk-mode)
1470 ("gawk" . awk-mode)
1471 ("scm" . scheme-mode)
1472 ("ash" . sh-mode)
1473 ("bash" . sh-mode)
1474 ("csh" . sh-mode)
1475 ("dtksh" . sh-mode)
1476 ("es" . sh-mode)
1477 ("itcsh" . sh-mode)
1478 ("jsh" . sh-mode)
1479 ("ksh" . sh-mode)
1480 ("oash" . sh-mode)
1481 ("pdksh" . sh-mode)
1482 ("rc" . sh-mode)
1483 ("rpm" . sh-mode)
1484 ("sh" . sh-mode)
1485 ("sh5" . sh-mode)
1486 ("tcsh" . sh-mode)
1487 ("wksh" . sh-mode)
1488 ("wsh" . sh-mode)
1489 ("zsh" . sh-mode)
1490 ("tail" . text-mode)
1491 ("more" . text-mode)
1492 ("less" . text-mode)
1493 ("pg" . text-mode)
1494 ("make" . makefile-mode) ; Debian uses this
1495 ("guile" . scheme-mode)
1496 ("clisp" . lisp-mode)))
1497 "Alist mapping interpreter names to major modes.
1498 This alist applies to files whose first line starts with `#!'.
1499 Each element looks like (INTERPRETER . MODE).
1500 The car of each element is compared with
1501 the name of the interpreter specified in the first line.
1502 If it matches, mode MODE is selected.")
1503
1504 (defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
1505 "List of regexps; if one matches a file name, don't look for `-*-'.")
1506
1507 (defvar inhibit-first-line-modes-suffixes nil
1508 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1509 When checking `inhibit-first-line-modes-regexps', we first discard
1510 from the end of the file name anything that matches one of these regexps.")
1511
1512 (defun set-auto-mode (&optional just-from-file-name)
1513 "Select major mode appropriate for current buffer.
1514 This checks for a -*- mode tag in the buffer's text,
1515 compares the filename against the entries in `auto-mode-alist',
1516 or checks the interpreter that runs this file against
1517 `interpreter-mode-alist'.
1518
1519 It does not check for the `mode:' local variable in the
1520 Local Variables section of the file; for that, use `hack-local-variables'.
1521
1522 If `enable-local-variables' is nil, this function does not check for a
1523 -*- mode tag.
1524
1525 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1526 then we do not set anything but the major mode,
1527 and we don't even do that unless it would come from the file name."
1528 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1529 (let (beg end done modes)
1530 (save-excursion
1531 (goto-char (point-min))
1532 (skip-chars-forward " \t\n")
1533 (and enable-local-variables
1534 ;; Don't look for -*- if this file name matches any
1535 ;; of the regexps in inhibit-first-line-modes-regexps.
1536 (let ((temp inhibit-first-line-modes-regexps)
1537 (name (if buffer-file-name
1538 (file-name-sans-versions buffer-file-name)
1539 (buffer-name))))
1540 (while (let ((sufs inhibit-first-line-modes-suffixes))
1541 (while (and sufs (not (string-match (car sufs) name)))
1542 (setq sufs (cdr sufs)))
1543 sufs)
1544 (setq name (substring name 0 (match-beginning 0))))
1545 (while (and temp
1546 (not (string-match (car temp) name)))
1547 (setq temp (cdr temp)))
1548 (not temp))
1549 (search-forward "-*-" (save-excursion
1550 ;; If the file begins with "#!"
1551 ;; (exec interpreter magic), look
1552 ;; for mode frobs in the first two
1553 ;; lines. You cannot necessarily
1554 ;; put them in the first line of
1555 ;; such a file without screwing up
1556 ;; the interpreter invocation.
1557 (end-of-line (and (looking-at "^#!") 2))
1558 (point)) t)
1559 (progn
1560 (skip-chars-forward " \t")
1561 (setq beg (point))
1562 (search-forward "-*-"
1563 (save-excursion (end-of-line) (point))
1564 t))
1565 (progn
1566 (forward-char -3)
1567 (skip-chars-backward " \t")
1568 (setq end (point))
1569 (goto-char beg)
1570 (if (save-excursion (search-forward ":" end t))
1571 ;; Find all specifications for the `mode:' variable
1572 ;; and execute them left to right.
1573 (while (let ((case-fold-search t))
1574 (or (and (looking-at "mode:")
1575 (goto-char (match-end 0)))
1576 (re-search-forward "[ \t;]mode:" end t)))
1577 (skip-chars-forward " \t")
1578 (setq beg (point))
1579 (if (search-forward ";" end t)
1580 (forward-char -1)
1581 (goto-char end))
1582 (skip-chars-backward " \t")
1583 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1584 modes)))
1585 ;; Simple -*-MODE-*- case.
1586 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1587 "-mode"))
1588 modes))))))
1589 ;; If we found modes to use, invoke them now,
1590 ;; outside the save-excursion.
1591 (when modes
1592 (unless just-from-file-name
1593 (mapc 'funcall (nreverse modes)))
1594 (setq done t))
1595 ;; If we didn't find a mode from a -*- line, try using the file name.
1596 (if (and (not done) buffer-file-name)
1597 (let ((name buffer-file-name)
1598 (keep-going t))
1599 ;; Remove backup-suffixes from file name.
1600 (setq name (file-name-sans-versions name))
1601 (while keep-going
1602 (setq keep-going nil)
1603 (let ((alist auto-mode-alist)
1604 (mode nil))
1605 ;; Find first matching alist entry.
1606 (let ((case-fold-search
1607 (memq system-type '(vax-vms windows-nt))))
1608 (while (and (not mode) alist)
1609 (if (string-match (car (car alist)) name)
1610 (if (and (consp (cdr (car alist)))
1611 (nth 2 (car alist)))
1612 (setq mode (car (cdr (car alist)))
1613 name (substring name 0 (match-beginning 0))
1614 keep-going t)
1615 (setq mode (cdr (car alist))
1616 keep-going nil)))
1617 (setq alist (cdr alist))))
1618 (if mode
1619 ;; When JUST-FROM-FILE-NAME is set,
1620 ;; we are working on behalf of set-visited-file-name.
1621 ;; In that case, if the major mode specified is the
1622 ;; same one we already have, don't actually reset it.
1623 ;; We don't want to lose minor modes such as Font Lock.
1624 (unless (and just-from-file-name (eq mode major-mode))
1625 (funcall mode))
1626 ;; If we can't deduce a mode from the file name,
1627 ;; look for an interpreter specified in the first line.
1628 ;; As a special case, allow for things like "#!/bin/env perl",
1629 ;; which finds the interpreter anywhere in $PATH.
1630 (let ((interpreter
1631 (save-excursion
1632 (goto-char (point-min))
1633 (if (looking-at "#![ \t]?\\([^ \t\n]*\
1634 /bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1635 (match-string 2)
1636 "")))
1637 elt)
1638 ;; Map interpreter name to a mode.
1639 (setq elt (assoc (file-name-nondirectory interpreter)
1640 interpreter-mode-alist))
1641 (unless just-from-file-name
1642 (if elt
1643 (funcall (cdr elt))))))))))))
1644
1645 (defun hack-local-variables-prop-line ()
1646 "Set local variables specified in the -*- line.
1647 Ignore any specification for `mode:' and `coding:';
1648 `set-auto-mode' should already have handled `mode:',
1649 `set-auto-coding' should already have handled `coding:'."
1650 (save-excursion
1651 (goto-char (point-min))
1652 (let ((result nil)
1653 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point)))
1654 (enable-local-variables
1655 (and local-enable-local-variables enable-local-variables)))
1656 ;; Parse the -*- line into the `result' alist.
1657 (cond ((not (search-forward "-*-" end t))
1658 ;; doesn't have one.
1659 nil)
1660 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1661 ;; Simple form: "-*- MODENAME -*-". Already handled.
1662 nil)
1663 (t
1664 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1665 ;; (last ";" is optional).
1666 (save-excursion
1667 (if (search-forward "-*-" end t)
1668 (setq end (- (point) 3))
1669 (error "-*- not terminated before end of line")))
1670 (while (< (point) end)
1671 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1672 (error "Malformed -*- line"))
1673 (goto-char (match-end 0))
1674 ;; There used to be a downcase here,
1675 ;; but the manual didn't say so,
1676 ;; and people want to set var names that aren't all lc.
1677 (let ((key (intern (buffer-substring
1678 (match-beginning 1)
1679 (match-end 1))))
1680 (val (save-restriction
1681 (narrow-to-region (point) end)
1682 (read (current-buffer)))))
1683 ;; It is traditional to ignore
1684 ;; case when checking for `mode' in set-auto-mode,
1685 ;; so we must do that here as well.
1686 ;; That is inconsistent, but we're stuck with it.
1687 ;; The same can be said for `coding' in set-auto-coding.
1688 (or (equal (downcase (symbol-name key)) "mode")
1689 (equal (downcase (symbol-name key)) "coding")
1690 (setq result (cons (cons key val) result)))
1691 (skip-chars-forward " \t;")))
1692 (setq result (nreverse result))))
1693
1694 (if (and result
1695 (or (eq enable-local-variables t)
1696 (and enable-local-variables
1697 (save-window-excursion
1698 (condition-case nil
1699 (switch-to-buffer (current-buffer))
1700 (error
1701 ;; If we fail to switch in the selected window,
1702 ;; it is probably a minibuffer.
1703 ;; So try another window.
1704 (condition-case nil
1705 (switch-to-buffer-other-window (current-buffer))
1706 (error
1707 (switch-to-buffer-other-frame (current-buffer))))))
1708 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1709 (file-name-nondirectory buffer-file-name)))))))
1710 (let ((enable-local-eval enable-local-eval))
1711 (while result
1712 (hack-one-local-variable (car (car result)) (cdr (car result)))
1713 (setq result (cdr result))))))))
1714
1715 (defvar hack-local-variables-hook nil
1716 "Normal hook run after processing a file's local variables specs.
1717 Major modes can use this to examine user-specified local variables
1718 in order to initialize other data structure based on them.")
1719
1720 (defun hack-local-variables (&optional mode-only)
1721 "Parse and put into effect this buffer's local variables spec.
1722 If MODE-ONLY is non-nil, all we do is check whether the major mode
1723 is specified, returning t if it is specified."
1724 (unless mode-only
1725 (hack-local-variables-prop-line))
1726 ;; Look for "Local variables:" line in last page.
1727 (let (mode-specified
1728 (enable-local-variables
1729 (and local-enable-local-variables enable-local-variables)))
1730 (save-excursion
1731 (goto-char (point-max))
1732 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1733 (if (let ((case-fold-search t))
1734 (and (search-forward "Local Variables:" nil t)
1735 (or (eq enable-local-variables t)
1736 mode-only
1737 (and enable-local-variables
1738 (save-window-excursion
1739 (switch-to-buffer (current-buffer))
1740 (save-excursion
1741 (beginning-of-line)
1742 (set-window-start (selected-window) (point)))
1743 (y-or-n-p (format "Set local variables as specified at end of %s? "
1744 (if buffer-file-name
1745 (file-name-nondirectory
1746 buffer-file-name)
1747 (concat "buffer "
1748 (buffer-name))))))))))
1749 (let ((continue t)
1750 prefix prefixlen suffix beg
1751 mode-specified
1752 (enable-local-eval enable-local-eval))
1753 ;; The prefix is what comes before "local variables:" in its line.
1754 ;; The suffix is what comes after "local variables:" in its line.
1755 (skip-chars-forward " \t")
1756 (or (eolp)
1757 (setq suffix (buffer-substring (point)
1758 (progn (end-of-line) (point)))))
1759 (goto-char (match-beginning 0))
1760 (or (bolp)
1761 (setq prefix
1762 (buffer-substring (point)
1763 (progn (beginning-of-line) (point)))))
1764
1765 (if prefix (setq prefixlen (length prefix)
1766 prefix (regexp-quote prefix)))
1767 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1768 (while continue
1769 ;; Look at next local variable spec.
1770 (if selective-display (re-search-forward "[\n\C-m]")
1771 (forward-line 1))
1772 ;; Skip the prefix, if any.
1773 (if prefix
1774 (if (looking-at prefix)
1775 (forward-char prefixlen)
1776 (error "Local variables entry is missing the prefix")))
1777 ;; Find the variable name; strip whitespace.
1778 (skip-chars-forward " \t")
1779 (setq beg (point))
1780 (skip-chars-forward "^:\n")
1781 (if (eolp) (error "Missing colon in local variables entry"))
1782 (skip-chars-backward " \t")
1783 (let* ((str (buffer-substring beg (point)))
1784 (var (read str))
1785 val)
1786 ;; Setting variable named "end" means end of list.
1787 (if (string-equal (downcase str) "end")
1788 (setq continue nil)
1789 ;; Otherwise read the variable value.
1790 (skip-chars-forward "^:")
1791 (forward-char 1)
1792 (setq val (read (current-buffer)))
1793 (skip-chars-backward "\n")
1794 (skip-chars-forward " \t")
1795 (or (if suffix (looking-at suffix) (eolp))
1796 (error "Local variables entry is terminated incorrectly"))
1797 (if mode-only
1798 (if (eq var 'mode)
1799 (setq mode-specified t))
1800 ;; Set the variable. "Variables" mode and eval are funny.
1801 (hack-one-local-variable var val))))))))
1802 (unless mode-only
1803 (run-hooks 'hack-local-variables-hook))
1804 mode-specified))
1805
1806 (defvar ignored-local-variables
1807 '(enable-local-eval)
1808 "Variables to be ignored in a file's local variable spec.")
1809
1810 ;; Get confirmation before setting these variables as locals in a file.
1811 (put 'debugger 'risky-local-variable t)
1812 (put 'enable-local-eval 'risky-local-variable t)
1813 (put 'ignored-local-variables 'risky-local-variable t)
1814 (put 'eval 'risky-local-variable t)
1815 (put 'file-name-handler-alist 'risky-local-variable t)
1816 (put 'minor-mode-map-alist 'risky-local-variable t)
1817 (put 'after-load-alist 'risky-local-variable t)
1818 (put 'buffer-file-name 'risky-local-variable t)
1819 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1820 (put 'buffer-file-truename 'risky-local-variable t)
1821 (put 'exec-path 'risky-local-variable t)
1822 (put 'load-path 'risky-local-variable t)
1823 (put 'exec-directory 'risky-local-variable t)
1824 (put 'process-environment 'risky-local-variable t)
1825 (put 'dabbrev-case-fold-search 'risky-local-variable t)
1826 (put 'dabbrev-case-replace 'risky-local-variable t)
1827 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1828 (put 'outline-level 'risky-local-variable t)
1829 (put 'rmail-output-file-alist 'risky-local-variable t)
1830
1831 ;; This one is safe because the user gets to check it before it is used.
1832 (put 'compile-command 'safe-local-variable t)
1833
1834 (defun hack-one-local-variable-quotep (exp)
1835 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1836
1837 (defun hack-one-local-variable (var val)
1838 "\"Set\" one variable in a local variables spec.
1839 A few variable names are treated specially."
1840 (cond ((eq var 'mode)
1841 (funcall (intern (concat (downcase (symbol-name val))
1842 "-mode"))))
1843 ((eq var 'coding)
1844 ;; We have already handled coding: tag in set-auto-coding.
1845 nil)
1846 ((memq var ignored-local-variables)
1847 nil)
1848 ;; "Setting" eval means either eval it or do nothing.
1849 ;; Likewise for setting hook variables.
1850 ((or (get var 'risky-local-variable)
1851 (and
1852 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$\\|-predicate$"
1853 (symbol-name var))
1854 (not (get var 'safe-local-variable))))
1855 ;; Permit evalling a put of a harmless property.
1856 ;; if the args do nothing tricky.
1857 (if (or (and (eq var 'eval)
1858 (consp val)
1859 (eq (car val) 'put)
1860 (hack-one-local-variable-quotep (nth 1 val))
1861 (hack-one-local-variable-quotep (nth 2 val))
1862 ;; Only allow safe values of lisp-indent-hook;
1863 ;; not functions.
1864 (or (numberp (nth 3 val))
1865 (equal (nth 3 val) ''defun))
1866 (memq (nth 1 (nth 2 val))
1867 '(lisp-indent-hook)))
1868 ;; Permit eval if not root and user says ok.
1869 (and (not (zerop (user-uid)))
1870 (or (eq enable-local-eval t)
1871 (and enable-local-eval
1872 (save-window-excursion
1873 (switch-to-buffer (current-buffer))
1874 (save-excursion
1875 (beginning-of-line)
1876 (set-window-start (selected-window) (point)))
1877 (setq enable-local-eval
1878 (y-or-n-p (format "Process `eval' or hook local variables in %s? "
1879 (if buffer-file-name
1880 (concat "file " (file-name-nondirectory buffer-file-name))
1881 (concat "buffer " (buffer-name)))))))))))
1882 (if (eq var 'eval)
1883 (save-excursion (eval val))
1884 (make-local-variable var)
1885 (set var val))
1886 (message "Ignoring `eval:' in the local variables list")))
1887 ;; Ordinary variable, really set it.
1888 (t (make-local-variable var)
1889 (set var val))))
1890
1891 \f
1892 (defcustom change-major-mode-with-file-name t
1893 "*Non-nil means \\[write-file] should set the major mode from the file name.
1894 However, the mode will not be changed if
1895 \(1) a local variables list or the `-*-' line specifies a major mode, or
1896 \(2) the current major mode is a \"special\" mode,
1897 \ not suitable for ordinary files, or
1898 \(3) the new file name does not particularly specify any mode."
1899 :type 'boolean
1900 :group 'editing-basics)
1901
1902 (defun set-visited-file-name (filename &optional no-query along-with-file)
1903 "Change name of file visited in current buffer to FILENAME.
1904 The next time the buffer is saved it will go in the newly specified file.
1905 nil or empty string as argument means make buffer not be visiting any file.
1906 Remember to delete the initial contents of the minibuffer
1907 if you wish to pass an empty string as the argument.
1908
1909 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1910 confirmation in the case where another buffer is already visiting FILENAME.
1911
1912 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1913 the old visited file has been renamed to the new name FILENAME."
1914 (interactive "FSet visited file name: ")
1915 (if (buffer-base-buffer)
1916 (error "An indirect buffer cannot visit a file"))
1917 (let (truename)
1918 (if filename
1919 (setq filename
1920 (if (string-equal filename "")
1921 nil
1922 (expand-file-name filename))))
1923 (if filename
1924 (progn
1925 (setq truename (file-truename filename))
1926 (if find-file-visit-truename
1927 (setq filename truename))))
1928 (let ((buffer (and filename (find-buffer-visiting filename))))
1929 (and buffer (not (eq buffer (current-buffer)))
1930 (not no-query)
1931 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1932 filename)))
1933 (error "Aborted")))
1934 (or (equal filename buffer-file-name)
1935 (progn
1936 (and filename (lock-buffer filename))
1937 (unlock-buffer)))
1938 (setq buffer-file-name filename)
1939 (if filename ; make buffer name reflect filename.
1940 (let ((new-name (file-name-nondirectory buffer-file-name)))
1941 (if (string= new-name "")
1942 (error "Empty file name"))
1943 (if (eq system-type 'vax-vms)
1944 (setq new-name (downcase new-name)))
1945 (setq default-directory (file-name-directory buffer-file-name))
1946 (or (string= new-name (buffer-name))
1947 (rename-buffer new-name t))))
1948 (setq buffer-backed-up nil)
1949 (or along-with-file
1950 (clear-visited-file-modtime))
1951 ;; Abbreviate the file names of the buffer.
1952 (if truename
1953 (progn
1954 (setq buffer-file-truename (abbreviate-file-name truename))
1955 (if find-file-visit-truename
1956 (setq buffer-file-name buffer-file-truename))))
1957 (setq buffer-file-number
1958 (if filename
1959 (nthcdr 10 (file-attributes buffer-file-name))
1960 nil)))
1961 ;; write-file-hooks is normally used for things like ftp-find-file
1962 ;; that visit things that are not local files as if they were files.
1963 ;; Changing to visit an ordinary local file instead should flush the hook.
1964 (kill-local-variable 'write-file-hooks)
1965 (kill-local-variable 'local-write-file-hooks)
1966 (kill-local-variable 'revert-buffer-function)
1967 (kill-local-variable 'backup-inhibited)
1968 ;; If buffer was read-only because of version control,
1969 ;; that reason is gone now, so make it writable.
1970 (if vc-mode
1971 (setq buffer-read-only nil))
1972 (kill-local-variable 'vc-mode)
1973 ;; Turn off backup files for certain file names.
1974 ;; Since this is a permanent local, the major mode won't eliminate it.
1975 (and buffer-file-name
1976 (not (funcall backup-enable-predicate buffer-file-name))
1977 (progn
1978 (make-local-variable 'backup-inhibited)
1979 (setq backup-inhibited t)))
1980 (let ((oauto buffer-auto-save-file-name))
1981 ;; If auto-save was not already on, turn it on if appropriate.
1982 (if (not buffer-auto-save-file-name)
1983 (and buffer-file-name auto-save-default
1984 (auto-save-mode t))
1985 ;; If auto save is on, start using a new name.
1986 ;; We deliberately don't rename or delete the old auto save
1987 ;; for the old visited file name. This is because perhaps
1988 ;; the user wants to save the new state and then compare with the
1989 ;; previous state from the auto save file.
1990 (setq buffer-auto-save-file-name
1991 (make-auto-save-file-name)))
1992 ;; Rename the old auto save file if any.
1993 (and oauto buffer-auto-save-file-name
1994 (file-exists-p oauto)
1995 (rename-file oauto buffer-auto-save-file-name t)))
1996 (and buffer-file-name
1997 (not along-with-file)
1998 (set-buffer-modified-p t))
1999 ;; Update the major mode, if the file name determines it.
2000 (condition-case nil
2001 ;; Don't change the mode if it is special.
2002 (or (not change-major-mode-with-file-name)
2003 (get major-mode 'mode-class)
2004 ;; Don't change the mode if the local variable list specifies it.
2005 (hack-local-variables t)
2006 (set-auto-mode t))
2007 (error nil)))
2008
2009 (defun write-file (filename &optional confirm)
2010 "Write current buffer into file FILENAME.
2011 This makes the buffer visit that file, and marks it as not modified.
2012
2013 If you specify just a directory name as FILENAME, that means to use
2014 the default file name but in that directory. You can also yank
2015 the default file name into the minibuffer to edit it, using M-n.
2016
2017 If the buffer is not already visiting a file, the default file name
2018 for the output file is the buffer name.
2019
2020 If optional second arg CONFIRM is non-nil, this function
2021 asks for confirmation before overwriting an existing file.
2022 Interactively, confirmation is required unless you supply a prefix argument."
2023 ;; (interactive "FWrite file: ")
2024 (interactive
2025 (list (if buffer-file-name
2026 (read-file-name "Write file: "
2027 nil nil nil nil)
2028 (read-file-name "Write file: " default-directory
2029 (expand-file-name
2030 (file-name-nondirectory (buffer-name))
2031 default-directory)
2032 nil nil))
2033 (not current-prefix-arg)))
2034 (or (null filename) (string-equal filename "")
2035 (progn
2036 ;; If arg is just a directory,
2037 ;; use the default file name, but in that directory.
2038 (if (file-directory-p filename)
2039 (setq filename (concat (file-name-as-directory filename)
2040 (file-name-nondirectory
2041 (or buffer-file-name (buffer-name))))))
2042 (and confirm
2043 (file-exists-p filename)
2044 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
2045 (error "Canceled")))
2046 (set-visited-file-name filename (not confirm))))
2047 (set-buffer-modified-p t)
2048 ;; Make buffer writable if file is writable.
2049 (and buffer-file-name
2050 (file-writable-p buffer-file-name)
2051 (setq buffer-read-only nil))
2052 (save-buffer))
2053 \f
2054 (defun backup-buffer ()
2055 "Make a backup of the disk file visited by the current buffer, if appropriate.
2056 This is normally done before saving the buffer the first time.
2057 If the value is non-nil, it is the result of `file-modes' on the original
2058 file; this means that the caller, after saving the buffer, should change
2059 the modes of the new file to agree with the old modes.
2060
2061 A backup may be done by renaming or by copying; see documentation of
2062 variable `make-backup-files'. If it's done by renaming, then the file is
2063 no longer accessible under its old name."
2064 (if (and make-backup-files (not backup-inhibited)
2065 (not buffer-backed-up)
2066 (file-exists-p buffer-file-name)
2067 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
2068 '(?- ?l)))
2069 (let ((real-file-name buffer-file-name)
2070 backup-info backupname targets setmodes)
2071 ;; If specified name is a symbolic link, chase it to the target.
2072 ;; Thus we make the backups in the directory where the real file is.
2073 (setq real-file-name (file-chase-links real-file-name))
2074 (setq backup-info (find-backup-file-name real-file-name)
2075 backupname (car backup-info)
2076 targets (cdr backup-info))
2077 ;;; (if (file-directory-p buffer-file-name)
2078 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
2079 (if backup-info
2080 (condition-case ()
2081 (let ((delete-old-versions
2082 ;; If have old versions to maybe delete,
2083 ;; ask the user to confirm now, before doing anything.
2084 ;; But don't actually delete til later.
2085 (and targets
2086 (or (eq delete-old-versions t) (eq delete-old-versions nil))
2087 (or delete-old-versions
2088 (y-or-n-p (format "Delete excess backup versions of %s? "
2089 real-file-name))))))
2090 ;; Actually write the back up file.
2091 (condition-case ()
2092 (if (or file-precious-flag
2093 ; (file-symlink-p buffer-file-name)
2094 backup-by-copying
2095 (and backup-by-copying-when-linked
2096 (> (file-nlinks real-file-name) 1))
2097 (and (or backup-by-copying-when-mismatch
2098 (integerp backup-by-copying-when-privileged-mismatch))
2099 (let ((attr (file-attributes real-file-name)))
2100 (and (or backup-by-copying-when-mismatch
2101 (and (integerp (nth 2 attr))
2102 (integerp backup-by-copying-when-privileged-mismatch)
2103 (<= (nth 2 attr) backup-by-copying-when-privileged-mismatch)))
2104 (or (nth 9 attr)
2105 (not (file-ownership-preserved-p real-file-name)))))))
2106 (condition-case ()
2107 (copy-file real-file-name backupname t t)
2108 (file-error
2109 ;; If copying fails because file BACKUPNAME
2110 ;; is not writable, delete that file and try again.
2111 (if (and (file-exists-p backupname)
2112 (not (file-writable-p backupname)))
2113 (delete-file backupname))
2114 (copy-file real-file-name backupname t t)))
2115 ;; rename-file should delete old backup.
2116 (rename-file real-file-name backupname t)
2117 (setq setmodes (file-modes backupname)))
2118 (file-error
2119 ;; If trouble writing the backup, write it in ~.
2120 (setq backupname (expand-file-name
2121 (convert-standard-filename
2122 "~/%backup%~")))
2123 (message "Cannot write backup file; backing up in %s"
2124 (file-name-nondirectory backupname))
2125 (sleep-for 1)
2126 (condition-case ()
2127 (copy-file real-file-name backupname t t)
2128 (file-error
2129 ;; If copying fails because file BACKUPNAME
2130 ;; is not writable, delete that file and try again.
2131 (if (and (file-exists-p backupname)
2132 (not (file-writable-p backupname)))
2133 (delete-file backupname))
2134 (copy-file real-file-name backupname t t)))))
2135 (setq buffer-backed-up t)
2136 ;; Now delete the old versions, if desired.
2137 (if delete-old-versions
2138 (while targets
2139 (condition-case ()
2140 (delete-file (car targets))
2141 (file-error nil))
2142 (setq targets (cdr targets))))
2143 setmodes)
2144 (file-error nil))))))
2145
2146 (defun file-name-sans-versions (name &optional keep-backup-version)
2147 "Return file NAME sans backup versions or strings.
2148 This is a separate procedure so your site-init or startup file can
2149 redefine it.
2150 If the optional argument KEEP-BACKUP-VERSION is non-nil,
2151 we do not remove backup version numbers, only true file version numbers."
2152 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
2153 (if handler
2154 (funcall handler 'file-name-sans-versions name keep-backup-version)
2155 (substring name 0
2156 (if (eq system-type 'vax-vms)
2157 ;; VMS version number is (a) semicolon, optional
2158 ;; sign, zero or more digits or (b) period, option
2159 ;; sign, zero or more digits, provided this is the
2160 ;; second period encountered outside of the
2161 ;; device/directory part of the file name.
2162 (or (string-match ";[-+]?[0-9]*\\'" name)
2163 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
2164 name)
2165 (match-beginning 1))
2166 (length name))
2167 (if keep-backup-version
2168 (length name)
2169 (or (string-match "\\.~[0-9.]+~\\'" name)
2170 (string-match "~\\'" name)
2171 (length name))))))))
2172
2173 (defun file-ownership-preserved-p (file)
2174 "Return t if deleting FILE and rewriting it would preserve the owner."
2175 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
2176 (if handler
2177 (funcall handler 'file-ownership-preserved-p file)
2178 (let ((attributes (file-attributes file)))
2179 ;; Return t if the file doesn't exist, since it's true that no
2180 ;; information would be lost by an (attempted) delete and create.
2181 (or (null attributes)
2182 (= (nth 2 attributes) (user-uid)))))))
2183
2184 (defun file-name-sans-extension (filename)
2185 "Return FILENAME sans final \"extension\".
2186 The extension, in a file name, is the part that follows the last `.'."
2187 (save-match-data
2188 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
2189 directory)
2190 (if (string-match "\\.[^.]*\\'" file)
2191 (if (setq directory (file-name-directory filename))
2192 (expand-file-name (substring file 0 (match-beginning 0))
2193 directory)
2194 (substring file 0 (match-beginning 0)))
2195 filename))))
2196
2197 (defun file-name-extension (filename &optional period)
2198 "Return FILENAME's final \"extension\".
2199 The extension, in a file name, is the part that follows the last `.'.
2200 Return nil for extensionless file names such as `foo'.
2201 Return the empty string for file names such as `foo.'.
2202
2203 If PERIOD is non-nil, then the returned value includes the period
2204 that delimits the extension, and if FILENAME has no extension,
2205 the value is \"\"."
2206 (save-match-data
2207 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
2208 (if (string-match "\\.[^.]*\\'" file)
2209 (substring file (+ (match-beginning 0) (if period 0 1)))
2210 (if period
2211 "")))))
2212
2213 (defcustom make-backup-file-name-function nil
2214 "A function to use instead of the default `make-backup-file-name'.
2215 A value of nil gives the default `make-backup-file-name' behaviour.
2216
2217 This could be buffer-local to do something special for for specific
2218 files. If you define it, you may need to change `backup-file-name-p'
2219 and `file-name-sans-versions' too.
2220
2221 See also `backup-directory-alist'."
2222 :group 'backup
2223 :type '(choice (const :tag "Default" nil)
2224 (function :tag "Your function")))
2225
2226 (defcustom backup-directory-alist nil
2227 "Alist of filename patterns and backup directory names.
2228 Each element looks like (REGEXP . DIRECTORY). Backups of files with
2229 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
2230 relative or absolute. If it is absolute, so that all matching files
2231 are backed up into the same directory, the file names in this
2232 directory will be the full name of the file backed up with all
2233 directory separators changed to `|' to prevent clashes. This will not
2234 work correctly if your filesystem truncates the resulting name.
2235
2236 For the common case of all backups going into one directory, the alist
2237 should contain a single element pairing \".\" with the appropriate
2238 directory name.
2239
2240 If this variable is nil, or it fails to match a filename, the backup
2241 is made in the original file's directory.
2242
2243 On MS-DOS filesystems without long names this variable is always
2244 ignored."
2245 :group 'backup
2246 :type '(repeat (cons (regexp :tag "Regexp macthing filename")
2247 (directory :tag "Backup directory name"))))
2248
2249 (defun make-backup-file-name (file)
2250 "Create the non-numeric backup file name for FILE.
2251 Normally this will just be the file's name with `~' appended.
2252 Customization hooks are provided as follows.
2253
2254 If the variable `make-backup-file-name-function' is non-nil, its value
2255 should be a function which will be called with FILE as its argument;
2256 the resulting name is used.
2257
2258 Otherwise a match for FILE is sought in `backup-directory-alist'; see
2259 the documentation of that variable. If the directory for the backup
2260 doesn't exist, it is created."
2261 (if make-backup-file-name-function
2262 (funcall make-backup-file-name-function file)
2263 (if (and (eq system-type 'ms-dos)
2264 (not (msdos-long-file-names)))
2265 (let ((fn (file-name-nondirectory file)))
2266 (concat (file-name-directory file)
2267 (or (and (string-match "\\`[^.]+\\'" fn)
2268 (concat (match-string 0 fn) ".~"))
2269 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
2270 (concat (match-string 0 fn) "~")))))
2271 (concat (make-backup-file-name-1 file) "~"))))
2272
2273 (defun make-backup-file-name-1 (file)
2274 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
2275 (let ((alist backup-directory-alist)
2276 elt backup-directory)
2277 (while alist
2278 (setq elt (pop alist))
2279 (if (string-match (car elt) file)
2280 (setq backup-directory (cdr elt)
2281 alist nil)))
2282 (if (null backup-directory)
2283 file
2284 (unless (file-exists-p backup-directory)
2285 (condition-case nil
2286 (make-directory backup-directory 'parents)
2287 (file-error file)))
2288 (if (file-name-absolute-p backup-directory)
2289 ;; Make the name unique by substituting directory
2290 ;; separators. It may not really be worth bothering about
2291 ;; doubling `|'s in the original name...
2292 (expand-file-name
2293 (subst-char-in-string
2294 directory-sep-char ?|
2295 (replace-regexp-in-string "|" "||" file))
2296 backup-directory)
2297 (expand-file-name (file-name-nondirectory file)
2298 (file-name-as-directory
2299 (expand-file-name backup-directory
2300 (file-name-directory file))))))))
2301
2302 (defun backup-file-name-p (file)
2303 "Return non-nil if FILE is a backup file name (numeric or not).
2304 This is a separate function so you can redefine it for customization.
2305 You may need to redefine `file-name-sans-versions' as well."
2306 (string-match "~\\'" file))
2307
2308 (defvar backup-extract-version-start)
2309
2310 ;; This is used in various files.
2311 ;; The usage of backup-extract-version-start is not very clean,
2312 ;; but I can't see a good alternative, so as of now I am leaving it alone.
2313 (defun backup-extract-version (fn)
2314 "Given the name of a numeric backup file, FN, return the backup number.
2315 Uses the free variable `backup-extract-version-start', whose value should be
2316 the index in the name where the version number begins."
2317 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
2318 (= (match-beginning 0) backup-extract-version-start))
2319 (string-to-int (substring fn backup-extract-version-start -1))
2320 0))
2321
2322 ;; I believe there is no need to alter this behavior for VMS;
2323 ;; since backup files are not made on VMS, it should not get called.
2324 (defun find-backup-file-name (fn)
2325 "Find a file name for a backup file FN, and suggestions for deletions.
2326 Value is a list whose car is the name for the backup file
2327 and whose cdr is a list of old versions to consider deleting now.
2328 If the value is nil, don't make a backup.
2329 Uses `backup-directory-alist' in the same way as does
2330 `make-backup-file-name'."
2331 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2332 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2333 (if handler
2334 (funcall handler 'find-backup-file-name fn)
2335 (if (eq version-control 'never)
2336 (list (make-backup-file-name fn))
2337 (let* ((basic-name (make-backup-file-name-1 fn))
2338 (base-versions (concat (file-name-nondirectory basic-name)
2339 ".~"))
2340 (backup-extract-version-start (length base-versions))
2341 (high-water-mark 0)
2342 (number-to-delete 0)
2343 possibilities deserve-versions-p versions)
2344 (condition-case ()
2345 (setq possibilities (file-name-all-completions
2346 base-versions
2347 (file-name-directory basic-name))
2348 versions (sort (mapcar #'backup-extract-version
2349 possibilities)
2350 #'<)
2351 high-water-mark (apply 'max 0 versions)
2352 deserve-versions-p (or version-control
2353 (> high-water-mark 0))
2354 number-to-delete (- (length versions)
2355 kept-old-versions
2356 kept-new-versions
2357 -1))
2358 (file-error (setq possibilities nil)))
2359 (if (not deserve-versions-p)
2360 (list (concat basic-name "~"))
2361 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
2362 (if (and (> number-to-delete 0)
2363 ;; Delete nothing if there is overflow
2364 ;; in the number of versions to keep.
2365 (>= (+ kept-new-versions kept-old-versions -1) 0))
2366 (mapcar (lambda (n)
2367 (format "%s.~%d~" basic-name n))
2368 (let ((v (nthcdr kept-old-versions versions)))
2369 (rplacd (nthcdr (1- number-to-delete) v) ())
2370 v))))))))))
2371
2372 (defun file-nlinks (filename)
2373 "Return number of names file FILENAME has."
2374 (car (cdr (file-attributes filename))))
2375
2376 (defun file-relative-name (filename &optional directory)
2377 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
2378 This function returns a relative file name which is equivalent to FILENAME
2379 when used with that default directory as the default.
2380 If this is impossible (which can happen on MSDOS and Windows
2381 when the file name and directory use different drive names)
2382 then it returns FILENAME."
2383 (save-match-data
2384 (let ((fname (expand-file-name filename)))
2385 (setq directory (file-name-as-directory
2386 (expand-file-name (or directory default-directory))))
2387 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2388 ;; drive names, they can't be relative, so return the absolute name.
2389 (if (and (or (eq system-type 'ms-dos)
2390 (eq system-type 'windows-nt))
2391 (not (string-equal (substring fname 0 2)
2392 (substring directory 0 2))))
2393 filename
2394 (let ((ancestor ".")
2395 (fname-dir (file-name-as-directory fname)))
2396 (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
2397 (not (string-match (concat "^" (regexp-quote directory)) fname)))
2398 (setq directory (file-name-directory (substring directory 0 -1))
2399 ancestor (if (equal ancestor ".")
2400 ".."
2401 (concat "../" ancestor))))
2402 ;; Now ancestor is empty, or .., or ../.., etc.
2403 (if (string-match (concat "^" (regexp-quote directory)) fname)
2404 ;; We matched within FNAME's directory part.
2405 ;; Add the rest of FNAME onto ANCESTOR.
2406 (let ((rest (substring fname (match-end 0))))
2407 (if (and (equal ancestor ".")
2408 (not (equal rest "")))
2409 ;; But don't bother with ANCESTOR if it would give us `./'.
2410 rest
2411 (concat (file-name-as-directory ancestor) rest)))
2412 ;; We matched FNAME's directory equivalent.
2413 ancestor))))))
2414 \f
2415 (defun save-buffer (&optional args)
2416 "Save current buffer in visited file if modified. Versions described below.
2417 By default, makes the previous version into a backup file
2418 if previously requested or if this is the first save.
2419 With 1 \\[universal-argument], marks this version
2420 to become a backup when the next save is done.
2421 With 2 \\[universal-argument]'s,
2422 unconditionally makes the previous version into a backup file.
2423 With 3 \\[universal-argument]'s, marks this version
2424 to become a backup when the next save is done,
2425 and unconditionally makes the previous version into a backup file.
2426
2427 With argument of 0, never make the previous version into a backup file.
2428
2429 If a file's name is FOO, the names of its numbered backup versions are
2430 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2431 Numeric backups (rather than FOO~) will be made if value of
2432 `version-control' is not the atom `never' and either there are already
2433 numeric versions of the file being backed up, or `version-control' is
2434 non-nil.
2435 We don't want excessive versions piling up, so there are variables
2436 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2437 and `kept-new-versions', which tells how many newest versions to keep.
2438 Defaults are 2 old versions and 2 new.
2439 `dired-kept-versions' controls dired's clean-directory (.) command.
2440 If `delete-old-versions' is nil, system will query user
2441 before trimming versions. Otherwise it does it silently.
2442
2443 If `vc-make-backup-files' is nil, which is the default,
2444 no backup files are made for files managed by version control.
2445 (This is because the version control system itself records previous versions.)
2446
2447 See the subroutine `basic-save-buffer' for more information."
2448 (interactive "p")
2449 (let ((modp (buffer-modified-p))
2450 (large (> (buffer-size) 50000))
2451 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2452 (memq args '(16 64)))))
2453 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2454 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
2455 (basic-save-buffer)
2456 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2457
2458 (defun delete-auto-save-file-if-necessary (&optional force)
2459 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2460 Normally delete only if the file was written by this Emacs since
2461 the last real save, but optional arg FORCE non-nil means delete anyway."
2462 (and buffer-auto-save-file-name delete-auto-save-files
2463 (not (string= buffer-file-name buffer-auto-save-file-name))
2464 (or force (recent-auto-save-p))
2465 (progn
2466 (condition-case ()
2467 (delete-file buffer-auto-save-file-name)
2468 (file-error nil))
2469 (set-buffer-auto-saved))))
2470
2471 (defvar auto-save-hook nil
2472 "Normal hook run just before auto-saving.")
2473
2474 (defvar after-save-hook nil
2475 "Normal hook that is run after a buffer is saved to its file.")
2476
2477 (defvar save-buffer-coding-system nil
2478 "If non-nil, use this coding system for saving the buffer.
2479 More precisely, use this coding system in place of the
2480 value of `buffer-file-coding-system', when saving the buffer.
2481 Calling `write-region' for any purpose other than saving the buffer
2482 will still use `buffer-file-coding-system'; this variable has no effect
2483 in such cases.")
2484
2485 (make-variable-buffer-local 'save-buffer-coding-system)
2486 (put 'save-buffer-coding-system 'permanent-local t)
2487
2488 (defun basic-save-buffer ()
2489 "Save the current buffer in its visited file, if it has been modified.
2490 The hooks `write-contents-hooks', `local-write-file-hooks' and
2491 `write-file-hooks' get a chance to do the job of saving; if they do not,
2492 then the buffer is saved in the visited file file in the usual way.
2493 After saving the buffer, this function runs `after-save-hook'."
2494 (interactive)
2495 (save-current-buffer
2496 ;; In an indirect buffer, save its base buffer instead.
2497 (if (buffer-base-buffer)
2498 (set-buffer (buffer-base-buffer)))
2499 (if (buffer-modified-p)
2500 (let ((recent-save (recent-auto-save-p))
2501 setmodes tempsetmodes)
2502 ;; On VMS, rename file and buffer to get rid of version number.
2503 (if (and (eq system-type 'vax-vms)
2504 (not (string= buffer-file-name
2505 (file-name-sans-versions buffer-file-name))))
2506 (let (buffer-new-name)
2507 ;; Strip VMS version number before save.
2508 (setq buffer-file-name
2509 (file-name-sans-versions buffer-file-name))
2510 ;; Construct a (unique) buffer name to correspond.
2511 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2512 (setq buffer-new-name (buffer-name buf))
2513 (kill-buffer buf))
2514 (rename-buffer buffer-new-name)))
2515 ;; If buffer has no file name, ask user for one.
2516 (or buffer-file-name
2517 (let ((filename
2518 (expand-file-name
2519 (read-file-name "File to save in: ") nil)))
2520 (and (file-exists-p filename)
2521 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2522 filename))
2523 (error "Canceled")))
2524 (set-visited-file-name filename)))
2525 (or (verify-visited-file-modtime (current-buffer))
2526 (not (file-exists-p buffer-file-name))
2527 (yes-or-no-p
2528 (format "%s has changed since visited or saved. Save anyway? "
2529 (file-name-nondirectory buffer-file-name)))
2530 (error "Save not confirmed"))
2531 (save-restriction
2532 (widen)
2533 (save-excursion
2534 (and (> (point-max) 1)
2535 (/= (char-after (1- (point-max))) ?\n)
2536 (not (and (eq selective-display t)
2537 (= (char-after (1- (point-max))) ?\r)))
2538 (or (eq require-final-newline t)
2539 (and require-final-newline
2540 (y-or-n-p
2541 (format "Buffer %s does not end in newline. Add one? "
2542 (buffer-name)))))
2543 (save-excursion
2544 (goto-char (point-max))
2545 (insert ?\n))))
2546 (or (run-hook-with-args-until-success 'write-contents-hooks)
2547 (run-hook-with-args-until-success 'local-write-file-hooks)
2548 (run-hook-with-args-until-success 'write-file-hooks)
2549 ;; If a hook returned t, file is already "written".
2550 ;; Otherwise, write it the usual way now.
2551 (setq setmodes (basic-save-buffer-1)))
2552 ;; Now we have saved the current buffer. Let's make sure
2553 ;; that buffer-file-coding-system is fixed to what
2554 ;; actually used for saving by binding it locally.
2555 (if save-buffer-coding-system
2556 (setq save-buffer-coding-system last-coding-system-used)
2557 (setq buffer-file-coding-system last-coding-system-used))
2558 (setq buffer-file-number
2559 (nthcdr 10 (file-attributes buffer-file-name)))
2560 (if setmodes
2561 (condition-case ()
2562 (set-file-modes buffer-file-name setmodes)
2563 (error nil))))
2564 ;; If the auto-save file was recent before this command,
2565 ;; delete it now.
2566 (delete-auto-save-file-if-necessary recent-save)
2567 ;; Support VC `implicit' locking.
2568 (vc-after-save)
2569 (run-hooks 'after-save-hook))
2570 (message "(No changes need to be saved)"))))
2571
2572 ;; This does the "real job" of writing a buffer into its visited file
2573 ;; and making a backup file. This is what is normally done
2574 ;; but inhibited if one of write-file-hooks returns non-nil.
2575 ;; It returns a value to store in setmodes.
2576 (defun basic-save-buffer-1 ()
2577 (if save-buffer-coding-system
2578 (let ((coding-system-for-write save-buffer-coding-system))
2579 (basic-save-buffer-2))
2580 (basic-save-buffer-2)))
2581
2582 (defun basic-save-buffer-2 ()
2583 (let (tempsetmodes setmodes)
2584 (if (not (file-writable-p buffer-file-name))
2585 (let ((dir (file-name-directory buffer-file-name)))
2586 (if (not (file-directory-p dir))
2587 (if (file-exists-p dir)
2588 (error "%s is not a directory" dir)
2589 (error "%s: no such directory" buffer-file-name))
2590 (if (not (file-exists-p buffer-file-name))
2591 (error "Directory %s write-protected" dir)
2592 (if (yes-or-no-p
2593 (format "File %s is write-protected; try to save anyway? "
2594 (file-name-nondirectory
2595 buffer-file-name)))
2596 (setq tempsetmodes t)
2597 (error "Attempt to save to a file which you aren't allowed to write"))))))
2598 (or buffer-backed-up
2599 (setq setmodes (backup-buffer)))
2600 (let ((dir (file-name-directory buffer-file-name)))
2601 (if (and file-precious-flag
2602 (file-writable-p dir))
2603 ;; If file is precious, write temp name, then rename it.
2604 ;; This requires write access to the containing dir,
2605 ;; which is why we don't try it if we don't have that access.
2606 (let ((realname buffer-file-name)
2607 tempname temp nogood i succeed
2608 (old-modtime (visited-file-modtime)))
2609 (setq i 0)
2610 (setq nogood t)
2611 ;; Find the temporary name to write under.
2612 (while nogood
2613 (setq tempname (format
2614 (if (and (eq system-type 'ms-dos)
2615 (not (msdos-long-file-names)))
2616 "%s#%d.tm#" ; MSDOS limits files to 8+3
2617 (if (memq system-type '(vax-vms axp-vms))
2618 "%s$tmp$%d"
2619 "%s#tmp#%d"))
2620 dir i))
2621 (setq nogood (file-exists-p tempname))
2622 (setq i (1+ i)))
2623 (unwind-protect
2624 (progn (clear-visited-file-modtime)
2625 (write-region (point-min) (point-max)
2626 tempname nil realname
2627 buffer-file-truename)
2628 (setq succeed t))
2629 ;; If writing the temp file fails,
2630 ;; delete the temp file.
2631 (or succeed
2632 (progn
2633 (delete-file tempname)
2634 (set-visited-file-modtime old-modtime))))
2635 ;; Since we have created an entirely new file
2636 ;; and renamed it, make sure it gets the
2637 ;; right permission bits set.
2638 (setq setmodes (file-modes buffer-file-name))
2639 ;; We succeeded in writing the temp file,
2640 ;; so rename it.
2641 (rename-file tempname buffer-file-name t))
2642 ;; If file not writable, see if we can make it writable
2643 ;; temporarily while we write it.
2644 ;; But no need to do so if we have just backed it up
2645 ;; (setmodes is set) because that says we're superseding.
2646 (cond ((and tempsetmodes (not setmodes))
2647 ;; Change the mode back, after writing.
2648 (setq setmodes (file-modes buffer-file-name))
2649 (set-file-modes buffer-file-name 511)))
2650 (write-region (point-min) (point-max)
2651 buffer-file-name nil t buffer-file-truename)))
2652 setmodes))
2653
2654 (defun save-some-buffers (&optional arg pred)
2655 "Save some modified file-visiting buffers. Asks user about each one.
2656 Optional argument (the prefix) non-nil means save all with no questions.
2657 Optional second argument PRED determines which buffers are considered:
2658 If PRED is nil, all the file-visiting buffers are considered.
2659 If PRED is t, then certain non-file buffers will also be considered.
2660 If PRED is a zero-argument function, it indicates for each buffer whether
2661 to consider it or not when called with that buffer current."
2662 (interactive "P")
2663 (save-window-excursion
2664 (let* ((queried nil)
2665 (files-done
2666 (map-y-or-n-p
2667 (function
2668 (lambda (buffer)
2669 (and (buffer-modified-p buffer)
2670 (not (buffer-base-buffer buffer))
2671 (or
2672 (buffer-file-name buffer)
2673 (and pred
2674 (progn
2675 (set-buffer buffer)
2676 (and buffer-offer-save (> (buffer-size) 0)))))
2677 (or (not (functionp pred))
2678 (with-current-buffer buffer (funcall pred)))
2679 (if arg
2680 t
2681 (setq queried t)
2682 (if (buffer-file-name buffer)
2683 (format "Save file %s? "
2684 (buffer-file-name buffer))
2685 (format "Save buffer %s? "
2686 (buffer-name buffer)))))))
2687 (function
2688 (lambda (buffer)
2689 (set-buffer buffer)
2690 (save-buffer)))
2691 (buffer-list)
2692 '("buffer" "buffers" "save")
2693 (list (list ?\C-r (lambda (buf)
2694 (view-buffer buf
2695 (function
2696 (lambda (ignore)
2697 (exit-recursive-edit))))
2698 (recursive-edit)
2699 ;; Return nil to ask about BUF again.
2700 nil)
2701 "display the current buffer"))))
2702 (abbrevs-done
2703 (and save-abbrevs abbrevs-changed
2704 (progn
2705 (if (or arg
2706 (y-or-n-p (format "Save abbrevs in %s? "
2707 abbrev-file-name)))
2708 (write-abbrev-file nil))
2709 ;; Don't keep bothering user if he says no.
2710 (setq abbrevs-changed nil)
2711 t))))
2712 (or queried (> files-done 0) abbrevs-done
2713 (message "(No files need saving)")))))
2714 \f
2715 (defun not-modified (&optional arg)
2716 "Mark current buffer as unmodified, not needing to be saved.
2717 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2718
2719 It is not a good idea to use this function in Lisp programs, because it
2720 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2721 (interactive "P")
2722 (message (if arg "Modification-flag set"
2723 "Modification-flag cleared"))
2724 (set-buffer-modified-p arg))
2725
2726 (defun toggle-read-only (&optional arg)
2727 "Change whether this buffer is visiting its file read-only.
2728 With arg, set read-only iff arg is positive.
2729 If visiting file read-only and `view-read-only' is non-nil, enter view mode."
2730 (interactive "P")
2731 (cond
2732 ((and arg (if (> (prefix-numeric-value arg) 0) buffer-read-only
2733 (not buffer-read-only))) ; If buffer-read-only is set correctly,
2734 nil) ; do nothing.
2735 ;; Toggle.
2736 ((and buffer-read-only view-mode)
2737 (View-exit-and-edit)
2738 (make-local-variable 'view-read-only)
2739 (setq view-read-only t)) ; Must leave view mode.
2740 ((and (not buffer-read-only) view-read-only
2741 (not (eq (get major-mode 'mode-class) 'special)))
2742 (view-mode-enter))
2743 (t (setq buffer-read-only (not buffer-read-only))
2744 (force-mode-line-update))))
2745
2746 (defun insert-file (filename)
2747 "Insert contents of file FILENAME into buffer after point.
2748 Set mark after the inserted text.
2749
2750 This function is meant for the user to run interactively.
2751 Don't call it from programs! Use `insert-file-contents' instead.
2752 \(Its calling sequence is different; see its documentation)."
2753 (interactive "*fInsert file: ")
2754 (if (file-directory-p filename)
2755 (signal 'file-error (list "Opening input file" "file is a directory"
2756 filename)))
2757 (let ((tem (insert-file-contents filename)))
2758 (push-mark (+ (point) (car (cdr tem))))))
2759
2760 (defun append-to-file (start end filename)
2761 "Append the contents of the region to the end of file FILENAME.
2762 When called from a function, expects three arguments,
2763 START, END and FILENAME. START and END are buffer positions
2764 saying what text to write."
2765 (interactive "r\nFAppend to file: ")
2766 (write-region start end filename t))
2767
2768 (defun file-newest-backup (filename)
2769 "Return most recent backup file for FILENAME or nil if no backups exist."
2770 ;; `make-backup-file-name' will get us the right directory for
2771 ;; ordinary or numeric backups. It might create a directory for
2772 ;; backups as a side-effect, according to `backup-directory-alist'.
2773 (let* ((filename (file-name-sans-versions
2774 (make-backup-file-name filename)))
2775 (file (file-name-nondirectory filename))
2776 (dir (file-name-directory filename))
2777 (comp (file-name-all-completions file dir))
2778 (newest nil)
2779 tem)
2780 (while comp
2781 (setq tem (pop comp))
2782 (cond ((and (backup-file-name-p tem)
2783 (string= (file-name-sans-versions tem) file))
2784 (setq tem (concat dir tem))
2785 (if (or (null newest)
2786 (file-newer-than-file-p tem newest))
2787 (setq newest tem)))))
2788 newest))
2789
2790 (defun rename-uniquely ()
2791 "Rename current buffer to a similar name not already taken.
2792 This function is useful for creating multiple shell process buffers
2793 or multiple mail buffers, etc."
2794 (interactive)
2795 (save-match-data
2796 (let ((base-name (buffer-name)))
2797 (and (string-match "<[0-9]+>\\'" base-name)
2798 (not (and buffer-file-name
2799 (string= base-name
2800 (file-name-nondirectory buffer-file-name))))
2801 ;; If the existing buffer name has a <NNN>,
2802 ;; which isn't part of the file name (if any),
2803 ;; then get rid of that.
2804 (setq base-name (substring base-name 0 (match-beginning 0))))
2805 (rename-buffer (generate-new-buffer-name base-name))
2806 (force-mode-line-update))))
2807
2808 (defun make-directory (dir &optional parents)
2809 "Create the directory DIR and any nonexistent parent dirs.
2810 Interactively, the default choice of directory to create
2811 is the current default directory for file names.
2812 That is useful when you have visited a file in a nonexistent directory.
2813
2814 Noninteractively, the second (optional) argument PARENTS says whether
2815 to create parent directories if they don't exist."
2816 (interactive
2817 (list (read-file-name "Make directory: " default-directory default-directory
2818 nil nil)
2819 t))
2820 (let ((handler (find-file-name-handler dir 'make-directory)))
2821 (if handler
2822 (funcall handler 'make-directory dir parents)
2823 (if (not parents)
2824 (make-directory-internal dir)
2825 (let ((dir (directory-file-name (expand-file-name dir)))
2826 create-list)
2827 (while (not (file-exists-p dir))
2828 (setq create-list (cons dir create-list)
2829 dir (directory-file-name (file-name-directory dir))))
2830 (while create-list
2831 (make-directory-internal (car create-list))
2832 (setq create-list (cdr create-list))))))))
2833 \f
2834 (put 'revert-buffer-function 'permanent-local t)
2835 (defvar revert-buffer-function nil
2836 "Function to use to revert this buffer, or nil to do the default.
2837 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2838 which are the arguments that `revert-buffer' received.")
2839
2840 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2841 (defvar revert-buffer-insert-file-contents-function nil
2842 "Function to use to insert contents when reverting this buffer.
2843 Gets two args, first the nominal file name to use,
2844 and second, t if reading the auto-save file.
2845
2846 The function you specify is responsible for updating (or preserving) point.")
2847
2848 (defvar before-revert-hook nil
2849 "Normal hook for `revert-buffer' to run before reverting.
2850 If `revert-buffer-function' is used to override the normal revert
2851 mechanism, this hook is not used.")
2852
2853 (defvar after-revert-hook nil
2854 "Normal hook for `revert-buffer' to run after reverting.
2855 Note that the hook value that it runs is the value that was in effect
2856 before reverting; that makes a difference if you have buffer-local
2857 hook functions.
2858
2859 If `revert-buffer-function' is used to override the normal revert
2860 mechanism, this hook is not used.")
2861
2862 (defvar revert-buffer-internal-hook)
2863
2864 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2865 "Replace current buffer text with the text of the visited file on disk.
2866 This undoes all changes since the file was visited or saved.
2867 With a prefix argument, offer to revert from latest auto-save file, if
2868 that is more recent than the visited file.
2869
2870 This command also works for special buffers that contain text which
2871 doesn't come from a file, but reflects some other data base instead:
2872 for example, Dired buffers and buffer-list buffers. In these cases,
2873 it reconstructs the buffer contents from the appropriate data base.
2874
2875 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2876 to revert from the auto-save file when this is nil. Note that the
2877 sense of this argument is the reverse of the prefix argument, for the
2878 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2879 to nil.
2880
2881 Optional second argument NOCONFIRM means don't ask for confirmation at
2882 all. (The local variable `revert-without-query', if non-nil, prevents
2883 confirmation.)
2884
2885 Optional third argument PRESERVE-MODES non-nil means don't alter
2886 the files modes. Normally we reinitialize them using `normal-mode'.
2887
2888 If the value of `revert-buffer-function' is non-nil, it is called to
2889 do all the work for this command. Otherwise, the hooks
2890 `before-revert-hook' and `after-revert-hook' are run at the beginning
2891 and the end, and if `revert-buffer-insert-file-contents-function' is
2892 non-nil, it is called instead of rereading visited file contents."
2893
2894 ;; I admit it's odd to reverse the sense of the prefix argument, but
2895 ;; there is a lot of code out there which assumes that the first
2896 ;; argument should be t to avoid consulting the auto-save file, and
2897 ;; there's no straightforward way to encourage authors to notice a
2898 ;; reversal of the argument sense. So I'm just changing the user
2899 ;; interface, but leaving the programmatic interface the same.
2900 (interactive (list (not current-prefix-arg)))
2901 (if revert-buffer-function
2902 (funcall revert-buffer-function ignore-auto noconfirm)
2903 (let* ((auto-save-p (and (not ignore-auto)
2904 (recent-auto-save-p)
2905 buffer-auto-save-file-name
2906 (file-readable-p buffer-auto-save-file-name)
2907 (y-or-n-p
2908 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2909 (file-name (if auto-save-p
2910 buffer-auto-save-file-name
2911 buffer-file-name)))
2912 (cond ((null file-name)
2913 (error "Buffer does not seem to be associated with any file"))
2914 ((or noconfirm
2915 (and (not (buffer-modified-p))
2916 (let ((tail revert-without-query)
2917 (found nil))
2918 (while tail
2919 (if (string-match (car tail) file-name)
2920 (setq found t))
2921 (setq tail (cdr tail)))
2922 found))
2923 (yes-or-no-p (format "Revert buffer from file %s? "
2924 file-name)))
2925 (run-hooks 'before-revert-hook)
2926 ;; If file was backed up but has changed since,
2927 ;; we shd make another backup.
2928 (and (not auto-save-p)
2929 (not (verify-visited-file-modtime (current-buffer)))
2930 (setq buffer-backed-up nil))
2931 ;; Get rid of all undo records for this buffer.
2932 (or (eq buffer-undo-list t)
2933 (setq buffer-undo-list nil))
2934 ;; Effectively copy the after-revert-hook status,
2935 ;; since after-find-file will clobber it.
2936 (let ((global-hook (default-value 'after-revert-hook))
2937 (local-hook-p (local-variable-p 'after-revert-hook))
2938 (local-hook (and (local-variable-p 'after-revert-hook)
2939 after-revert-hook)))
2940 (let (buffer-read-only
2941 ;; Don't make undo records for the reversion.
2942 (buffer-undo-list t))
2943 (if revert-buffer-insert-file-contents-function
2944 (funcall revert-buffer-insert-file-contents-function
2945 file-name auto-save-p)
2946 (if (not (file-exists-p file-name))
2947 (error "File %s no longer exists!" file-name))
2948 ;; Bind buffer-file-name to nil
2949 ;; so that we don't try to lock the file.
2950 (let ((buffer-file-name nil))
2951 (or auto-save-p
2952 (unlock-buffer)))
2953 (widen)
2954 (let ((coding-system-for-read
2955 ;; Auto-saved file shoule be read without
2956 ;; any code conversion.
2957 (if auto-save-p 'no-conversion
2958 coding-system-for-read)))
2959 ;; Note that this preserves point in an intelligent way.
2960 (insert-file-contents file-name (not auto-save-p)
2961 nil nil t))))
2962 ;; Recompute the truename in case changes in symlinks
2963 ;; have changed the truename.
2964 (setq buffer-file-truename
2965 (abbreviate-file-name (file-truename buffer-file-name)))
2966 (after-find-file nil nil t t preserve-modes)
2967 ;; Run after-revert-hook as it was before we reverted.
2968 (setq-default revert-buffer-internal-hook global-hook)
2969 (if local-hook-p
2970 (progn
2971 (make-local-variable 'revert-buffer-internal-hook)
2972 (setq revert-buffer-internal-hook local-hook))
2973 (kill-local-variable 'revert-buffer-internal-hook))
2974 (run-hooks 'revert-buffer-internal-hook))
2975 t)))))
2976
2977 (defun recover-file (file)
2978 "Visit file FILE, but get contents from its last auto-save file."
2979 ;; Actually putting the file name in the minibuffer should be used
2980 ;; only rarely.
2981 ;; Not just because users often use the default.
2982 (interactive "FRecover file: ")
2983 (setq file (expand-file-name file))
2984 (if (auto-save-file-name-p (file-name-nondirectory file))
2985 (error "%s is an auto-save file" file))
2986 (let ((file-name (let ((buffer-file-name file))
2987 (make-auto-save-file-name))))
2988 (cond ((if (file-exists-p file)
2989 (not (file-newer-than-file-p file-name file))
2990 (not (file-exists-p file-name)))
2991 (error "Auto-save file %s not current" file-name))
2992 ((save-window-excursion
2993 (if (not (memq system-type '(vax-vms windows-nt)))
2994 (with-output-to-temp-buffer "*Directory*"
2995 (buffer-disable-undo standard-output)
2996 (call-process "ls" nil standard-output nil
2997 (if (file-symlink-p file) "-lL" "-l")
2998 file file-name)))
2999 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3000 (switch-to-buffer (find-file-noselect file t))
3001 (let ((buffer-read-only nil)
3002 ;; Keep the current buffer-file-coding-system.
3003 (coding-system buffer-file-coding-system)
3004 ;; Auto-saved file shoule be read without any code conversion.
3005 (coding-system-for-read 'no-conversion))
3006 (erase-buffer)
3007 (insert-file-contents file-name nil)
3008 (set-buffer-file-coding-system coding-system))
3009 (after-find-file nil nil t))
3010 (t (error "Recover-file cancelled")))))
3011
3012 (defun recover-session ()
3013 "Recover auto save files from a previous Emacs session.
3014 This command first displays a Dired buffer showing you the
3015 previous sessions that you could recover from.
3016 To choose one, move point to the proper line and then type C-c C-c.
3017 Then you'll be asked about a number of files to recover."
3018 (interactive)
3019 (if (null auto-save-list-file-prefix)
3020 (error "You set `auto-save-list-file-prefix' to disable making session files"))
3021 (let ((dir (file-name-directory auto-save-list-file-prefix)))
3022 (unless (file-directory-p dir)
3023 (make-directory dir t)))
3024 (let ((ls-lisp-support-shell-wildcards t))
3025 (dired (concat auto-save-list-file-prefix "*")
3026 (concat dired-listing-switches "t")))
3027 (save-excursion
3028 (goto-char (point-min))
3029 (or (looking-at " Move to the session you want to recover,")
3030 (let ((inhibit-read-only t))
3031 ;; Each line starts with a space
3032 ;; so that Font Lock mode won't highlight the first character.
3033 (insert " Move to the session you want to recover,\n"
3034 " then type C-c C-c to select it.\n\n"
3035 " You can also delete some of these files;\n"
3036 " type d on a line to mark that file for deletion.\n\n"))))
3037 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
3038 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
3039
3040 (defun recover-session-finish ()
3041 "Choose one saved session to recover auto-save files from.
3042 This command is used in the special Dired buffer created by
3043 \\[recover-session]."
3044 (interactive)
3045 ;; Get the name of the session file to recover from.
3046 (let ((file (dired-get-filename))
3047 files
3048 (buffer (get-buffer-create " *recover*")))
3049 (dired-unmark 1)
3050 (dired-do-flagged-delete t)
3051 (unwind-protect
3052 (save-excursion
3053 ;; Read in the auto-save-list file.
3054 (set-buffer buffer)
3055 (erase-buffer)
3056 (insert-file-contents file)
3057 ;; Loop thru the text of that file
3058 ;; and get out the names of the files to recover.
3059 (while (not (eobp))
3060 (let (thisfile autofile)
3061 (if (eolp)
3062 ;; This is a pair of lines for a non-file-visiting buffer.
3063 ;; Get the auto-save file name and manufacture
3064 ;; a "visited file name" from that.
3065 (progn
3066 (forward-line 1)
3067 (setq autofile
3068 (buffer-substring-no-properties
3069 (point)
3070 (save-excursion
3071 (end-of-line)
3072 (point))))
3073 (setq thisfile
3074 (expand-file-name
3075 (substring
3076 (file-name-nondirectory autofile)
3077 1 -1)
3078 (file-name-directory autofile)))
3079 (forward-line 1))
3080 ;; This pair of lines is a file-visiting
3081 ;; buffer. Use the visited file name.
3082 (progn
3083 (setq thisfile
3084 (buffer-substring-no-properties
3085 (point) (progn (end-of-line) (point))))
3086 (forward-line 1)
3087 (setq autofile
3088 (buffer-substring-no-properties
3089 (point) (progn (end-of-line) (point))))
3090 (forward-line 1)))
3091 ;; Ignore a file if its auto-save file does not exist now.
3092 (if (file-exists-p autofile)
3093 (setq files (cons thisfile files)))))
3094 (setq files (nreverse files))
3095 ;; The file contains a pair of line for each auto-saved buffer.
3096 ;; The first line of the pair contains the visited file name
3097 ;; or is empty if the buffer was not visiting a file.
3098 ;; The second line is the auto-save file name.
3099 (if files
3100 (map-y-or-n-p "Recover %s? "
3101 (lambda (file)
3102 (condition-case nil
3103 (save-excursion (recover-file file))
3104 (error
3105 "Failed to recover `%s'" file)))
3106 files
3107 '("file" "files" "recover"))
3108 (message "No files can be recovered from this session now")))
3109 (kill-buffer buffer))))
3110
3111 (defun kill-some-buffers (&optional list)
3112 "For each buffer in LIST, ask whether to kill it.
3113 LIST defaults to all existing live buffers."
3114 (interactive)
3115 (if (null list)
3116 (setq list (buffer-list)))
3117 (while list
3118 (let* ((buffer (car list))
3119 (name (buffer-name buffer)))
3120 (and (not (string-equal name ""))
3121 (/= (aref name 0) ? )
3122 (yes-or-no-p
3123 (format "Buffer %s %s. Kill? "
3124 name
3125 (if (buffer-modified-p buffer)
3126 "HAS BEEN EDITED" "is unmodified")))
3127 (kill-buffer buffer)))
3128 (setq list (cdr list))))
3129 \f
3130 (defun auto-save-mode (arg)
3131 "Toggle auto-saving of contents of current buffer.
3132 With prefix argument ARG, turn auto-saving on if positive, else off."
3133 (interactive "P")
3134 (setq buffer-auto-save-file-name
3135 (and (if (null arg)
3136 (or (not buffer-auto-save-file-name)
3137 ;; If auto-save is off because buffer has shrunk,
3138 ;; then toggling should turn it on.
3139 (< buffer-saved-size 0))
3140 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
3141 (if (and buffer-file-name auto-save-visited-file-name
3142 (not buffer-read-only))
3143 buffer-file-name
3144 (make-auto-save-file-name))))
3145 ;; If -1 was stored here, to temporarily turn off saving,
3146 ;; turn it back on.
3147 (and (< buffer-saved-size 0)
3148 (setq buffer-saved-size 0))
3149 (if (interactive-p)
3150 (message "Auto-save %s (in this buffer)"
3151 (if buffer-auto-save-file-name "on" "off")))
3152 buffer-auto-save-file-name)
3153
3154 (defun rename-auto-save-file ()
3155 "Adjust current buffer's auto save file name for current conditions.
3156 Also rename any existing auto save file, if it was made in this session."
3157 (let ((osave buffer-auto-save-file-name))
3158 (setq buffer-auto-save-file-name
3159 (make-auto-save-file-name))
3160 (if (and osave buffer-auto-save-file-name
3161 (not (string= buffer-auto-save-file-name buffer-file-name))
3162 (not (string= buffer-auto-save-file-name osave))
3163 (file-exists-p osave)
3164 (recent-auto-save-p))
3165 (rename-file osave buffer-auto-save-file-name t))))
3166
3167 (defun make-auto-save-file-name ()
3168 "Return file name to use for auto-saves of current buffer.
3169 Does not consider `auto-save-visited-file-name' as that variable is checked
3170 before calling this function. You can redefine this for customization.
3171 See also `auto-save-file-name-p'."
3172 (if buffer-file-name
3173 (let ((list auto-save-file-name-transforms)
3174 (filename buffer-file-name)
3175 result)
3176 ;; Apply user-specified translations
3177 ;; to the file name.
3178 (while (and list (not result))
3179 (if (string-match (car (car list)) filename)
3180 (setq result (replace-match (cadr (car list)) t nil
3181 filename)))
3182 (setq list (cdr list)))
3183 (if result (setq filename result))
3184
3185 (if (and (eq system-type 'ms-dos)
3186 (not (msdos-long-file-names)))
3187 (let ((fn (file-name-nondirectory buffer-file-name)))
3188 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
3189 (concat (file-name-directory buffer-file-name)
3190 "#" (match-string 1 fn)
3191 "." (match-string 3 fn) "#"))
3192 (concat (file-name-directory filename)
3193 "#"
3194 (file-name-nondirectory filename)
3195 "#")))
3196
3197 ;; Deal with buffers that don't have any associated files. (Mail
3198 ;; mode tends to create a good number of these.)
3199
3200 (let ((buffer-name (buffer-name))
3201 (limit 0))
3202 ;; Eliminate all slashes and backslashes by
3203 ;; replacing them with sequences that start with %.
3204 ;; Quote % also, to keep distinct names distinct.
3205 (while (string-match "[/\\%]" buffer-name limit)
3206 (let* ((character (aref buffer-name (match-beginning 0)))
3207 (replacement
3208 (cond ((eq character ?%) "%%")
3209 ((eq character ?/) "%+")
3210 ((eq character ?\\) "%-"))))
3211 (setq buffer-name (replace-match replacement t t buffer-name))
3212 (setq limit (1+ (match-end 0)))))
3213 ;; Generate the file name.
3214 (expand-file-name
3215 (format "#%s#%s#" buffer-name (make-temp-name ""))
3216 ;; Try a few alternative directories, to get one we can write it.
3217 (cond
3218 ((file-writable-p default-directory) default-directory)
3219 ((file-writable-p "/var/tmp/") "/var/tmp/")
3220 ("~/"))))))
3221
3222 (defun auto-save-file-name-p (filename)
3223 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
3224 FILENAME should lack slashes. You can redefine this for customization."
3225 (string-match "^#.*#$" filename))
3226 \f
3227 (defun wildcard-to-regexp (wildcard)
3228 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
3229 The generated regexp will match a filename iff the filename
3230 matches that wildcard according to shell rules. Only wildcards known
3231 by `sh' are supported."
3232 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
3233 ;; Copy the initial run of non-special characters.
3234 (result (substring wildcard 0 i))
3235 (len (length wildcard)))
3236 ;; If no special characters, we're almost done.
3237 (if i
3238 (while (< i len)
3239 (let ((ch (aref wildcard i))
3240 j)
3241 (setq
3242 result
3243 (concat result
3244 (cond
3245 ((and (eq ch ?\[)
3246 (< (1+ i) len)
3247 (eq (aref wildcard (1+ i)) ?\]))
3248 "\\[")
3249 ((eq ch ?\[) ; [...] maps to regexp char class
3250 (progn
3251 (setq i (1+ i))
3252 (concat
3253 (cond
3254 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
3255 (progn
3256 (setq i (1+ i))
3257 (if (eq (aref wildcard i) ?\])
3258 (progn
3259 (setq i (1+ i))
3260 "[^]")
3261 "[^")))
3262 ((eq (aref wildcard i) ?^)
3263 ;; Found "[^". Insert a `\0' character
3264 ;; (which cannot happen in a filename)
3265 ;; into the character class, so that `^'
3266 ;; is not the first character after `[',
3267 ;; and thus non-special in a regexp.
3268 (progn
3269 (setq i (1+ i))
3270 "[\000^"))
3271 ((eq (aref wildcard i) ?\])
3272 ;; I don't think `]' can appear in a
3273 ;; character class in a wildcard, but
3274 ;; let's be general here.
3275 (progn
3276 (setq i (1+ i))
3277 "[]"))
3278 (t "["))
3279 (prog1 ; copy everything upto next `]'.
3280 (substring wildcard
3281 i
3282 (setq j (string-match
3283 "]" wildcard i)))
3284 (setq i (if j (1- j) (1- len)))))))
3285 ((eq ch ?.) "\\.")
3286 ((eq ch ?*) "[^\000]*")
3287 ((eq ch ?+) "\\+")
3288 ((eq ch ?^) "\\^")
3289 ((eq ch ?$) "\\$")
3290 ((eq ch ?\\) "\\\\") ; probably cannot happen...
3291 ((eq ch ??) "[^\000]")
3292 (t (char-to-string ch)))))
3293 (setq i (1+ i)))))
3294 ;; Shell wildcards should match the entire filename,
3295 ;; not its part. Make the regexp say so.
3296 (concat "\\`" result "\\'")))
3297 \f
3298 (defcustom list-directory-brief-switches
3299 (if (eq system-type 'vax-vms) "" "-CF")
3300 "*Switches for `list-directory' to pass to `ls' for brief listing."
3301 :type 'string
3302 :group 'dired)
3303
3304 (defcustom list-directory-verbose-switches
3305 (if (eq system-type 'vax-vms)
3306 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
3307 "-l")
3308 "*Switches for `list-directory' to pass to `ls' for verbose listing."
3309 :type 'string
3310 :group 'dired)
3311
3312 (defun file-expand-wildcards (pattern &optional full)
3313 "Expand wildcard pattern PATTERN.
3314 This returns a list of file names which match the pattern.
3315
3316 If PATTERN is written as an absolute relative file name,
3317 the values are absolute also.
3318
3319 If PATTERN is written as a relative file name, it is interpreted
3320 relative to the current default directory, `default-directory'.
3321 The file names returned are normally also relative to the current
3322 default directory. However, if FULL is non-nil, they are absolute."
3323 (let* ((nondir (file-name-nondirectory pattern))
3324 (dirpart (file-name-directory pattern))
3325 ;; A list of all dirs that DIRPART specifies.
3326 ;; This can be more than one dir
3327 ;; if DIRPART contains wildcards.
3328 (dirs (if (and dirpart (string-match "[[*?]" dirpart))
3329 (mapcar 'file-name-as-directory
3330 (file-expand-wildcards (directory-file-name dirpart)))
3331 (list dirpart)))
3332 contents)
3333 (while dirs
3334 (when (or (null (car dirs)) ; Possible if DIRPART is not wild.
3335 (file-directory-p (directory-file-name (car dirs))))
3336 (let ((this-dir-contents
3337 ;; Filter out "." and ".."
3338 (delq nil
3339 (mapcar #'(lambda (name)
3340 (unless (string-match "\\`\\.\\.?\\'"
3341 (file-name-nondirectory name))
3342 name))
3343 (directory-files (or (car dirs) ".") full
3344 (wildcard-to-regexp nondir))))))
3345 (setq contents
3346 (nconc
3347 (if (and (car dirs) (not full))
3348 (mapcar (function (lambda (name) (concat (car dirs) name)))
3349 this-dir-contents)
3350 this-dir-contents)
3351 contents))))
3352 (setq dirs (cdr dirs)))
3353 contents))
3354
3355 (defun list-directory (dirname &optional verbose)
3356 "Display a list of files in or matching DIRNAME, a la `ls'.
3357 DIRNAME is globbed by the shell if necessary.
3358 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
3359 Actions controlled by variables `list-directory-brief-switches'
3360 and `list-directory-verbose-switches'."
3361 (interactive (let ((pfx current-prefix-arg))
3362 (list (read-file-name (if pfx "List directory (verbose): "
3363 "List directory (brief): ")
3364 nil default-directory nil)
3365 pfx)))
3366 (let ((switches (if verbose list-directory-verbose-switches
3367 list-directory-brief-switches)))
3368 (or dirname (setq dirname default-directory))
3369 (setq dirname (expand-file-name dirname))
3370 (with-output-to-temp-buffer "*Directory*"
3371 (buffer-disable-undo standard-output)
3372 (princ "Directory ")
3373 (princ dirname)
3374 (terpri)
3375 (save-excursion
3376 (set-buffer "*Directory*")
3377 (setq default-directory
3378 (if (file-directory-p dirname)
3379 (file-name-as-directory dirname)
3380 (file-name-directory dirname)))
3381 (let ((wildcard (not (file-directory-p dirname))))
3382 (insert-directory dirname switches wildcard (not wildcard)))))))
3383
3384 (defvar insert-directory-program "ls"
3385 "Absolute or relative name of the `ls' program used by `insert-directory'.")
3386
3387 ;; insert-directory
3388 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3389 ;; FULL-DIRECTORY-P is nil.
3390 ;; The single line of output must display FILE's name as it was
3391 ;; given, namely, an absolute path name.
3392 ;; - must insert exactly one line for each file if WILDCARD or
3393 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
3394 ;; before the file lines, plus optional text after the file lines.
3395 ;; Lines are delimited by "\n", so filenames containing "\n" are not
3396 ;; allowed.
3397 ;; File lines should display the basename.
3398 ;; - must be consistent with
3399 ;; - functions dired-move-to-filename, (these two define what a file line is)
3400 ;; dired-move-to-end-of-filename,
3401 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
3402 ;; dired-insert-headerline
3403 ;; dired-after-subdir-garbage (defines what a "total" line is)
3404 ;; - variable dired-subdir-regexp
3405 (defun insert-directory (file switches &optional wildcard full-directory-p)
3406 "Insert directory listing for FILE, formatted according to SWITCHES.
3407 Leaves point after the inserted text.
3408 SWITCHES may be a string of options, or a list of strings.
3409 Optional third arg WILDCARD means treat FILE as shell wildcard.
3410 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3411 switches do not contain `d', so that a full listing is expected.
3412
3413 This works by running a directory listing program
3414 whose name is in the variable `insert-directory-program'.
3415 If WILDCARD, it also runs the shell specified by `shell-file-name'."
3416 ;; We need the directory in order to find the right handler.
3417 (let ((handler (find-file-name-handler (expand-file-name file)
3418 'insert-directory)))
3419 (if handler
3420 (funcall handler 'insert-directory file switches
3421 wildcard full-directory-p)
3422 (if (eq system-type 'vax-vms)
3423 (vms-read-directory file switches (current-buffer))
3424 (let* ((coding-system-for-read
3425 (and enable-multibyte-characters
3426 (or file-name-coding-system
3427 default-file-name-coding-system)))
3428 ;; This is to control encoding the arguments in call-process.
3429 (coding-system-for-write coding-system-for-read)
3430 (result
3431 (if wildcard
3432 ;; Run ls in the directory of the file pattern we asked for.
3433 (let ((default-directory
3434 (if (file-name-absolute-p file)
3435 (file-name-directory file)
3436 (file-name-directory (expand-file-name file))))
3437 (pattern (file-name-nondirectory file))
3438 (beg 0))
3439 ;; Quote some characters that have special meanings in shells;
3440 ;; but don't quote the wildcards--we want them to be special.
3441 ;; We also currently don't quote the quoting characters
3442 ;; in case people want to use them explicitly to quote
3443 ;; wildcard characters.
3444 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
3445 (setq pattern
3446 (concat (substring pattern 0 (match-beginning 0))
3447 "\\"
3448 (substring pattern (match-beginning 0)))
3449 beg (1+ (match-end 0))))
3450 (call-process shell-file-name nil t nil
3451 "-c" (concat "\\";; Disregard shell aliases!
3452 insert-directory-program
3453 " -d "
3454 (if (stringp switches)
3455 switches
3456 (mapconcat 'identity switches " "))
3457 " -- "
3458 pattern)))
3459 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3460 ;; directory if FILE is a symbolic link.
3461 (apply 'call-process
3462 insert-directory-program nil t nil
3463 (let (list)
3464 (if (listp switches)
3465 (setq list switches)
3466 (if (not (equal switches ""))
3467 (progn
3468 ;; Split the switches at any spaces
3469 ;; so we can pass separate options as separate args.
3470 (while (string-match " " switches)
3471 (setq list (cons (substring switches 0 (match-beginning 0))
3472 list)
3473 switches (substring switches (match-end 0))))
3474 (setq list (nreverse (cons switches list))))))
3475 (append list
3476 ;; Avoid lossage if FILE starts with `-'.
3477 '("--")
3478 (progn
3479 (if (string-match "\\`~" file)
3480 (setq file (expand-file-name file)))
3481 (list
3482 (if full-directory-p
3483 (concat (file-name-as-directory file) ".")
3484 file)))))))))
3485 (if (/= result 0)
3486 ;; We get here if ls failed.
3487 ;; Access the file to get a suitable error.
3488 (access-file file "Reading directory")
3489 ;; Replace "total" with "used", to avoid confusion.
3490 ;; Add in the amount of free space.
3491 (save-excursion
3492 (goto-char (point-min))
3493 (when (re-search-forward "^total" nil t)
3494 (replace-match "used")
3495 (end-of-line)
3496 (let (available)
3497 (with-temp-buffer
3498 (call-process "df" nil t nil ".")
3499 (goto-char (point-min))
3500 (forward-line 1)
3501 (skip-chars-forward "^ \t")
3502 (forward-word 3)
3503 (let ((end (point)))
3504 (forward-word -1)
3505 (setq available (buffer-substring (point) end))))
3506 (insert " available " available))))))))))
3507
3508 (defvar kill-emacs-query-functions nil
3509 "Functions to call with no arguments to query about killing Emacs.
3510 If any of these functions returns nil, killing Emacs is cancelled.
3511 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3512 but `kill-emacs', the low level primitive, does not.
3513 See also `kill-emacs-hook'.")
3514
3515 (defun save-buffers-kill-emacs (&optional arg)
3516 "Offer to save each buffer, then kill this Emacs process.
3517 With prefix arg, silently save all file-visiting buffers, then kill."
3518 (interactive "P")
3519 (save-some-buffers arg t)
3520 (and (or (not (memq t (mapcar (function
3521 (lambda (buf) (and (buffer-file-name buf)
3522 (buffer-modified-p buf))))
3523 (buffer-list))))
3524 (yes-or-no-p "Modified buffers exist; exit anyway? "))
3525 (or (not (fboundp 'process-list))
3526 ;; process-list is not defined on VMS.
3527 (let ((processes (process-list))
3528 active)
3529 (while processes
3530 (and (memq (process-status (car processes)) '(run stop open))
3531 (let ((val (process-kill-without-query (car processes))))
3532 (process-kill-without-query (car processes) val)
3533 val)
3534 (setq active t))
3535 (setq processes (cdr processes)))
3536 (or (not active)
3537 (list-processes)
3538 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
3539 ;; Query the user for other things, perhaps.
3540 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
3541 (kill-emacs)))
3542 \f
3543 ;; We use /: as a prefix to "quote" a file name
3544 ;; so that magic file name handlers will not apply to it.
3545
3546 (setq file-name-handler-alist
3547 (cons '("\\`/:" . file-name-non-special)
3548 file-name-handler-alist))
3549
3550 ;; We depend on being the last handler on the list,
3551 ;; so that anything else which does need handling
3552 ;; has been handled already.
3553 ;; So it is safe for us to inhibit *all* magic file name handlers.
3554
3555 (defun file-name-non-special (operation &rest arguments)
3556 (let ((file-name-handler-alist nil)
3557 (default-directory
3558 (if (eq operation 'insert-directory)
3559 (directory-file-name
3560 (expand-file-name
3561 (unhandled-file-name-directory default-directory)))
3562 default-directory))
3563 ;; Get a list of the indices of the args which are file names.
3564 (file-arg-indices
3565 (cdr (or (assq operation
3566 ;; The first four are special because they
3567 ;; return a file name. We want to include the /:
3568 ;; in the return value.
3569 ;; So just avoid stripping it in the first place.
3570 '((expand-file-name . nil)
3571 ;; `identity' means just return the first arg
3572 ;; as stripped of its quoting.
3573 (substitute-in-file-name . identity)
3574 (file-name-directory . nil)
3575 (file-name-as-directory . nil)
3576 (directory-file-name . nil)
3577 (file-name-completion 0 1)
3578 (file-name-all-completions 0 1)
3579 (rename-file 0 1)
3580 (copy-file 0 1)
3581 (make-symbolic-link 0 1)
3582 (add-name-to-file 0 1)))
3583 ;; For all other operations, treat the first argument only
3584 ;; as the file name.
3585 '(nil 0))))
3586 ;; Copy ARGUMENTS so we can replace elements in it.
3587 (arguments (copy-sequence arguments)))
3588 ;; Strip off the /: from the file names that have this handler.
3589 (save-match-data
3590 (while (consp file-arg-indices)
3591 (let ((pair (nthcdr (car file-arg-indices) arguments)))
3592 (and (car pair)
3593 (string-match "\\`/:" (car pair))
3594 (setcar pair
3595 (if (= (length (car pair)) 2)
3596 "/"
3597 (substring (car pair) 2)))))
3598 (setq file-arg-indices (cdr file-arg-indices))))
3599 (if (eq file-arg-indices 'identity)
3600 (car arguments)
3601 (apply operation arguments))))
3602 \f
3603 (define-key ctl-x-map "\C-f" 'find-file)
3604 (define-key ctl-x-map "\C-r" 'find-file-read-only)
3605 (define-key ctl-x-map "\C-v" 'find-alternate-file)
3606 (define-key ctl-x-map "\C-s" 'save-buffer)
3607 (define-key ctl-x-map "s" 'save-some-buffers)
3608 (define-key ctl-x-map "\C-w" 'write-file)
3609 (define-key ctl-x-map "i" 'insert-file)
3610 (define-key esc-map "~" 'not-modified)
3611 (define-key ctl-x-map "\C-d" 'list-directory)
3612 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3613
3614 (define-key ctl-x-4-map "f" 'find-file-other-window)
3615 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3616 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3617 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
3618 (define-key ctl-x-4-map "\C-o" 'display-buffer)
3619
3620 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3621 (define-key ctl-x-5-map "f" 'find-file-other-frame)
3622 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3623 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
3624
3625 ;;; files.el ends here