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