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