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