(x_term_init): Don't use initializer for null_bits.
[emacs.git] / lisp / files.el
blobd2557e4bee7a5c039c9c6e807c5a3610651c74fe
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 (defun find-file-literally (filename)
948 "Visit file FILENAME with no conversion of any kind.
949 Format conversion and character code conversion are both disabled,
950 and multibyte characters are disabled in the resulting buffer.
951 Automatic uncompression is also disabled."
952 (interactive "FFind file literally: ")
953 (let ((coding-system-for-read 'no-conversion)
954 (coding-system-for-write 'no-conversion)
955 (jka-compr-compression-info-list nil)
956 (format-alist nil)
957 (after-insert-file-functions nil))
958 (prog1
959 (find-file filename)
960 (setq enable-multibyte-characters nil))))
962 (defvar after-find-file-from-revert-buffer nil)
964 (defun after-find-file (&optional error warn noauto
965 after-find-file-from-revert-buffer
966 nomodes)
967 "Called after finding a file and by the default revert function.
968 Sets buffer mode, parses local variables.
969 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
970 error in reading the file. WARN non-nil means warn if there
971 exists an auto-save file more recent than the visited file.
972 NOAUTO means don't mess with auto-save mode.
973 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
974 means this call was from `revert-buffer'.
975 Fifth arg NOMODES non-nil means don't alter the file's modes.
976 Finishes by calling the functions in `find-file-hooks'
977 unless NOMODES is non-nil."
978 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
979 (if noninteractive
981 (let* (not-serious
982 (msg
983 (cond ((and error (file-attributes buffer-file-name))
984 (setq buffer-read-only t)
985 "File exists, but cannot be read.")
986 ((not buffer-read-only)
987 (if (and warn
988 (file-newer-than-file-p (make-auto-save-file-name)
989 buffer-file-name))
990 (format "%s has auto save data; consider M-x recover-file"
991 (file-name-nondirectory buffer-file-name))
992 (setq not-serious t)
993 (if error "(New file)" nil)))
994 ((not error)
995 (setq not-serious t)
996 "Note: file is write protected")
997 ((file-attributes (directory-file-name default-directory))
998 "File not found and directory write-protected")
999 ((file-exists-p (file-name-directory buffer-file-name))
1000 (setq buffer-read-only nil))
1002 (setq buffer-read-only nil)
1003 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1004 "Use M-x make-dir RET RET to create the directory"
1005 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
1006 (if msg
1007 (progn
1008 (message msg)
1009 (or not-serious (sit-for 1 nil t)))))
1010 (if (and auto-save-default (not noauto))
1011 (auto-save-mode t)))
1012 (if nomodes
1014 (normal-mode t)
1015 (if (and buffer-read-only view-read-only
1016 (not (eq (get major-mode 'mode-class) 'special)))
1017 (view-mode-enter))
1018 (run-hooks 'find-file-hooks)))
1020 (defun normal-mode (&optional find-file)
1021 "Choose the major mode for this buffer automatically.
1022 Also sets up any specified local variables of the file.
1023 Uses the visited file name, the -*- line, and the local variables spec.
1025 This function is called automatically from `find-file'. In that case,
1026 we may set up specified local variables depending on the value of
1027 `enable-local-variables': if it is t, we do; if it is nil, we don't;
1028 otherwise, we query. `enable-local-variables' is ignored if you
1029 run `normal-mode' explicitly."
1030 (interactive)
1031 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1032 (condition-case err
1033 (set-auto-mode)
1034 (error (message "File mode specification error: %s"
1035 (prin1-to-string err))))
1036 (condition-case err
1037 (let ((enable-local-variables (or (not find-file)
1038 enable-local-variables)))
1039 (hack-local-variables))
1040 (error (message "File local-variables error: %s"
1041 (prin1-to-string err)))))
1043 (defvar auto-mode-alist
1044 '(("\\.te?xt\\'" . text-mode)
1045 ("\\.c\\'" . c-mode)
1046 ("\\.h\\'" . c-mode)
1047 ("\\.tex\\'" . tex-mode)
1048 ("\\.ltx\\'" . latex-mode)
1049 ("\\.el\\'" . emacs-lisp-mode)
1050 ("\\.mm\\'" . nroff-mode)
1051 ("\\.me\\'" . nroff-mode)
1052 ("\\.ms\\'" . nroff-mode)
1053 ("\\.man\\'" . nroff-mode)
1054 ("\\.scm\\'" . scheme-mode)
1055 ("\\.l\\'" . lisp-mode)
1056 ("\\.lisp\\'" . lisp-mode)
1057 ("\\.f\\'" . fortran-mode)
1058 ("\\.F\\'" . fortran-mode)
1059 ("\\.for\\'" . fortran-mode)
1060 ("\\.p\\'" . pascal-mode)
1061 ("\\.pas\\'" . pascal-mode)
1062 ("\\.ad[abs]\\'" . ada-mode)
1063 ("\\.pl\\'" . perl-mode)
1064 ("\\.pm\\'" . perl-mode)
1065 ("\\.s?html?\\'" . html-mode)
1066 ("\\.cc\\'" . c++-mode)
1067 ("\\.hh\\'" . c++-mode)
1068 ("\\.hpp\\'" . c++-mode)
1069 ("\\.C\\'" . c++-mode)
1070 ("\\.H\\'" . c++-mode)
1071 ("\\.cpp\\'" . c++-mode)
1072 ("\\.cxx\\'" . c++-mode)
1073 ("\\.hxx\\'" . c++-mode)
1074 ("\\.c\\+\\+\\'" . c++-mode)
1075 ("\\.h\\+\\+\\'" . c++-mode)
1076 ("\\.m\\'" . objc-mode)
1077 ("\\.java\\'" . java-mode)
1078 ("\\.mk\\'" . makefile-mode)
1079 ("\\(M\\|m\\|GNUm\\)akefile\\(.in\\)?\\'" . makefile-mode)
1080 ;;; Less common extensions come here
1081 ;;; so more common ones above are found faster.
1082 ("\\.texinfo\\'" . texinfo-mode)
1083 ("\\.te?xi\\'" . texinfo-mode)
1084 ("\\.s\\'" . asm-mode)
1085 ("\\.S\\'" . asm-mode)
1086 ("\\.asm\\'" . asm-mode)
1087 ("ChangeLog\\'" . change-log-mode)
1088 ("change.log\\'" . change-log-mode)
1089 ("changelo\\'" . change-log-mode)
1090 ("ChangeLog.[0-9]+\\'" . change-log-mode)
1091 ;; for MSDOS and MS-Windows (which are case-insensitive)
1092 ("changelog\\'" . change-log-mode)
1093 ("changelog.[0-9]+\\'" . change-log-mode)
1094 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1095 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
1096 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
1097 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1098 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1099 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
1100 ;;; The following should come after the ChangeLog pattern
1101 ;;; for the sake of ChangeLog.1, etc.
1102 ;;; and after the .scm.[0-9] pattern too.
1103 ("\\.[12345678]\\'" . nroff-mode)
1104 ("\\.TeX\\'" . tex-mode)
1105 ("\\.sty\\'" . latex-mode)
1106 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
1107 ("\\.bbl\\'" . latex-mode)
1108 ("\\.bib\\'" . bibtex-mode)
1109 ("\\.article\\'" . text-mode)
1110 ("\\.letter\\'" . text-mode)
1111 ("\\.tcl\\'" . tcl-mode)
1112 ("\\.exp\\'" . tcl-mode)
1113 ("\\.itcl\\'" . tcl-mode)
1114 ("\\.itk\\'" . tcl-mode)
1115 ("\\.icn\\'" . icon-mode)
1116 ("\\.sim\\'" . simula-mode)
1117 ("\\.mss\\'" . scribe-mode)
1118 ("\\.f90\\'" . f90-mode)
1119 ("\\.lsp\\'" . lisp-mode)
1120 ("\\.awk\\'" . awk-mode)
1121 ("\\.prolog\\'" . prolog-mode)
1122 ("\\.tar\\'" . tar-mode)
1123 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode)
1124 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\)\\'" . archive-mode)
1125 ;; Mailer puts message to be edited in
1126 ;; /tmp/Re.... or Message
1127 ("\\`/tmp/Re" . text-mode)
1128 ("/Message[0-9]*\\'" . text-mode)
1129 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1130 ;; some news reader is reported to use this
1131 ("\\`/tmp/fol/" . text-mode)
1132 ("\\.y\\'" . c-mode)
1133 ("\\.lex\\'" . c-mode)
1134 ("\\.oak\\'" . scheme-mode)
1135 ("\\.sgml?\\'" . sgml-mode)
1136 ("\\.dtd\\'" . sgml-mode)
1137 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
1138 ;; .emacs following a directory delimiter
1139 ;; in either Unix or VMS syntax.
1140 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
1141 ;; _emacs following a directory delimiter
1142 ;; in MsDos syntax
1143 ("[:/]_emacs\\'" . emacs-lisp-mode)
1144 ("\\.ml\\'" . lisp-mode))
1146 Alist of filename patterns vs corresponding major mode functions.
1147 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1148 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1149 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1150 mode function to use. FUNCTION will be called, unless it is nil.
1152 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1153 calling FUNCTION (if it's not nil), we delete the suffix that matched
1154 REGEXP and search the list again for another match.")
1156 (defvar interpreter-mode-alist
1157 '(("perl" . perl-mode)
1158 ("perl5" . perl-mode)
1159 ("wish" . tcl-mode)
1160 ("wishx" . tcl-mode)
1161 ("tcl" . tcl-mode)
1162 ("tclsh" . tcl-mode)
1163 ("awk" . awk-mode)
1164 ("mawk" . awk-mode)
1165 ("nawk" . awk-mode)
1166 ("gawk" . awk-mode)
1167 ("scm" . scheme-mode)
1168 ("ash" . sh-mode)
1169 ("bash" . sh-mode)
1170 ("csh" . sh-mode)
1171 ("dtksh" . sh-mode)
1172 ("es" . sh-mode)
1173 ("itcsh" . sh-mode)
1174 ("jsh" . sh-mode)
1175 ("ksh" . sh-mode)
1176 ("oash" . sh-mode)
1177 ("pdksh" . sh-mode)
1178 ("rc" . sh-mode)
1179 ("sh" . sh-mode)
1180 ("sh5" . sh-mode)
1181 ("tcsh" . sh-mode)
1182 ("wksh" . sh-mode)
1183 ("wsh" . sh-mode)
1184 ("zsh" . sh-mode)
1185 ("tail" . text-mode)
1186 ("more" . text-mode)
1187 ("less" . text-mode)
1188 ("pg" . text-mode))
1189 "Alist mapping interpreter names to major modes.
1190 This alist applies to files whose first line starts with `#!'.
1191 Each element looks like (INTERPRETER . MODE).
1192 The car of each element is compared with
1193 the name of the interpreter specified in the first line.
1194 If it matches, mode MODE is selected.")
1196 (defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
1197 "List of regexps; if one matches a file name, don't look for `-*-'.")
1199 (defvar inhibit-first-line-modes-suffixes nil
1200 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1201 When checking `inhibit-first-line-modes-regexps', we first discard
1202 from the end of the file name anything that matches one of these regexps.")
1204 (defvar user-init-file
1205 "" ; set by command-line
1206 "File name including directory of user's initialization file.")
1208 (defun set-auto-mode (&optional just-from-file-name)
1209 "Select major mode appropriate for current buffer.
1210 This checks for a -*- mode tag in the buffer's text,
1211 compares the filename against the entries in `auto-mode-alist',
1212 or checks the interpreter that runs this file against
1213 `interpreter-mode-alist'.
1215 It does not check for the `mode:' local variable in the
1216 Local Variables section of the file; for that, use `hack-local-variables'.
1218 If `enable-local-variables' is nil, this function does not check for a
1219 -*- mode tag.
1221 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1222 then we do not set anything but the major mode,
1223 and we don't even do that unless it would come from the file name."
1224 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1225 (let (beg end done modes)
1226 (save-excursion
1227 (goto-char (point-min))
1228 (skip-chars-forward " \t\n")
1229 (and enable-local-variables
1230 ;; Don't look for -*- if this file name matches any
1231 ;; of the regexps in inhibit-first-line-modes-regexps.
1232 (let ((temp inhibit-first-line-modes-regexps)
1233 (name (if buffer-file-name
1234 (file-name-sans-versions buffer-file-name)
1235 (buffer-name))))
1236 (while (let ((sufs inhibit-first-line-modes-suffixes))
1237 (while (and sufs (not (string-match (car sufs) name)))
1238 (setq sufs (cdr sufs)))
1239 sufs)
1240 (setq name (substring name 0 (match-beginning 0))))
1241 (while (and temp
1242 (not (string-match (car temp) name)))
1243 (setq temp (cdr temp)))
1244 (not temp))
1245 (search-forward "-*-" (save-excursion
1246 ;; If the file begins with "#!"
1247 ;; (exec interpreter magic), look
1248 ;; for mode frobs in the first two
1249 ;; lines. You cannot necessarily
1250 ;; put them in the first line of
1251 ;; such a file without screwing up
1252 ;; the interpreter invocation.
1253 (end-of-line (and (looking-at "^#!") 2))
1254 (point)) t)
1255 (progn
1256 (skip-chars-forward " \t")
1257 (setq beg (point))
1258 (search-forward "-*-"
1259 (save-excursion (end-of-line) (point))
1261 (progn
1262 (forward-char -3)
1263 (skip-chars-backward " \t")
1264 (setq end (point))
1265 (goto-char beg)
1266 (if (save-excursion (search-forward ":" end t))
1267 ;; Find all specifications for the `mode:' variable
1268 ;; and execute them left to right.
1269 (while (let ((case-fold-search t))
1270 (or (and (looking-at "mode:")
1271 (goto-char (match-end 0)))
1272 (re-search-forward "[ \t;]mode:" end t)))
1273 (skip-chars-forward " \t")
1274 (setq beg (point))
1275 (if (search-forward ";" end t)
1276 (forward-char -1)
1277 (goto-char end))
1278 (skip-chars-backward " \t")
1279 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1280 modes)))
1281 ;; Simple -*-MODE-*- case.
1282 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1283 "-mode"))
1284 modes))))))
1285 ;; If we found modes to use, invoke them now,
1286 ;; outside the save-excursion.
1287 (if modes
1288 (unless just-from-file-name
1289 (mapcar 'funcall (nreverse modes))
1290 (setq done t)))
1291 ;; If we didn't find a mode from a -*- line, try using the file name.
1292 (if (and (not done) buffer-file-name)
1293 (let ((name buffer-file-name)
1294 (keep-going t))
1295 ;; Remove backup-suffixes from file name.
1296 (setq name (file-name-sans-versions name))
1297 (while keep-going
1298 (setq keep-going nil)
1299 (let ((alist auto-mode-alist)
1300 (mode nil))
1301 ;; Find first matching alist entry.
1302 (let ((case-fold-search
1303 (memq system-type '(vax-vms windows-nt))))
1304 (while (and (not mode) alist)
1305 (if (string-match (car (car alist)) name)
1306 (if (and (consp (cdr (car alist)))
1307 (nth 2 (car alist)))
1308 (progn
1309 (setq mode (car (cdr (car alist)))
1310 name (substring name 0 (match-beginning 0))
1311 keep-going t))
1312 (setq mode (cdr (car alist))
1313 keep-going nil)))
1314 (setq alist (cdr alist))))
1315 (if mode
1316 (funcall mode)
1317 ;; If we can't deduce a mode from the file name,
1318 ;; look for an interpreter specified in the first line.
1319 ;; As a special case, allow for things like "#!/bin/env perl",
1320 ;; which finds the interpreter anywhere in $PATH.
1321 (let ((interpreter
1322 (save-excursion
1323 (goto-char (point-min))
1324 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1325 (buffer-substring (match-beginning 2)
1326 (match-end 2))
1327 "")))
1328 elt)
1329 ;; Map interpreter name to a mode.
1330 (setq elt (assoc (file-name-nondirectory interpreter)
1331 interpreter-mode-alist))
1332 (unless just-from-file-name
1333 (if elt
1334 (funcall (cdr elt))))))))))))
1336 (defun hack-local-variables-prop-line ()
1337 ;; Set local variables specified in the -*- line.
1338 ;; Ignore any specification for `mode:';
1339 ;; set-auto-mode should already have handled that.
1340 (save-excursion
1341 (goto-char (point-min))
1342 (let ((result nil)
1343 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1344 ;; Parse the -*- line into the `result' alist.
1345 (cond ((not (search-forward "-*-" end t))
1346 ;; doesn't have one.
1347 nil)
1348 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1349 ;; Simple form: "-*- MODENAME -*-". Already handled.
1350 nil)
1352 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1353 ;; (last ";" is optional).
1354 (save-excursion
1355 (if (search-forward "-*-" end t)
1356 (setq end (- (point) 3))
1357 (error "-*- not terminated before end of line")))
1358 (while (< (point) end)
1359 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1360 (error "malformed -*- line"))
1361 (goto-char (match-end 0))
1362 ;; There used to be a downcase here,
1363 ;; but the manual didn't say so,
1364 ;; and people want to set var names that aren't all lc.
1365 (let ((key (intern (buffer-substring
1366 (match-beginning 1)
1367 (match-end 1))))
1368 (val (save-restriction
1369 (narrow-to-region (point) end)
1370 (read (current-buffer)))))
1371 ;; It is traditional to ignore
1372 ;; case when checking for `mode' in set-auto-mode,
1373 ;; so we must do that here as well.
1374 ;; That is inconsistent, but we're stuck with it.
1375 (or (equal (downcase (symbol-name key)) "mode")
1376 (setq result (cons (cons key val) result)))
1377 (skip-chars-forward " \t;")))
1378 (setq result (nreverse result))))
1380 (if (and result
1381 (or (eq enable-local-variables t)
1382 (and enable-local-variables
1383 (save-window-excursion
1384 (condition-case nil
1385 (switch-to-buffer (current-buffer))
1386 (error
1387 ;; If we fail to switch in the selected window,
1388 ;; it is probably a minibuffer.
1389 ;; So try another window.
1390 (condition-case nil
1391 (switch-to-buffer-other-window (current-buffer))
1392 (error
1393 (switch-to-buffer-other-frame (current-buffer))))))
1394 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1395 (file-name-nondirectory buffer-file-name)))))))
1396 (let ((enable-local-eval enable-local-eval))
1397 (while result
1398 (hack-one-local-variable (car (car result)) (cdr (car result)))
1399 (setq result (cdr result))))))))
1401 (defvar hack-local-variables-hook nil
1402 "Normal hook run after processing a file's local variables specs.
1403 Major modes can use this to examine user-specified local variables
1404 in order to initialize other data structure based on them.")
1406 (defun hack-local-variables (&optional mode-only)
1407 "Parse and put into effect this buffer's local variables spec.
1408 If MODE-ONLY is non-nil, all we do is check whether the major mode
1409 is specified, returning t if it is specified."
1410 (unless mode-only
1411 (hack-local-variables-prop-line))
1412 ;; Look for "Local variables:" line in last page.
1413 (let (mode-specified)
1414 (save-excursion
1415 (goto-char (point-max))
1416 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1417 (if (let ((case-fold-search t))
1418 (and (search-forward "Local Variables:" nil t)
1419 (or (eq enable-local-variables t)
1420 mode-only
1421 (and enable-local-variables
1422 (save-window-excursion
1423 (switch-to-buffer (current-buffer))
1424 (save-excursion
1425 (beginning-of-line)
1426 (set-window-start (selected-window) (point)))
1427 (y-or-n-p (format "Set local variables as specified at end of %s? "
1428 (if buffer-file-name
1429 (file-name-nondirectory
1430 buffer-file-name)
1431 (concat "buffer "
1432 (buffer-name))))))))))
1433 (let ((continue t)
1434 prefix prefixlen suffix beg
1435 mode-specified
1436 (enable-local-eval enable-local-eval))
1437 ;; The prefix is what comes before "local variables:" in its line.
1438 ;; The suffix is what comes after "local variables:" in its line.
1439 (skip-chars-forward " \t")
1440 (or (eolp)
1441 (setq suffix (buffer-substring (point)
1442 (progn (end-of-line) (point)))))
1443 (goto-char (match-beginning 0))
1444 (or (bolp)
1445 (setq prefix
1446 (buffer-substring (point)
1447 (progn (beginning-of-line) (point)))))
1449 (if prefix (setq prefixlen (length prefix)
1450 prefix (regexp-quote prefix)))
1451 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1452 (while continue
1453 ;; Look at next local variable spec.
1454 (if selective-display (re-search-forward "[\n\C-m]")
1455 (forward-line 1))
1456 ;; Skip the prefix, if any.
1457 (if prefix
1458 (if (looking-at prefix)
1459 (forward-char prefixlen)
1460 (error "Local variables entry is missing the prefix")))
1461 ;; Find the variable name; strip whitespace.
1462 (skip-chars-forward " \t")
1463 (setq beg (point))
1464 (skip-chars-forward "^:\n")
1465 (if (eolp) (error "Missing colon in local variables entry"))
1466 (skip-chars-backward " \t")
1467 (let* ((str (buffer-substring beg (point)))
1468 (var (read str))
1469 val)
1470 ;; Setting variable named "end" means end of list.
1471 (if (string-equal (downcase str) "end")
1472 (setq continue nil)
1473 ;; Otherwise read the variable value.
1474 (skip-chars-forward "^:")
1475 (forward-char 1)
1476 (setq val (read (current-buffer)))
1477 (skip-chars-backward "\n")
1478 (skip-chars-forward " \t")
1479 (or (if suffix (looking-at suffix) (eolp))
1480 (error "Local variables entry is terminated incorrectly"))
1481 (if mode-only
1482 (if (eq var 'mode)
1483 (setq mode-specified t))
1484 ;; Set the variable. "Variables" mode and eval are funny.
1485 (hack-one-local-variable var val))))))))
1486 (unless mode-only
1487 (run-hooks 'hack-local-variables-hook))
1488 mode-specified))
1490 (defvar ignored-local-variables
1491 '(enable-local-eval)
1492 "Variables to be ignored in a file's local variable spec.")
1494 ;; Get confirmation before setting these variables as locals in a file.
1495 (put 'debugger 'risky-local-variable t)
1496 (put 'enable-local-eval 'risky-local-variable t)
1497 (put 'ignored-local-variables 'risky-local-variable t)
1498 (put 'eval 'risky-local-variable t)
1499 (put 'file-name-handler-alist 'risky-local-variable t)
1500 (put 'minor-mode-map-alist 'risky-local-variable t)
1501 (put 'after-load-alist 'risky-local-variable t)
1502 (put 'buffer-file-name 'risky-local-variable t)
1503 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1504 (put 'buffer-file-truename 'risky-local-variable t)
1505 (put 'exec-path 'risky-local-variable t)
1506 (put 'load-path 'risky-local-variable t)
1507 (put 'exec-directory 'risky-local-variable t)
1508 (put 'process-environment 'risky-local-variable t)
1509 (put 'dabbrev-case-fold-search 'risky-local-variable t)
1510 (put 'dabbrev-case-replace 'risky-local-variable t)
1511 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1512 (put 'outline-level 'risky-local-variable t)
1513 (put 'rmail-output-file-alist 'risky-local-variable t)
1515 ;; This one is safe because the user gets to check it before it is used.
1516 (put 'compile-command 'safe-local-variable t)
1518 (defun hack-one-local-variable-quotep (exp)
1519 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1521 ;; "Set" one variable in a local variables spec.
1522 ;; A few variable names are treated specially.
1523 (defun hack-one-local-variable (var val)
1524 (cond ((eq var 'mode)
1525 (funcall (intern (concat (downcase (symbol-name val))
1526 "-mode"))))
1527 ((memq var ignored-local-variables)
1528 nil)
1529 ;; "Setting" eval means either eval it or do nothing.
1530 ;; Likewise for setting hook variables.
1531 ((or (get var 'risky-local-variable)
1532 (and
1533 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1534 (symbol-name var))
1535 (not (get var 'safe-local-variable))))
1536 ;; Permit evalling a put of a harmless property.
1537 ;; if the args do nothing tricky.
1538 (if (or (and (eq var 'eval)
1539 (consp val)
1540 (eq (car val) 'put)
1541 (hack-one-local-variable-quotep (nth 1 val))
1542 (hack-one-local-variable-quotep (nth 2 val))
1543 ;; Only allow safe values of lisp-indent-hook;
1544 ;; not functions.
1545 (or (numberp (nth 3 val))
1546 (equal (nth 3 val) ''defun))
1547 (memq (nth 1 (nth 2 val))
1548 '(lisp-indent-hook)))
1549 ;; Permit eval if not root and user says ok.
1550 (and (not (zerop (user-uid)))
1551 (or (eq enable-local-eval t)
1552 (and enable-local-eval
1553 (save-window-excursion
1554 (switch-to-buffer (current-buffer))
1555 (save-excursion
1556 (beginning-of-line)
1557 (set-window-start (selected-window) (point)))
1558 (setq enable-local-eval
1559 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1560 (file-name-nondirectory buffer-file-name)))))))))
1561 (if (eq var 'eval)
1562 (save-excursion (eval val))
1563 (make-local-variable var)
1564 (set var val))
1565 (message "Ignoring `eval:' in file's local variables")))
1566 ;; Ordinary variable, really set it.
1567 (t (make-local-variable var)
1568 (set var val))))
1571 (defcustom change-major-mode-with-file-name t
1572 "*Non-nil means \\[write-file] should set the major mode from the file name.
1573 However, the mode will not be changed if
1574 \(1) a local variables list or the `-*-' line specifies a major mode, or
1575 \(2) the current major mode is a \"special\" mode,
1576 \ not suitable for ordinary files, or
1577 \(3) the new file name does not particularly specify any mode."
1578 :type 'boolean
1579 :group 'editing-basics)
1581 (defun set-visited-file-name (filename &optional no-query along-with-file)
1582 "Change name of file visited in current buffer to FILENAME.
1583 The next time the buffer is saved it will go in the newly specified file.
1584 nil or empty string as argument means make buffer not be visiting any file.
1585 Remember to delete the initial contents of the minibuffer
1586 if you wish to pass an empty string as the argument.
1588 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1589 confirmation in the case where another buffer is already visiting FILENAME.
1591 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1592 the old visited file has been renamed to the new name FILENAME."
1593 (interactive "FSet visited file name: ")
1594 (if (buffer-base-buffer)
1595 (error "An indirect buffer cannot visit a file"))
1596 (let (truename)
1597 (if filename
1598 (setq filename
1599 (if (string-equal filename "")
1601 (expand-file-name filename))))
1602 (if filename
1603 (progn
1604 (setq truename (file-truename filename))
1605 (if find-file-visit-truename
1606 (setq filename truename))))
1607 (let ((buffer (and filename (find-buffer-visiting filename))))
1608 (and buffer (not (eq buffer (current-buffer)))
1609 (not no-query)
1610 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1611 filename)))
1612 (error "Aborted")))
1613 (or (equal filename buffer-file-name)
1614 (progn
1615 (and filename (lock-buffer filename))
1616 (unlock-buffer)))
1617 (setq buffer-file-name filename)
1618 (if filename ; make buffer name reflect filename.
1619 (let ((new-name (file-name-nondirectory buffer-file-name)))
1620 (if (string= new-name "")
1621 (error "Empty file name"))
1622 (if (eq system-type 'vax-vms)
1623 (setq new-name (downcase new-name)))
1624 (setq default-directory (file-name-directory buffer-file-name))
1625 (or (string= new-name (buffer-name))
1626 (rename-buffer new-name t))))
1627 (setq buffer-backed-up nil)
1628 (or along-with-file
1629 (clear-visited-file-modtime))
1630 ;; Abbreviate the file names of the buffer.
1631 (if truename
1632 (progn
1633 (setq buffer-file-truename (abbreviate-file-name truename))
1634 (if find-file-visit-truename
1635 (setq buffer-file-name buffer-file-truename))))
1636 (setq buffer-file-number
1637 (if filename
1638 (nthcdr 10 (file-attributes buffer-file-name))
1639 nil)))
1640 ;; write-file-hooks is normally used for things like ftp-find-file
1641 ;; that visit things that are not local files as if they were files.
1642 ;; Changing to visit an ordinary local file instead should flush the hook.
1643 (kill-local-variable 'write-file-hooks)
1644 (kill-local-variable 'local-write-file-hooks)
1645 (kill-local-variable 'revert-buffer-function)
1646 (kill-local-variable 'backup-inhibited)
1647 ;; If buffer was read-only because of version control,
1648 ;; that reason is gone now, so make it writable.
1649 (if vc-mode
1650 (setq buffer-read-only nil))
1651 (kill-local-variable 'vc-mode)
1652 ;; Turn off backup files for certain file names.
1653 ;; Since this is a permanent local, the major mode won't eliminate it.
1654 (and (not (funcall backup-enable-predicate buffer-file-name))
1655 (progn
1656 (make-local-variable 'backup-inhibited)
1657 (setq backup-inhibited t)))
1658 (let ((oauto buffer-auto-save-file-name))
1659 ;; If auto-save was not already on, turn it on if appropriate.
1660 (if (not buffer-auto-save-file-name)
1661 (and buffer-file-name auto-save-default
1662 (auto-save-mode t))
1663 ;; If auto save is on, start using a new name.
1664 ;; We deliberately don't rename or delete the old auto save
1665 ;; for the old visited file name. This is because perhaps
1666 ;; the user wants to save the new state and then compare with the
1667 ;; previous state from the auto save file.
1668 (setq buffer-auto-save-file-name
1669 (make-auto-save-file-name)))
1670 ;; Rename the old auto save file if any.
1671 (and oauto buffer-auto-save-file-name
1672 (file-exists-p oauto)
1673 (rename-file oauto buffer-auto-save-file-name t)))
1674 (and buffer-file-name
1675 (not along-with-file)
1676 (set-buffer-modified-p t))
1677 ;; Update the major mode, if the file name determines it.
1678 (condition-case nil
1679 ;; Don't change the mode if it is special.
1680 (or (not change-major-mode-with-file-name)
1681 (get major-mode 'mode-class)
1682 ;; Don't change the mode if the local variable list specifies it.
1683 (hack-local-variables t)
1684 (set-auto-mode t))
1685 (error nil)))
1687 (defun write-file (filename &optional confirm)
1688 "Write current buffer into file FILENAME.
1689 Makes buffer visit that file, and marks it not modified.
1690 If the buffer is already visiting a file, you can specify
1691 a directory name as FILENAME, to write a file of the same
1692 old name in that directory.
1694 If optional second arg CONFIRM is non-nil,
1695 ask for confirmation for overwriting an existing file.
1696 Interactively, confirmation is required unless you supply a prefix argument."
1697 ;; (interactive "FWrite file: ")
1698 (interactive
1699 (list (if buffer-file-name
1700 (read-file-name "Write file: "
1701 nil nil nil nil)
1702 (read-file-name "Write file: "
1703 (cdr (assq 'default-directory
1704 (buffer-local-variables)))
1705 nil nil (buffer-name)))
1706 (not current-prefix-arg)))
1707 (or (null filename) (string-equal filename "")
1708 (progn
1709 ;; If arg is just a directory,
1710 ;; use same file name, but in that directory.
1711 (if (and (file-directory-p filename) buffer-file-name)
1712 (setq filename (concat (file-name-as-directory filename)
1713 (file-name-nondirectory buffer-file-name))))
1714 (and confirm
1715 (file-exists-p filename)
1716 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1717 (error "Canceled")))
1718 (set-visited-file-name filename (not confirm))))
1719 (set-buffer-modified-p t)
1720 (save-buffer))
1722 (defun backup-buffer ()
1723 "Make a backup of the disk file visited by the current buffer, if appropriate.
1724 This is normally done before saving the buffer the first time.
1725 If the value is non-nil, it is the result of `file-modes' on the original
1726 file; this means that the caller, after saving the buffer, should change
1727 the modes of the new file to agree with the old modes.
1729 A backup may be done by renaming or by copying; see documentation of
1730 variable `make-backup-files'. If it's done by renaming, then the file is
1731 no longer accessible under its old name."
1732 (if (and make-backup-files (not backup-inhibited)
1733 (not buffer-backed-up)
1734 (file-exists-p buffer-file-name)
1735 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1736 '(?- ?l)))
1737 (let ((real-file-name buffer-file-name)
1738 backup-info backupname targets setmodes)
1739 ;; If specified name is a symbolic link, chase it to the target.
1740 ;; Thus we make the backups in the directory where the real file is.
1741 (setq real-file-name (file-chase-links real-file-name))
1742 (setq backup-info (find-backup-file-name real-file-name)
1743 backupname (car backup-info)
1744 targets (cdr backup-info))
1745 ;;; (if (file-directory-p buffer-file-name)
1746 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1747 (if backup-info
1748 (condition-case ()
1749 (let ((delete-old-versions
1750 ;; If have old versions to maybe delete,
1751 ;; ask the user to confirm now, before doing anything.
1752 ;; But don't actually delete til later.
1753 (and targets
1754 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1755 (or delete-old-versions
1756 (y-or-n-p (format "Delete excess backup versions of %s? "
1757 real-file-name))))))
1758 ;; Actually write the back up file.
1759 (condition-case ()
1760 (if (or file-precious-flag
1761 ; (file-symlink-p buffer-file-name)
1762 backup-by-copying
1763 (and backup-by-copying-when-linked
1764 (> (file-nlinks real-file-name) 1))
1765 (and backup-by-copying-when-mismatch
1766 (let ((attr (file-attributes real-file-name)))
1767 (or (nth 9 attr)
1768 (not (file-ownership-preserved-p real-file-name))))))
1769 (condition-case ()
1770 (copy-file real-file-name backupname t t)
1771 (file-error
1772 ;; If copying fails because file BACKUPNAME
1773 ;; is not writable, delete that file and try again.
1774 (if (and (file-exists-p backupname)
1775 (not (file-writable-p backupname)))
1776 (delete-file backupname))
1777 (copy-file real-file-name backupname t t)))
1778 ;; rename-file should delete old backup.
1779 (rename-file real-file-name backupname t)
1780 (setq setmodes (file-modes backupname)))
1781 (file-error
1782 ;; If trouble writing the backup, write it in ~.
1783 (setq backupname (expand-file-name
1784 (convert-standard-filename
1785 "~/%backup%~")))
1786 (message "Cannot write backup file; backing up in %s"
1787 (file-name-nondirectory backupname))
1788 (sleep-for 1)
1789 (condition-case ()
1790 (copy-file real-file-name backupname t t)
1791 (file-error
1792 ;; If copying fails because file BACKUPNAME
1793 ;; is not writable, delete that file and try again.
1794 (if (and (file-exists-p backupname)
1795 (not (file-writable-p backupname)))
1796 (delete-file backupname))
1797 (copy-file real-file-name backupname t t)))))
1798 (setq buffer-backed-up t)
1799 ;; Now delete the old versions, if desired.
1800 (if delete-old-versions
1801 (while targets
1802 (condition-case ()
1803 (delete-file (car targets))
1804 (file-error nil))
1805 (setq targets (cdr targets))))
1806 setmodes)
1807 (file-error nil))))))
1809 (defun file-name-sans-versions (name &optional keep-backup-version)
1810 "Return FILENAME sans backup versions or strings.
1811 This is a separate procedure so your site-init or startup file can
1812 redefine it.
1813 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1814 we do not remove backup version numbers, only true file version numbers."
1815 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1816 (if handler
1817 (funcall handler 'file-name-sans-versions name keep-backup-version)
1818 (substring name 0
1819 (if (eq system-type 'vax-vms)
1820 ;; VMS version number is (a) semicolon, optional
1821 ;; sign, zero or more digits or (b) period, option
1822 ;; sign, zero or more digits, provided this is the
1823 ;; second period encountered outside of the
1824 ;; device/directory part of the file name.
1825 (or (string-match ";[-+]?[0-9]*\\'" name)
1826 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1827 name)
1828 (match-beginning 1))
1829 (length name))
1830 (if keep-backup-version
1831 (length name)
1832 (or (string-match "\\.~[0-9.]+~\\'" name)
1833 (string-match "~\\'" name)
1834 (length name))))))))
1836 (defun file-ownership-preserved-p (file)
1837 "Returns t if deleting FILE and rewriting it would preserve the owner."
1838 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1839 (if handler
1840 (funcall handler 'file-ownership-preserved-p file)
1841 (let ((attributes (file-attributes file)))
1842 ;; Return t if the file doesn't exist, since it's true that no
1843 ;; information would be lost by an (attempted) delete and create.
1844 (or (null attributes)
1845 (= (nth 2 attributes) (user-uid)))))))
1847 (defun file-name-sans-extension (filename)
1848 "Return FILENAME sans final \"extension\".
1849 The extension, in a file name, is the part that follows the last `.'."
1850 (save-match-data
1851 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1852 directory)
1853 (if (string-match "\\.[^.]*\\'" file)
1854 (if (setq directory (file-name-directory filename))
1855 (expand-file-name (substring file 0 (match-beginning 0))
1856 directory)
1857 (substring file 0 (match-beginning 0)))
1858 filename))))
1860 (defun file-name-extension (filename &optional period)
1861 "Return FILENAME's final \"extension\".
1862 The extension, in a file name, is the part that follows the last `.'.
1863 Return nil for extensionless file names such as `foo'.
1864 Return the empty string for file names such as `foo.'.
1866 If PERIOD is non-nil, then the returned value includes the period
1867 that delimits the extension, and if FILENAME has no extension,
1868 the value is \"\"."
1869 (save-match-data
1870 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
1871 (if (string-match "\\.[^.]*\\'" file)
1872 (substring file (+ (match-beginning 0) (if period 0 1)))
1873 (if period
1874 "")))))
1876 (defun make-backup-file-name (file)
1877 "Create the non-numeric backup file name for FILE.
1878 This is a separate function so you can redefine it for customization."
1879 (if (and (eq system-type 'ms-dos)
1880 (not (msdos-long-file-names)))
1881 (let ((fn (file-name-nondirectory file)))
1882 (concat (file-name-directory file)
1884 (and (string-match "\\`[^.]+\\'" fn)
1885 (concat (match-string 0 fn) ".~"))
1886 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
1887 (concat (match-string 0 fn) "~")))))
1888 (concat file "~")))
1890 (defun backup-file-name-p (file)
1891 "Return non-nil if FILE is a backup file name (numeric or not).
1892 This is a separate function so you can redefine it for customization.
1893 You may need to redefine `file-name-sans-versions' as well."
1894 (string-match "~\\'" file))
1896 (defvar backup-extract-version-start)
1898 ;; This is used in various files.
1899 ;; The usage of bv-length is not very clean,
1900 ;; but I can't see a good alternative,
1901 ;; so as of now I am leaving it alone.
1902 (defun backup-extract-version (fn)
1903 "Given the name of a numeric backup file, return the backup number.
1904 Uses the free variable `backup-extract-version-start', whose value should be
1905 the index in the name where the version number begins."
1906 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
1907 (= (match-beginning 0) backup-extract-version-start))
1908 (string-to-int (substring fn backup-extract-version-start -1))
1911 ;; I believe there is no need to alter this behavior for VMS;
1912 ;; since backup files are not made on VMS, it should not get called.
1913 (defun find-backup-file-name (fn)
1914 "Find a file name for a backup file, and suggestions for deletions.
1915 Value is a list whose car is the name for the backup file
1916 and whose cdr is a list of old versions to consider deleting now.
1917 If the value is nil, don't make a backup."
1918 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
1919 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1920 (if handler
1921 (funcall handler 'find-backup-file-name fn)
1922 (if (eq version-control 'never)
1923 (list (make-backup-file-name fn))
1924 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1925 (backup-extract-version-start (length base-versions))
1926 possibilities
1927 (versions nil)
1928 (high-water-mark 0)
1929 (deserve-versions-p nil)
1930 (number-to-delete 0))
1931 (condition-case ()
1932 (setq possibilities (file-name-all-completions
1933 base-versions
1934 (file-name-directory fn))
1935 versions (sort (mapcar
1936 (function backup-extract-version)
1937 possibilities)
1939 high-water-mark (apply 'max 0 versions)
1940 deserve-versions-p (or version-control
1941 (> high-water-mark 0))
1942 number-to-delete (- (length versions)
1943 kept-old-versions kept-new-versions -1))
1944 (file-error
1945 (setq possibilities nil)))
1946 (if (not deserve-versions-p)
1947 (list (make-backup-file-name fn))
1948 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1949 (if (and (> number-to-delete 0)
1950 ;; Delete nothing if there is overflow
1951 ;; in the number of versions to keep.
1952 (>= (+ kept-new-versions kept-old-versions -1) 0))
1953 (mapcar (function (lambda (n)
1954 (concat fn ".~" (int-to-string n) "~")))
1955 (let ((v (nthcdr kept-old-versions versions)))
1956 (rplacd (nthcdr (1- number-to-delete) v) ())
1957 v))))))))))
1959 (defun file-nlinks (filename)
1960 "Return number of names file FILENAME has."
1961 (car (cdr (file-attributes filename))))
1963 (defun file-relative-name (filename &optional directory)
1964 "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
1965 This function returns a relative file name which is equivalent to FILENAME
1966 when used with that default directory as the default.
1967 If this is impossible (which can happen on MSDOS and Windows
1968 when the file name and directory use different drive names)
1969 then it returns FILENAME."
1970 (save-match-data
1971 (let ((fname (expand-file-name filename)))
1972 (setq directory (file-name-as-directory
1973 (expand-file-name (or directory default-directory))))
1974 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
1975 ;; drive names, they can't be relative, so return the absolute name.
1976 (if (and (or (eq system-type 'ms-dos)
1977 (eq system-type 'windows-nt))
1978 (not (string-equal (substring fname 0 2)
1979 (substring directory 0 2))))
1980 filename
1981 (let ((ancestor ".")
1982 (fname-dir (file-name-as-directory fname)))
1983 (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
1984 (not (string-match (concat "^" (regexp-quote directory)) fname)))
1985 (setq directory (file-name-directory (substring directory 0 -1))
1986 ancestor (if (equal ancestor ".")
1987 ".."
1988 (concat "../" ancestor))))
1989 ;; Now ancestor is empty, or .., or ../.., etc.
1990 (if (string-match (concat "^" (regexp-quote directory)) fname)
1991 ;; We matched within FNAME's directory part.
1992 ;; Add the rest of FNAME onto ANCESTOR.
1993 (let ((rest (substring fname (match-end 0))))
1994 (if (and (equal ancestor ".")
1995 (not (equal rest "")))
1996 ;; But don't bother with ANCESTOR if it would give us `./'.
1997 rest
1998 (concat (file-name-as-directory ancestor) rest)))
1999 ;; We matched FNAME's directory equivalent.
2000 ancestor))))))
2002 (defun save-buffer (&optional args)
2003 "Save current buffer in visited file if modified. Versions described below.
2004 By default, makes the previous version into a backup file
2005 if previously requested or if this is the first save.
2006 With 1 \\[universal-argument], marks this version
2007 to become a backup when the next save is done.
2008 With 2 \\[universal-argument]'s,
2009 unconditionally makes the previous version into a backup file.
2010 With 3 \\[universal-argument]'s, marks this version
2011 to become a backup when the next save is done,
2012 and unconditionally makes the previous version into a backup file.
2014 With argument of 0, never makes the previous version into a backup file.
2016 If a file's name is FOO, the names of its numbered backup versions are
2017 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2018 Numeric backups (rather than FOO~) will be made if value of
2019 `version-control' is not the atom `never' and either there are already
2020 numeric versions of the file being backed up, or `version-control' is
2021 non-nil.
2022 We don't want excessive versions piling up, so there are variables
2023 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2024 and `kept-new-versions', which tells how many newest versions to keep.
2025 Defaults are 2 old versions and 2 new.
2026 `dired-kept-versions' controls dired's clean-directory (.) command.
2027 If `delete-old-versions' is nil, system will query user
2028 before trimming versions. Otherwise it does it silently."
2029 (interactive "p")
2030 (let ((modp (buffer-modified-p))
2031 (large (> (buffer-size) 50000))
2032 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2033 (memq args '(16 64)))))
2034 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2035 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
2036 (basic-save-buffer)
2037 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2039 (defun delete-auto-save-file-if-necessary (&optional force)
2040 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2041 Normally delete only if the file was written by this Emacs since
2042 the last real save, but optional arg FORCE non-nil means delete anyway."
2043 (and buffer-auto-save-file-name delete-auto-save-files
2044 (not (string= buffer-file-name buffer-auto-save-file-name))
2045 (or force (recent-auto-save-p))
2046 (progn
2047 (condition-case ()
2048 (delete-file buffer-auto-save-file-name)
2049 (file-error nil))
2050 (set-buffer-auto-saved))))
2052 (defvar after-save-hook nil
2053 "Normal hook that is run after a buffer is saved to its file.")
2055 (defun basic-save-buffer ()
2056 "Save the current buffer in its visited file, if it has been modified.
2057 After saving the buffer, run `after-save-hook'."
2058 (interactive)
2059 (save-excursion
2060 ;; In an indirect buffer, save its base buffer instead.
2061 (if (buffer-base-buffer)
2062 (set-buffer (buffer-base-buffer)))
2063 (if (buffer-modified-p)
2064 (let ((recent-save (recent-auto-save-p))
2065 setmodes tempsetmodes)
2066 ;; On VMS, rename file and buffer to get rid of version number.
2067 (if (and (eq system-type 'vax-vms)
2068 (not (string= buffer-file-name
2069 (file-name-sans-versions buffer-file-name))))
2070 (let (buffer-new-name)
2071 ;; Strip VMS version number before save.
2072 (setq buffer-file-name
2073 (file-name-sans-versions buffer-file-name))
2074 ;; Construct a (unique) buffer name to correspond.
2075 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2076 (setq buffer-new-name (buffer-name buf))
2077 (kill-buffer buf))
2078 (rename-buffer buffer-new-name)))
2079 ;; If buffer has no file name, ask user for one.
2080 (or buffer-file-name
2081 (let ((filename
2082 (expand-file-name
2083 (read-file-name "File to save in: ") nil)))
2084 (and (file-exists-p filename)
2085 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2086 filename))
2087 (error "Canceled")))
2088 (set-visited-file-name filename)))
2089 (or (verify-visited-file-modtime (current-buffer))
2090 (not (file-exists-p buffer-file-name))
2091 (yes-or-no-p
2092 (format "%s has changed since visited or saved. Save anyway? "
2093 (file-name-nondirectory buffer-file-name)))
2094 (error "Save not confirmed"))
2095 (save-restriction
2096 (widen)
2097 (and (> (point-max) 1)
2098 (/= (char-after (1- (point-max))) ?\n)
2099 (not (and (eq selective-display t)
2100 (= (char-after (1- (point-max))) ?\r)))
2101 (or (eq require-final-newline t)
2102 (and require-final-newline
2103 (y-or-n-p
2104 (format "Buffer %s does not end in newline. Add one? "
2105 (buffer-name)))))
2106 (save-excursion
2107 (goto-char (point-max))
2108 (insert ?\n)))
2109 (or (run-hook-with-args-until-success 'write-contents-hooks)
2110 (run-hook-with-args-until-success 'local-write-file-hooks)
2111 (run-hook-with-args-until-success 'write-file-hooks)
2112 ;; If a hook returned t, file is already "written".
2113 ;; Otherwise, write it the usual way now.
2114 (setq setmodes (basic-save-buffer-1)))
2115 (setq buffer-file-number
2116 (nthcdr 10 (file-attributes buffer-file-name)))
2117 (if setmodes
2118 (condition-case ()
2119 (set-file-modes buffer-file-name setmodes)
2120 (error nil))))
2121 ;; If the auto-save file was recent before this command,
2122 ;; delete it now.
2123 (delete-auto-save-file-if-necessary recent-save)
2124 ;; Support VC `implicit' locking.
2125 (vc-after-save)
2126 (run-hooks 'after-save-hook))
2127 (message "(No changes need to be saved)"))))
2129 ;; This does the "real job" of writing a buffer into its visited file
2130 ;; and making a backup file. This is what is normally done
2131 ;; but inhibited if one of write-file-hooks returns non-nil.
2132 ;; It returns a value to store in setmodes.
2133 (defun basic-save-buffer-1 ()
2134 (let (tempsetmodes setmodes)
2135 (if (not (file-writable-p buffer-file-name))
2136 (let ((dir (file-name-directory buffer-file-name)))
2137 (if (not (file-directory-p dir))
2138 (error "%s is not a directory" dir)
2139 (if (not (file-exists-p buffer-file-name))
2140 (error "Directory %s write-protected" dir)
2141 (if (yes-or-no-p
2142 (format "File %s is write-protected; try to save anyway? "
2143 (file-name-nondirectory
2144 buffer-file-name)))
2145 (setq tempsetmodes t)
2146 (error "Attempt to save to a file which you aren't allowed to write"))))))
2147 (or buffer-backed-up
2148 (setq setmodes (backup-buffer)))
2149 (let ((dir (file-name-directory buffer-file-name)))
2150 (if (and file-precious-flag
2151 (file-writable-p dir))
2152 ;; If file is precious, write temp name, then rename it.
2153 ;; This requires write access to the containing dir,
2154 ;; which is why we don't try it if we don't have that access.
2155 (let ((realname buffer-file-name)
2156 tempname temp nogood i succeed
2157 (old-modtime (visited-file-modtime)))
2158 (setq i 0)
2159 (setq nogood t)
2160 ;; Find the temporary name to write under.
2161 (while nogood
2162 (setq tempname (format
2163 (if (and (eq system-type 'ms-dos)
2164 (not (msdos-long-file-names)))
2165 "%s#%d.tm#" ; MSDOS limits files to 8+3
2166 "%s#tmp#%d")
2167 dir i))
2168 (setq nogood (file-exists-p tempname))
2169 (setq i (1+ i)))
2170 (unwind-protect
2171 (progn (clear-visited-file-modtime)
2172 (write-region (point-min) (point-max)
2173 tempname nil realname
2174 buffer-file-truename)
2175 (setq succeed t))
2176 ;; If writing the temp file fails,
2177 ;; delete the temp file.
2178 (or succeed
2179 (progn
2180 (delete-file tempname)
2181 (set-visited-file-modtime old-modtime))))
2182 ;; Since we have created an entirely new file
2183 ;; and renamed it, make sure it gets the
2184 ;; right permission bits set.
2185 (setq setmodes (file-modes buffer-file-name))
2186 ;; We succeeded in writing the temp file,
2187 ;; so rename it.
2188 (rename-file tempname buffer-file-name t))
2189 ;; If file not writable, see if we can make it writable
2190 ;; temporarily while we write it.
2191 ;; But no need to do so if we have just backed it up
2192 ;; (setmodes is set) because that says we're superseding.
2193 (cond ((and tempsetmodes (not setmodes))
2194 ;; Change the mode back, after writing.
2195 (setq setmodes (file-modes buffer-file-name))
2196 (set-file-modes buffer-file-name 511)))
2197 (write-region (point-min) (point-max)
2198 buffer-file-name nil t buffer-file-truename)))
2199 setmodes))
2201 (defun save-some-buffers (&optional arg exiting)
2202 "Save some modified file-visiting buffers. Asks user about each one.
2203 Optional argument (the prefix) non-nil means save all with no questions.
2204 Optional second argument EXITING means ask about certain non-file buffers
2205 as well as about file buffers."
2206 (interactive "P")
2207 (save-window-excursion
2208 (let* ((queried nil)
2209 (files-done
2210 (map-y-or-n-p
2211 (function
2212 (lambda (buffer)
2213 (and (buffer-modified-p buffer)
2214 (not (buffer-base-buffer buffer))
2216 (buffer-file-name buffer)
2217 (and exiting
2218 (progn
2219 (set-buffer buffer)
2220 (and buffer-offer-save (> (buffer-size) 0)))))
2221 (if arg
2223 (setq queried t)
2224 (if (buffer-file-name buffer)
2225 (format "Save file %s? "
2226 (buffer-file-name buffer))
2227 (format "Save buffer %s? "
2228 (buffer-name buffer)))))))
2229 (function
2230 (lambda (buffer)
2231 (set-buffer buffer)
2232 (save-buffer)))
2233 (buffer-list)
2234 '("buffer" "buffers" "save")
2235 (list (list ?\C-r (lambda (buf)
2236 (view-buffer buf
2237 (function
2238 (lambda (ignore)
2239 (exit-recursive-edit))))
2240 (recursive-edit)
2241 ;; Return nil to ask about BUF again.
2242 nil)
2243 "display the current buffer"))))
2244 (abbrevs-done
2245 (and save-abbrevs abbrevs-changed
2246 (progn
2247 (if (or arg
2248 (y-or-n-p (format "Save abbrevs in %s? "
2249 abbrev-file-name)))
2250 (write-abbrev-file nil))
2251 ;; Don't keep bothering user if he says no.
2252 (setq abbrevs-changed nil)
2253 t))))
2254 (or queried (> files-done 0) abbrevs-done
2255 (message "(No files need saving)")))))
2257 (defun not-modified (&optional arg)
2258 "Mark current buffer as unmodified, not needing to be saved.
2259 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2261 It is not a good idea to use this function in Lisp programs, because it
2262 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2263 (interactive "P")
2264 (message (if arg "Modification-flag set"
2265 "Modification-flag cleared"))
2266 (set-buffer-modified-p arg))
2268 (defun toggle-read-only (&optional arg)
2269 "Change whether this buffer is visiting its file read-only.
2270 With arg, set read-only iff arg is positive.
2271 If visiting file read-only and `view-read-only' is non-nil, enter view mode."
2272 (interactive "P")
2273 (cond
2274 ((and arg (if (> (prefix-numeric-value arg) 0) buffer-read-only
2275 (not buffer-read-only))) ; If buffer-read-only is set correctly,
2276 nil) ; do nothing.
2277 ;; Toggle.
2278 ((and buffer-read-only view-mode)
2279 (View-exit-and-edit)) ; Must leave view mode.
2280 ((and (not buffer-read-only) view-read-only
2281 (not (eq (get major-mode 'mode-class) 'special)))
2282 (view-mode-enter))
2283 (t (setq buffer-read-only (not buffer-read-only))
2284 (force-mode-line-update))))
2286 (defun insert-file (filename)
2287 "Insert contents of file FILENAME into buffer after point.
2288 Set mark after the inserted text.
2290 This function is meant for the user to run interactively.
2291 Don't call it from programs! Use `insert-file-contents' instead.
2292 \(Its calling sequence is different; see its documentation)."
2293 (interactive "*fInsert file: ")
2294 (if (file-directory-p filename)
2295 (signal 'file-error (list "Opening input file" "file is a directory"
2296 filename)))
2297 (let ((tem (insert-file-contents filename)))
2298 (push-mark (+ (point) (car (cdr tem))))))
2300 (defun append-to-file (start end filename)
2301 "Append the contents of the region to the end of file FILENAME.
2302 When called from a function, expects three arguments,
2303 START, END and FILENAME. START and END are buffer positions
2304 saying what text to write.
2305 A prefix argument enables user to specify the coding-system interactively."
2306 (interactive "r\nFAppend to file: ")
2307 (write-region start end filename t))
2309 (defun file-newest-backup (filename)
2310 "Return most recent backup file for FILENAME or nil if no backups exist."
2311 (let* ((filename (expand-file-name filename))
2312 (file (file-name-nondirectory filename))
2313 (dir (file-name-directory filename))
2314 (comp (file-name-all-completions file dir))
2315 (newest nil)
2316 tem)
2317 (while comp
2318 (setq tem (car comp)
2319 comp (cdr comp))
2320 (cond ((and (backup-file-name-p tem)
2321 (string= (file-name-sans-versions tem) file))
2322 (setq tem (concat dir tem))
2323 (if (or (null newest)
2324 (file-newer-than-file-p tem newest))
2325 (setq newest tem)))))
2326 newest))
2328 (defun rename-uniquely ()
2329 "Rename current buffer to a similar name not already taken.
2330 This function is useful for creating multiple shell process buffers
2331 or multiple mail buffers, etc."
2332 (interactive)
2333 (save-match-data
2334 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2335 (not (and buffer-file-name
2336 (string= (buffer-name)
2337 (file-name-nondirectory
2338 buffer-file-name)))))
2339 ;; If the existing buffer name has a <NNN>,
2340 ;; which isn't part of the file name (if any),
2341 ;; then get rid of that.
2342 (substring (buffer-name) 0 (match-beginning 0))
2343 (buffer-name)))
2344 (new-buf (generate-new-buffer base-name))
2345 (name (buffer-name new-buf)))
2346 (kill-buffer new-buf)
2347 (rename-buffer name)
2348 (force-mode-line-update))))
2350 (defun make-directory (dir &optional parents)
2351 "Create the directory DIR and any nonexistent parent dirs.
2352 Interactively, the default choice of directory to create
2353 is the current default directory for file names.
2354 That is useful when you have visited a file in a nonexistent directory.
2356 Noninteractively, the second (optional) argument PARENTS says whether
2357 to create parent directories if they don't exist."
2358 (interactive
2359 (list (read-file-name "Make directory: " default-directory default-directory
2360 nil nil)
2362 (let ((handler (find-file-name-handler dir 'make-directory)))
2363 (if handler
2364 (funcall handler 'make-directory dir parents)
2365 (if (not parents)
2366 (make-directory-internal dir)
2367 (let ((dir (directory-file-name (expand-file-name dir)))
2368 create-list)
2369 (while (not (file-exists-p dir))
2370 (setq create-list (cons dir create-list)
2371 dir (directory-file-name (file-name-directory dir))))
2372 (while create-list
2373 (make-directory-internal (car create-list))
2374 (setq create-list (cdr create-list))))))))
2376 (put 'revert-buffer-function 'permanent-local t)
2377 (defvar revert-buffer-function nil
2378 "Function to use to revert this buffer, or nil to do the default.
2379 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2380 which are the arguments that `revert-buffer' received.")
2382 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2383 (defvar revert-buffer-insert-file-contents-function nil
2384 "Function to use to insert contents when reverting this buffer.
2385 Gets two args, first the nominal file name to use,
2386 and second, t if reading the auto-save file.")
2388 (defvar before-revert-hook nil
2389 "Normal hook for `revert-buffer' to run before reverting.
2390 If `revert-buffer-function' is used to override the normal revert
2391 mechanism, this hook is not used.")
2393 (defvar after-revert-hook nil
2394 "Normal hook for `revert-buffer' to run after reverting.
2395 Note that the hook value that it runs is the value that was in effect
2396 before reverting; that makes a difference if you have buffer-local
2397 hook functions.
2399 If `revert-buffer-function' is used to override the normal revert
2400 mechanism, this hook is not used.")
2402 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2403 "Replace current buffer text with the text of the visited file on disk.
2404 This undoes all changes since the file was visited or saved.
2405 With a prefix argument, offer to revert from latest auto-save file, if
2406 that is more recent than the visited file.
2408 This command also works for special buffers that contain text which
2409 doesn't come from a file, but reflects some other data base instead:
2410 for example, Dired buffers and buffer-list buffers. In these cases,
2411 it reconstructs the buffer contents from the appropriate data base.
2413 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2414 to revert from the auto-save file when this is nil. Note that the
2415 sense of this argument is the reverse of the prefix argument, for the
2416 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2417 to nil.
2419 Optional second argument NOCONFIRM means don't ask for confirmation at
2420 all.
2422 Optional third argument PRESERVE-MODES non-nil means don't alter
2423 the files modes. Normally we reinitialize them using `normal-mode'.
2425 If the value of `revert-buffer-function' is non-nil, it is called to
2426 do all the work for this command. Otherwise, the hooks
2427 `before-revert-hook' and `after-revert-hook' are run at the beginning
2428 and the end, and if `revert-buffer-insert-file-contents-function' is
2429 non-nil, it is called instead of rereading visited file contents."
2431 ;; I admit it's odd to reverse the sense of the prefix argument, but
2432 ;; there is a lot of code out there which assumes that the first
2433 ;; argument should be t to avoid consulting the auto-save file, and
2434 ;; there's no straightforward way to encourage authors to notice a
2435 ;; reversal of the argument sense. So I'm just changing the user
2436 ;; interface, but leaving the programmatic interface the same.
2437 (interactive (list (not current-prefix-arg)))
2438 (if revert-buffer-function
2439 (funcall revert-buffer-function ignore-auto noconfirm)
2440 (let* ((opoint (point))
2441 (auto-save-p (and (not ignore-auto)
2442 (recent-auto-save-p)
2443 buffer-auto-save-file-name
2444 (file-readable-p buffer-auto-save-file-name)
2445 (y-or-n-p
2446 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2447 (file-name (if auto-save-p
2448 buffer-auto-save-file-name
2449 buffer-file-name)))
2450 (cond ((null file-name)
2451 (error "Buffer does not seem to be associated with any file"))
2452 ((or noconfirm
2453 (and (not (buffer-modified-p))
2454 (let ((tail revert-without-query)
2455 (found nil))
2456 (while tail
2457 (if (string-match (car tail) file-name)
2458 (setq found t))
2459 (setq tail (cdr tail)))
2460 found))
2461 (yes-or-no-p (format "Revert buffer from file %s? "
2462 file-name)))
2463 (run-hooks 'before-revert-hook)
2464 ;; If file was backed up but has changed since,
2465 ;; we shd make another backup.
2466 (and (not auto-save-p)
2467 (not (verify-visited-file-modtime (current-buffer)))
2468 (setq buffer-backed-up nil))
2469 ;; Get rid of all undo records for this buffer.
2470 (or (eq buffer-undo-list t)
2471 (setq buffer-undo-list nil))
2472 ;; Effectively copy the after-revert-hook status,
2473 ;; since after-find-file will clobber it.
2474 (let ((global-hook (default-value 'after-revert-hook))
2475 (local-hook-p (local-variable-p 'after-revert-hook))
2476 (local-hook (and (local-variable-p 'after-revert-hook)
2477 after-revert-hook)))
2478 (let (buffer-read-only
2479 ;; Don't make undo records for the reversion.
2480 (buffer-undo-list t))
2481 (if revert-buffer-insert-file-contents-function
2482 (funcall revert-buffer-insert-file-contents-function
2483 file-name auto-save-p)
2484 (if (not (file-exists-p file-name))
2485 (error "File %s no longer exists!" file-name))
2486 ;; Bind buffer-file-name to nil
2487 ;; so that we don't try to lock the file.
2488 (let ((buffer-file-name nil))
2489 (or auto-save-p
2490 (unlock-buffer)))
2491 (widen)
2492 (insert-file-contents file-name (not auto-save-p)
2493 nil nil t)))
2494 (goto-char (min opoint (point-max)))
2495 ;; Recompute the truename in case changes in symlinks
2496 ;; have changed the truename.
2497 (setq buffer-file-truename
2498 (abbreviate-file-name (file-truename buffer-file-name)))
2499 (after-find-file nil nil t t preserve-modes)
2500 ;; Run after-revert-hook as it was before we reverted.
2501 (setq-default revert-buffer-internal-hook global-hook)
2502 (if local-hook-p
2503 (progn
2504 (make-local-variable 'revert-buffer-internal-hook)
2505 (setq revert-buffer-internal-hook local-hook))
2506 (kill-local-variable 'revert-buffer-internal-hook))
2507 (run-hooks 'revert-buffer-internal-hook))
2508 t)))))
2510 (defun recover-file (file)
2511 "Visit file FILE, but get contents from its last auto-save file."
2512 ;; Actually putting the file name in the minibuffer should be used
2513 ;; only rarely.
2514 ;; Not just because users often use the default.
2515 (interactive "FRecover file: ")
2516 (setq file (expand-file-name file))
2517 (if (auto-save-file-name-p (file-name-nondirectory file))
2518 (error "%s is an auto-save file" file))
2519 (let ((file-name (let ((buffer-file-name file))
2520 (make-auto-save-file-name))))
2521 (cond ((if (file-exists-p file)
2522 (not (file-newer-than-file-p file-name file))
2523 (not (file-exists-p file-name)))
2524 (error "Auto-save file %s not current" file-name))
2525 ((save-window-excursion
2526 (if (not (eq system-type 'vax-vms))
2527 (with-output-to-temp-buffer "*Directory*"
2528 (buffer-disable-undo standard-output)
2529 (call-process "ls" nil standard-output nil
2530 (if (file-symlink-p file) "-lL" "-l")
2531 file file-name)))
2532 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2533 (switch-to-buffer (find-file-noselect file t))
2534 (let ((buffer-read-only nil)
2535 ;; Auto-saved file shoule be read without any code conversion.
2536 (coding-system-for-read 'no-conversion))
2537 (erase-buffer)
2538 (insert-file-contents file-name nil))
2539 (after-find-file nil nil t))
2540 (t (error "Recover-file cancelled")))))
2542 (defun recover-session ()
2543 "Recover auto save files from a previous Emacs session.
2544 This command first displays a Dired buffer showing you the
2545 previous sessions that you could recover from.
2546 To choose one, move point to the proper line and then type C-c C-c.
2547 Then you'll be asked about a number of files to recover."
2548 (interactive)
2549 (if (null auto-save-list-file-prefix)
2550 (error "You set `auto-save-list-file-prefix' to disable making session files"))
2551 (let ((ls-lisp-support-shell-wildcards t))
2552 (dired (concat auto-save-list-file-prefix "*")
2553 (concat dired-listing-switches "t")))
2554 (goto-char (point-min))
2555 (or (looking-at "Move to the session you want to recover,")
2556 (let ((inhibit-read-only t))
2557 (insert "Move to the session you want to recover,\n"
2558 "then type C-c C-c to select it.\n\n"
2559 "You can also delete some of these files;\n"
2560 "type d on a line to mark that file for deletion.\n\n")))
2561 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2562 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2564 (defun recover-session-finish ()
2565 "Choose one saved session to recover auto-save files from.
2566 This command is used in the special Dired buffer created by
2567 \\[recover-session]."
2568 (interactive)
2569 ;; Get the name of the session file to recover from.
2570 (let ((file (dired-get-filename))
2571 files
2572 (buffer (get-buffer-create " *recover*")))
2573 (dired-do-flagged-delete t)
2574 (unwind-protect
2575 (save-excursion
2576 ;; Read in the auto-save-list file.
2577 (set-buffer buffer)
2578 (erase-buffer)
2579 (insert-file-contents file)
2580 ;; Loop thru the text of that file
2581 ;; and get out the names of the files to recover.
2582 (while (not (eobp))
2583 (let (thisfile autofile)
2584 (if (eolp)
2585 ;; This is a pair of lines for a non-file-visiting buffer.
2586 ;; Get the auto-save file name and manufacture
2587 ;; a "visited file name" from that.
2588 (progn
2589 (forward-line 1)
2590 (setq autofile
2591 (buffer-substring-no-properties
2592 (point)
2593 (save-excursion
2594 (end-of-line)
2595 (point))))
2596 (setq thisfile
2597 (expand-file-name
2598 (substring
2599 (file-name-nondirectory autofile)
2600 1 -1)
2601 (file-name-directory autofile)))
2602 (forward-line 1))
2603 ;; This pair of lines is a file-visiting
2604 ;; buffer. Use the visited file name.
2605 (progn
2606 (setq thisfile
2607 (buffer-substring-no-properties
2608 (point) (progn (end-of-line) (point))))
2609 (forward-line 1)
2610 (setq autofile
2611 (buffer-substring-no-properties
2612 (point) (progn (end-of-line) (point))))
2613 (forward-line 1)))
2614 ;; Ignore a file if its auto-save file does not exist now.
2615 (if (file-exists-p autofile)
2616 (setq files (cons thisfile files)))))
2617 (setq files (nreverse files))
2618 ;; The file contains a pair of line for each auto-saved buffer.
2619 ;; The first line of the pair contains the visited file name
2620 ;; or is empty if the buffer was not visiting a file.
2621 ;; The second line is the auto-save file name.
2622 (if files
2623 (map-y-or-n-p "Recover %s? "
2624 (lambda (file)
2625 (condition-case nil
2626 (save-excursion (recover-file file))
2627 (error
2628 "Failed to recover `%s'" file)))
2629 files
2630 '("file" "files" "recover"))
2631 (message "No files can be recovered from this session now")))
2632 (kill-buffer buffer))))
2634 (defun kill-some-buffers (&optional list)
2635 "For each buffer in LIST, ask whether to kill it.
2636 LIST defaults to all existing live buffers."
2637 (interactive)
2638 (if (null list)
2639 (setq list (buffer-list)))
2640 (while list
2641 (let* ((buffer (car list))
2642 (name (buffer-name buffer)))
2643 (and (not (string-equal name ""))
2644 (/= (aref name 0) ? )
2645 (yes-or-no-p
2646 (format "Buffer %s %s. Kill? "
2647 name
2648 (if (buffer-modified-p buffer)
2649 "HAS BEEN EDITED" "is unmodified")))
2650 (kill-buffer buffer)))
2651 (setq list (cdr list))))
2653 (defun auto-save-mode (arg)
2654 "Toggle auto-saving of contents of current buffer.
2655 With prefix argument ARG, turn auto-saving on if positive, else off."
2656 (interactive "P")
2657 (setq buffer-auto-save-file-name
2658 (and (if (null arg)
2659 (or (not buffer-auto-save-file-name)
2660 ;; If autosave is off because buffer has shrunk,
2661 ;; then toggling should turn it on.
2662 (< buffer-saved-size 0))
2663 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2664 (if (and buffer-file-name auto-save-visited-file-name
2665 (not buffer-read-only))
2666 buffer-file-name
2667 (make-auto-save-file-name))))
2668 ;; If -1 was stored here, to temporarily turn off saving,
2669 ;; turn it back on.
2670 (and (< buffer-saved-size 0)
2671 (setq buffer-saved-size 0))
2672 (if (interactive-p)
2673 (message "Auto-save %s (in this buffer)"
2674 (if buffer-auto-save-file-name "on" "off")))
2675 buffer-auto-save-file-name)
2677 (defun rename-auto-save-file ()
2678 "Adjust current buffer's auto save file name for current conditions.
2679 Also rename any existing auto save file, if it was made in this session."
2680 (let ((osave buffer-auto-save-file-name))
2681 (setq buffer-auto-save-file-name
2682 (make-auto-save-file-name))
2683 (if (and osave buffer-auto-save-file-name
2684 (not (string= buffer-auto-save-file-name buffer-file-name))
2685 (not (string= buffer-auto-save-file-name osave))
2686 (file-exists-p osave)
2687 (recent-auto-save-p))
2688 (rename-file osave buffer-auto-save-file-name t))))
2690 (defun make-auto-save-file-name ()
2691 "Return file name to use for auto-saves of current buffer.
2692 Does not consider `auto-save-visited-file-name' as that variable is checked
2693 before calling this function. You can redefine this for customization.
2694 See also `auto-save-file-name-p'."
2695 (if buffer-file-name
2696 (if (and (eq system-type 'ms-dos)
2697 (not (msdos-long-file-names)))
2698 (let ((fn (file-name-nondirectory buffer-file-name)))
2699 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
2700 (concat (file-name-directory buffer-file-name)
2701 "#" (match-string 1 fn)
2702 "." (match-string 3 fn) "#"))
2703 (concat (file-name-directory buffer-file-name)
2705 (file-name-nondirectory buffer-file-name)
2706 "#"))
2708 ;; Deal with buffers that don't have any associated files. (Mail
2709 ;; mode tends to create a good number of these.)
2711 (let ((buffer-name (buffer-name))
2712 (limit 0))
2713 ;; Eliminate all slashes and backslashes by
2714 ;; replacing them with sequences that start with %.
2715 ;; Quote % also, to keep distinct names distinct.
2716 (while (string-match "[/\\%]" buffer-name limit)
2717 (let* ((character (aref buffer-name (match-beginning 0)))
2718 (replacement
2719 (cond ((eq character ?%) "%%")
2720 ((eq character ?/) "%+")
2721 ((eq character ?\\) "%-"))))
2722 (setq buffer-name (replace-match replacement t t buffer-name))
2723 (setq limit (1+ (match-end 0)))))
2724 ;; Generate the file name.
2725 (expand-file-name
2726 (format "#%s#%s#" buffer-name (make-temp-name ""))
2727 ;; Try a few alternative directories, to get one we can write it.
2728 (cond
2729 ((file-writable-p default-directory) default-directory)
2730 ((file-writable-p "/var/tmp/") "/var/tmp/")
2731 ("~/"))))))
2733 (defun auto-save-file-name-p (filename)
2734 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2735 FILENAME should lack slashes. You can redefine this for customization."
2736 (string-match "^#.*#$" filename))
2738 (defun wildcard-to-regexp (wildcard)
2739 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2740 The generated regexp will match a filename iff the filename
2741 matches that wildcard according to shell rules. Only wildcards known
2742 by `sh' are supported."
2743 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2744 ;; Copy the initial run of non-special characters.
2745 (result (substring wildcard 0 i))
2746 (len (length wildcard)))
2747 ;; If no special characters, we're almost done.
2748 (if i
2749 (while (< i len)
2750 (let ((ch (aref wildcard i))
2752 (setq
2753 result
2754 (concat result
2755 (cond
2756 ((and (eq ch ?\[)
2757 (< (1+ i) len)
2758 (eq (aref wildcard (1+ i)) ?\]))
2759 "\\[")
2760 ((eq ch ?\[) ; [...] maps to regexp char class
2761 (progn
2762 (setq i (1+ i))
2763 (concat
2764 (cond
2765 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2766 (progn
2767 (setq i (1+ i))
2768 (if (eq (aref wildcard i) ?\])
2769 (progn
2770 (setq i (1+ i))
2771 "[^]")
2772 "[^")))
2773 ((eq (aref wildcard i) ?^)
2774 ;; Found "[^". Insert a `\0' character
2775 ;; (which cannot happen in a filename)
2776 ;; into the character class, so that `^'
2777 ;; is not the first character after `[',
2778 ;; and thus non-special in a regexp.
2779 (progn
2780 (setq i (1+ i))
2781 "[\000^"))
2782 ((eq (aref wildcard i) ?\])
2783 ;; I don't think `]' can appear in a
2784 ;; character class in a wildcard, but
2785 ;; let's be general here.
2786 (progn
2787 (setq i (1+ i))
2788 "[]"))
2789 (t "["))
2790 (prog1 ; copy everything upto next `]'.
2791 (substring wildcard
2793 (setq j (string-match
2794 "]" wildcard i)))
2795 (setq i (if j (1- j) (1- len)))))))
2796 ((eq ch ?.) "\\.")
2797 ((eq ch ?*) "[^\000]*")
2798 ((eq ch ?+) "\\+")
2799 ((eq ch ?^) "\\^")
2800 ((eq ch ?$) "\\$")
2801 ((eq ch ?\\) "\\\\") ; probably cannot happen...
2802 ((eq ch ??) "[^\000]")
2803 (t (char-to-string ch)))))
2804 (setq i (1+ i)))))
2805 ;; Shell wildcards should match the entire filename,
2806 ;; not its part. Make the regexp say so.
2807 (concat "\\`" result "\\'")))
2809 (defcustom list-directory-brief-switches
2810 (if (eq system-type 'vax-vms) "" "-CF")
2811 "*Switches for list-directory to pass to `ls' for brief listing,"
2812 :type 'string
2813 :group 'dired)
2815 (defcustom list-directory-verbose-switches
2816 (if (eq system-type 'vax-vms)
2817 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2818 "-l")
2819 "*Switches for list-directory to pass to `ls' for verbose listing,"
2820 :type 'string
2821 :group 'dired)
2823 (defun list-directory (dirname &optional verbose)
2824 "Display a list of files in or matching DIRNAME, a la `ls'.
2825 DIRNAME is globbed by the shell if necessary.
2826 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2827 Actions controlled by variables `list-directory-brief-switches'
2828 and `list-directory-verbose-switches'."
2829 (interactive (let ((pfx current-prefix-arg))
2830 (list (read-file-name (if pfx "List directory (verbose): "
2831 "List directory (brief): ")
2832 nil default-directory nil)
2833 pfx)))
2834 (let ((switches (if verbose list-directory-verbose-switches
2835 list-directory-brief-switches)))
2836 (or dirname (setq dirname default-directory))
2837 (setq dirname (expand-file-name dirname))
2838 (with-output-to-temp-buffer "*Directory*"
2839 (buffer-disable-undo standard-output)
2840 (princ "Directory ")
2841 (princ dirname)
2842 (terpri)
2843 (save-excursion
2844 (set-buffer "*Directory*")
2845 (setq default-directory
2846 (if (file-directory-p dirname)
2847 (file-name-as-directory dirname)
2848 (file-name-directory dirname)))
2849 (let ((wildcard (not (file-directory-p dirname))))
2850 (insert-directory dirname switches wildcard (not wildcard)))))))
2852 (defvar insert-directory-program "ls"
2853 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2855 ;; insert-directory
2856 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2857 ;; FULL-DIRECTORY-P is nil.
2858 ;; The single line of output must display FILE's name as it was
2859 ;; given, namely, an absolute path name.
2860 ;; - must insert exactly one line for each file if WILDCARD or
2861 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2862 ;; before the file lines, plus optional text after the file lines.
2863 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2864 ;; allowed.
2865 ;; File lines should display the basename.
2866 ;; - must be consistent with
2867 ;; - functions dired-move-to-filename, (these two define what a file line is)
2868 ;; dired-move-to-end-of-filename,
2869 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2870 ;; dired-insert-headerline
2871 ;; dired-after-subdir-garbage (defines what a "total" line is)
2872 ;; - variable dired-subdir-regexp
2873 (defun insert-directory (file switches &optional wildcard full-directory-p)
2874 "Insert directory listing for FILE, formatted according to SWITCHES.
2875 Leaves point after the inserted text.
2876 SWITCHES may be a string of options, or a list of strings.
2877 Optional third arg WILDCARD means treat FILE as shell wildcard.
2878 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2879 switches do not contain `d', so that a full listing is expected.
2881 This works by running a directory listing program
2882 whose name is in the variable `insert-directory-program'.
2883 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2884 ;; We need the directory in order to find the right handler.
2885 (let ((handler (find-file-name-handler (expand-file-name file)
2886 'insert-directory)))
2887 (if handler
2888 (funcall handler 'insert-directory file switches
2889 wildcard full-directory-p)
2890 (if (eq system-type 'vax-vms)
2891 (vms-read-directory file switches (current-buffer))
2892 (or (= 0
2893 (if wildcard
2894 ;; Run ls in the directory of the file pattern we asked for.
2895 (let ((default-directory
2896 (if (file-name-absolute-p file)
2897 (file-name-directory file)
2898 (file-name-directory (expand-file-name file))))
2899 (pattern (file-name-nondirectory file))
2900 (beg 0))
2901 ;; Quote some characters that have special meanings in shells;
2902 ;; but don't quote the wildcards--we want them to be special.
2903 ;; We also currently don't quote the quoting characters
2904 ;; in case people want to use them explicitly to quote
2905 ;; wildcard characters.
2906 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
2907 (setq pattern
2908 (concat (substring pattern 0 (match-beginning 0))
2909 "\\"
2910 (substring pattern (match-beginning 0)))
2911 beg (1+ (match-end 0))))
2912 (call-process shell-file-name nil t nil
2913 "-c" (concat "\\" ;; Disregard shell aliases!
2914 insert-directory-program
2915 " -d "
2916 (if (stringp switches)
2917 switches
2918 (mapconcat 'identity switches " "))
2919 " -- "
2920 pattern)))
2921 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2922 ;; directory if FILE is a symbolic link.
2923 (apply 'call-process
2924 insert-directory-program nil t nil
2925 (let (list)
2926 (if (listp switches)
2927 (setq list switches)
2928 (if (not (equal switches ""))
2929 (progn
2930 ;; Split the switches at any spaces
2931 ;; so we can pass separate options as separate args.
2932 (while (string-match " " switches)
2933 (setq list (cons (substring switches 0 (match-beginning 0))
2934 list)
2935 switches (substring switches (match-end 0))))
2936 (setq list (nreverse (cons switches list))))))
2937 (append list
2938 ;; Avoid lossage if FILE starts with `-'.
2939 '("--")
2940 (list
2941 (if full-directory-p
2942 (concat (file-name-as-directory file) ".")
2943 file)))))))
2944 ;; We get here if ls failed.
2945 ;; Access the file to get a suitable error.
2946 (access-file file "Reading directory"))))))
2948 (defvar kill-emacs-query-functions nil
2949 "Functions to call with no arguments to query about killing Emacs.
2950 If any of these functions returns nil, killing Emacs is cancelled.
2951 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2952 but `kill-emacs', the low level primitive, does not.
2953 See also `kill-emacs-hook'.")
2955 (defun save-buffers-kill-emacs (&optional arg)
2956 "Offer to save each buffer, then kill this Emacs process.
2957 With prefix arg, silently save all file-visiting buffers, then kill."
2958 (interactive "P")
2959 (save-some-buffers arg t)
2960 (and (or (not (memq t (mapcar (function
2961 (lambda (buf) (and (buffer-file-name buf)
2962 (buffer-modified-p buf))))
2963 (buffer-list))))
2964 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2965 (or (not (fboundp 'process-list))
2966 ;; process-list is not defined on VMS.
2967 (let ((processes (process-list))
2968 active)
2969 (while processes
2970 (and (memq (process-status (car processes)) '(run stop open))
2971 (let ((val (process-kill-without-query (car processes))))
2972 (process-kill-without-query (car processes) val)
2973 val)
2974 (setq active t))
2975 (setq processes (cdr processes)))
2976 (or (not active)
2977 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2978 ;; Query the user for other things, perhaps.
2979 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
2980 (kill-emacs)))
2982 ;; We use /: as a prefix to "quote" a file name
2983 ;; so that magic file name handlers will not apply to it.
2985 (setq file-name-handler-alist
2986 (cons '("\\`/:" . file-name-non-special)
2987 file-name-handler-alist))
2989 ;; We depend on being the last handler on the list,
2990 ;; so that anything else which does need handling
2991 ;; has been handled already.
2992 ;; So it is safe for us to inhibit *all* magic file name handlers.
2994 (defun file-name-non-special (operation &rest arguments)
2995 (let ((file-name-handler-alist nil)
2996 ;; Get a list of the indices of the args which are file names.
2997 (file-arg-indices
2998 (cdr (or (assq operation
2999 ;; The first four are special because they
3000 ;; return a file name. We want to include the /:
3001 ;; in the return value.
3002 ;; So just avoid stripping it in the first place.
3003 '((expand-file-name . nil)
3004 ;; `identity' means just return the first arg
3005 ;; as stripped of its quoting.
3006 (substitute-in-file-name . identity)
3007 (file-name-directory . nil)
3008 (file-name-as-directory . nil)
3009 (directory-file-name . nil)
3010 (file-name-completion 0 1)
3011 (file-name-all-completions 0 1)
3012 (rename-file 0 1)
3013 (copy-file 0 1)
3014 (make-symbolic-link 0 1)
3015 (add-name-to-file 0 1)))
3016 ;; For all other operations, treat the first argument only
3017 ;; as the file name.
3018 '(nil 0))))
3019 ;; Copy ARGUMENTS so we can replace elements in it.
3020 (arguments (copy-sequence arguments)))
3021 ;; Strip off the /: from the file names that have this handler.
3022 (save-match-data
3023 (while (consp file-arg-indices)
3024 (and (nth (car file-arg-indices) arguments)
3025 (string-match "\\`/:" (nth (car file-arg-indices) arguments))
3026 (setcar (nthcdr (car file-arg-indices) arguments)
3027 (substring (nth (car file-arg-indices) arguments) 2)))
3028 (setq file-arg-indices (cdr file-arg-indices))))
3029 (if (eq file-arg-indices 'identity)
3030 (car arguments)
3031 (apply operation arguments))))
3033 (define-key ctl-x-map "\C-f" 'find-file)
3034 (define-key ctl-x-map "\C-r" 'find-file-read-only)
3035 (define-key ctl-x-map "\C-v" 'find-alternate-file)
3036 (define-key ctl-x-map "\C-s" 'save-buffer)
3037 (define-key ctl-x-map "s" 'save-some-buffers)
3038 (define-key ctl-x-map "\C-w" 'write-file)
3039 (define-key ctl-x-map "i" 'insert-file)
3040 (define-key esc-map "~" 'not-modified)
3041 (define-key ctl-x-map "\C-d" 'list-directory)
3042 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3044 (define-key ctl-x-4-map "f" 'find-file-other-window)
3045 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3046 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3047 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
3048 (define-key ctl-x-4-map "\C-o" 'display-buffer)
3050 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3051 (define-key ctl-x-5-map "f" 'find-file-other-frame)
3052 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3053 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
3055 ;;; files.el ends here