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