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