(apropos, super-apropos): Doc fix.
[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
b4da00e9
RM
576(defun find-file-noselect (filename &optional nowarn)
577 "Read file FILENAME into a buffer and return the buffer.
578If a buffer exists visiting FILENAME, return that one, but
579verify that the file has not changed since visited or saved.
580The buffer is not selected, just returned to the caller."
e373f201
JB
581 (setq filename
582 (abbreviate-file-name
583 (expand-file-name filename)))
b4da00e9
RM
584 (if (file-directory-p filename)
585 (if find-file-run-dired
586 (dired-noselect filename)
587 (error "%s is a directory." filename))
f3e23606
RS
588 (let* ((buf (get-file-buffer filename))
589 (truename (abbreviate-file-name (file-truename filename)))
590 (number (nthcdr 10 (file-attributes truename)))
591 ;; Find any buffer for a file which has same truename.
592 (same-truename
593 (or buf ; Shortcut
594 (let (found
595 (list (buffer-list)))
596 (while (and (not found) list)
597 (save-excursion
598 (set-buffer (car list))
4269ed64
RM
599 (if (and buffer-file-name
600 (string= buffer-file-truename truename))
f3e23606
RS
601 (setq found (car list))))
602 (setq list (cdr list)))
603 found)))
604 (same-number
605 (or buf ; Shortcut
606 (and number
607 (let (found
608 (list (buffer-list)))
609 (while (and (not found) list)
610 (save-excursion
611 (set-buffer (car list))
4e7afa86
RS
612 (if (and (equal buffer-file-number number)
613 ;; Verify this buffer's file number
614 ;; still belongs to its file.
615 (file-exists-p buffer-file-name)
616 (equal (nthcdr 10 (file-attributes buffer-file-name)) number))
f3e23606
RS
617 (setq found (car list))))
618 (setq list (cdr list)))
619 found))))
620 error)
621 ;; Let user know if there is a buffer with the same truename.
622 (if (and (not buf) same-truename (not nowarn))
623 (message "%s and %s are the same file (%s)"
624 filename (buffer-file-name same-truename)
625 truename)
626 (if (and (not buf) same-number (not nowarn))
627 (message "%s and %s are the same file"
628 filename (buffer-file-name same-number))))
629
630 ;; Optionally also find that buffer.
631 (if (or find-file-existing-other-name find-file-visit-truename)
632 (setq buf (or same-truename same-number)))
b4da00e9
RM
633 (if buf
634 (or nowarn
635 (verify-visited-file-modtime buf)
636 (cond ((not (file-exists-p filename))
637 (error "File %s no longer exists!" filename))
638 ((yes-or-no-p
639 (format
640 (if (buffer-modified-p buf)
641 "File %s changed on disk. Discard your edits? "
642 "File %s changed on disk. Read the new version? ")
643 (file-name-nondirectory filename)))
644 (save-excursion
645 (set-buffer buf)
646 (revert-buffer t t)))))
647 (save-excursion
f3e23606
RS
648;;; The truename stuff makes this obsolete.
649;;; (let* ((link-name (car (file-attributes filename)))
650;;; (linked-buf (and (stringp link-name)
651;;; (get-file-buffer link-name))))
652;;; (if (bufferp linked-buf)
653;;; (message "Symbolic link to file in buffer %s"
654;;; (buffer-name linked-buf))))
b4da00e9
RM
655 (setq buf (create-file-buffer filename))
656 (set-buffer buf)
657 (erase-buffer)
658 (condition-case ()
659 (insert-file-contents filename t)
660 (file-error
661 (setq error t)
662 ;; Run find-file-not-found-hooks until one returns non-nil.
663 (let ((hooks find-file-not-found-hooks))
664 (while (and hooks
455d9d28
RS
665 (not (and (funcall (car hooks))
666 ;; If a hook succeeded, clear error.
667 (progn (setq error nil)
668 ;; Also exit the loop.
669 t))))
b4da00e9 670 (setq hooks (cdr hooks))))))
f3e23606
RS
671 ;; Find the file's truename, and maybe use that as visited name.
672 (setq buffer-file-truename (abbreviate-file-name truename))
1770543d
RS
673 (setq buffer-file-number number)
674 ;; On VMS, we may want to remember which directory in a search list
675 ;; the file was found in.
676 (and (eq system-type 'vax-vms)
677 (let (logical)
678 (if (string-match ":" (file-name-directory filename))
679 (setq logical (substring (file-name-directory filename)
680 0 (match-beginning 0))))
681 (not (member logical find-file-not-true-dirname-list)))
682 (setq buffer-file-name buffer-file-truename))
1cc2fbeb 683 (if find-file-visit-truename
27d0420c
RS
684 (setq buffer-file-name
685 (setq filename
686 (expand-file-name buffer-file-truename))))
b4da00e9
RM
687 ;; Set buffer's default directory to that of the file.
688 (setq default-directory (file-name-directory filename))
689 ;; Turn off backup files for certain file names. Since
690 ;; this is a permanent local, the major mode won't eliminate it.
691 (and (not (funcall backup-enable-predicate buffer-file-name))
692 (progn
693 (make-local-variable 'backup-inhibited)
694 (setq backup-inhibited t)))
695 (after-find-file error (not nowarn))))
696 buf)))
697\f
8cfb9d46 698(defun after-find-file (&optional error warn noauto)
b4da00e9
RM
699 "Called after finding a file and by the default revert function.
700Sets buffer mode, parses local variables.
8cfb9d46 701Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
b4da00e9
RM
702error in reading the file. WARN non-nil means warn if there
703exists an auto-save file more recent than the visited file.
8cfb9d46 704NOAUTO means don't mess with auto-save mode.
b4da00e9
RM
705Finishes by calling the functions in `find-file-hooks'."
706 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
707 (if noninteractive
708 nil
709 (let* (not-serious
710 (msg
711 (cond ((and error (file-attributes buffer-file-name))
712 (setq buffer-read-only t)
ff78d520 713 "File exists, but cannot be read.")
b4da00e9
RM
714 ((not buffer-read-only)
715 (if (and warn
716 (file-newer-than-file-p (make-auto-save-file-name)
717 buffer-file-name))
718 "Auto save file is newer; consider M-x recover-file"
719 (setq not-serious t)
720 (if error "(New file)" nil)))
721 ((not error)
722 (setq not-serious t)
723 "Note: file is write protected")
724 ((file-attributes (directory-file-name default-directory))
725 "File not found and directory write-protected")
4e43240a
RS
726 ((file-exists-p (file-name-directory buffer-file-name))
727 (setq buffer-read-only nil))
b4da00e9 728 (t
5bbbceb1 729 (setq buffer-read-only nil)
4e43240a
RS
730 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
731 "Use M-x make-dir RET RET to create the directory"
732 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
b4da00e9
RM
733 (if msg
734 (progn
735 (message msg)
736 (or not-serious (sit-for 1 nil t)))))
8cfb9d46 737 (if (and auto-save-default (not noauto))
b4da00e9
RM
738 (auto-save-mode t)))
739 (normal-mode t)
740 (mapcar 'funcall find-file-hooks))
741
742(defun normal-mode (&optional find-file)
743 "Choose the major mode for this buffer automatically.
744Also sets up any specified local variables of the file.
745Uses the visited file name, the -*- line, and the local variables spec.
746
747This function is called automatically from `find-file'. In that case,
748we may set up specified local variables depending on the value of
749`enable-local-variables': if it is t, we do; if it is nil, we don't;
750otherwise, we query. `enable-local-variables' is ignored if you
751run `normal-mode' explicitly."
752 (interactive)
753 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
754 (condition-case err
755 (set-auto-mode)
756 (error (message "File mode specification error: %s"
757 (prin1-to-string err))))
758 (condition-case err
7b3f3dc2
JB
759 (let ((enable-local-variables (or (not find-file)
760 enable-local-variables)))
761 (hack-local-variables))
b4da00e9
RM
762 (error (message "File local-variables error: %s"
763 (prin1-to-string err)))))
764
7b3f3dc2
JB
765(defvar auto-mode-alist (mapcar 'purecopy
766 '(("\\.text\\'" . text-mode)
767 ("\\.c\\'" . c-mode)
768 ("\\.h\\'" . c-mode)
769 ("\\.tex\\'" . TeX-mode)
770 ("\\.ltx\\'" . LaTeX-mode)
771 ("\\.el\\'" . emacs-lisp-mode)
772 ("\\.mm\\'" . nroff-mode)
773 ("\\.me\\'" . nroff-mode)
c80d2575
ER
774 ("\\.ms\\'" . nroff-mode)
775 ("\\.man\\'" . nroff-mode)
7b3f3dc2
JB
776 ("\\.scm\\'" . scheme-mode)
777 ("\\.l\\'" . lisp-mode)
778 ("\\.lisp\\'" . lisp-mode)
779 ("\\.f\\'" . fortran-mode)
780 ("\\.for\\'" . fortran-mode)
e70991d4
RS
781 ("\\.p\\'" . pascal-mode)
782 ("\\.pas\\'" . pascal-mode)
7b3f3dc2
JB
783 ("\\.mss\\'" . scribe-mode)
784 ("\\.pl\\'" . prolog-mode)
785 ("\\.cc\\'" . c++-mode)
2b845a8c 786 ("\\.hh\\'" . c++-mode)
7b3f3dc2 787 ("\\.C\\'" . c++-mode)
2b845a8c 788 ("\\.H\\'" . c++-mode)
a3666e47
RS
789;;; ("\\.mk\\'" . makefile-mode)
790;;; ("[Mm]akefile" . makefile-mode)
7b3f3dc2
JB
791;;; Less common extensions come here
792;;; so more common ones above are found faster.
7ca1d903
RS
793 ("\\.texinfo\\'" . texinfo-mode)
794 ("\\.texi\\'" . texinfo-mode)
7b3f3dc2
JB
795 ("\\.s\\'" . asm-mode)
796 ("ChangeLog\\'" . change-log-mode)
bb157910 797 ("change.log\\'" . change-log-mode)
9bb004f6 798 ("changelo\\'" . change-log-mode)
7adc58e5 799 ("ChangeLog.[0-9]+\\'" . change-log-mode)
7b3f3dc2 800 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
7adc58e5
RS
801;; The following should come after the ChangeLog pattern
802;; for the sake of ChangeLog.1, etc.
803 ("\\.[12345678]\\'" . nroff-mode)
7b3f3dc2
JB
804 ("\\.TeX\\'" . TeX-mode)
805 ("\\.sty\\'" . LaTeX-mode)
806 ("\\.bbl\\'" . LaTeX-mode)
807 ("\\.bib\\'" . bibtex-mode)
808 ("\\.article\\'" . text-mode)
809 ("\\.letter\\'" . text-mode)
7ca1d903 810 ("\\.tcl\\'" . tcl-mode)
7b3f3dc2
JB
811 ("\\.lsp\\'" . lisp-mode)
812 ("\\.awk\\'" . awk-mode)
813 ("\\.prolog\\'" . prolog-mode)
c80d2575 814 ("\\.tar\\'" . tar-mode)
7b3f3dc2
JB
815 ;; Mailer puts message to be edited in
816 ;; /tmp/Re.... or Message
817 ("^/tmp/Re" . text-mode)
818 ("/Message[0-9]*\\'" . text-mode)
819 ;; some news reader is reported to use this
820 ("^/tmp/fol/" . text-mode)
821 ("\\.y\\'" . c-mode)
c80d2575 822 ("\\.lex\\'" . c-mode)
7b3f3dc2
JB
823 ("\\.oak\\'" . scheme-mode)
824 ("\\.scm.[0-9]*\\'" . scheme-mode)
278584fb
RS
825 ("\\.sgm\\'" . sgml-mode)
826 ("\\.sgml\\'" . sgml-mode)
827 ("\\.dtd\\'" . sgml-mode)
7b3f3dc2
JB
828 ;; .emacs following a directory delimiter
829 ;; in either Unix or VMS syntax.
830 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
bb157910
RS
831 ;; _emacs following a directory delimiter
832 ;; in MsDos syntax
833 ("[:/]_emacs\\'" . emacs-lisp-mode)
7b3f3dc2
JB
834 ("\\.ml\\'" . lisp-mode)))
835 "\
836Alist of filename patterns vs corresponding major mode functions.
81860e46
RS
837Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION).
838Visiting a file whose name matches REGEXP causes FUNCTION to be called.
839If the element has the form (REGEXP FUNCTION), then after calling
840FUNCTION, we delete the suffix that matched REGEXP and search the list
841again for another match.")
7b3f3dc2 842
c907d156
RS
843(defconst interpreter-mode-alist
844 '(("perl" . perl-mode)
845 ("scope" . tcl-mode)
846 ("wish" . tcl-mode)
847 ("shell" . tcl-mode)
848 ("form" . tcl-mode)
8db739de
NF
849 ("tcl" . tcl-mode)
850 ("awk" . awk-mode)
851 ("gawk" . awk-mode)
852 ("scm" . scheme-mode))
c907d156
RS
853 "Alist mapping interpreter names to major modes.
854This alist applies to files whose first line starts with `#!'.
855Each element looks like (INTERPRETER . MODE).
856The car of each element is compared with
857the name of the interpreter specified in the first line.
858If it matches, mode MODE is selected.")
859
a0c9f21b
RS
860(defconst inhibit-local-variables-regexps '("\\.tar$")
861 "List of regexps; if one matches a file name, don't look for local vars.")
862
bb157910
RS
863(defvar user-init-file
864 "" ; set by command-line
865 "File name including directory of user's initialization file.")
866
b4da00e9
RM
867(defun set-auto-mode ()
868 "Select major mode appropriate for current buffer.
7b3f3dc2 869This checks for a -*- mode tag in the buffer's text, or
81860e46 870compares the filename against the entries in `auto-mode-alist'. It does
7b3f3dc2
JB
871not check for the \"mode:\" local variable in the Local Variables
872section of the file; for that, use `hack-local-variables'.
873
f3e23606 874If `enable-local-variables' is nil, this function does not check for a
7b3f3dc2 875-*- mode tag."
b4da00e9 876 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
9fa7bfe5 877 (let (beg end done)
b4da00e9
RM
878 (save-excursion
879 (goto-char (point-min))
880 (skip-chars-forward " \t\n")
9fa7bfe5
RS
881 (and enable-local-variables
882 ;; Don't look for -*- if this file name matches any
883 ;; of the regexps in inhibit-local-variables-regexps.
884 (let ((temp inhibit-local-variables-regexps))
885 (while (and temp
886 (not (string-match (car temp)
887 buffer-file-name)))
888 (setq temp (cdr temp)))
889 (not temp))
890 (search-forward "-*-" (save-excursion
891 ;; If the file begins with "#!"
892 ;; (exec interpreter magic), look
893 ;; for mode frobs in the first two
894 ;; lines. You cannot necessarily
895 ;; put them in the first line of
896 ;; such a file without screwing up
897 ;; the interpreter invocation.
898 (end-of-line (and (looking-at "^#!") 2))
899 (point)) t)
900 (progn
901 (skip-chars-forward " \t")
902 (setq beg (point))
903 (search-forward "-*-"
904 (save-excursion (end-of-line) (point))
905 t))
906 (progn
907 (forward-char -3)
908 (skip-chars-backward " \t")
909 (setq end (point))
910 (goto-char beg)
911 (if (save-excursion (search-forward ":" end t))
912 ;; Find all specifications for the `mode:' variable
913 ;; and execute hem left to right.
914 (while (let ((case-fold-search t))
915 (search-forward "mode:" end t))
916 (skip-chars-forward " \t")
917 (setq beg (point))
918 (if (search-forward ";" end t)
919 (forward-char -1)
920 (goto-char end))
921 (skip-chars-backward " \t")
922 (funcall (intern (concat (downcase (buffer-substring beg (point))) "-mode"))))
923 ;; Simple -*-MODE-*- case.
924 (funcall (intern (concat (downcase (buffer-substring beg end)) "-mode"))))
925 (setq done t)))
926 ;; If we didn't find a mode from a -*- line, try using the file name.
927 (if (and (not done) buffer-file-name)
81860e46
RS
928 (let ((name buffer-file-name)
929 (case-fold-search (eq system-type 'vax-vms))
930 (keep-going t))
931 ;; Remove backup-suffixes from file name.
932 (setq name (file-name-sans-versions name))
933 (while keep-going
934 (setq keep-going nil)
935 (let ((alist auto-mode-alist)
936 (mode nil))
937 ;; Find first matching alist entry.
938 (while (and (not mode) alist)
939 (if (string-match (car (car alist)) name)
940 (if (and (consp (cdr (car alist)))
941 (nth 2 (car alist)))
942 (progn
943 (setq mode (car (cdr (car alist)))
944 name (substring name 0 (match-beginning 0))
945 keep-going t))
946 (setq mode (cdr (car alist))
947 keep-going nil)))
948 (setq alist (cdr alist)))
c907d156
RS
949 (if mode
950 (funcall mode)
951 ;; If we can't deduce a mode from the file name,
952 ;; look for an interpreter specified in the first line.
953 (let ((interpreter
954 (save-excursion
955 (goto-char (point-min))
956 (if (looking-at "#! *")
957 (progn
958 (goto-char (match-end 0))
959 (buffer-substring (point)
960 (progn (end-of-line) (point))))
961 "")))
962 elt)
963 ;; Map interpreter name to a mode.
964 (setq elt (assoc (file-name-nondirectory interpreter)
965 interpreter-mode-alist))
966 (if elt
967 (funcall (cdr elt))))))))))))
b4da00e9 968
f3e23606
RS
969(defun hack-local-variables-prop-line ()
970 ;; Set local variables specified in the -*- line.
9fa7bfe5
RS
971 ;; Ignore any specification for `mode:';
972 ;; set-auto-mode should already have handled that.
f3e23606
RS
973 (save-excursion
974 (goto-char (point-min))
975 (skip-chars-forward " \t\n\r")
976 (let ((result '())
9fa7bfe5 977 (end (save-excursion (end-of-line) (point))))
f3e23606
RS
978 ;; Parse the -*- line into the `result' alist.
979 (cond ((not (search-forward "-*-" end t))
980 ;; doesn't have one.
981 nil)
982 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
983 ;; Simple form: "-*- MODENAME -*-".
984 (setq result
985 (list (cons 'mode
986 (intern (buffer-substring
987 (match-beginning 1)
988 (match-end 1)))))))
989 (t
990 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
991 ;; (last ";" is optional).
992 (save-excursion
993 (if (search-forward "-*-" end t)
994 (setq end (- (point) 3))
995 (error "-*- not terminated before end of line")))
996 (while (< (point) end)
997 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
998 (error "malformed -*- line"))
999 (goto-char (match-end 0))
1000 (let ((key (intern (downcase (buffer-substring
1001 (match-beginning 1)
1002 (match-end 1)))))
1003 (val (save-restriction
1004 (narrow-to-region (point) end)
1005 (read (current-buffer)))))
1006 (setq result (cons (cons key val) result))
1007 (skip-chars-forward " \t;")))
1008 (setq result (nreverse result))))
f3e23606
RS
1009
1010 (if (and result
1011 (or (eq enable-local-variables t)
1012 (and enable-local-variables
1013 (save-window-excursion
6f931919
RS
1014 (condition-case nil
1015 (switch-to-buffer (current-buffer))
1016 (error
1017 ;; If we fail to switch in the selected window,
1018 ;; it is probably a minibuffer.
1019 ;; So try another window.
1020 (condition-case nil
1021 (switch-to-buffer-other-window (current-buffer))
1022 (error
1023 (switch-to-buffer-other-frame (current-buffer))))))
f3e23606
RS
1024 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1025 (file-name-nondirectory buffer-file-name)))))))
1026 (while result
1027 (let ((key (car (car result)))
1028 (val (cdr (car result))))
9fa7bfe5
RS
1029 (or (eq key 'mode)
1030 (hack-one-local-variable key val)))
1031 (setq result (cdr result)))))))
f3e23606 1032
7b3f3dc2 1033(defun hack-local-variables ()
5792c834 1034 "Parse and put into effect this buffer's local variables spec."
f3e23606 1035 (hack-local-variables-prop-line)
b4da00e9
RM
1036 ;; Look for "Local variables:" line in last page.
1037 (save-excursion
1038 (goto-char (point-max))
1039 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1040 (if (let ((case-fold-search t))
1041 (and (search-forward "Local Variables:" nil t)
7b3f3dc2 1042 (or (eq enable-local-variables t)
b4da00e9
RM
1043 (and enable-local-variables
1044 (save-window-excursion
1045 (switch-to-buffer (current-buffer))
1046 (save-excursion
1047 (beginning-of-line)
1048 (set-window-start (selected-window) (point)))
1049 (y-or-n-p (format "Set local variables as specified at end of %s? "
51de78c1
RS
1050 (if buffer-file-name
1051 (file-name-nondirectory
1052 buffer-file-name)
1053 (concat "buffer "
1054 (buffer-name))))))))))
b4da00e9 1055 (let ((continue t)
2bba782c
RS
1056 prefix prefixlen suffix beg
1057 (enable-local-eval enable-local-eval))
b4da00e9
RM
1058 ;; The prefix is what comes before "local variables:" in its line.
1059 ;; The suffix is what comes after "local variables:" in its line.
1060 (skip-chars-forward " \t")
1061 (or (eolp)
1062 (setq suffix (buffer-substring (point)
1063 (progn (end-of-line) (point)))))
1064 (goto-char (match-beginning 0))
1065 (or (bolp)
1066 (setq prefix
1067 (buffer-substring (point)
1068 (progn (beginning-of-line) (point)))))
7b3f3dc2 1069
b4da00e9
RM
1070 (if prefix (setq prefixlen (length prefix)
1071 prefix (regexp-quote prefix)))
1072 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1073 (while continue
1074 ;; Look at next local variable spec.
1075 (if selective-display (re-search-forward "[\n\C-m]")
1076 (forward-line 1))
1077 ;; Skip the prefix, if any.
1078 (if prefix
1079 (if (looking-at prefix)
1080 (forward-char prefixlen)
1081 (error "Local variables entry is missing the prefix")))
1082 ;; Find the variable name; strip whitespace.
1083 (skip-chars-forward " \t")
1084 (setq beg (point))
1085 (skip-chars-forward "^:\n")
1086 (if (eolp) (error "Missing colon in local variables entry"))
1087 (skip-chars-backward " \t")
1088 (let* ((str (buffer-substring beg (point)))
1089 (var (read str))
1090 val)
1091 ;; Setting variable named "end" means end of list.
1092 (if (string-equal (downcase str) "end")
1093 (setq continue nil)
1094 ;; Otherwise read the variable value.
1095 (skip-chars-forward "^:")
1096 (forward-char 1)
1097 (setq val (read (current-buffer)))
1098 (skip-chars-backward "\n")
1099 (skip-chars-forward " \t")
1100 (or (if suffix (looking-at suffix) (eolp))
1101 (error "Local variables entry is terminated incorrectly"))
1102 ;; Set the variable. "Variables" mode and eval are funny.
f3e23606
RS
1103 (hack-one-local-variable var val))))))))
1104
1105(defconst ignored-local-variables
1106 '(enable-local-eval)
1107 "Variables to be ignored in a file's local variable spec.")
1108
1109;; "Set" one variable in a local variables spec.
1110;; A few variable names are treated specially.
1111(defun hack-one-local-variable (var val)
1112 (cond ((eq var 'mode)
1113 (funcall (intern (concat (downcase (symbol-name val))
1114 "-mode"))))
1115 ((memq var ignored-local-variables)
1116 nil)
1117 ;; "Setting" eval means either eval it or do nothing.
7d3221d7 1118 ;; Likewise for setting hook variables.
fea504fb 1119 ((or (memq var '(eval file-name-handler-alist after-load-alist))
7d3221d7 1120 (string-match "-hooks?$\\|-functions?$" (symbol-name var)))
f3e23606
RS
1121 (if (and (not (string= (user-login-name) "root"))
1122 (or (eq enable-local-eval t)
1123 (and enable-local-eval
1124 (save-window-excursion
1125 (switch-to-buffer (current-buffer))
1126 (save-excursion
1127 (beginning-of-line)
1128 (set-window-start (selected-window) (point)))
1129 (setq enable-local-eval
7d3221d7 1130 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
f3e23606 1131 (file-name-nondirectory buffer-file-name))))))))
7d3221d7
RS
1132 (if (eq var 'eval)
1133 (save-excursion (eval val))
1134 (make-local-variable var)
1135 (set var val))
f3e23606
RS
1136 (message "Ignoring `eval:' in file's local variables")))
1137 ;; Ordinary variable, really set it.
1138 (t (make-local-variable var)
1139 (set var val))))
1140
b4da00e9
RM
1141\f
1142(defun set-visited-file-name (filename)
1143 "Change name of file visited in current buffer to FILENAME.
1144The next time the buffer is saved it will go in the newly specified file.
1145nil or empty string as argument means make buffer not be visiting any file.
1146Remember to delete the initial contents of the minibuffer
1147if you wish to pass an empty string as the argument."
1148 (interactive "FSet visited file name: ")
1149 (if filename
1150 (setq filename
1151 (if (string-equal filename "")
1152 nil
1153 (expand-file-name filename))))
1154 (or (equal filename buffer-file-name)
b4da00e9 1155 (progn
6a8f71e7 1156 (and filename (lock-buffer filename))
b4da00e9
RM
1157 (unlock-buffer)))
1158 (setq buffer-file-name filename)
1159 (if filename ; make buffer name reflect filename.
5bbbceb1 1160 (let ((new-name (file-name-nondirectory buffer-file-name)))
b4da00e9
RM
1161 (if (string= new-name "")
1162 (error "Empty file name"))
1163 (if (eq system-type 'vax-vms)
1164 (setq new-name (downcase new-name)))
1165 (setq default-directory (file-name-directory buffer-file-name))
6f931919
RS
1166 (or (string= new-name (buffer-name))
1167 (rename-buffer new-name t))))
b4da00e9
RM
1168 (setq buffer-backed-up nil)
1169 (clear-visited-file-modtime)
f3e23606
RS
1170 (if filename
1171 (progn
1172 (setq buffer-file-truename
1173 (abbreviate-file-name (file-truename buffer-file-name)))
1174 (if find-file-visit-truename
1175 (setq buffer-file-name buffer-file-truename))
1176 (setq buffer-file-number (nth 10 (file-attributes buffer-file-name))))
1177 (setq buffer-file-truename nil buffer-file-number nil))
b4da00e9
RM
1178 ;; write-file-hooks is normally used for things like ftp-find-file
1179 ;; that visit things that are not local files as if they were files.
1180 ;; Changing to visit an ordinary local file instead should flush the hook.
1181 (kill-local-variable 'write-file-hooks)
c9dca4e0 1182 (kill-local-variable 'local-write-file-hooks)
b4da00e9
RM
1183 (kill-local-variable 'revert-buffer-function)
1184 (kill-local-variable 'backup-inhibited)
1185 ;; Turn off backup files for certain file names.
1186 ;; Since this is a permanent local, the major mode won't eliminate it.
1187 (and (not (funcall backup-enable-predicate buffer-file-name))
1188 (progn
1189 (make-local-variable 'backup-inhibited)
1190 (setq backup-inhibited t)))
c77a81cf
RS
1191 (let ((oauto buffer-auto-save-file-name))
1192 ;; If auto-save was not already on, turn it on if appropriate.
1193 (if (not buffer-auto-save-file-name)
1194 (and buffer-file-name auto-save-default
1195 (auto-save-mode t))
1196 ;; If auto save is on, start using a new name.
1197 ;; We deliberately don't rename or delete the old auto save
1198 ;; for the old visited file name. This is because perhaps
1199 ;; the user wants to save the new state and then compare with the
1200 ;; previous state from the auto save file.
1201 (setq buffer-auto-save-file-name
1202 (make-auto-save-file-name)))
1203 ;; Rename the old auto save file if any.
1204 (and oauto buffer-auto-save-file-name
e6f0e76c 1205 (file-exists-p oauto)
c77a81cf 1206 (rename-file oauto buffer-auto-save-file-name t)))
b4da00e9
RM
1207 (if buffer-file-name
1208 (set-buffer-modified-p t)))
1209
1210(defun write-file (filename)
1211 "Write current buffer into file FILENAME.
41f48cb1
RS
1212Makes buffer visit that file, and marks it not modified.
1213If the buffer is already visiting a file, you can specify
1214a directory name as FILENAME, to write a file of the same
1215old name in that directory."
b4da00e9
RM
1216;; (interactive "FWrite file: ")
1217 (interactive
1218 (list (if buffer-file-name
1219 (read-file-name "Write file: "
1220 nil nil nil nil)
1221 (read-file-name "Write file: "
1222 (cdr (assq 'default-directory
1223 (buffer-local-variables)))
1224 nil nil (buffer-name)))))
1225 (or (null filename) (string-equal filename "")
41f48cb1
RS
1226 (progn
1227 ;; If arg is just a directory,
1228 ;; use same file name, but in that directory.
1229 (if (and (file-directory-p filename) buffer-file-name)
1230 (setq filename (concat (file-name-as-directory filename)
1231 (file-name-nondirectory buffer-file-name))))
1232 (set-visited-file-name filename)))
b4da00e9
RM
1233 (set-buffer-modified-p t)
1234 (save-buffer))
1235\f
1236(defun backup-buffer ()
1237 "Make a backup of the disk file visited by the current buffer, if appropriate.
1238This is normally done before saving the buffer the first time.
1239If the value is non-nil, it is the result of `file-modes' on the original
1240file; this means that the caller, after saving the buffer, should change
1241the modes of the new file to agree with the old modes."
1242 (if (and make-backup-files (not backup-inhibited)
1243 (not buffer-backed-up)
1244 (file-exists-p buffer-file-name)
1245 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1246 '(?- ?l)))
1247 (let ((real-file-name buffer-file-name)
1248 backup-info backupname targets setmodes)
1249 ;; If specified name is a symbolic link, chase it to the target.
1250 ;; Thus we make the backups in the directory where the real file is.
5dadeb29 1251 (setq real-file-name (file-chase-links real-file-name))
b4da00e9
RM
1252 (setq backup-info (find-backup-file-name real-file-name)
1253 backupname (car backup-info)
1254 targets (cdr backup-info))
1255;;; (if (file-directory-p buffer-file-name)
1256;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1257 (condition-case ()
1258 (let ((delete-old-versions
1259 ;; If have old versions to maybe delete,
1260 ;; ask the user to confirm now, before doing anything.
1261 ;; But don't actually delete til later.
1262 (and targets
6d74b528 1263 (or (eq trim-versions-without-asking t) (eq trim-versions-without-asking nil))
b4da00e9
RM
1264 (or trim-versions-without-asking
1265 (y-or-n-p (format "Delete excess backup versions of %s? "
1266 real-file-name))))))
1267 ;; Actually write the back up file.
1268 (condition-case ()
1269 (if (or file-precious-flag
1270; (file-symlink-p buffer-file-name)
1271 backup-by-copying
1272 (and backup-by-copying-when-linked
1273 (> (file-nlinks real-file-name) 1))
1274 (and backup-by-copying-when-mismatch
1275 (let ((attr (file-attributes real-file-name)))
1276 (or (nth 9 attr)
1277 (/= (nth 2 attr) (user-uid))))))
65864ae0
RS
1278 (condition-case ()
1279 (copy-file real-file-name backupname t t)
1280 (file-error
1281 ;; If copying fails because file BACKUPNAME
1282 ;; is not writable, delete that file and try again.
1283 (if (and (file-exists-p backupname)
1284 (not (file-writable-p backupname)))
1285 (delete-file backupname))
1286 (copy-file real-file-name backupname t t)))
1287 ;; rename-file should delete old backup.
b4da00e9
RM
1288 (rename-file real-file-name backupname t)
1289 (setq setmodes (file-modes backupname)))
1290 (file-error
1291 ;; If trouble writing the backup, write it in ~.
1292 (setq backupname (expand-file-name "~/%backup%~"))
1293 (message "Cannot write backup file; backing up in ~/%%backup%%~")
1294 (sleep-for 1)
65864ae0
RS
1295 (condition-case ()
1296 (copy-file real-file-name backupname t t)
1297 (file-error
1298 ;; If copying fails because file BACKUPNAME
1299 ;; is not writable, delete that file and try again.
1300 (if (and (file-exists-p backupname)
1301 (not (file-writable-p backupname)))
1302 (delete-file backupname))
1303 (copy-file real-file-name backupname t t)))))
b4da00e9
RM
1304 (setq buffer-backed-up t)
1305 ;; Now delete the old versions, if desired.
1306 (if delete-old-versions
1307 (while targets
1308 (condition-case ()
1309 (delete-file (car targets))
1310 (file-error nil))
1311 (setq targets (cdr targets))))
1312 setmodes)
1313 (file-error nil)))))
1314
c3554e95 1315(defun file-name-sans-versions (name &optional keep-backup-version)
b4da00e9
RM
1316 "Return FILENAME sans backup versions or strings.
1317This is a separate procedure so your site-init or startup file can
c3554e95
RS
1318redefine it.
1319If the optional argument KEEP-BACKUP-VERSION is non-nil,
1320we do not remove backup version numbers, only true file version numbers."
5dbfdacd 1321 (let ((handler (find-file-name-handler name)))
c3554e95
RS
1322 (if handler
1323 (funcall handler 'file-name-sans-versions name keep-backup-version)
1324 (substring name 0
1325 (if (eq system-type 'vax-vms)
1326 ;; VMS version number is (a) semicolon, optional
1327 ;; sign, zero or more digits or (b) period, option
1328 ;; sign, zero or more digits, provided this is the
1329 ;; second period encountered outside of the
1330 ;; device/directory part of the file name.
1331 (or (string-match ";[---+]?[0-9]*\\'" name)
1332 (if (string-match "\\.[^]>:]*\\(\\.[---+]?[0-9]*\\)\\'"
1333 name)
1334 (match-beginning 1))
1335 (length name))
1336 (if keep-backup-version
1337 (length name)
1338 (or (string-match "\\.~[0-9]+~\\'" name)
1339 (string-match "~\\'" name)
1340 (length name))))))))
b4da00e9
RM
1341
1342(defun make-backup-file-name (file)
1343 "Create the non-numeric backup file name for FILE.
1344This is a separate function so you can redefine it for customization."
bb157910
RS
1345 (if (eq system-type 'ms-dos)
1346 (let ((fn (file-name-nondirectory file)))
1347 (concat (file-name-directory file)
1348 (if (string-match "\\([^.]*\\)\\(\\..*\\)?" fn)
1349 (substring fn 0 (match-end 1)))
1350 ".bak"))
1351 (concat file "~")))
b4da00e9
RM
1352
1353(defun backup-file-name-p (file)
1354 "Return non-nil if FILE is a backup file name (numeric or not).
1355This is a separate function so you can redefine it for customization.
1356You may need to redefine `file-name-sans-versions' as well."
bb157910
RS
1357 (if (eq system-type 'ms-dos)
1358 (string-match "\\.bak$" file)
1359 (string-match "~$" file)))
b4da00e9 1360
2d051399
RS
1361;; This is used in various files.
1362;; The usage of bv-length is not very clean,
1363;; but I can't see a good alternative,
1364;; so as of now I am leaving it alone.
1365(defun backup-extract-version (fn)
1366 "Given the name of a numeric backup file, return the backup number.
1367Uses the free variable `bv-length', whose value should be
1368the index in the name where the version number begins."
1369 (if (and (string-match "[0-9]+~$" fn bv-length)
1370 (= (match-beginning 0) bv-length))
1371 (string-to-int (substring fn bv-length -1))
1372 0))
1373
b4da00e9
RM
1374;; I believe there is no need to alter this behavior for VMS;
1375;; since backup files are not made on VMS, it should not get called.
1376(defun find-backup-file-name (fn)
1377 "Find a file name for a backup file, and suggestions for deletions.
1378Value is a list whose car is the name for the backup file
1379 and whose cdr is a list of old versions to consider deleting now."
1380 (if (eq version-control 'never)
1381 (list (make-backup-file-name fn))
1382 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1383 (bv-length (length base-versions))
7a5a26a6
RS
1384 possibilities
1385 (versions nil)
1386 (high-water-mark 0)
1387 (deserve-versions-p nil)
1388 (number-to-delete 0))
1389 (condition-case ()
1390 (setq possibilities (file-name-all-completions
1391 base-versions
1392 (file-name-directory fn))
1393 versions (sort (mapcar
1394 (function backup-extract-version)
1395 possibilities)
1396 '<)
1397 high-water-mark (apply 'max 0 versions)
1398 deserve-versions-p (or version-control
1399 (> high-water-mark 0))
1400 number-to-delete (- (length versions)
1401 kept-old-versions kept-new-versions -1))
1402 (file-error
1403 (setq possibilities nil)))
b4da00e9
RM
1404 (if (not deserve-versions-p)
1405 (list (make-backup-file-name fn))
1406 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
9115e938
NF
1407 (if (and (> number-to-delete 0)
1408 ;; Delete nothing if there is overflow
1409 ;; in the number of versions to keep.
1410 (>= (+ kept-new-versions kept-old-versions -1) 0))
b4da00e9
RM
1411 (mapcar (function (lambda (n)
1412 (concat fn ".~" (int-to-string n) "~")))
1413 (let ((v (nthcdr kept-old-versions versions)))
1414 (rplacd (nthcdr (1- number-to-delete) v) ())
1415 v))))))))
1416
b4da00e9
RM
1417(defun file-nlinks (filename)
1418 "Return number of names file FILENAME has."
1419 (car (cdr (file-attributes filename))))
6c636af9
RM
1420
1421(defun file-relative-name (filename &optional directory)
1422 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1423 (setq filename (expand-file-name filename)
77fb6aed
RS
1424 directory (file-name-as-directory (expand-file-name
1425 (or directory default-directory))))
b1fa544f
KH
1426 (let ((ancestor ""))
1427 (while (not (string-match (concat "^" (regexp-quote directory)) filename))
1428 (setq directory (file-name-directory (substring directory 0 -1))
1429 ancestor (concat "../" ancestor)))
1430 (concat ancestor (substring filename (match-end 0)))))
b4da00e9
RM
1431\f
1432(defun save-buffer (&optional args)
1433 "Save current buffer in visited file if modified. Versions described below.
1434By default, makes the previous version into a backup file
1435 if previously requested or if this is the first save.
1436With 1 or 3 \\[universal-argument]'s, marks this version
1437 to become a backup when the next save is done.
1438With 2 or 3 \\[universal-argument]'s,
1439 unconditionally makes the previous version into a backup file.
1440With argument of 0, never makes the previous version into a backup file.
1441
1442If a file's name is FOO, the names of its numbered backup versions are
1443 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1444Numeric backups (rather than FOO~) will be made if value of
1445 `version-control' is not the atom `never' and either there are already
1446 numeric versions of the file being backed up, or `version-control' is
1447 non-nil.
1448We don't want excessive versions piling up, so there are variables
1449 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1450 and `kept-new-versions', which tells how many newest versions to keep.
1451 Defaults are 2 old versions and 2 new.
1452`dired-kept-versions' controls dired's clean-directory (.) command.
1453If `trim-versions-without-asking' is nil, system will query user
1454 before trimming versions. Otherwise it does it silently."
1455 (interactive "p")
1456 (let ((modp (buffer-modified-p))
1457 (large (> (buffer-size) 50000))
1458 (make-backup-files (and make-backup-files (not (eq args 0)))))
1459 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
1460 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
1461 (basic-save-buffer)
1462 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
1463
1464(defun delete-auto-save-file-if-necessary (&optional force)
1465 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1466Normally delete only if the file was written by this Emacs since
1467the last real save, but optional arg FORCE non-nil means delete anyway."
1468 (and buffer-auto-save-file-name delete-auto-save-files
1469 (not (string= buffer-file-name buffer-auto-save-file-name))
1470 (or force (recent-auto-save-p))
1471 (progn
1472 (condition-case ()
1473 (delete-file buffer-auto-save-file-name)
1474 (file-error nil))
1475 (set-buffer-auto-saved))))
1476
1477(defun basic-save-buffer ()
1478 "Save the current buffer in its visited file, if it has been modified."
1479 (interactive)
1480 (if (buffer-modified-p)
1481 (let ((recent-save (recent-auto-save-p))
1482 setmodes tempsetmodes)
1483 ;; On VMS, rename file and buffer to get rid of version number.
1484 (if (and (eq system-type 'vax-vms)
1485 (not (string= buffer-file-name
1486 (file-name-sans-versions buffer-file-name))))
1487 (let (buffer-new-name)
1488 ;; Strip VMS version number before save.
1489 (setq buffer-file-name
1490 (file-name-sans-versions buffer-file-name))
1491 ;; Construct a (unique) buffer name to correspond.
1492 (let ((buf (create-file-buffer (downcase buffer-file-name))))
1493 (setq buffer-new-name (buffer-name buf))
1494 (kill-buffer buf))
1495 (rename-buffer buffer-new-name)))
1496 ;; If buffer has no file name, ask user for one.
1497 (or buffer-file-name
2943f983
RS
1498 (set-visited-file-name
1499 (expand-file-name (read-file-name "File to save in: ") nil)))
b4da00e9
RM
1500 (or (verify-visited-file-modtime (current-buffer))
1501 (not (file-exists-p buffer-file-name))
1502 (yes-or-no-p
1503 (format "%s has changed since visited or saved. Save anyway? "
1504 (file-name-nondirectory buffer-file-name)))
1505 (error "Save not confirmed"))
1506 (save-restriction
1507 (widen)
1508 (and (> (point-max) 1)
1509 (/= (char-after (1- (point-max))) ?\n)
1510 (or (eq require-final-newline t)
1511 (and require-final-newline
1512 (y-or-n-p
1513 (format "Buffer %s does not end in newline. Add one? "
1514 (buffer-name)))))
1515 (save-excursion
1516 (goto-char (point-max))
1517 (insert ?\n)))
c9dca4e0
RS
1518 (let ((hooks (append write-contents-hooks local-write-file-hooks
1519 write-file-hooks))
b4da00e9
RM
1520 (done nil))
1521 (while (and hooks
1522 (not (setq done (funcall (car hooks)))))
1523 (setq hooks (cdr hooks)))
1524 ;; If a hook returned t, file is already "written".
1525 (cond ((not done)
1526 (if (not (file-writable-p buffer-file-name))
1527 (let ((dir (file-name-directory buffer-file-name)))
1528 (if (not (file-directory-p dir))
1529 (error "%s is not a directory" dir)
1530 (if (not (file-exists-p buffer-file-name))
1531 (error "Directory %s write-protected" dir)
1532 (if (yes-or-no-p
1533 (format "File %s is write-protected; try to save anyway? "
1534 (file-name-nondirectory
1535 buffer-file-name)))
1536 (setq tempsetmodes t)
1537 (error "Attempt to save to a file which you aren't allowed to write"))))))
1538 (or buffer-backed-up
1539 (setq setmodes (backup-buffer)))
1540 (if file-precious-flag
f3e23606
RS
1541 ;; If file is precious, write temp name, then rename it.
1542 (let ((dir (file-name-directory buffer-file-name))
1543 (realname buffer-file-name)
1544 tempname temp nogood i succeed)
1545 (setq i 0)
1546 (setq nogood t)
1547 ;; Find the temporary name to write under.
1548 (while nogood
1549 (setq tempname (format "%s#tmp#%d" dir i))
1550 (setq nogood (file-exists-p tempname))
1551 (setq i (1+ i)))
b4da00e9
RM
1552 (unwind-protect
1553 (progn (clear-visited-file-modtime)
1554 (write-region (point-min) (point-max)
f3e23606
RS
1555 tempname nil realname)
1556 (setq succeed t))
1557 ;; If writing the temp file fails,
1558 ;; delete the temp file.
1559 (or succeed (delete-file tempname)))
b411d947
JB
1560 ;; Since we have created an entirely new file
1561 ;; and renamed it, make sure it gets the
1562 ;; right permission bits set.
1563 (setq setmodes (file-modes buffer-file-name))
f3e23606
RS
1564 ;; We succeeded in writing the temp file,
1565 ;; so rename it.
1566 (rename-file tempname buffer-file-name t))
b4da00e9
RM
1567 ;; If file not writable, see if we can make it writable
1568 ;; temporarily while we write it.
1569 ;; But no need to do so if we have just backed it up
1570 ;; (setmodes is set) because that says we're superseding.
1571 (cond ((and tempsetmodes (not setmodes))
1572 ;; Change the mode back, after writing.
1573 (setq setmodes (file-modes buffer-file-name))
1574 (set-file-modes buffer-file-name 511)))
1575 (write-region (point-min) (point-max)
1576 buffer-file-name nil t)))))
f3e23606 1577 (setq buffer-file-number (nth 10 (file-attributes buffer-file-name)))
b4da00e9
RM
1578 (if setmodes
1579 (condition-case ()
f3e23606 1580 (set-file-modes buffer-file-name setmodes)
b4da00e9
RM
1581 (error nil))))
1582 ;; If the auto-save file was recent before this command,
1583 ;; delete it now.
1584 (delete-auto-save-file-if-necessary recent-save)
1bf3d475 1585 (run-hooks 'after-save-hook))
b4da00e9
RM
1586 (message "(No changes need to be saved)")))
1587
b4da00e9
RM
1588(defun save-some-buffers (&optional arg exiting)
1589 "Save some modified file-visiting buffers. Asks user about each one.
5bbbceb1
JB
1590Optional argument (the prefix) non-nil means save all with no questions.
1591Optional second argument EXITING means ask about certain non-file buffers
1592 as well as about file buffers."
b4da00e9 1593 (interactive "P")
907482b9 1594 (save-window-excursion
5625c2fc
RS
1595 (let ((files-done
1596 (map-y-or-n-p
1597 (function
1598 (lambda (buffer)
1599 (and (buffer-modified-p buffer)
1600 (or
1601 (buffer-file-name buffer)
1602 (and exiting
1603 (progn
1604 (set-buffer buffer)
1605 (and buffer-offer-save (> (buffer-size) 0)))))
1606 (if arg
1607 t
1608 (if (buffer-file-name buffer)
1609 (format "Save file %s? "
1610 (buffer-file-name buffer))
1611 (format "Save buffer %s? "
1612 (buffer-name buffer)))))))
1613 (function
1614 (lambda (buffer)
1615 (set-buffer buffer)
1616 (save-buffer)))
1617 (buffer-list)
1618 '("buffer" "buffers" "save")
1619 (list (list ?\C-r (lambda (buf)
1620 (view-buffer buf)
1621 (setq view-exit-action
1622 '(lambda (ignore)
1623 (exit-recursive-edit)))
1624 (recursive-edit)
1625 ;; Return nil to ask about BUF again.
1626 nil)
1627 "display the current buffer"))))
1628 (abbrevs-done
1629 (and save-abbrevs abbrevs-changed
1630 (progn
1631 (if (or arg
1632 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
1633 (write-abbrev-file nil))
1634 ;; Don't keep bothering user if he says no.
1635 (setq abbrevs-changed nil)
1636 t))))
1637 (or (> files-done 0) abbrevs-done
1638 (message "(No files need saving)")))))
b4da00e9
RM
1639\f
1640(defun not-modified (&optional arg)
1641 "Mark current buffer as unmodified, not needing to be saved.
1642With prefix arg, mark buffer as modified, so \\[save-buffer] will save."
1643 (interactive "P")
1644 (message (if arg "Modification-flag set"
1645 "Modification-flag cleared"))
1646 (set-buffer-modified-p arg))
1647
1648(defun toggle-read-only (&optional arg)
1649 "Change whether this buffer is visiting its file read-only.
1650With arg, set read-only iff arg is positive."
1651 (interactive "P")
1652 (setq buffer-read-only
1653 (if (null arg)
1654 (not buffer-read-only)
1655 (> (prefix-numeric-value arg) 0)))
1656 ;; Force mode-line redisplay
1657 (set-buffer-modified-p (buffer-modified-p)))
1658
1659(defun insert-file (filename)
1660 "Insert contents of file FILENAME into buffer after point.
1661Set mark after the inserted text.
1662
1663This function is meant for the user to run interactively.
1664Don't call it from programs! Use `insert-file-contents' instead.
1665\(Its calling sequence is different; see its documentation)."
6f931919 1666 (interactive "*fInsert file: ")
3be6243a
RS
1667 (if (file-directory-p filename)
1668 (signal 'file-error (list "Opening input file" "file is a directory"
1669 filename)))
b4da00e9
RM
1670 (let ((tem (insert-file-contents filename)))
1671 (push-mark (+ (point) (car (cdr tem))))))
1672
1673(defun append-to-file (start end filename)
1674 "Append the contents of the region to the end of file FILENAME.
1675When called from a function, expects three arguments,
1676START, END and FILENAME. START and END are buffer positions
1677saying what text to write."
1678 (interactive "r\nFAppend to file: ")
1679 (write-region start end filename t))
1680
1681(defun file-newest-backup (filename)
1682 "Return most recent backup file for FILENAME or nil if no backups exist."
1683 (let* ((filename (expand-file-name filename))
1684 (file (file-name-nondirectory filename))
1685 (dir (file-name-directory filename))
1686 (comp (file-name-all-completions file dir))
1687 newest)
1688 (while comp
1689 (setq file (concat dir (car comp))
1690 comp (cdr comp))
1691 (if (and (backup-file-name-p file)
1692 (or (null newest) (file-newer-than-file-p file newest)))
1693 (setq newest file)))
1694 newest))
1695
1696(defun rename-uniquely ()
1697 "Rename current buffer to a similar name not already taken.
1698This function is useful for creating multiple shell process buffers
1699or multiple mail buffers, etc."
1700 (interactive)
1701 (let* ((new-buf (generate-new-buffer (buffer-name)))
1702 (name (buffer-name new-buf)))
1703 (kill-buffer new-buf)
1704 (rename-buffer name)
1705 (set-buffer-modified-p (buffer-modified-p)))) ; force mode line update
5bbbceb1 1706
4e43240a 1707(defun make-directory (dir &optional parents)
5ce8bb89
RS
1708 "Create the directory DIR and any nonexistent parent dirs.
1709Interactively, the default choice of directory to create
1710is the current default directory for file names.
1711That is useful when you have visited a file in a nonexistint directory.
1712
1713Noninteractively, the second (optional) argument PARENTS says whether
1714to create parent directories if they don't exist."
1715 (interactive
1716 (list (read-file-name "Make directory: " default-directory default-directory
1717 nil nil)
1718 t))
5dbfdacd 1719 (let ((handler (find-file-name-handler dir)))
4e43240a
RS
1720 (if handler
1721 (funcall handler 'make-directory dir parents)
1722 (if (not parents)
1723 (make-directory-internal dir)
1724 (let ((dir (directory-file-name (expand-file-name dir)))
1725 create-list)
1726 (while (not (file-exists-p dir))
1727 (setq create-list (cons dir create-list)
1728 dir (directory-file-name (file-name-directory dir))))
1729 (while create-list
1730 (make-directory-internal (car create-list))
1731 (setq create-list (cdr create-list))))))))
b4da00e9
RM
1732\f
1733(put 'revert-buffer-function 'permanent-local t)
1734(defvar revert-buffer-function nil
1735 "Function to use to revert this buffer, or nil to do the default.")
1736
1737(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
1738(defvar revert-buffer-insert-file-contents-function nil
1739 "Function to use to insert contents when reverting this buffer.
1740Gets two args, first the nominal file name to use,
1741and second, t if reading the auto-save file.")
1742
1ab31687 1743(defun revert-buffer (&optional ignore-auto noconfirm)
b4da00e9
RM
1744 "Replace the buffer text with the text of the visited file on disk.
1745This undoes all changes since the file was visited or saved.
8c0e7b73
JB
1746With a prefix argument, offer to revert from latest auto-save file, if
1747that is more recent than the visited file.
1ab31687 1748
fc51b251 1749When called from lisp, The first argument is IGNORE-AUTO; only offer
1ab31687
JB
1750to revert from the auto-save file when this is nil. Note that the
1751sense of this argument is the reverse of the prefix argument, for the
1752sake of backward compatibility. IGNORE-AUTO is optional, defaulting
1753to nil.
1754
1755Optional second argument NOCONFIRM means don't ask for confirmation at
1756all.
b4da00e9 1757
8c0e7b73 1758If the value of `revert-buffer-function' is non-nil, it is called to
fb6208a6
RS
1759do the work.
1760
4fbf62ee
KH
1761The default revert function runs the hook `before-revert-hook' at the
1762beginning and `after-revert-hook' at the end."
1ab31687
JB
1763 ;; I admit it's odd to reverse the sense of the prefix argument, but
1764 ;; there is a lot of code out there which assumes that the first
1765 ;; argument should be t to avoid consulting the auto-save file, and
1766 ;; there's no straightforward way to encourage authors to notice a
1767 ;; reversal of the argument sense. So I'm just changing the user
1768 ;; interface, but leaving the programmatic interface the same.
1769 (interactive (list (not prefix-arg)))
b4da00e9 1770 (if revert-buffer-function
1ab31687 1771 (funcall revert-buffer-function ignore-auto noconfirm)
b4da00e9 1772 (let* ((opoint (point))
1ab31687
JB
1773 (auto-save-p (and (not ignore-auto)
1774 (recent-auto-save-p)
b4da00e9
RM
1775 buffer-auto-save-file-name
1776 (file-readable-p buffer-auto-save-file-name)
1777 (y-or-n-p
1778 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
1779 (file-name (if auto-save-p
1780 buffer-auto-save-file-name
1781 buffer-file-name)))
1782 (cond ((null file-name)
1783 (error "Buffer does not seem to be associated with any file"))
1784 ((or noconfirm
1785 (yes-or-no-p (format "Revert buffer from file %s? "
1786 file-name)))
4fbf62ee 1787 (run-hooks 'before-revert-hook)
b4da00e9
RM
1788 ;; If file was backed up but has changed since,
1789 ;; we shd make another backup.
1790 (and (not auto-save-p)
5bbbceb1 1791 (not (verify-visited-file-modtime (current-buffer)))
b4da00e9
RM
1792 (setq buffer-backed-up nil))
1793 ;; Get rid of all undo records for this buffer.
1794 (or (eq buffer-undo-list t)
1795 (setq buffer-undo-list nil))
1796 (let ((buffer-read-only nil)
1797 ;; Don't make undo records for the reversion.
1798 (buffer-undo-list t))
1799 (if revert-buffer-insert-file-contents-function
1800 (funcall revert-buffer-insert-file-contents-function
1801 file-name auto-save-p)
1802 (if (not (file-exists-p file-name))
1803 (error "File %s no longer exists!" file-name))
1804 ;; Bind buffer-file-name to nil
1805 ;; so that we don't try to lock the file.
1806 (let ((buffer-file-name nil))
1807 (or auto-save-p
f9456b0a
RS
1808 (unlock-buffer)))
1809 (insert-file-contents file-name (not auto-save-p)
1810 nil nil t)))
b4da00e9 1811 (goto-char (min opoint (point-max)))
8cfb9d46 1812 (after-find-file nil nil t)
4fbf62ee
KH
1813 (run-hooks 'after-revert-hook)
1814 t)))))
b4da00e9
RM
1815
1816(defun recover-file (file)
1817 "Visit file FILE, but get contents from its last auto-save file."
1818 (interactive
1819 (let ((prompt-file buffer-file-name)
1820 (file-name nil)
1821 (file-dir nil))
1822 (and prompt-file
1823 (setq file-name (file-name-nondirectory prompt-file)
1824 file-dir (file-name-directory prompt-file)))
1825 (list (read-file-name "Recover file: "
1826 file-dir nil nil file-name))))
1827 (setq file (expand-file-name file))
f7da6740
RS
1828 (if (auto-save-file-name-p (file-name-nondirectory file))
1829 (error "%s is an auto-save file" file))
b4da00e9
RM
1830 (let ((file-name (let ((buffer-file-name file))
1831 (make-auto-save-file-name))))
1832 (cond ((not (file-newer-than-file-p file-name file))
1833 (error "Auto-save file %s not current" file-name))
1834 ((save-window-excursion
1835 (if (not (eq system-type 'vax-vms))
1836 (with-output-to-temp-buffer "*Directory*"
1837 (buffer-disable-undo standard-output)
1838 (call-process "ls" nil standard-output nil
2dc2b736
RS
1839 (if (file-symlink-p file) "-lL" "-l")
1840 file file-name)))
b4da00e9
RM
1841 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
1842 (switch-to-buffer (find-file-noselect file t))
1843 (let ((buffer-read-only nil))
1844 (erase-buffer)
1845 (insert-file-contents file-name nil))
8cfb9d46 1846 (after-find-file nil nil t))
b4da00e9
RM
1847 (t (error "Recover-file cancelled.")))))
1848
1849(defun kill-some-buffers ()
1850 "For each buffer, ask whether to kill it."
1851 (interactive)
1852 (let ((list (buffer-list)))
1853 (while list
1854 (let* ((buffer (car list))
1855 (name (buffer-name buffer)))
1856 (and (not (string-equal name ""))
1857 (/= (aref name 0) ? )
1858 (yes-or-no-p
1859 (format "Buffer %s %s. Kill? "
1860 name
1861 (if (buffer-modified-p buffer)
1862 "HAS BEEN EDITED" "is unmodified")))
1863 (kill-buffer buffer)))
1864 (setq list (cdr list)))))
1865\f
1866(defun auto-save-mode (arg)
1867 "Toggle auto-saving of contents of current buffer.
f3e23606 1868With prefix argument ARG, turn auto-saving on if positive, else off."
b4da00e9
RM
1869 (interactive "P")
1870 (setq buffer-auto-save-file-name
1871 (and (if (null arg)
1872 (not buffer-auto-save-file-name)
1873 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
1874 (if (and buffer-file-name auto-save-visited-file-name
1875 (not buffer-read-only))
1876 buffer-file-name
1877 (make-auto-save-file-name))))
1878 (if (interactive-p)
1879 (message "Auto-save %s (in this buffer)"
1880 (if buffer-auto-save-file-name "on" "off")))
1881 buffer-auto-save-file-name)
1882
1883(defun rename-auto-save-file ()
1884 "Adjust current buffer's auto save file name for current conditions.
1885Also rename any existing auto save file, if it was made in this session."
1886 (let ((osave buffer-auto-save-file-name))
1887 (setq buffer-auto-save-file-name
1888 (make-auto-save-file-name))
1889 (if (and osave buffer-auto-save-file-name
1890 (not (string= buffer-auto-save-file-name buffer-file-name))
1891 (not (string= buffer-auto-save-file-name osave))
1892 (file-exists-p osave)
1893 (recent-auto-save-p))
1894 (rename-file osave buffer-auto-save-file-name t))))
1895
1896(defun make-auto-save-file-name ()
1897 "Return file name to use for auto-saves of current buffer.
1898Does not consider `auto-save-visited-file-name' as that variable is checked
1899before calling this function. You can redefine this for customization.
1900See also `auto-save-file-name-p'."
1901 (if buffer-file-name
1902 (concat (file-name-directory buffer-file-name)
1903 "#"
1904 (file-name-nondirectory buffer-file-name)
1905 "#")
1906 ;; For non-file bfr, use bfr name and Emacs pid.
1907 (expand-file-name (format "#%s#%s#" (buffer-name) (make-temp-name "")))))
1908
1909(defun auto-save-file-name-p (filename)
1910 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
1911FILENAME should lack slashes. You can redefine this for customization."
1912 (string-match "^#.*#$" filename))
1913\f
1914(defconst list-directory-brief-switches
1915 (if (eq system-type 'vax-vms) "" "-CF")
1916 "*Switches for list-directory to pass to `ls' for brief listing,")
1917
1918(defconst list-directory-verbose-switches
1919 (if (eq system-type 'vax-vms)
1920 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
1921 "-l")
1922 "*Switches for list-directory to pass to `ls' for verbose listing,")
1923
1924(defun list-directory (dirname &optional verbose)
1925 "Display a list of files in or matching DIRNAME, a la `ls'.
1926DIRNAME is globbed by the shell if necessary.
1927Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
1928Actions controlled by variables `list-directory-brief-switches'
1929and `list-directory-verbose-switches'."
1930 (interactive (let ((pfx current-prefix-arg))
1931 (list (read-file-name (if pfx "List directory (verbose): "
1932 "List directory (brief): ")
1933 nil default-directory nil)
1934 pfx)))
1935 (let ((switches (if verbose list-directory-verbose-switches
1936 list-directory-brief-switches)))
1937 (or dirname (setq dirname default-directory))
1938 (setq dirname (expand-file-name dirname))
1939 (with-output-to-temp-buffer "*Directory*"
1940 (buffer-disable-undo standard-output)
1941 (princ "Directory ")
1942 (princ dirname)
1943 (terpri)
c3554e95
RS
1944 (save-excursion
1945 (set-buffer "*Directory*")
1946 (let ((wildcard (not (file-directory-p dirname))))
1947 (insert-directory dirname switches wildcard (not wildcard)))))))
1948
1949(defvar insert-directory-program "ls"
1950 "Absolute or relative name of the `ls' program used by `insert-directory'.")
1951
1952;; insert-directory
1953;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
1954;; FULL-DIRECTORY-P is nil.
1955;; The single line of output must display FILE's name as it was
1956;; given, namely, an absolute path name.
1957;; - must insert exactly one line for each file if WILDCARD or
1958;; FULL-DIRECTORY-P is t, plus one optional "total" line
1959;; before the file lines, plus optional text after the file lines.
1960;; Lines are delimited by "\n", so filenames containing "\n" are not
1961;; allowed.
1962;; File lines should display the basename.
1963;; - must be consistent with
1964;; - functions dired-move-to-filename, (these two define what a file line is)
1965;; dired-move-to-end-of-filename,
1966;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
1967;; dired-insert-headerline
1968;; dired-after-subdir-garbage (defines what a "total" line is)
1969;; - variable dired-subdir-regexp
1970(defun insert-directory (file switches &optional wildcard full-directory-p)
a18b7c81 1971 "Insert directory listing for FILE, formatted according to SWITCHES.
c3554e95
RS
1972Leaves point after the inserted text.
1973Optional third arg WILDCARD means treat FILE as shell wildcard.
1974Optional fourth arg FULL-DIRECTORY-P means file is a directory and
1975switches do not contain `d', so that a full listing is expected.
1976
1977This works by running a directory listing program
406e12d9 1978whose name is in the variable `insert-directory-program'.
c3554e95 1979If WILDCARD, it also runs the shell specified by `shell-file-name'."
5dbfdacd 1980 (let ((handler (find-file-name-handler file)))
c3554e95
RS
1981 (if handler
1982 (funcall handler 'insert-directory file switches
1983 wildcard full-directory-p)
b4da00e9 1984 (if (eq system-type 'vax-vms)
c3554e95
RS
1985 (vms-read-directory file switches (current-buffer))
1986 (if wildcard
a9fa0bd5
RS
1987 ;; Run ls in the directory of the file pattern we asked for.
1988 (let ((default-directory
1989 (if (file-name-absolute-p file)
1990 (file-name-directory file)
1991 (file-name-directory (expand-file-name file)))))
c3554e95
RS
1992 (call-process shell-file-name nil t nil
1993 "-c" (concat insert-directory-program
1994 " -d " switches " "
1995 (file-name-nondirectory file))))
a18b7c81
JB
1996 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
1997 ;; directory if FILE is a symbolic link.
1998 (call-process insert-directory-program nil t nil switches
1999 (if full-directory-p
2000 (concat (file-name-as-directory file) ".")
2001 file)))))))
b4da00e9 2002
88902b35
RS
2003(defvar kill-emacs-query-functions nil
2004 "Functions to call with no arguments to query about killing Emacs.")
2005
b4da00e9
RM
2006(defun save-buffers-kill-emacs (&optional arg)
2007 "Offer to save each buffer, then kill this Emacs process.
2008With prefix arg, silently save all file-visiting buffers, then kill."
2009 (interactive "P")
2010 (save-some-buffers arg t)
2011 (and (or (not (memq t (mapcar (function
2012 (lambda (buf) (and (buffer-file-name buf)
2013 (buffer-modified-p buf))))
2014 (buffer-list))))
2015 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2016 (or (not (fboundp 'process-list))
2017 ;; process-list is not defined on VMS.
2018 (let ((processes (process-list))
2019 active)
2020 (while processes
528415e7 2021 (and (memq (process-status (car processes)) '(run stop open))
b4da00e9
RM
2022 (let ((val (process-kill-without-query (car processes))))
2023 (process-kill-without-query (car processes) val)
2024 val)
2025 (setq active t))
2026 (setq processes (cdr processes)))
2027 (or (not active)
2028 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
88902b35
RS
2029 ;; Query the user for other things, perhaps.
2030 (let ((functions kill-emacs-query-functions)
2031 (yes t))
2032 (while (and functions yes)
2033 (setq yes (and yes (funcall (car functions))))
2034 (setq functions (cdr functions)))
2035 yes)
b4da00e9
RM
2036 (kill-emacs)))
2037\f
2038(define-key ctl-x-map "\C-f" 'find-file)
2039(define-key ctl-x-map "\C-q" 'toggle-read-only)
2040(define-key ctl-x-map "\C-r" 'find-file-read-only)
2041(define-key ctl-x-map "\C-v" 'find-alternate-file)
2042(define-key ctl-x-map "\C-s" 'save-buffer)
2043(define-key ctl-x-map "s" 'save-some-buffers)
2044(define-key ctl-x-map "\C-w" 'write-file)
2045(define-key ctl-x-map "i" 'insert-file)
2046(define-key esc-map "~" 'not-modified)
2047(define-key ctl-x-map "\C-d" 'list-directory)
2048(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
2049
2050(define-key ctl-x-4-map "f" 'find-file-other-window)
2051(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
2052(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
2053(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
924f0a24 2054(define-key ctl-x-4-map "\C-o" 'display-buffer)
5bbbceb1 2055
f98955ea
JB
2056(define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
2057(define-key ctl-x-5-map "f" 'find-file-other-frame)
2058(define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
2059(define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
c0274f38
ER
2060
2061;;; files.el ends here