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