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