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