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