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