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