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