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