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