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