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