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