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