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