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