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