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