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