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