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