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