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