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