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