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