1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 93,
4 ;; 94, 95, 96, 97, 98, 1999 Free Software Foundation, Inc.
8 ;; This file is part of GNU Emacs.
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)
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.
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.
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.
34 "Backups of edited data files."
37 (defgroup find-file nil
42 (defcustom delete-auto-save-files t
43 "*Non-nil means delete auto-save file when a buffer is saved or killed.
45 Note that auto-save file will not be deleted if the buffer is killed
46 when it has unsaved changes."
50 (defcustom directory-abbrev-alist
52 "*Alist of abbreviations for file directories.
53 A list of elements of the form (FROM . TO), each meaning to replace
54 FROM with TO when it appears in a directory name. This replacement is
55 done when setting up the default directory of a newly visited file.
56 *Every* FROM string should start with `^'.
58 Do not use `~' in the TO strings.
59 They should be ordinary absolute directory names.
61 Use this feature when you have directories which you normally refer to
62 via absolute symbolic links. Make TO the name of the link, and FROM
63 the name it is linked to."
64 :type
'(repeat (cons :format
"%v"
71 ;;; Turn off backup files on VMS since it has version numbers.
72 (defcustom make-backup-files
(not (eq system-type
'vax-vms
))
73 "*Non-nil means make a backup of a file the first time it is saved.
74 This can be done by renaming the file or by copying.
76 Renaming means that Emacs renames the existing file so that it is a
77 backup file, then writes the buffer into a new file. Any other names
78 that the old file had will now refer to the backup file. The new file
79 is owned by you and its group is defaulted.
81 Copying means that Emacs copies the existing file into the backup
82 file, then writes the buffer on top of the existing file. Any other
83 names that the old file had will now refer to the new (edited) file.
84 The file's owner and group are unchanged.
86 The choice of renaming or copying is controlled by the variables
87 `backup-by-copying', `backup-by-copying-when-linked',
88 `backup-by-copying-when-mismatch' and
89 `backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
93 ;; Do this so that local variables based on the file name
94 ;; are not overridden by the major mode.
95 (defvar backup-inhibited nil
96 "Non-nil means don't make a backup, regardless of the other parameters.
97 This variable is intended for use by making it local to a buffer.
98 But it is local only if you make it local.")
99 (put 'backup-inhibited
'permanent-local t
)
101 (defcustom backup-by-copying nil
102 "*Non-nil means always use copying to create backup files.
103 See documentation of variable `make-backup-files'."
107 (defcustom backup-by-copying-when-linked nil
108 "*Non-nil means use copying to create backups for files with multiple names.
109 This causes the alternate names to refer to the latest version as edited.
110 This variable is relevant only if `backup-by-copying' is nil."
114 (defcustom backup-by-copying-when-mismatch nil
115 "*Non-nil means create backups by copying if this preserves owner or group.
116 Renaming may still be used (subject to control of other variables)
117 when it would not result in changing the owner or group of the file;
118 that is, for files which are owned by you and whose group matches
119 the default for a new file created there by you.
120 This variable is relevant only if `backup-by-copying' is nil."
124 (defcustom backup-by-copying-when-privileged-mismatch
200
125 "*Non-nil means create backups by copying to preserve a privileged owner.
126 Renaming may still be used (subject to control of other variables)
127 when it would not result in changing the owner of the file or if the owner
128 has a user id greater than the value of this variable. This is useful
129 when low-numbered uid's are used for special system users (such as root)
130 that must maintain ownership of certain files.
131 This variable is relevant only if `backup-by-copying' and
132 `backup-by-copying-when-mismatch' are nil."
133 :type
'(choice (const nil
) integer
)
136 (defvar backup-enable-predicate
138 (or (< (length name
) 5)
139 (not (string-equal "/tmp/" (substring name
0 5)))))
140 "Predicate that looks at a file name and decides whether to make backups.
141 Called with an absolute file name as argument, it returns t to enable backup.")
143 (defcustom buffer-offer-save nil
144 "*Non-nil in a buffer means offer to save the buffer on exit
145 even if the buffer is not visiting a file.
146 Automatically local in all buffers."
149 (make-variable-buffer-local 'buffer-offer-save
)
151 (defcustom find-file-existing-other-name t
152 "*Non-nil means find a file under alternative names, in existing buffers.
153 This means if any existing buffer is visiting the file you want
154 under another name, you get the existing buffer instead of a new buffer."
158 (defcustom find-file-visit-truename nil
159 "*Non-nil means visit a file under its truename.
160 The truename of a file is found by chasing all links
161 both at the file level and at the levels of the containing directories."
165 (defcustom revert-without-query
167 "*Specify which files should be reverted without query.
168 The value is a list of regular expressions.
169 If the file name matches one of these regular expressions,
170 then `revert-buffer' reverts the file without querying
171 if the file has changed on disk and you have not edited the buffer."
172 :type
'(repeat regexp
)
175 (defvar buffer-file-number nil
176 "The device number and file number of the file visited in the current buffer.
177 The value is a list of the form (FILENUM DEVNUM).
178 This pair of numbers uniquely identifies the file.
179 If the buffer is visiting a new file, the value is nil.")
180 (make-variable-buffer-local 'buffer-file-number
)
181 (put 'buffer-file-number
'permanent-local t
)
183 (defvar buffer-file-numbers-unique
(not (memq system-type
'(windows-nt)))
184 "Non-nil means that buffer-file-number uniquely identifies files.")
186 (defvar file-name-invalid-regexp
187 (cond ((and (eq system-type
'ms-dos
) (not (msdos-long-file-names)))
188 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
189 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
190 "[\000-\031]\\|" ; control characters
191 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
192 "\\(/[^/.]+\\.[^/.]*\\.\\)")) ; more than a single dot
193 ((memq system-type
'(ms-dos windows-nt
))
194 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
195 "[|<>\"?*\000-\031]")) ; invalid characters
197 "Regexp recognizing file names which aren't allowed by the filesystem.")
199 (defcustom file-precious-flag nil
200 "*Non-nil means protect against I/O errors while saving files.
201 Some modes set this non-nil in particular buffers.
203 This feature works by writing the new contents into a temporary file
204 and then renaming the temporary file to replace the original.
205 In this way, any I/O error in writing leaves the original untouched,
206 and there is never any instant where the file is nonexistent.
208 Note that this feature forces backups to be made by copying.
209 Yet, at the same time, saving a precious file
210 breaks any hard links between it and other files."
214 (defcustom version-control nil
215 "*Control use of version numbers for backup files.
216 t means make numeric backup versions unconditionally.
217 nil means make them for files that have some already.
218 `never' means do not make them."
219 :type
'(choice (const :tag
"Never" never
)
220 (const :tag
"If existing" nil
)
221 (other :tag
"Always" t
))
225 (defcustom dired-kept-versions
2
226 "*When cleaning directory, number of versions to keep."
231 (defcustom delete-old-versions nil
232 "*If t, delete excess backup versions silently.
233 If nil, ask confirmation. Any other value prevents any trimming."
234 :type
'(choice (const :tag
"Delete" t
)
235 (const :tag
"Ask" nil
)
236 (other :tag
"Leave" other
))
239 (defcustom kept-old-versions
2
240 "*Number of oldest versions to keep when a new numbered backup is made."
244 (defcustom kept-new-versions
2
245 "*Number of newest versions to keep when a new numbered backup is made.
246 Includes the new backup. Must be > 0"
250 (defcustom require-final-newline nil
251 "*Value of t says silently ensure a file ends in a newline when it is saved.
252 Non-nil but not t says ask user whether to add a newline when there isn't one.
253 nil means don't add newlines."
254 :type
'(choice (const :tag
"Off" nil
)
256 (other :tag
"Ask" ask
))
257 :group
'editing-basics
)
259 (defcustom auto-save-default t
260 "*Non-nil says by default do auto-saving of every file-visiting buffer."
264 (defcustom auto-save-visited-file-name nil
265 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
266 Normally auto-save files are written under other names."
270 (defcustom save-abbrevs nil
271 "*Non-nil means save word abbrevs too when files are saved.
272 Loading an abbrev file sets this to t."
276 (defcustom find-file-run-dired t
277 "*Non-nil means allow `find-file' to visit directories.
278 To visit the directory, `find-file' runs `find-directory-functions'."
282 (defcustom find-directory-functions
'(cvs-dired-noselect dired-noselect
)
283 "*List of functions to try in sequence to visit a directory.
284 Each function is called with the directory name as the sole argument
285 and should return either a buffer or nil."
286 :type
'(hook :options
(cvs-dired-noselect dired-noselect
))
289 ;;;It is not useful to make this a local variable.
290 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
291 (defvar find-file-not-found-hooks nil
292 "List of functions to be called for `find-file' on nonexistent file.
293 These functions are called as soon as the error is detected.
294 `buffer-file-name' is already set up.
295 The functions are called in the order given until one of them returns non-nil.")
297 ;;;It is not useful to make this a local variable.
298 ;;;(put 'find-file-hooks 'permanent-local t)
299 (defvar find-file-hooks nil
300 "List of functions to be called after a buffer is loaded from a file.
301 The buffer's local variables (if any) will have been processed before the
302 functions are called.")
304 (defvar write-file-hooks nil
305 "List of functions to be called before writing out a buffer to a file.
306 If one of them returns non-nil, the file is considered already written
307 and the rest are not called.
308 These hooks are considered to pertain to the visited file.
309 So any buffer-local binding of `write-file-hooks' is
310 discarded if you change the visited file name with \\[set-visited-file-name].
312 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
313 See also `write-contents-hooks'.")
314 ;;; However, in case someone does make it local...
315 (put 'write-file-hooks
'permanent-local t
)
317 (defvar local-write-file-hooks nil
318 "Just like `write-file-hooks', except intended for per-buffer use.
319 The functions in this list are called before the ones in
322 This variable is meant to be used for hooks that have to do with a
323 particular visited file. Therefore, it is a permanent local, so that
324 changing the major mode does not clear it. However, calling
325 `set-visited-file-name' does clear it.")
326 (make-variable-buffer-local 'local-write-file-hooks
)
327 (put 'local-write-file-hooks
'permanent-local t
)
329 (defvar write-contents-hooks nil
330 "List of functions to be called before writing out a buffer to a file.
331 If one of them returns non-nil, the file is considered already written
332 and the rest are not called.
334 This variable is meant to be used for hooks that pertain to the
335 buffer's contents, not to the particular visited file; thus,
336 `set-visited-file-name' does not clear this variable; but changing the
337 major mode does clear it.
339 This variable automatically becomes buffer-local whenever it is set.
340 If you use `add-hook' to add elements to the list, use nil for the
343 See also `write-file-hooks'.")
344 (make-variable-buffer-local 'write-contents-hooks
)
346 (defcustom enable-local-variables t
347 "*Control use of local variables in files you visit.
348 The value can be t, nil or something else.
349 A value of t means file local variables specifications are obeyed;
350 nil means they are ignored; anything else means query.
351 This variable also controls use of major modes specified in
354 The command \\[normal-mode], when used interactively,
355 always obeys file local variable specifications and the -*- line,
356 and ignores this variable."
357 :type
'(choice (const :tag
"Obey" t
)
358 (const :tag
"Ignore" nil
)
359 (other :tag
"Query" other
))
362 (defvar local-enable-local-variables t
363 "Like `enable-local-variables' but meant for buffer-local bindings.
364 The meaningful values are nil and non-nil. The default is non-nil.
365 If a major mode sets this to nil, buffer-locally, then any local
366 variables list in the file will be ignored.
368 This variable does not affect the use of major modes
369 specified in a -*- line.")
371 (defcustom enable-local-eval
'maybe
372 "*Control processing of the \"variable\" `eval' in a file's local variables.
373 The value can be t, nil or something else.
374 A value of t means obey `eval' variables;
375 nil means ignore them; anything else means query.
377 The command \\[normal-mode] always obeys local-variables lists
378 and ignores this variable."
379 :type
'(choice (const :tag
"Obey" t
)
380 (const :tag
"Ignore" nil
)
381 (other :tag
"Query" other
))
384 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
385 (or (fboundp 'lock-buffer
)
386 (defalias 'lock-buffer
'ignore
))
387 (or (fboundp 'unlock-buffer
)
388 (defalias 'unlock-buffer
'ignore
))
389 (or (fboundp 'file-locked-p
)
390 (defalias 'file-locked-p
'ignore
))
392 (defvar view-read-only nil
393 "*Non-nil means buffers visiting files read-only, do it in view mode.")
395 (defvar temporary-file-directory
396 (file-name-as-directory
397 (cond ((memq system-type
'(ms-dos windows-nt
))
398 (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
399 ((memq system-type
'(vax-vms axp-vms
))
400 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
402 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
403 "The directory for writing temporary files.")
405 (defvar small-temporary-file-directory
406 (if (eq system-type
'ms-dos
) (getenv "TMPDIR"))
407 "The directory for writing small temporary files.
408 If non-nil, this directory is used instead of `temporary-file-directory'
409 by programs that create small temporary files. This is for systems that
410 have fast storage with limited space, such as a RAM disk.")
412 ;; The system null device. (Should reference NULL_DEVICE from C.)
413 (defvar null-device
"/dev/null" "The system null device.")
415 ;; This hook function provides support for ange-ftp host name
416 ;; completion. It runs the usual ange-ftp hook, but only for
417 ;; completion operations. Having this here avoids the need
418 ;; to load ange-ftp when it's not really in use.
419 (defun ange-ftp-completion-hook-function (op &rest args
)
420 (if (memq op
'(file-name-completion file-name-all-completions
))
421 (apply 'ange-ftp-hook-function op args
)
422 (let ((inhibit-file-name-handlers
423 (cons 'ange-ftp-completion-hook-function
424 (and (eq inhibit-file-name-operation op
)
425 inhibit-file-name-handlers
)))
426 (inhibit-file-name-operation op
))
429 (defun convert-standard-filename (filename)
430 "Convert a standard file's name to something suitable for the current OS.
431 This function's standard definition is trivial; it just returns the argument.
432 However, on some systems, the function is redefined
433 with a definition that really does change some file names."
437 "Show the current default directory."
439 (message "Directory %s" default-directory
))
442 "Value of the CDPATH environment variable, as a list.
443 Not actually set up until the first time you you use it.")
445 (defun parse-colon-path (cd-path)
446 "Explode a colon-separated search path into a list of directory names."
448 (let (cd-prefix cd-list
(cd-start 0) cd-colon
)
449 (setq cd-path
(concat cd-path path-separator
))
450 (while (setq cd-colon
(string-match path-separator cd-path cd-start
))
453 (list (if (= cd-start cd-colon
)
455 (substitute-in-file-name
456 (file-name-as-directory
457 (substring cd-path cd-start cd-colon
)))))))
458 (setq cd-start
(+ cd-colon
1)))
461 (defun cd-absolute (dir)
462 "Change current directory to given absolute file name DIR."
463 ;; Put the name into directory syntax now,
464 ;; because otherwise expand-file-name may give some bad results.
465 (if (not (eq system-type
'vax-vms
))
466 (setq dir
(file-name-as-directory dir
)))
467 (setq dir
(abbreviate-file-name (expand-file-name dir
)))
468 (if (not (file-directory-p dir
))
469 (if (file-exists-p dir
)
470 (error "%s is not a directory" dir
)
471 (error "%s: no such directory" dir
))
472 (if (file-executable-p dir
)
473 (setq default-directory dir
)
474 (error "Cannot cd to %s: Permission denied" dir
))))
477 "Make DIR become the current buffer's default directory.
478 If your environment includes a `CDPATH' variable, try each one of that
479 colon-separated list of directories when resolving a relative directory name."
481 (list (read-file-name "Change default directory: "
482 default-directory default-directory
483 (and (member cd-path
'(nil ("./")))
484 (null (getenv "CDPATH"))))))
485 (if (file-name-absolute-p dir
)
486 (cd-absolute (expand-file-name dir
))
488 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
489 (setq cd-path
(or trypath
(list "./")))))
490 (if (not (catch 'found
492 (function (lambda (x)
493 (let ((f (expand-file-name (concat x dir
))))
494 (if (file-directory-p f
)
497 (throw 'found t
))))))
500 (error "No such directory found via CDPATH environment variable"))))
502 (defun load-file (file)
503 "Load the Lisp file named FILE."
504 (interactive "fLoad file: ")
505 (let ((completion-ignored-extensions
506 (delete ".elc" completion-ignored-extensions
)))
507 (load (expand-file-name file
) nil nil t
)))
509 (defun load-library (library)
510 "Load the library named LIBRARY.
511 This is an interface to the function `load'."
512 (interactive "sLoad library: ")
515 (defun file-local-copy (file)
516 "Copy the file FILE into a temporary file on this machine.
517 Returns the name of the local copy, or nil, if FILE is directly
519 ;; This formerly had an optional BUFFER argument that wasn't used by
521 (let ((handler (find-file-name-handler file
'file-local-copy
)))
523 (funcall handler
'file-local-copy file
)
526 (defun file-truename (filename &optional counter prev-dirs
)
527 "Return the truename of FILENAME, which should be absolute.
528 The truename of a file name is found by chasing symbolic links
529 both at the level of the file and at the level of the directories
530 containing it, until no links are left at any level.
532 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
533 Do not specify them in other calls."
534 ;; COUNTER can be a cons cell whose car is the count of how many more links
535 ;; to chase before getting an error.
536 ;; PREV-DIRS can be a cons cell whose car is an alist
537 ;; of truenames we've just recently computed.
539 ;; The last test looks dubious, maybe `+' is meant here? --simon.
540 (if (or (string= filename
"") (string= filename
"~")
541 (and (string= (substring filename
0 1) "~")
542 (string-match "~[^/]*" filename
)))
544 (setq filename
(expand-file-name filename
))
545 (if (string= filename
"")
546 (setq filename
"/"))))
547 (or counter
(setq counter
(list 100)))
549 ;; For speed, remove the ange-ftp completion handler from the list.
550 ;; We know it's not needed here.
551 ;; For even more speed, do this only on the outermost call.
552 (file-name-handler-alist
553 (if prev-dirs file-name-handler-alist
554 (let ((tem (copy-sequence file-name-handler-alist
)))
555 (delq (rassq 'ange-ftp-completion-hook-function tem
) tem
)))))
556 (or prev-dirs
(setq prev-dirs
(list nil
)))
558 ;; andrewi@harlequin.co.uk - none of the following code (except for
559 ;; invoking the file-name handler) currently applies on Windows
560 ;; (ie. there are no native symlinks), but there is an issue with
561 ;; case differences being ignored by the OS, and short "8.3 DOS"
562 ;; name aliases existing for all files. (The short names are not
563 ;; reported by directory-files, but can be used to refer to files.)
564 ;; It seems appropriate for file-truename to resolve these issues in
565 ;; the most natural way, which on Windows is to call the function
566 ;; `w32-long-file-name' - this returns the exact name of a file as
567 ;; it is stored on disk (expanding short name aliases with the full
568 ;; name in the process).
569 (if (eq system-type
'windows-nt
)
570 (let ((handler (find-file-name-handler filename
'file-truename
))
572 ;; For file name that has a special handler, call handler.
573 ;; This is so that ange-ftp can save time by doing a no-op.
575 (setq filename
(funcall handler
'file-truename filename
))
576 ;; If filename contains a wildcard, newname will be the old name.
577 (if (string-match "[*?]" filename
)
578 (setq newname filename
)
579 ;; If filename doesn't exist, newname will be nil.
580 (setq newname
(w32-long-file-name filename
)))
581 (setq filename
(or newname filename
)))
584 ;; If this file directly leads to a link, process that iteratively
585 ;; so that we don't use lots of stack.
587 (setcar counter
(1- (car counter
)))
588 (if (< (car counter
) 0)
589 (error "Apparent cycle of symbolic links for %s" filename
))
590 (let ((handler (find-file-name-handler filename
'file-truename
)))
591 ;; For file name that has a special handler, call handler.
592 ;; This is so that ange-ftp can save time by doing a no-op.
594 (setq filename
(funcall handler
'file-truename filename
)
596 (let ((dir (or (file-name-directory filename
) default-directory
))
598 ;; Get the truename of the directory.
599 (setq dirfile
(directory-file-name dir
))
600 ;; If these are equal, we have the (or a) root directory.
601 (or (string= dir dirfile
)
602 ;; If this is the same dir we last got the truename for,
603 ;; save time--don't recalculate.
604 (if (assoc dir
(car prev-dirs
))
605 (setq dir
(cdr (assoc dir
(car prev-dirs
))))
607 (new (file-name-as-directory (file-truename dirfile counter prev-dirs
))))
608 (setcar prev-dirs
(cons (cons old new
) (car prev-dirs
)))
610 (if (equal ".." (file-name-nondirectory filename
))
612 (directory-file-name (file-name-directory (directory-file-name dir
)))
614 (if (equal "." (file-name-nondirectory filename
))
615 (setq filename
(directory-file-name dir
)
617 ;; Put it back on the file name.
618 (setq filename
(concat dir
(file-name-nondirectory filename
)))
619 ;; Is the file name the name of a link?
620 (setq target
(file-symlink-p filename
))
622 ;; Yes => chase that link, then start all over
623 ;; since the link may point to a directory name that uses links.
624 ;; We can't safely use expand-file-name here
625 ;; since target might look like foo/../bar where foo
626 ;; is itself a link. Instead, we handle . and .. above.
628 (if (file-name-absolute-p target
)
636 (defun file-chase-links (filename)
637 "Chase links in FILENAME until a name that is not a link.
638 Does not examine containing directories for links,
639 unlike `file-truename'."
640 (let (tem (count 100) (newname filename
))
641 (while (setq tem
(file-symlink-p newname
))
644 (error "Apparent cycle of symbolic links for %s" filename
))
645 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
646 (while (string-match "//+" tem
)
647 (setq tem
(replace-match "/" nil nil tem
)))
648 ;; Handle `..' by hand, since it needs to work in the
649 ;; target of any directory symlink.
650 ;; This code is not quite complete; it does not handle
651 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
652 (while (string-match "\\`\\.\\./" tem
)
653 (setq tem
(substring tem
3))
654 (setq newname
(expand-file-name newname
))
655 ;; Chase links in the default dir of the symlink.
658 (directory-file-name (file-name-directory newname
))))
659 ;; Now find the parent of that dir.
660 (setq newname
(file-name-directory newname
)))
661 (setq newname
(expand-file-name tem
(file-name-directory newname
)))
662 (setq count
(1- count
))))
665 (defun switch-to-buffer-other-window (buffer &optional norecord
)
666 "Select buffer BUFFER in another window.
667 Optional second arg NORECORD non-nil means
668 do not put this buffer at the front of the list of recently selected ones."
669 (interactive "BSwitch to buffer in other window: ")
670 (let ((pop-up-windows t
))
671 (pop-to-buffer buffer t norecord
)))
673 (defun switch-to-buffer-other-frame (buffer &optional norecord
)
674 "Switch to buffer BUFFER in another frame.
675 Optional second arg NORECORD non-nil means
676 do not put this buffer at the front of the list of recently selected ones."
677 (interactive "BSwitch to buffer in other frame: ")
678 (let ((pop-up-frames t
))
679 (pop-to-buffer buffer t norecord
)
680 (raise-frame (window-frame (selected-window)))))
682 (defun find-file (filename &optional wildcards
)
684 Switch to a buffer visiting file FILENAME,
685 creating one if none already exists.
686 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
687 expand wildcards (if any) and visit multiple files. Wildcard expansion
688 can be suppressed by setting `find-file-wildcards'."
689 (interactive "FFind file: \np")
690 (let ((value (find-file-noselect filename nil nil wildcards
)))
692 (mapcar 'switch-to-buffer
(nreverse value
))
693 (switch-to-buffer value
))))
695 (defun find-file-other-window (filename &optional wildcards
)
696 "Edit file FILENAME, in another window.
697 May create a new window, or reuse an existing one.
698 See the function `display-buffer'.
699 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
700 expand wildcards (if any) and visit multiple files."
701 (interactive "FFind file in other window: \np")
702 (let ((value (find-file-noselect filename nil nil wildcards
)))
705 (setq value
(nreverse value
))
706 (switch-to-buffer-other-window (car value
))
707 (mapcar 'switch-to-buffer
(cdr value
)))
708 (switch-to-buffer-other-window value
))))
710 (defun find-file-other-frame (filename &optional wildcards
)
711 "Edit file FILENAME, in another frame.
712 May create a new frame, or reuse an existing one.
713 See the function `display-buffer'.
714 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
715 expand wildcards (if any) and visit multiple files."
716 (interactive "FFind file in other frame: \np")
717 (let ((value (find-file-noselect filename nil nil wildcards
)))
720 (setq value
(nreverse value
))
721 (switch-to-buffer-other-frame (car value
))
722 (mapcar 'switch-to-buffer
(cdr value
)))
723 (switch-to-buffer-other-frame value
))))
725 (defun find-file-read-only (filename &optional wildcards
)
726 "Edit file FILENAME but don't allow changes.
727 Like \\[find-file] but marks buffer as read-only.
728 Use \\[toggle-read-only] to permit editing."
729 (interactive "fFind file read-only: \np")
730 (find-file filename wildcards
)
734 (defun find-file-read-only-other-window (filename &optional wildcards
)
735 "Edit file FILENAME in another window but don't allow changes.
736 Like \\[find-file-other-window] but marks buffer as read-only.
737 Use \\[toggle-read-only] to permit editing."
738 (interactive "fFind file read-only other window: \np")
739 (find-file-other-window filename wildcards
)
743 (defun find-file-read-only-other-frame (filename &optional wildcards
)
744 "Edit file FILENAME in another frame but don't allow changes.
745 Like \\[find-file-other-frame] but marks buffer as read-only.
746 Use \\[toggle-read-only] to permit editing."
747 (interactive "fFind file read-only other frame: \np")
748 (find-file-other-frame filename wildcards
)
752 (defun find-alternate-file-other-window (filename)
753 "Find file FILENAME as a replacement for the file in the next window.
754 This command does not select that window."
756 (save-selected-window
758 (let ((file buffer-file-name
)
762 (setq file-name
(file-name-nondirectory file
)
763 file-dir
(file-name-directory file
)))
764 (list (read-file-name
765 "Find alternate file: " file-dir nil nil file-name
)))))
767 (find-file-other-window filename
)
768 (save-selected-window
770 (find-alternate-file filename
))))
772 (defun find-alternate-file (filename)
773 "Find file FILENAME, select its buffer, kill previous buffer.
774 If the current buffer now contains an empty file that you just visited
775 \(presumably by mistake), use this command to visit the file you really want."
777 (let ((file buffer-file-name
)
781 (setq file-name
(file-name-nondirectory file
)
782 file-dir
(file-name-directory file
)))
783 (list (read-file-name
784 "Find alternate file: " file-dir nil nil file-name
))))
785 (and (buffer-modified-p) (buffer-file-name)
786 ;; (not buffer-read-only)
787 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
790 (let ((obuf (current-buffer))
791 (ofile buffer-file-name
)
792 (onum buffer-file-number
)
793 (otrue buffer-file-truename
)
794 (oname (buffer-name)))
795 (if (get-buffer " **lose**")
796 (kill-buffer " **lose**"))
797 (rename-buffer " **lose**")
801 (setq buffer-file-name nil
)
802 (setq buffer-file-number nil
)
803 (setq buffer-file-truename nil
)
804 (find-file filename
))
805 (cond ((eq obuf
(current-buffer))
806 (setq buffer-file-name ofile
)
807 (setq buffer-file-number onum
)
808 (setq buffer-file-truename otrue
)
810 (rename-buffer oname
))))
811 (or (eq (current-buffer) obuf
)
812 (kill-buffer obuf
))))
814 (defun create-file-buffer (filename)
815 "Create a suitably named buffer for visiting FILENAME, and return it.
816 FILENAME (sans directory) is used unchanged if that name is free;
817 otherwise a string <2> or <3> or ... is appended to get an unused name."
818 (let ((lastname (file-name-nondirectory filename
)))
819 (if (string= lastname
"")
820 (setq lastname filename
))
821 (generate-new-buffer lastname
)))
823 (defun generate-new-buffer (name)
824 "Create and return a buffer with a name based on NAME.
825 Choose the buffer's name using `generate-new-buffer-name'."
826 (get-buffer-create (generate-new-buffer-name name
)))
828 (defvar automount-dir-prefix
"^/tmp_mnt/"
829 "Regexp to match the automounter prefix in a directory name.")
831 (defvar abbreviated-home-dir nil
832 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
834 (defun abbreviate-file-name (filename)
835 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
836 This also substitutes \"~\" for the user's home directory.
837 Type \\[describe-variable] directory-abbrev-alist RET for more information."
838 ;; Get rid of the prefixes added by the automounter.
839 (if (and automount-dir-prefix
840 (string-match automount-dir-prefix filename
)
841 (file-exists-p (file-name-directory
842 (substring filename
(1- (match-end 0))))))
843 (setq filename
(substring filename
(1- (match-end 0)))))
844 (let ((tail directory-abbrev-alist
))
845 ;; If any elt of directory-abbrev-alist matches this name,
846 ;; abbreviate accordingly.
848 (if (string-match (car (car tail
)) filename
)
850 (concat (cdr (car tail
)) (substring filename
(match-end 0)))))
851 (setq tail
(cdr tail
)))
852 ;; Compute and save the abbreviated homedir name.
853 ;; We defer computing this until the first time it's needed, to
854 ;; give time for directory-abbrev-alist to be set properly.
855 ;; We include a slash at the end, to avoid spurious matches
856 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
857 (or abbreviated-home-dir
858 (setq abbreviated-home-dir
859 (let ((abbreviated-home-dir "$foo"))
860 (concat "^" (abbreviate-file-name (expand-file-name "~"))
863 ;; If FILENAME starts with the abbreviated homedir,
864 ;; make it start with `~' instead.
865 (if (and (string-match abbreviated-home-dir filename
)
866 ;; If the home dir is just /, don't change it.
867 (not (and (= (match-end 0) 1)
868 (= (aref filename
0) ?
/)))
869 ;; MS-DOS root directories can come with a drive letter;
870 ;; Novell Netware allows drive letters beyond `Z:'.
871 (not (and (or (eq system-type
'ms-dos
)
872 (eq system-type
'windows-nt
))
874 (string-match "^[a-zA-`]:/$" filename
)))))
877 (substring filename
(match-beginning 1) (match-end 1))
878 (substring filename
(match-end 0)))))
881 (defcustom find-file-not-true-dirname-list nil
882 "*List of logical names for which visiting shouldn't save the true dirname.
883 On VMS, when you visit a file using a logical name that searches a path,
884 you may or may not want the visited file name to record the specific
885 directory where the file was found. If you *do not* want that, add the logical
886 name to this list as a string."
887 :type
'(repeat (string :tag
"Name"))
890 (defun find-buffer-visiting (filename)
891 "Return the buffer visiting file FILENAME (a string).
892 This is like `get-file-buffer', except that it checks for any buffer
893 visiting the same file, possibly under a different name.
894 If there is no such live buffer, return nil."
895 (let ((buf (get-file-buffer filename
))
896 (truename (abbreviate-file-name (file-truename filename
))))
898 (let ((list (buffer-list)) found
)
899 (while (and (not found
) list
)
901 (set-buffer (car list
))
902 (if (and buffer-file-name
903 (string= buffer-file-truename truename
))
904 (setq found
(car list
))))
905 (setq list
(cdr list
)))
907 (let ((number (nthcdr 10 (file-attributes truename
)))
908 (list (buffer-list)) found
)
909 (and buffer-file-numbers-unique
911 (while (and (not found
) list
)
913 (set-buffer (car list
))
914 (if (and buffer-file-name
915 (equal buffer-file-number number
)
916 ;; Verify this buffer's file number
917 ;; still belongs to its file.
918 (file-exists-p buffer-file-name
)
919 (equal (nthcdr 10 (file-attributes buffer-file-name
))
921 (setq found
(car list
))))
922 (setq list
(cdr list
))))
925 (defcustom find-file-wildcards t
926 "*Non-nil means file-visiting commands should handle wildcards.
927 For example, if you specify `*.c', that would visit all the files
928 whose names match the pattern."
932 (defun find-file-noselect (filename &optional nowarn rawfile wildcards
)
933 "Read file FILENAME into a buffer and return the buffer.
934 If a buffer exists visiting FILENAME, return that one, but
935 verify that the file has not changed since visited or saved.
936 The buffer is not selected, just returned to the caller.
937 Optional first arg NOWARN non-nil means suppress any warning messages.
938 Optional second arg RAWFILE non-nil means the file is read literally.
939 Optional third arg WILDCARDS non-nil means do wildcard processing
940 and visit all the matching files. When wildcards are actually
941 used and expanded, the value is a list of buffers
942 that are visiting the various files."
944 (abbreviate-file-name
945 (expand-file-name filename
)))
946 (if (file-directory-p filename
)
947 (or (and find-file-run-dired
948 (run-hook-with-args-until-success
949 'find-directory-functions
950 (if find-file-visit-truename
951 (abbreviate-file-name (file-truename filename
))
953 (error "%s is a directory" filename
))
956 (not (string-match "\\`/:" filename
))
957 (string-match "[[*?]" filename
))
958 (let ((files (condition-case nil
959 (file-expand-wildcards filename t
)
960 (error (list filename
))))
961 (find-file-wildcards nil
))
963 (find-file-noselect filename
)
964 (car (mapcar #'(lambda (fn) (find-file-noselect fn
))
966 (let* ((buf (get-file-buffer filename
))
967 (truename (abbreviate-file-name (file-truename filename
)))
968 (number (nthcdr 10 (file-attributes truename
)))
969 ;; Find any buffer for a file which has same truename.
970 (other (and (not buf
) (find-buffer-visiting filename
))))
971 ;; Let user know if there is a buffer with the same truename.
975 (string-equal filename
(buffer-file-name other
))
976 (message "%s and %s are the same file"
977 filename
(buffer-file-name other
)))
978 ;; Optionally also find that buffer.
979 (if (or find-file-existing-other-name find-file-visit-truename
)
982 ;; We are using an existing buffer.
985 (verify-visited-file-modtime buf
)
986 (cond ((not (file-exists-p filename
))
987 (error "File %s no longer exists!" filename
))
988 ;; Certain files should be reverted automatically
989 ;; if they have changed on disk and not in the buffer.
990 ((and (not (buffer-modified-p buf
))
991 (let ((tail revert-without-query
)
994 (if (string-match (car tail
) filename
)
996 (setq tail
(cdr tail
)))
998 (with-current-buffer buf
999 (message "Reverting file %s..." filename
)
1001 (message "Reverting file %s...done" filename
)))
1003 (if (string= (file-name-nondirectory filename
)
1006 (if (buffer-modified-p buf
)
1007 "File %s changed on disk. Discard your edits? "
1008 "File %s changed on disk. Reread from disk? ")
1009 (file-name-nondirectory filename
))
1011 (if (buffer-modified-p buf
)
1012 "File %s changed on disk. Discard your edits in %s? "
1013 "File %s changed on disk. Reread from disk into %s? ")
1014 (file-name-nondirectory filename
)
1015 (buffer-name buf
))))
1016 (with-current-buffer buf
1017 (revert-buffer t t
)))))
1018 (with-current-buffer buf
1019 (when (not (eq (not (null rawfile
))
1020 (not (null find-file-literally
))))
1021 (if (buffer-modified-p)
1022 (if (y-or-n-p (if rawfile
1023 "Save file and revisit literally? "
1024 "Save file and revisit non-literally? "))
1027 (find-file-noselect-1 buf filename nowarn
1028 rawfile truename number
))
1029 (if (y-or-n-p (if rawfile
1030 "Discard your edits and revisit file literally? "
1031 "Discard your edits and revisit file non-literally? "))
1032 (find-file-noselect-1 buf filename nowarn
1033 rawfile truename number
)
1034 (error (if rawfile
"File already visited non-literally"
1035 "File already visited literally"))))
1036 (if (y-or-n-p (if rawfile
1037 "Revisit file literally? "
1038 "Revisit file non-literally? "))
1039 (find-file-noselect-1 buf filename nowarn
1040 rawfile truename number
)
1041 (error (if rawfile
"File already visited non-literally"
1042 "File already visited literally"))))))
1043 ;; Return the buffer we are using.
1045 ;; Create a new buffer.
1046 (setq buf
(create-file-buffer filename
))
1047 (set-buffer-major-mode buf
)
1048 ;; find-file-noselect-1 may use a different buffer.
1049 (find-file-noselect-1 buf filename nowarn
1050 rawfile truename number
))))))
1052 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number
)
1053 (let ((inhibit-read-only t
)
1055 (with-current-buffer buf
1056 (kill-local-variable 'find-file-literally
)
1057 ;; Needed in case we are re-visiting the file with a different
1058 ;; text representation.
1059 (kill-local-variable 'buffer-file-coding-system
)
1061 (and (default-value 'enable-multibyte-characters
)
1063 (set-buffer-multibyte t
))
1066 (insert-file-contents-literally filename t
)
1068 (when (and (file-exists-p filename
)
1069 (not (file-readable-p filename
)))
1071 (signal 'file-error
(list "File is not readable"
1073 ;; Unconditionally set error
1076 (insert-file-contents filename t
)
1078 (when (and (file-exists-p filename
)
1079 (not (file-readable-p filename
)))
1081 (signal 'file-error
(list "File is not readable"
1083 ;; Run find-file-not-found-hooks until one returns non-nil.
1084 (or (run-hook-with-args-until-success 'find-file-not-found-hooks
)
1085 ;; If they fail too, set error.
1087 ;; Record the file's truename, and maybe use that as visited name.
1088 (if (equal filename buffer-file-name
)
1089 (setq buffer-file-truename truename
)
1090 (setq buffer-file-truename
1091 (abbreviate-file-name (file-truename buffer-file-name
))))
1092 (setq buffer-file-number number
)
1093 ;; On VMS, we may want to remember which directory in a search list
1094 ;; the file was found in.
1095 (and (eq system-type
'vax-vms
)
1097 (if (string-match ":" (file-name-directory filename
))
1098 (setq logical
(substring (file-name-directory filename
)
1099 0 (match-beginning 0))))
1100 (not (member logical find-file-not-true-dirname-list
)))
1101 (setq buffer-file-name buffer-file-truename
))
1102 (if find-file-visit-truename
1103 (setq buffer-file-name
1105 (expand-file-name buffer-file-truename
))))
1106 ;; Set buffer's default directory to that of the file.
1107 (setq default-directory
(file-name-directory buffer-file-name
))
1108 ;; Turn off backup files for certain file names. Since
1109 ;; this is a permanent local, the major mode won't eliminate it.
1110 (and (not (funcall backup-enable-predicate buffer-file-name
))
1112 (make-local-variable 'backup-inhibited
)
1113 (setq backup-inhibited t
)))
1116 (set-buffer-multibyte nil
)
1117 (setq buffer-file-coding-system
'no-conversion
)
1118 (make-local-variable 'find-file-literally
)
1119 (setq find-file-literally t
))
1120 (after-find-file error
(not nowarn
)))
1123 (defun insert-file-contents-literally (filename &optional visit beg end replace
)
1124 "Like `insert-file-contents', but only reads in the file literally.
1125 A buffer may be modified in several ways after reading into the buffer,
1126 to Emacs features such as format decoding, character code
1127 conversion, find-file-hooks, automatic uncompression, etc.
1129 This function ensures that none of these modifications will take place."
1130 (let ((format-alist nil
)
1131 (after-insert-file-functions nil
)
1132 (coding-system-for-read 'no-conversion
)
1133 (coding-system-for-write 'no-conversion
)
1134 (jka-compr-compression-info-list nil
)
1135 (find-buffer-file-type-function
1136 (if (fboundp 'find-buffer-file-type
)
1137 (symbol-function 'find-buffer-file-type
)
1141 (fset 'find-buffer-file-type
(lambda (filename) t
))
1142 (insert-file-contents filename visit beg end replace
))
1143 (if find-buffer-file-type-function
1144 (fset 'find-buffer-file-type find-buffer-file-type-function
)
1145 (fmakunbound 'find-buffer-file-type
)))))
1147 (defun insert-file-literally (filename)
1148 "Insert contents of file FILENAME into buffer after point with no conversion.
1150 This function is meant for the user to run interactively.
1151 Don't call it from programs! Use `insert-file-contents-literally' instead.
1152 \(Its calling sequence is different; see its documentation)."
1153 (interactive "*fInsert file literally: ")
1154 (if (file-directory-p filename
)
1155 (signal 'file-error
(list "Opening input file" "file is a directory"
1157 (let ((tem (insert-file-contents-literally filename
)))
1158 (push-mark (+ (point) (car (cdr tem
))))))
1160 (defvar find-file-literally nil
1161 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1162 This is a permanent local.")
1163 (put 'find-file-literally
'permanent-local t
)
1165 (defun find-file-literally (filename)
1166 "Visit file FILENAME with no conversion of any kind.
1167 Format conversion and character code conversion are both disabled,
1168 and multibyte characters are disabled in the resulting buffer.
1169 The major mode used is Fundamental mode regardless of the file name,
1170 and local variable specifications in the file are ignored.
1171 Automatic uncompression is also disabled.
1173 You cannot absolutely rely on this function to result in
1174 visiting the file literally. If Emacs already has a buffer
1175 which is visiting the file, you get the existing buffer,
1176 regardless of whether it was created literally or not.
1178 In a Lisp program, if you want to be sure of accessing a file's
1179 contents literally, you should create a temporary buffer and then read
1180 the file contents into it using `insert-file-contents-literally'."
1181 (interactive "FFind file literally: ")
1182 (switch-to-buffer (find-file-noselect filename nil t
)))
1184 (defvar after-find-file-from-revert-buffer nil
)
1186 (defun after-find-file (&optional error warn noauto
1187 after-find-file-from-revert-buffer
1189 "Called after finding a file and by the default revert function.
1190 Sets buffer mode, parses local variables.
1191 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
1192 error in reading the file. WARN non-nil means warn if there
1193 exists an auto-save file more recent than the visited file.
1194 NOAUTO means don't mess with auto-save mode.
1195 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1196 means this call was from `revert-buffer'.
1197 Fifth arg NOMODES non-nil means don't alter the file's modes.
1198 Finishes by calling the functions in `find-file-hooks'
1199 unless NOMODES is non-nil."
1200 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
1205 (cond ((and error
(file-attributes buffer-file-name
))
1206 (setq buffer-read-only t
)
1207 "File exists, but cannot be read")
1208 ((not buffer-read-only
)
1210 ;; No need to warn if buffer is auto-saved
1211 ;; under the name of the visited file.
1212 (not (and buffer-file-name
1213 auto-save-visited-file-name
))
1214 (file-newer-than-file-p (or buffer-auto-save-file-name
1215 (make-auto-save-file-name))
1217 (format "%s has auto save data; consider M-x recover-file"
1218 (file-name-nondirectory buffer-file-name
))
1219 (setq not-serious t
)
1220 (if error
"(New file)" nil
)))
1222 (setq not-serious t
)
1223 "Note: file is write protected")
1224 ((file-attributes (directory-file-name default-directory
))
1225 "File not found and directory write-protected")
1226 ((file-exists-p (file-name-directory buffer-file-name
))
1227 (setq buffer-read-only nil
))
1229 (setq buffer-read-only nil
)
1230 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name
))))
1231 "Use M-x make-directory RET RET to create the directory"
1232 "Use C-u M-x make-directory RET RET to create directory and its parents")))))
1236 (or not-serious
(sit-for 1 nil t
)))))
1237 (if (and auto-save-default
(not noauto
))
1238 (auto-save-mode t
)))
1239 ;; Make people do a little extra work (C-x C-q)
1240 ;; before altering a backup file.
1241 (if (backup-file-name-p buffer-file-name
)
1242 (setq buffer-read-only t
))
1245 (and view-read-only view-mode
1246 (view-mode-disable))
1248 (if (and buffer-read-only view-read-only
1249 (not (eq (get major-mode
'mode-class
) 'special
)))
1251 (run-hooks 'find-file-hooks
)))
1253 (defun normal-mode (&optional find-file
)
1254 "Choose the major mode for this buffer automatically.
1255 Also sets up any specified local variables of the file.
1256 Uses the visited file name, the -*- line, and the local variables spec.
1258 This function is called automatically from `find-file'. In that case,
1259 we may set up the file-specified mode and local variables,
1260 depending on the value of `enable-local-variables': if it is t, we do;
1261 if it is nil, we don't; otherwise, we query.
1262 In addition, if `local-enable-local-variables' is nil, we do
1263 not set local variables (though we do notice a mode specified with -*-.)
1265 `enable-local-variables' is ignored if you run `normal-mode' interactively,
1266 or from Lisp without specifying the optional argument FIND-FILE;
1267 in that case, this function acts as if `enable-local-variables' were t."
1269 (or find-file
(funcall (or default-major-mode
'fundamental-mode
)))
1272 (error (message "File mode specification error: %s"
1273 (prin1-to-string err
))))
1275 (let ((enable-local-variables (or (not find-file
)
1276 enable-local-variables
)))
1277 (hack-local-variables))
1278 (error (message "File local-variables error: %s"
1279 (prin1-to-string err
)))))
1281 (defvar auto-mode-alist
1282 '(("\\.te?xt\\'" . text-mode
)
1283 ("\\.c\\'" . c-mode
)
1284 ("\\.h\\'" . c-mode
)
1285 ("\\.tex\\'" . tex-mode
)
1286 ("\\.ltx\\'" . latex-mode
)
1287 ("\\.el\\'" . emacs-lisp-mode
)
1288 ("\\.scm\\'" . scheme-mode
)
1289 ("\\.l\\'" . lisp-mode
)
1290 ("\\.lisp\\'" . lisp-mode
)
1291 ("\\.f\\'" . fortran-mode
)
1292 ("\\.F\\'" . fortran-mode
)
1293 ("\\.for\\'" . fortran-mode
)
1294 ("\\.p\\'" . pascal-mode
)
1295 ("\\.pas\\'" . pascal-mode
)
1296 ("\\.ad[abs]\\'" . ada-mode
)
1297 ("\\.\\([pP][Llm]\\|al\\)\\'" . perl-mode
)
1298 ("\\.s?html?\\'" . html-mode
)
1299 ("\\.cc\\'" . c
++-mode
)
1300 ("\\.hh\\'" . c
++-mode
)
1301 ("\\.hpp\\'" . c
++-mode
)
1302 ("\\.C\\'" . c
++-mode
)
1303 ("\\.H\\'" . c
++-mode
)
1304 ("\\.cpp\\'" . c
++-mode
)
1305 ("\\.cxx\\'" . c
++-mode
)
1306 ("\\.hxx\\'" . c
++-mode
)
1307 ("\\.c\\+\\+\\'" . c
++-mode
)
1308 ("\\.h\\+\\+\\'" . c
++-mode
)
1309 ("\\.m\\'" . objc-mode
)
1310 ("\\.java\\'" . java-mode
)
1311 ("\\.mk\\'" . makefile-mode
)
1312 ("\\(M\\|m\\|GNUm\\)akefile\\(\\.in\\)?\\'" . makefile-mode
)
1313 ("\\.am\\'" . makefile-mode
) ;For Automake.
1314 ;;; Less common extensions come here
1315 ;;; so more common ones above are found faster.
1316 ("\\.texinfo\\'" . texinfo-mode
)
1317 ("\\.te?xi\\'" . texinfo-mode
)
1318 ("\\.s\\'" . asm-mode
)
1319 ("\\.S\\'" . asm-mode
)
1320 ("\\.asm\\'" . asm-mode
)
1321 ("ChangeLog\\'" . change-log-mode
)
1322 ("change\\.log\\'" . change-log-mode
)
1323 ("changelo\\'" . change-log-mode
)
1324 ("ChangeLog\\.[0-9]+\\'" . change-log-mode
)
1325 ;; for MSDOS and MS-Windows (which are case-insensitive)
1326 ("changelog\\'" . change-log-mode
)
1327 ("changelog\\.[0-9]+\\'" . change-log-mode
)
1328 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
1329 ("\\.scm\\.[0-9]*\\'" . scheme-mode
)
1330 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode
)
1331 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode
)
1332 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode
)
1333 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode
)
1334 ("\\.m?spec$" . sh-mode
)
1335 ("\\.mm\\'" . nroff-mode
)
1336 ("\\.me\\'" . nroff-mode
)
1337 ("\\.ms\\'" . nroff-mode
)
1338 ("\\.man\\'" . nroff-mode
)
1339 ("\\.\\(u?lpc\\|pike\\|pmod\\)\\'" . pike-mode
)
1340 ;;; The following should come after the ChangeLog pattern
1341 ;;; for the sake of ChangeLog.1, etc.
1342 ;;; and after the .scm.[0-9] pattern too.
1343 ("\\.[12345678]\\'" . nroff-mode
)
1344 ("\\.TeX\\'" . tex-mode
)
1345 ("\\.sty\\'" . latex-mode
)
1346 ("\\.cls\\'" . latex-mode
) ;LaTeX 2e class
1347 ("\\.clo\\'" . latex-mode
) ;LaTeX 2e class option
1348 ("\\.bbl\\'" . latex-mode
)
1349 ("\\.bib\\'" . bibtex-mode
)
1350 ("\\.sql\\'" . sql-mode
)
1351 ("\\.m4\\'" . m4-mode
)
1352 ("\\.mc\\'" . m4-mode
)
1353 ("\\.mf\\'" . metafont-mode
)
1354 ("\\.mp\\'" . metapost-mode
)
1355 ("\\.vhdl?\\'" . vhdl-mode
)
1356 ("\\.article\\'" . text-mode
)
1357 ("\\.letter\\'" . text-mode
)
1358 ("\\.tcl\\'" . tcl-mode
)
1359 ("\\.exp\\'" . tcl-mode
)
1360 ("\\.itcl\\'" . tcl-mode
)
1361 ("\\.itk\\'" . tcl-mode
)
1362 ("\\.icn\\'" . icon-mode
)
1363 ("\\.sim\\'" . simula-mode
)
1364 ("\\.mss\\'" . scribe-mode
)
1365 ("\\.f90\\'" . f90-mode
)
1366 ("\\.pro\\'" . idlwave-mode
)
1367 ("\\.lsp\\'" . lisp-mode
)
1368 ("\\.awk\\'" . awk-mode
)
1369 ("\\.prolog\\'" . prolog-mode
)
1370 ("\\.tar\\'" . tar-mode
)
1371 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|jar\\)\\'" . archive-mode
)
1372 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|JAR\\)\\'" . archive-mode
)
1373 ;; Mailer puts message to be edited in
1374 ;; /tmp/Re.... or Message
1375 ("\\`/tmp/Re" . text-mode
)
1376 ("/Message[0-9]*\\'" . text-mode
)
1377 ("/drafts/[0-9]+\\'" . mh-letter-mode
)
1378 ("\\.zone\\'" . zone-mode
)
1379 ;; some news reader is reported to use this
1380 ("\\`/tmp/fol/" . text-mode
)
1381 ("\\.y\\'" . c-mode
)
1382 ("\\.lex\\'" . c-mode
)
1383 ("\\.oak\\'" . scheme-mode
)
1384 ("\\.sgml?\\'" . sgml-mode
)
1385 ("\\.xml\\'" . sgml-mode
)
1386 ("\\.dtd\\'" . sgml-mode
)
1387 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode
)
1388 ("\\.idl\\'" . idl-mode
)
1389 ;; .emacs following a directory delimiter
1390 ;; in Unix, MSDOG or VMS syntax.
1391 ("[]>:/\\]\\..*emacs\\'" . emacs-lisp-mode
)
1392 ("\\`\\..*emacs\\'" . emacs-lisp-mode
)
1393 ;; _emacs following a directory delimiter
1395 ("[:/]_emacs\\'" . emacs-lisp-mode
)
1396 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode
)
1397 ("\\.ml\\'" . lisp-mode
)
1398 ("\\.asn$" . snmp-mode
)
1399 ("\\.mib$" . snmp-mode
)
1400 ("\\.smi$" . snmp-mode
)
1401 ("\\.as2$" . snmpv2-mode
)
1402 ("\\.mi2$" . snmpv2-mode
)
1403 ("\\.sm2$" . snmpv2-mode
)
1404 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode
)
1405 ("\\.[eE]?[pP][sS]$" . ps-mode
)
1406 ("configure\\.in\\'" . autoconf-mode
))
1408 Alist of filename patterns vs corresponding major mode functions.
1409 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1410 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1411 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1412 mode function to use. FUNCTION will be called, unless it is nil.
1414 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1415 calling FUNCTION (if it's not nil), we delete the suffix that matched
1416 REGEXP and search the list again for another match.")
1419 (defvar interpreter-mode-alist
1420 '(("perl" . perl-mode
)
1421 ("perl5" . perl-mode
)
1422 ("miniperl" . perl-mode
)
1424 ("wishx" . tcl-mode
)
1426 ("tclsh" . tcl-mode
)
1431 ("scm" . scheme-mode
)
1450 ("tail" . text-mode
)
1451 ("more" . text-mode
)
1452 ("less" . text-mode
)
1454 ("make" . makefile-mode
) ; Debian uses this
1455 ("guile" . scheme-mode
)
1456 ("clisp" . lisp-mode
))
1457 "Alist mapping interpreter names to major modes.
1458 This alist applies to files whose first line starts with `#!'.
1459 Each element looks like (INTERPRETER . MODE).
1460 The car of each element is compared with
1461 the name of the interpreter specified in the first line.
1462 If it matches, mode MODE is selected.")
1464 (defvar inhibit-first-line-modes-regexps
'("\\.tar\\'" "\\.tgz\\'")
1465 "List of regexps; if one matches a file name, don't look for `-*-'.")
1467 (defvar inhibit-first-line-modes-suffixes nil
1468 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1469 When checking `inhibit-first-line-modes-regexps', we first discard
1470 from the end of the file name anything that matches one of these regexps.")
1472 (defun set-auto-mode (&optional just-from-file-name
)
1473 "Select major mode appropriate for current buffer.
1474 This checks for a -*- mode tag in the buffer's text,
1475 compares the filename against the entries in `auto-mode-alist',
1476 or checks the interpreter that runs this file against
1477 `interpreter-mode-alist'.
1479 It does not check for the `mode:' local variable in the
1480 Local Variables section of the file; for that, use `hack-local-variables'.
1482 If `enable-local-variables' is nil, this function does not check for a
1485 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1486 then we do not set anything but the major mode,
1487 and we don't even do that unless it would come from the file name."
1488 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1489 (let (beg end done modes
)
1491 (goto-char (point-min))
1492 (skip-chars-forward " \t\n")
1493 (and enable-local-variables
1494 ;; Don't look for -*- if this file name matches any
1495 ;; of the regexps in inhibit-first-line-modes-regexps.
1496 (let ((temp inhibit-first-line-modes-regexps
)
1497 (name (if buffer-file-name
1498 (file-name-sans-versions buffer-file-name
)
1500 (while (let ((sufs inhibit-first-line-modes-suffixes
))
1501 (while (and sufs
(not (string-match (car sufs
) name
)))
1502 (setq sufs
(cdr sufs
)))
1504 (setq name
(substring name
0 (match-beginning 0))))
1506 (not (string-match (car temp
) name
)))
1507 (setq temp
(cdr temp
)))
1509 (search-forward "-*-" (save-excursion
1510 ;; If the file begins with "#!"
1511 ;; (exec interpreter magic), look
1512 ;; for mode frobs in the first two
1513 ;; lines. You cannot necessarily
1514 ;; put them in the first line of
1515 ;; such a file without screwing up
1516 ;; the interpreter invocation.
1517 (end-of-line (and (looking-at "^#!") 2))
1520 (skip-chars-forward " \t")
1522 (search-forward "-*-"
1523 (save-excursion (end-of-line) (point))
1527 (skip-chars-backward " \t")
1530 (if (save-excursion (search-forward ":" end t
))
1531 ;; Find all specifications for the `mode:' variable
1532 ;; and execute them left to right.
1533 (while (let ((case-fold-search t
))
1534 (or (and (looking-at "mode:")
1535 (goto-char (match-end 0)))
1536 (re-search-forward "[ \t;]mode:" end t
)))
1537 (skip-chars-forward " \t")
1539 (if (search-forward ";" end t
)
1542 (skip-chars-backward " \t")
1543 (setq modes
(cons (intern (concat (downcase (buffer-substring beg
(point))) "-mode"))
1545 ;; Simple -*-MODE-*- case.
1546 (setq modes
(cons (intern (concat (downcase (buffer-substring beg end
))
1549 ;; If we found modes to use, invoke them now,
1550 ;; outside the save-excursion.
1552 (unless just-from-file-name
1553 (mapcar 'funcall
(nreverse modes
)))
1555 ;; If we didn't find a mode from a -*- line, try using the file name.
1556 (if (and (not done
) buffer-file-name
)
1557 (let ((name buffer-file-name
)
1559 ;; Remove backup-suffixes from file name.
1560 (setq name
(file-name-sans-versions name
))
1562 (setq keep-going nil
)
1563 (let ((alist auto-mode-alist
)
1565 ;; Find first matching alist entry.
1566 (let ((case-fold-search
1567 (memq system-type
'(vax-vms windows-nt
))))
1568 (while (and (not mode
) alist
)
1569 (if (string-match (car (car alist
)) name
)
1570 (if (and (consp (cdr (car alist
)))
1571 (nth 2 (car alist
)))
1573 (setq mode
(car (cdr (car alist
)))
1574 name
(substring name
0 (match-beginning 0))
1576 (setq mode
(cdr (car alist
))
1578 (setq alist
(cdr alist
))))
1580 ;; When JUST-FROM-FILE-NAME is set,
1581 ;; we are working on behalf of set-visited-file-name.
1582 ;; In that case, if the major mode specified is the
1583 ;; same one we already have, don't actually reset it.
1584 ;; We don't want to lose minor modes such as Font Lock.
1585 (unless (and just-from-file-name
(eq mode major-mode
))
1587 ;; If we can't deduce a mode from the file name,
1588 ;; look for an interpreter specified in the first line.
1589 ;; As a special case, allow for things like "#!/bin/env perl",
1590 ;; which finds the interpreter anywhere in $PATH.
1593 (goto-char (point-min))
1594 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1595 (buffer-substring (match-beginning 2)
1599 ;; Map interpreter name to a mode.
1600 (setq elt
(assoc (file-name-nondirectory interpreter
)
1601 interpreter-mode-alist
))
1602 (unless just-from-file-name
1604 (funcall (cdr elt
))))))))))))
1606 (defun hack-local-variables-prop-line ()
1607 ;; Set local variables specified in the -*- line.
1608 ;; Ignore any specification for `mode:' and `coding:';
1609 ;; set-auto-mode should already have handled `mode:',
1610 ;; set-auto-coding should already have handled `coding:'.
1612 (goto-char (point-min))
1614 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point)))
1615 (enable-local-variables
1616 (and local-enable-local-variables enable-local-variables
)))
1617 ;; Parse the -*- line into the `result' alist.
1618 (cond ((not (search-forward "-*-" end t
))
1619 ;; doesn't have one.
1621 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1622 ;; Simple form: "-*- MODENAME -*-". Already handled.
1625 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1626 ;; (last ";" is optional).
1628 (if (search-forward "-*-" end t
)
1629 (setq end
(- (point) 3))
1630 (error "-*- not terminated before end of line")))
1631 (while (< (point) end
)
1632 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1633 (error "malformed -*- line"))
1634 (goto-char (match-end 0))
1635 ;; There used to be a downcase here,
1636 ;; but the manual didn't say so,
1637 ;; and people want to set var names that aren't all lc.
1638 (let ((key (intern (buffer-substring
1641 (val (save-restriction
1642 (narrow-to-region (point) end
)
1643 (read (current-buffer)))))
1644 ;; It is traditional to ignore
1645 ;; case when checking for `mode' in set-auto-mode,
1646 ;; so we must do that here as well.
1647 ;; That is inconsistent, but we're stuck with it.
1648 ;; The same can be said for `coding' in set-auto-coding.
1649 (or (equal (downcase (symbol-name key
)) "mode")
1650 (equal (downcase (symbol-name key
)) "coding")
1651 (setq result
(cons (cons key val
) result
)))
1652 (skip-chars-forward " \t;")))
1653 (setq result
(nreverse result
))))
1656 (or (eq enable-local-variables t
)
1657 (and enable-local-variables
1658 (save-window-excursion
1660 (switch-to-buffer (current-buffer))
1662 ;; If we fail to switch in the selected window,
1663 ;; it is probably a minibuffer.
1664 ;; So try another window.
1666 (switch-to-buffer-other-window (current-buffer))
1668 (switch-to-buffer-other-frame (current-buffer))))))
1669 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1670 (file-name-nondirectory buffer-file-name
)))))))
1671 (let ((enable-local-eval enable-local-eval
))
1673 (hack-one-local-variable (car (car result
)) (cdr (car result
)))
1674 (setq result
(cdr result
))))))))
1676 (defvar hack-local-variables-hook nil
1677 "Normal hook run after processing a file's local variables specs.
1678 Major modes can use this to examine user-specified local variables
1679 in order to initialize other data structure based on them.")
1681 (defun hack-local-variables (&optional mode-only
)
1682 "Parse and put into effect this buffer's local variables spec.
1683 If MODE-ONLY is non-nil, all we do is check whether the major mode
1684 is specified, returning t if it is specified."
1686 (hack-local-variables-prop-line))
1687 ;; Look for "Local variables:" line in last page.
1688 (let (mode-specified
1689 (enable-local-variables
1690 (and local-enable-local-variables enable-local-variables
)))
1692 (goto-char (point-max))
1693 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move
)
1694 (if (let ((case-fold-search t
))
1695 (and (search-forward "Local Variables:" nil t
)
1696 (or (eq enable-local-variables t
)
1698 (and enable-local-variables
1699 (save-window-excursion
1700 (switch-to-buffer (current-buffer))
1703 (set-window-start (selected-window) (point)))
1704 (y-or-n-p (format "Set local variables as specified at end of %s? "
1705 (if buffer-file-name
1706 (file-name-nondirectory
1709 (buffer-name))))))))))
1711 prefix prefixlen suffix beg
1713 (enable-local-eval enable-local-eval
))
1714 ;; The prefix is what comes before "local variables:" in its line.
1715 ;; The suffix is what comes after "local variables:" in its line.
1716 (skip-chars-forward " \t")
1718 (setq suffix
(buffer-substring (point)
1719 (progn (end-of-line) (point)))))
1720 (goto-char (match-beginning 0))
1723 (buffer-substring (point)
1724 (progn (beginning-of-line) (point)))))
1726 (if prefix
(setq prefixlen
(length prefix
)
1727 prefix
(regexp-quote prefix
)))
1728 (if suffix
(setq suffix
(concat (regexp-quote suffix
) "$")))
1730 ;; Look at next local variable spec.
1731 (if selective-display
(re-search-forward "[\n\C-m]")
1733 ;; Skip the prefix, if any.
1735 (if (looking-at prefix
)
1736 (forward-char prefixlen
)
1737 (error "Local variables entry is missing the prefix")))
1738 ;; Find the variable name; strip whitespace.
1739 (skip-chars-forward " \t")
1741 (skip-chars-forward "^:\n")
1742 (if (eolp) (error "Missing colon in local variables entry"))
1743 (skip-chars-backward " \t")
1744 (let* ((str (buffer-substring beg
(point)))
1747 ;; Setting variable named "end" means end of list.
1748 (if (string-equal (downcase str
) "end")
1750 ;; Otherwise read the variable value.
1751 (skip-chars-forward "^:")
1753 (setq val
(read (current-buffer)))
1754 (skip-chars-backward "\n")
1755 (skip-chars-forward " \t")
1756 (or (if suffix
(looking-at suffix
) (eolp))
1757 (error "Local variables entry is terminated incorrectly"))
1760 (setq mode-specified t
))
1761 ;; Set the variable. "Variables" mode and eval are funny.
1762 (hack-one-local-variable var val
))))))))
1764 (run-hooks 'hack-local-variables-hook
))
1767 (defvar ignored-local-variables
1768 '(enable-local-eval)
1769 "Variables to be ignored in a file's local variable spec.")
1771 ;; Get confirmation before setting these variables as locals in a file.
1772 (put 'debugger
'risky-local-variable t
)
1773 (put 'enable-local-eval
'risky-local-variable t
)
1774 (put 'ignored-local-variables
'risky-local-variable t
)
1775 (put 'eval
'risky-local-variable t
)
1776 (put 'file-name-handler-alist
'risky-local-variable t
)
1777 (put 'minor-mode-map-alist
'risky-local-variable t
)
1778 (put 'after-load-alist
'risky-local-variable t
)
1779 (put 'buffer-file-name
'risky-local-variable t
)
1780 (put 'buffer-auto-save-file-name
'risky-local-variable t
)
1781 (put 'buffer-file-truename
'risky-local-variable t
)
1782 (put 'exec-path
'risky-local-variable t
)
1783 (put 'load-path
'risky-local-variable t
)
1784 (put 'exec-directory
'risky-local-variable t
)
1785 (put 'process-environment
'risky-local-variable t
)
1786 (put 'dabbrev-case-fold-search
'risky-local-variable t
)
1787 (put 'dabbrev-case-replace
'risky-local-variable t
)
1788 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1789 (put 'outline-level
'risky-local-variable t
)
1790 (put 'rmail-output-file-alist
'risky-local-variable t
)
1792 ;; This one is safe because the user gets to check it before it is used.
1793 (put 'compile-command
'safe-local-variable t
)
1795 (defun hack-one-local-variable-quotep (exp)
1796 (and (consp exp
) (eq (car exp
) 'quote
) (consp (cdr exp
))))
1798 ;; "Set" one variable in a local variables spec.
1799 ;; A few variable names are treated specially.
1800 (defun hack-one-local-variable (var val
)
1801 (cond ((eq var
'mode
)
1802 (funcall (intern (concat (downcase (symbol-name val
))
1805 ;; We have already handled coding: tag in set-auto-coding.
1807 ((memq var ignored-local-variables
)
1809 ;; "Setting" eval means either eval it or do nothing.
1810 ;; Likewise for setting hook variables.
1811 ((or (get var
'risky-local-variable
)
1813 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$\\|-predicate$"
1815 (not (get var
'safe-local-variable
))))
1816 ;; Permit evalling a put of a harmless property.
1817 ;; if the args do nothing tricky.
1818 (if (or (and (eq var
'eval
)
1821 (hack-one-local-variable-quotep (nth 1 val
))
1822 (hack-one-local-variable-quotep (nth 2 val
))
1823 ;; Only allow safe values of lisp-indent-hook;
1825 (or (numberp (nth 3 val
))
1826 (equal (nth 3 val
) ''defun
))
1827 (memq (nth 1 (nth 2 val
))
1828 '(lisp-indent-hook)))
1829 ;; Permit eval if not root and user says ok.
1830 (and (not (zerop (user-uid)))
1831 (or (eq enable-local-eval t
)
1832 (and enable-local-eval
1833 (save-window-excursion
1834 (switch-to-buffer (current-buffer))
1837 (set-window-start (selected-window) (point)))
1838 (setq enable-local-eval
1839 (y-or-n-p (format "Process `eval' or hook local variables in %s? "
1840 (if buffer-file-name
1841 (concat "file " (file-name-nondirectory buffer-file-name
))
1842 (concat "buffer " (buffer-name)))))))))))
1844 (save-excursion (eval val
))
1845 (make-local-variable var
)
1847 (message "Ignoring `eval:' in the local variables list")))
1848 ;; Ordinary variable, really set it.
1849 (t (make-local-variable var
)
1853 (defcustom change-major-mode-with-file-name t
1854 "*Non-nil means \\[write-file] should set the major mode from the file name.
1855 However, the mode will not be changed if
1856 \(1) a local variables list or the `-*-' line specifies a major mode, or
1857 \(2) the current major mode is a \"special\" mode,
1858 \ not suitable for ordinary files, or
1859 \(3) the new file name does not particularly specify any mode."
1861 :group
'editing-basics
)
1863 (defun set-visited-file-name (filename &optional no-query along-with-file
)
1864 "Change name of file visited in current buffer to FILENAME.
1865 The next time the buffer is saved it will go in the newly specified file.
1866 nil or empty string as argument means make buffer not be visiting any file.
1867 Remember to delete the initial contents of the minibuffer
1868 if you wish to pass an empty string as the argument.
1870 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1871 confirmation in the case where another buffer is already visiting FILENAME.
1873 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1874 the old visited file has been renamed to the new name FILENAME."
1875 (interactive "FSet visited file name: ")
1876 (if (buffer-base-buffer)
1877 (error "An indirect buffer cannot visit a file"))
1881 (if (string-equal filename
"")
1883 (expand-file-name filename
))))
1886 (setq truename
(file-truename filename
))
1887 (if find-file-visit-truename
1888 (setq filename truename
))))
1889 (let ((buffer (and filename
(find-buffer-visiting filename
))))
1890 (and buffer
(not (eq buffer
(current-buffer)))
1892 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1895 (or (equal filename buffer-file-name
)
1897 (and filename
(lock-buffer filename
))
1899 (setq buffer-file-name filename
)
1900 (if filename
; make buffer name reflect filename.
1901 (let ((new-name (file-name-nondirectory buffer-file-name
)))
1902 (if (string= new-name
"")
1903 (error "Empty file name"))
1904 (if (eq system-type
'vax-vms
)
1905 (setq new-name
(downcase new-name
)))
1906 (setq default-directory
(file-name-directory buffer-file-name
))
1907 (or (string= new-name
(buffer-name))
1908 (rename-buffer new-name t
))))
1909 (setq buffer-backed-up nil
)
1911 (clear-visited-file-modtime))
1912 ;; Abbreviate the file names of the buffer.
1915 (setq buffer-file-truename
(abbreviate-file-name truename
))
1916 (if find-file-visit-truename
1917 (setq buffer-file-name buffer-file-truename
))))
1918 (setq buffer-file-number
1920 (nthcdr 10 (file-attributes buffer-file-name
))
1922 ;; write-file-hooks is normally used for things like ftp-find-file
1923 ;; that visit things that are not local files as if they were files.
1924 ;; Changing to visit an ordinary local file instead should flush the hook.
1925 (kill-local-variable 'write-file-hooks
)
1926 (kill-local-variable 'local-write-file-hooks
)
1927 (kill-local-variable 'revert-buffer-function
)
1928 (kill-local-variable 'backup-inhibited
)
1929 ;; If buffer was read-only because of version control,
1930 ;; that reason is gone now, so make it writable.
1932 (setq buffer-read-only nil
))
1933 (kill-local-variable 'vc-mode
)
1934 ;; Turn off backup files for certain file names.
1935 ;; Since this is a permanent local, the major mode won't eliminate it.
1936 (and buffer-file-name
1937 (not (funcall backup-enable-predicate buffer-file-name
))
1939 (make-local-variable 'backup-inhibited
)
1940 (setq backup-inhibited t
)))
1941 (let ((oauto buffer-auto-save-file-name
))
1942 ;; If auto-save was not already on, turn it on if appropriate.
1943 (if (not buffer-auto-save-file-name
)
1944 (and buffer-file-name auto-save-default
1946 ;; If auto save is on, start using a new name.
1947 ;; We deliberately don't rename or delete the old auto save
1948 ;; for the old visited file name. This is because perhaps
1949 ;; the user wants to save the new state and then compare with the
1950 ;; previous state from the auto save file.
1951 (setq buffer-auto-save-file-name
1952 (make-auto-save-file-name)))
1953 ;; Rename the old auto save file if any.
1954 (and oauto buffer-auto-save-file-name
1955 (file-exists-p oauto
)
1956 (rename-file oauto buffer-auto-save-file-name t
)))
1957 (and buffer-file-name
1958 (not along-with-file
)
1959 (set-buffer-modified-p t
))
1960 ;; Update the major mode, if the file name determines it.
1962 ;; Don't change the mode if it is special.
1963 (or (not change-major-mode-with-file-name
)
1964 (get major-mode
'mode-class
)
1965 ;; Don't change the mode if the local variable list specifies it.
1966 (hack-local-variables t
)
1970 (defun write-file (filename &optional confirm
)
1971 "Write current buffer into file FILENAME.
1972 This makes the buffer visit that file, and marks it as not modified.
1974 If you specify just a directory name as FILENAME, that means to use
1975 the default file name but in that directory. You can also yank
1976 the default file name into the minibuffer to edit it, using M-n.
1978 If the buffer is not already visiting a file, the default file name
1979 for the output file is the buffer name.
1981 If optional second arg CONFIRM is non-nil, this function
1982 asks for confirmation before overwriting an existing file.
1983 Interactively, confirmation is required unless you supply a prefix argument."
1984 ;; (interactive "FWrite file: ")
1986 (list (if buffer-file-name
1987 (read-file-name "Write file: "
1989 (read-file-name "Write file: " default-directory
1991 (file-name-nondirectory (buffer-name))
1994 (not current-prefix-arg
)))
1995 (or (null filename
) (string-equal filename
"")
1997 ;; If arg is just a directory,
1998 ;; use the default file name, but in that directory.
1999 (if (file-directory-p filename
)
2000 (setq filename
(concat (file-name-as-directory filename
)
2001 (file-name-nondirectory
2002 (or buffer-file-name
(buffer-name))))))
2004 (file-exists-p filename
)
2005 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename
))
2006 (error "Canceled")))
2007 (set-visited-file-name filename
(not confirm
))))
2008 (set-buffer-modified-p t
)
2009 ;; Make buffer writable if file is writable.
2010 (and buffer-file-name
2011 (file-writable-p buffer-file-name
)
2012 (setq buffer-read-only nil
))
2015 (defun backup-buffer ()
2016 "Make a backup of the disk file visited by the current buffer, if appropriate.
2017 This is normally done before saving the buffer the first time.
2018 If the value is non-nil, it is the result of `file-modes' on the original
2019 file; this means that the caller, after saving the buffer, should change
2020 the modes of the new file to agree with the old modes.
2022 A backup may be done by renaming or by copying; see documentation of
2023 variable `make-backup-files'. If it's done by renaming, then the file is
2024 no longer accessible under its old name."
2025 (if (and make-backup-files
(not backup-inhibited
)
2026 (not buffer-backed-up
)
2027 (file-exists-p buffer-file-name
)
2028 (memq (aref (elt (file-attributes buffer-file-name
) 8) 0)
2030 (let ((real-file-name buffer-file-name
)
2031 backup-info backupname targets setmodes
)
2032 ;; If specified name is a symbolic link, chase it to the target.
2033 ;; Thus we make the backups in the directory where the real file is.
2034 (setq real-file-name
(file-chase-links real-file-name
))
2035 (setq backup-info
(find-backup-file-name real-file-name
)
2036 backupname
(car backup-info
)
2037 targets
(cdr backup-info
))
2038 ;;; (if (file-directory-p buffer-file-name)
2039 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
2042 (let ((delete-old-versions
2043 ;; If have old versions to maybe delete,
2044 ;; ask the user to confirm now, before doing anything.
2045 ;; But don't actually delete til later.
2047 (or (eq delete-old-versions t
) (eq delete-old-versions nil
))
2048 (or delete-old-versions
2049 (y-or-n-p (format "Delete excess backup versions of %s? "
2050 real-file-name
))))))
2051 ;; Actually write the back up file.
2053 (if (or file-precious-flag
2054 ; (file-symlink-p buffer-file-name)
2056 (and backup-by-copying-when-linked
2057 (> (file-nlinks real-file-name
) 1))
2058 (and (or backup-by-copying-when-mismatch
2059 (integerp backup-by-copying-when-privileged-mismatch
))
2060 (let ((attr (file-attributes real-file-name
)))
2061 (and (or backup-by-copying-when-mismatch
2062 (and (integerp (nth 2 attr
))
2063 (integerp backup-by-copying-when-privileged-mismatch
)
2064 (<= (nth 2 attr
) backup-by-copying-when-privileged-mismatch
)))
2066 (not (file-ownership-preserved-p real-file-name
)))))))
2068 (copy-file real-file-name backupname t t
)
2070 ;; If copying fails because file BACKUPNAME
2071 ;; is not writable, delete that file and try again.
2072 (if (and (file-exists-p backupname
)
2073 (not (file-writable-p backupname
)))
2074 (delete-file backupname
))
2075 (copy-file real-file-name backupname t t
)))
2076 ;; rename-file should delete old backup.
2077 (rename-file real-file-name backupname t
)
2078 (setq setmodes
(file-modes backupname
)))
2080 ;; If trouble writing the backup, write it in ~.
2081 (setq backupname
(expand-file-name
2082 (convert-standard-filename
2084 (message "Cannot write backup file; backing up in %s"
2085 (file-name-nondirectory backupname
))
2088 (copy-file real-file-name backupname t t
)
2090 ;; If copying fails because file BACKUPNAME
2091 ;; is not writable, delete that file and try again.
2092 (if (and (file-exists-p backupname
)
2093 (not (file-writable-p backupname
)))
2094 (delete-file backupname
))
2095 (copy-file real-file-name backupname t t
)))))
2096 (setq buffer-backed-up t
)
2097 ;; Now delete the old versions, if desired.
2098 (if delete-old-versions
2101 (delete-file (car targets
))
2103 (setq targets
(cdr targets
))))
2105 (file-error nil
))))))
2107 (defun file-name-sans-versions (name &optional keep-backup-version
)
2108 "Return FILENAME sans backup versions or strings.
2109 This is a separate procedure so your site-init or startup file can
2111 If the optional argument KEEP-BACKUP-VERSION is non-nil,
2112 we do not remove backup version numbers, only true file version numbers."
2113 (let ((handler (find-file-name-handler name
'file-name-sans-versions
)))
2115 (funcall handler
'file-name-sans-versions name keep-backup-version
)
2117 (if (eq system-type
'vax-vms
)
2118 ;; VMS version number is (a) semicolon, optional
2119 ;; sign, zero or more digits or (b) period, option
2120 ;; sign, zero or more digits, provided this is the
2121 ;; second period encountered outside of the
2122 ;; device/directory part of the file name.
2123 (or (string-match ";[-+]?[0-9]*\\'" name
)
2124 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
2126 (match-beginning 1))
2128 (if keep-backup-version
2130 (or (string-match "\\.~[0-9.]+~\\'" name
)
2131 (string-match "~\\'" name
)
2132 (length name
))))))))
2134 (defun file-ownership-preserved-p (file)
2135 "Returns t if deleting FILE and rewriting it would preserve the owner."
2136 (let ((handler (find-file-name-handler file
'file-ownership-preserved-p
)))
2138 (funcall handler
'file-ownership-preserved-p file
)
2139 (let ((attributes (file-attributes file
)))
2140 ;; Return t if the file doesn't exist, since it's true that no
2141 ;; information would be lost by an (attempted) delete and create.
2142 (or (null attributes
)
2143 (= (nth 2 attributes
) (user-uid)))))))
2145 (defun file-name-sans-extension (filename)
2146 "Return FILENAME sans final \"extension\".
2147 The extension, in a file name, is the part that follows the last `.'."
2149 (let ((file (file-name-sans-versions (file-name-nondirectory filename
)))
2151 (if (string-match "\\.[^.]*\\'" file
)
2152 (if (setq directory
(file-name-directory filename
))
2153 (expand-file-name (substring file
0 (match-beginning 0))
2155 (substring file
0 (match-beginning 0)))
2158 (defun file-name-extension (filename &optional period
)
2159 "Return FILENAME's final \"extension\".
2160 The extension, in a file name, is the part that follows the last `.'.
2161 Return nil for extensionless file names such as `foo'.
2162 Return the empty string for file names such as `foo.'.
2164 If PERIOD is non-nil, then the returned value includes the period
2165 that delimits the extension, and if FILENAME has no extension,
2168 (let ((file (file-name-sans-versions (file-name-nondirectory filename
))))
2169 (if (string-match "\\.[^.]*\\'" file
)
2170 (substring file
(+ (match-beginning 0) (if period
0 1)))
2174 (defun make-backup-file-name (file)
2175 "Create the non-numeric backup file name for FILE.
2176 This is a separate function so you can redefine it for customization."
2177 (if (and (eq system-type
'ms-dos
)
2178 (not (msdos-long-file-names)))
2179 (let ((fn (file-name-nondirectory file
)))
2180 (concat (file-name-directory file
)
2182 (and (string-match "\\`[^.]+\\'" fn
)
2183 (concat (match-string 0 fn
) ".~"))
2184 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn
)
2185 (concat (match-string 0 fn
) "~")))))
2188 (defun backup-file-name-p (file)
2189 "Return non-nil if FILE is a backup file name (numeric or not).
2190 This is a separate function so you can redefine it for customization.
2191 You may need to redefine `file-name-sans-versions' as well."
2192 (string-match "~\\'" file
))
2194 (defvar backup-extract-version-start
)
2196 ;; This is used in various files.
2197 ;; The usage of backup-extract-version-start is not very clean,
2198 ;; but I can't see a good alternative, so as of now I am leaving it alone.
2199 (defun backup-extract-version (fn)
2200 "Given the name of a numeric backup file, return the backup number.
2201 Uses the free variable `backup-extract-version-start', whose value should be
2202 the index in the name where the version number begins."
2203 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start
)
2204 (= (match-beginning 0) backup-extract-version-start
))
2205 (string-to-int (substring fn backup-extract-version-start -
1))
2208 ;; I believe there is no need to alter this behavior for VMS;
2209 ;; since backup files are not made on VMS, it should not get called.
2210 (defun find-backup-file-name (fn)
2211 "Find a file name for a backup file, and suggestions for deletions.
2212 Value is a list whose car is the name for the backup file
2213 and whose cdr is a list of old versions to consider deleting now.
2214 If the value is nil, don't make a backup."
2215 (let ((handler (find-file-name-handler fn
'find-backup-file-name
)))
2216 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2218 (funcall handler
'find-backup-file-name fn
)
2219 (if (eq version-control
'never
)
2220 (list (make-backup-file-name fn
))
2221 (let* ((base-versions (concat (file-name-nondirectory fn
) ".~"))
2222 (backup-extract-version-start (length base-versions
))
2226 (deserve-versions-p nil
)
2227 (number-to-delete 0))
2229 (setq possibilities
(file-name-all-completions
2231 (file-name-directory fn
))
2232 versions
(sort (mapcar
2233 (function backup-extract-version
)
2236 high-water-mark
(apply 'max
0 versions
)
2237 deserve-versions-p
(or version-control
2238 (> high-water-mark
0))
2239 number-to-delete
(- (length versions
)
2240 kept-old-versions kept-new-versions -
1))
2242 (setq possibilities nil
)))
2243 (if (not deserve-versions-p
)
2244 (list (make-backup-file-name fn
))
2245 (cons (concat fn
".~" (int-to-string (1+ high-water-mark
)) "~")
2246 (if (and (> number-to-delete
0)
2247 ;; Delete nothing if there is overflow
2248 ;; in the number of versions to keep.
2249 (>= (+ kept-new-versions kept-old-versions -
1) 0))
2250 (mapcar (function (lambda (n)
2251 (concat fn
".~" (int-to-string n
) "~")))
2252 (let ((v (nthcdr kept-old-versions versions
)))
2253 (rplacd (nthcdr (1- number-to-delete
) v
) ())
2256 (defun file-nlinks (filename)
2257 "Return number of names file FILENAME has."
2258 (car (cdr (file-attributes filename
))))
2260 (defun file-relative-name (filename &optional directory
)
2261 "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
2262 This function returns a relative file name which is equivalent to FILENAME
2263 when used with that default directory as the default.
2264 If this is impossible (which can happen on MSDOS and Windows
2265 when the file name and directory use different drive names)
2266 then it returns FILENAME."
2268 (let ((fname (expand-file-name filename
)))
2269 (setq directory
(file-name-as-directory
2270 (expand-file-name (or directory default-directory
))))
2271 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2272 ;; drive names, they can't be relative, so return the absolute name.
2273 (if (and (or (eq system-type
'ms-dos
)
2274 (eq system-type
'windows-nt
))
2275 (not (string-equal (substring fname
0 2)
2276 (substring directory
0 2))))
2278 (let ((ancestor ".")
2279 (fname-dir (file-name-as-directory fname
)))
2280 (while (and (not (string-match (concat "^" (regexp-quote directory
)) fname-dir
))
2281 (not (string-match (concat "^" (regexp-quote directory
)) fname
)))
2282 (setq directory
(file-name-directory (substring directory
0 -
1))
2283 ancestor
(if (equal ancestor
".")
2285 (concat "../" ancestor
))))
2286 ;; Now ancestor is empty, or .., or ../.., etc.
2287 (if (string-match (concat "^" (regexp-quote directory
)) fname
)
2288 ;; We matched within FNAME's directory part.
2289 ;; Add the rest of FNAME onto ANCESTOR.
2290 (let ((rest (substring fname
(match-end 0))))
2291 (if (and (equal ancestor
".")
2292 (not (equal rest
"")))
2293 ;; But don't bother with ANCESTOR if it would give us `./'.
2295 (concat (file-name-as-directory ancestor
) rest
)))
2296 ;; We matched FNAME's directory equivalent.
2299 (defun save-buffer (&optional args
)
2300 "Save current buffer in visited file if modified. Versions described below.
2301 By default, makes the previous version into a backup file
2302 if previously requested or if this is the first save.
2303 With 1 \\[universal-argument], marks this version
2304 to become a backup when the next save is done.
2305 With 2 \\[universal-argument]'s,
2306 unconditionally makes the previous version into a backup file.
2307 With 3 \\[universal-argument]'s, marks this version
2308 to become a backup when the next save is done,
2309 and unconditionally makes the previous version into a backup file.
2311 With argument of 0, never make the previous version into a backup file.
2313 If a file's name is FOO, the names of its numbered backup versions are
2314 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2315 Numeric backups (rather than FOO~) will be made if value of
2316 `version-control' is not the atom `never' and either there are already
2317 numeric versions of the file being backed up, or `version-control' is
2319 We don't want excessive versions piling up, so there are variables
2320 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2321 and `kept-new-versions', which tells how many newest versions to keep.
2322 Defaults are 2 old versions and 2 new.
2323 `dired-kept-versions' controls dired's clean-directory (.) command.
2324 If `delete-old-versions' is nil, system will query user
2325 before trimming versions. Otherwise it does it silently.
2327 If `vc-make-backup-files' is nil, which is the default,
2328 no backup files are made for files managed by version control.
2329 (This is because the version control system itself records previous versions.)
2331 See the subroutine `basic-save-buffer' for more information."
2333 (let ((modp (buffer-modified-p))
2334 (large (> (buffer-size) 50000))
2335 (make-backup-files (or (and make-backup-files
(not (eq args
0)))
2336 (memq args
'(16 64)))))
2337 (and modp
(memq args
'(16 64)) (setq buffer-backed-up nil
))
2338 (if (and modp large
) (message "Saving file %s..." (buffer-file-name)))
2340 (and modp
(memq args
'(4 64)) (setq buffer-backed-up nil
))))
2342 (defun delete-auto-save-file-if-necessary (&optional force
)
2343 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2344 Normally delete only if the file was written by this Emacs since
2345 the last real save, but optional arg FORCE non-nil means delete anyway."
2346 (and buffer-auto-save-file-name delete-auto-save-files
2347 (not (string= buffer-file-name buffer-auto-save-file-name
))
2348 (or force
(recent-auto-save-p))
2351 (delete-file buffer-auto-save-file-name
)
2353 (set-buffer-auto-saved))))
2355 (defvar auto-save-hook nil
2356 "Normal hook run just before auto-saving.")
2358 (defvar after-save-hook nil
2359 "Normal hook that is run after a buffer is saved to its file.")
2361 (defvar save-buffer-coding-system nil
2362 "If non-nil, use this coding system for saving the buffer.
2363 More precisely, use this coding system in place of the
2364 value of `buffer-file-coding-system', when saving the buffer.
2365 Calling `write-region' for any purpose other than saving the buffer
2366 will still use `buffer-file-coding-system'; this variable has no effect
2369 (make-variable-buffer-local 'save-buffer-coding-system
)
2370 (put 'save-buffer-coding-system
'permanent-local t
)
2372 (defun basic-save-buffer ()
2373 "Save the current buffer in its visited file, if it has been modified.
2374 The hooks `write-contents-hooks', `local-write-file-hooks' and
2375 `write-file-hooks' get a chance to do the job of saving; if they do not,
2376 then the buffer is saved in the visited file file in the usual way.
2377 After saving the buffer, this function runs `after-save-hook'."
2379 (save-current-buffer
2380 ;; In an indirect buffer, save its base buffer instead.
2381 (if (buffer-base-buffer)
2382 (set-buffer (buffer-base-buffer)))
2383 (if (buffer-modified-p)
2384 (let ((recent-save (recent-auto-save-p))
2385 setmodes tempsetmodes
)
2386 ;; On VMS, rename file and buffer to get rid of version number.
2387 (if (and (eq system-type
'vax-vms
)
2388 (not (string= buffer-file-name
2389 (file-name-sans-versions buffer-file-name
))))
2390 (let (buffer-new-name)
2391 ;; Strip VMS version number before save.
2392 (setq buffer-file-name
2393 (file-name-sans-versions buffer-file-name
))
2394 ;; Construct a (unique) buffer name to correspond.
2395 (let ((buf (create-file-buffer (downcase buffer-file-name
))))
2396 (setq buffer-new-name
(buffer-name buf
))
2398 (rename-buffer buffer-new-name
)))
2399 ;; If buffer has no file name, ask user for one.
2400 (or buffer-file-name
2403 (read-file-name "File to save in: ") nil
)))
2404 (and (file-exists-p filename
)
2405 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2407 (error "Canceled")))
2408 (set-visited-file-name filename
)))
2409 (or (verify-visited-file-modtime (current-buffer))
2410 (not (file-exists-p buffer-file-name
))
2412 (format "%s has changed since visited or saved. Save anyway? "
2413 (file-name-nondirectory buffer-file-name
)))
2414 (error "Save not confirmed"))
2418 (and (> (point-max) 1)
2419 (/= (char-after (1- (point-max))) ?
\n)
2420 (not (and (eq selective-display t
)
2421 (= (char-after (1- (point-max))) ?
\r)))
2422 (or (eq require-final-newline t
)
2423 (and require-final-newline
2425 (format "Buffer %s does not end in newline. Add one? "
2428 (goto-char (point-max))
2430 (or (run-hook-with-args-until-success 'write-contents-hooks
)
2431 (run-hook-with-args-until-success 'local-write-file-hooks
)
2432 (run-hook-with-args-until-success 'write-file-hooks
)
2433 ;; If a hook returned t, file is already "written".
2434 ;; Otherwise, write it the usual way now.
2435 (setq setmodes
(basic-save-buffer-1)))
2436 ;; Now we have saved the current buffer. Let's make sure
2437 ;; that buffer-file-coding-system is fixed to what
2438 ;; actually used for saving by binding it locally.
2439 (if save-buffer-coding-system
2440 (setq save-buffer-coding-system last-coding-system-used
)
2441 (setq buffer-file-coding-system last-coding-system-used
))
2442 (setq buffer-file-number
2443 (nthcdr 10 (file-attributes buffer-file-name
)))
2446 (set-file-modes buffer-file-name setmodes
)
2448 ;; If the auto-save file was recent before this command,
2450 (delete-auto-save-file-if-necessary recent-save
)
2451 ;; Support VC `implicit' locking.
2453 (run-hooks 'after-save-hook
))
2454 (message "(No changes need to be saved)"))))
2456 ;; This does the "real job" of writing a buffer into its visited file
2457 ;; and making a backup file. This is what is normally done
2458 ;; but inhibited if one of write-file-hooks returns non-nil.
2459 ;; It returns a value to store in setmodes.
2460 (defun basic-save-buffer-1 ()
2461 (if save-buffer-coding-system
2462 (let ((coding-system-for-write save-buffer-coding-system
))
2463 (basic-save-buffer-2))
2464 (basic-save-buffer-2)))
2466 (defun basic-save-buffer-2 ()
2467 (let (tempsetmodes setmodes
)
2468 (if (not (file-writable-p buffer-file-name
))
2469 (let ((dir (file-name-directory buffer-file-name
)))
2470 (if (not (file-directory-p dir
))
2471 (if (file-exists-p dir
)
2472 (error "%s is not a directory" dir
)
2473 (error "%s: no such directory" buffer-file-name
))
2474 (if (not (file-exists-p buffer-file-name
))
2475 (error "Directory %s write-protected" dir
)
2477 (format "File %s is write-protected; try to save anyway? "
2478 (file-name-nondirectory
2480 (setq tempsetmodes t
)
2481 (error "Attempt to save to a file which you aren't allowed to write"))))))
2482 (or buffer-backed-up
2483 (setq setmodes
(backup-buffer)))
2484 (let ((dir (file-name-directory buffer-file-name
)))
2485 (if (and file-precious-flag
2486 (file-writable-p dir
))
2487 ;; If file is precious, write temp name, then rename it.
2488 ;; This requires write access to the containing dir,
2489 ;; which is why we don't try it if we don't have that access.
2490 (let ((realname buffer-file-name
)
2491 tempname temp nogood i succeed
2492 (old-modtime (visited-file-modtime)))
2495 ;; Find the temporary name to write under.
2497 (setq tempname
(format
2498 (if (and (eq system-type
'ms-dos
)
2499 (not (msdos-long-file-names)))
2500 "%s#%d.tm#" ; MSDOS limits files to 8+3
2503 (setq nogood
(file-exists-p tempname
))
2506 (progn (clear-visited-file-modtime)
2507 (write-region (point-min) (point-max)
2508 tempname nil realname
2509 buffer-file-truename
)
2511 ;; If writing the temp file fails,
2512 ;; delete the temp file.
2515 (delete-file tempname
)
2516 (set-visited-file-modtime old-modtime
))))
2517 ;; Since we have created an entirely new file
2518 ;; and renamed it, make sure it gets the
2519 ;; right permission bits set.
2520 (setq setmodes
(file-modes buffer-file-name
))
2521 ;; We succeeded in writing the temp file,
2523 (rename-file tempname buffer-file-name t
))
2524 ;; If file not writable, see if we can make it writable
2525 ;; temporarily while we write it.
2526 ;; But no need to do so if we have just backed it up
2527 ;; (setmodes is set) because that says we're superseding.
2528 (cond ((and tempsetmodes
(not setmodes
))
2529 ;; Change the mode back, after writing.
2530 (setq setmodes
(file-modes buffer-file-name
))
2531 (set-file-modes buffer-file-name
511)))
2532 (write-region (point-min) (point-max)
2533 buffer-file-name nil t buffer-file-truename
)))
2536 (defun save-some-buffers (&optional arg pred
)
2537 "Save some modified file-visiting buffers. Asks user about each one.
2538 Optional argument (the prefix) non-nil means save all with no questions.
2539 Optional second argument PRED determines which buffers are considered:
2540 If PRED is nil, all the file-visiting buffers are considered.
2541 If PRED is t, then certain non-file buffers will also be considered.
2542 If PRED is a zero-argument function, it indicates for each buffer whether
2543 to consider it or not."
2545 (save-window-excursion
2546 (let* ((queried nil
)
2551 (and (buffer-modified-p buffer
)
2552 (not (buffer-base-buffer buffer
))
2554 (buffer-file-name buffer
)
2558 (and buffer-offer-save
(> (buffer-size) 0)))))
2559 (or (not (functionp pred
))
2560 (with-current-buffer buffer
(funcall pred
)))
2564 (if (buffer-file-name buffer
)
2565 (format "Save file %s? "
2566 (buffer-file-name buffer
))
2567 (format "Save buffer %s? "
2568 (buffer-name buffer
)))))))
2574 '("buffer" "buffers" "save")
2575 (list (list ?\C-r
(lambda (buf)
2579 (exit-recursive-edit))))
2581 ;; Return nil to ask about BUF again.
2583 "display the current buffer"))))
2585 (and save-abbrevs abbrevs-changed
2588 (y-or-n-p (format "Save abbrevs in %s? "
2590 (write-abbrev-file nil
))
2591 ;; Don't keep bothering user if he says no.
2592 (setq abbrevs-changed nil
)
2594 (or queried
(> files-done
0) abbrevs-done
2595 (message "(No files need saving)")))))
2597 (defun not-modified (&optional arg
)
2598 "Mark current buffer as unmodified, not needing to be saved.
2599 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2601 It is not a good idea to use this function in Lisp programs, because it
2602 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2604 (message (if arg
"Modification-flag set"
2605 "Modification-flag cleared"))
2606 (set-buffer-modified-p arg
))
2608 (defun toggle-read-only (&optional arg
)
2609 "Change whether this buffer is visiting its file read-only.
2610 With arg, set read-only iff arg is positive.
2611 If visiting file read-only and `view-read-only' is non-nil, enter view mode."
2614 ((and arg
(if (> (prefix-numeric-value arg
) 0) buffer-read-only
2615 (not buffer-read-only
))) ; If buffer-read-only is set correctly,
2618 ((and buffer-read-only view-mode
)
2619 (View-exit-and-edit)
2620 (make-local-variable 'view-read-only
)
2621 (setq view-read-only t
)) ; Must leave view mode.
2622 ((and (not buffer-read-only
) view-read-only
2623 (not (eq (get major-mode
'mode-class
) 'special
)))
2625 (t (setq buffer-read-only
(not buffer-read-only
))
2626 (force-mode-line-update))))
2628 (defun insert-file (filename)
2629 "Insert contents of file FILENAME into buffer after point.
2630 Set mark after the inserted text.
2632 This function is meant for the user to run interactively.
2633 Don't call it from programs! Use `insert-file-contents' instead.
2634 \(Its calling sequence is different; see its documentation)."
2635 (interactive "*fInsert file: ")
2636 (if (file-directory-p filename
)
2637 (signal 'file-error
(list "Opening input file" "file is a directory"
2639 (let ((tem (insert-file-contents filename
)))
2640 (push-mark (+ (point) (car (cdr tem
))))))
2642 (defun append-to-file (start end filename
)
2643 "Append the contents of the region to the end of file FILENAME.
2644 When called from a function, expects three arguments,
2645 START, END and FILENAME. START and END are buffer positions
2646 saying what text to write."
2647 (interactive "r\nFAppend to file: ")
2648 (write-region start end filename t
))
2650 (defun file-newest-backup (filename)
2651 "Return most recent backup file for FILENAME or nil if no backups exist."
2652 (let* ((filename (expand-file-name filename
))
2653 (file (file-name-nondirectory filename
))
2654 (dir (file-name-directory filename
))
2655 (comp (file-name-all-completions file dir
))
2659 (setq tem
(car comp
)
2661 (cond ((and (backup-file-name-p tem
)
2662 (string= (file-name-sans-versions tem
) file
))
2663 (setq tem
(concat dir tem
))
2664 (if (or (null newest
)
2665 (file-newer-than-file-p tem newest
))
2666 (setq newest tem
)))))
2669 (defun rename-uniquely ()
2670 "Rename current buffer to a similar name not already taken.
2671 This function is useful for creating multiple shell process buffers
2672 or multiple mail buffers, etc."
2675 (let ((base-name (buffer-name)))
2676 (and (string-match "<[0-9]+>\\'" base-name
)
2677 (not (and buffer-file-name
2679 (file-name-nondirectory buffer-file-name
))))
2680 ;; If the existing buffer name has a <NNN>,
2681 ;; which isn't part of the file name (if any),
2682 ;; then get rid of that.
2683 (setq base-name
(substring base-name
0 (match-beginning 0))))
2684 (rename-buffer (generate-new-buffer-name base-name
))
2685 (force-mode-line-update))))
2687 (defun make-directory (dir &optional parents
)
2688 "Create the directory DIR and any nonexistent parent dirs.
2689 Interactively, the default choice of directory to create
2690 is the current default directory for file names.
2691 That is useful when you have visited a file in a nonexistent directory.
2693 Noninteractively, the second (optional) argument PARENTS says whether
2694 to create parent directories if they don't exist."
2696 (list (read-file-name "Make directory: " default-directory default-directory
2699 (let ((handler (find-file-name-handler dir
'make-directory
)))
2701 (funcall handler
'make-directory dir parents
)
2703 (make-directory-internal dir
)
2704 (let ((dir (directory-file-name (expand-file-name dir
)))
2706 (while (not (file-exists-p dir
))
2707 (setq create-list
(cons dir create-list
)
2708 dir
(directory-file-name (file-name-directory dir
))))
2710 (make-directory-internal (car create-list
))
2711 (setq create-list
(cdr create-list
))))))))
2713 (put 'revert-buffer-function
'permanent-local t
)
2714 (defvar revert-buffer-function nil
2715 "Function to use to revert this buffer, or nil to do the default.
2716 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2717 which are the arguments that `revert-buffer' received.")
2719 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
2720 (defvar revert-buffer-insert-file-contents-function nil
2721 "Function to use to insert contents when reverting this buffer.
2722 Gets two args, first the nominal file name to use,
2723 and second, t if reading the auto-save file.
2725 The function you specify is responsible for updating (or preserving) point.")
2727 (defvar before-revert-hook nil
2728 "Normal hook for `revert-buffer' to run before reverting.
2729 If `revert-buffer-function' is used to override the normal revert
2730 mechanism, this hook is not used.")
2732 (defvar after-revert-hook nil
2733 "Normal hook for `revert-buffer' to run after reverting.
2734 Note that the hook value that it runs is the value that was in effect
2735 before reverting; that makes a difference if you have buffer-local
2738 If `revert-buffer-function' is used to override the normal revert
2739 mechanism, this hook is not used.")
2741 (defvar revert-buffer-internal-hook
)
2743 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes
)
2744 "Replace current buffer text with the text of the visited file on disk.
2745 This undoes all changes since the file was visited or saved.
2746 With a prefix argument, offer to revert from latest auto-save file, if
2747 that is more recent than the visited file.
2749 This command also works for special buffers that contain text which
2750 doesn't come from a file, but reflects some other data base instead:
2751 for example, Dired buffers and buffer-list buffers. In these cases,
2752 it reconstructs the buffer contents from the appropriate data base.
2754 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2755 to revert from the auto-save file when this is nil. Note that the
2756 sense of this argument is the reverse of the prefix argument, for the
2757 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2760 Optional second argument NOCONFIRM means don't ask for confirmation at
2761 all. (The local variable `revert-without-query', if non-nil, prevents
2764 Optional third argument PRESERVE-MODES non-nil means don't alter
2765 the files modes. Normally we reinitialize them using `normal-mode'.
2767 If the value of `revert-buffer-function' is non-nil, it is called to
2768 do all the work for this command. Otherwise, the hooks
2769 `before-revert-hook' and `after-revert-hook' are run at the beginning
2770 and the end, and if `revert-buffer-insert-file-contents-function' is
2771 non-nil, it is called instead of rereading visited file contents."
2773 ;; I admit it's odd to reverse the sense of the prefix argument, but
2774 ;; there is a lot of code out there which assumes that the first
2775 ;; argument should be t to avoid consulting the auto-save file, and
2776 ;; there's no straightforward way to encourage authors to notice a
2777 ;; reversal of the argument sense. So I'm just changing the user
2778 ;; interface, but leaving the programmatic interface the same.
2779 (interactive (list (not current-prefix-arg
)))
2780 (if revert-buffer-function
2781 (funcall revert-buffer-function ignore-auto noconfirm
)
2782 (let* ((auto-save-p (and (not ignore-auto
)
2783 (recent-auto-save-p)
2784 buffer-auto-save-file-name
2785 (file-readable-p buffer-auto-save-file-name
)
2787 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2788 (file-name (if auto-save-p
2789 buffer-auto-save-file-name
2791 (cond ((null file-name
)
2792 (error "Buffer does not seem to be associated with any file"))
2794 (and (not (buffer-modified-p))
2795 (let ((tail revert-without-query
)
2798 (if (string-match (car tail
) file-name
)
2800 (setq tail
(cdr tail
)))
2802 (yes-or-no-p (format "Revert buffer from file %s? "
2804 (run-hooks 'before-revert-hook
)
2805 ;; If file was backed up but has changed since,
2806 ;; we shd make another backup.
2807 (and (not auto-save-p
)
2808 (not (verify-visited-file-modtime (current-buffer)))
2809 (setq buffer-backed-up nil
))
2810 ;; Get rid of all undo records for this buffer.
2811 (or (eq buffer-undo-list t
)
2812 (setq buffer-undo-list nil
))
2813 ;; Effectively copy the after-revert-hook status,
2814 ;; since after-find-file will clobber it.
2815 (let ((global-hook (default-value 'after-revert-hook
))
2816 (local-hook-p (local-variable-p 'after-revert-hook
))
2817 (local-hook (and (local-variable-p 'after-revert-hook
)
2818 after-revert-hook
)))
2819 (let (buffer-read-only
2820 ;; Don't make undo records for the reversion.
2821 (buffer-undo-list t
))
2822 (if revert-buffer-insert-file-contents-function
2823 (funcall revert-buffer-insert-file-contents-function
2824 file-name auto-save-p
)
2825 (if (not (file-exists-p file-name
))
2826 (error "File %s no longer exists!" file-name
))
2827 ;; Bind buffer-file-name to nil
2828 ;; so that we don't try to lock the file.
2829 (let ((buffer-file-name nil
))
2833 (let ((coding-system-for-read
2834 ;; Auto-saved file shoule be read without
2835 ;; any code conversion.
2836 (if auto-save-p
'no-conversion
2837 coding-system-for-read
)))
2838 ;; Note that this preserves point in an intelligent way.
2839 (insert-file-contents file-name
(not auto-save-p
)
2841 ;; Recompute the truename in case changes in symlinks
2842 ;; have changed the truename.
2843 (setq buffer-file-truename
2844 (abbreviate-file-name (file-truename buffer-file-name
)))
2845 (after-find-file nil nil t t preserve-modes
)
2846 ;; Run after-revert-hook as it was before we reverted.
2847 (setq-default revert-buffer-internal-hook global-hook
)
2850 (make-local-variable 'revert-buffer-internal-hook
)
2851 (setq revert-buffer-internal-hook local-hook
))
2852 (kill-local-variable 'revert-buffer-internal-hook
))
2853 (run-hooks 'revert-buffer-internal-hook
))
2856 (defun recover-file (file)
2857 "Visit file FILE, but get contents from its last auto-save file."
2858 ;; Actually putting the file name in the minibuffer should be used
2860 ;; Not just because users often use the default.
2861 (interactive "FRecover file: ")
2862 (setq file
(expand-file-name file
))
2863 (if (auto-save-file-name-p (file-name-nondirectory file
))
2864 (error "%s is an auto-save file" file
))
2865 (let ((file-name (let ((buffer-file-name file
))
2866 (make-auto-save-file-name))))
2867 (cond ((if (file-exists-p file
)
2868 (not (file-newer-than-file-p file-name file
))
2869 (not (file-exists-p file-name
)))
2870 (error "Auto-save file %s not current" file-name
))
2871 ((save-window-excursion
2872 (if (not (memq system-type
'(vax-vms windows-nt
)))
2873 (with-output-to-temp-buffer "*Directory*"
2874 (buffer-disable-undo standard-output
)
2875 (call-process "ls" nil standard-output nil
2876 (if (file-symlink-p file
) "-lL" "-l")
2878 (yes-or-no-p (format "Recover auto save file %s? " file-name
)))
2879 (switch-to-buffer (find-file-noselect file t
))
2880 (let ((buffer-read-only nil
)
2881 ;; Keep the current buffer-file-coding-system.
2882 (coding-system buffer-file-coding-system
)
2883 ;; Auto-saved file shoule be read without any code conversion.
2884 (coding-system-for-read 'no-conversion
))
2886 (insert-file-contents file-name nil
)
2887 (set-buffer-file-coding-system coding-system
))
2888 (after-find-file nil nil t
))
2889 (t (error "Recover-file cancelled")))))
2891 (defun recover-session ()
2892 "Recover auto save files from a previous Emacs session.
2893 This command first displays a Dired buffer showing you the
2894 previous sessions that you could recover from.
2895 To choose one, move point to the proper line and then type C-c C-c.
2896 Then you'll be asked about a number of files to recover."
2898 (if (null auto-save-list-file-prefix
)
2899 (error "You set `auto-save-list-file-prefix' to disable making session files"))
2900 (let ((ls-lisp-support-shell-wildcards t
))
2901 (dired (concat auto-save-list-file-prefix
"*")
2902 (concat dired-listing-switches
"t")))
2904 (goto-char (point-min))
2905 (or (looking-at " Move to the session you want to recover,")
2906 (let ((inhibit-read-only t
))
2907 ;; Each line starts with a space
2908 ;; so that Font Lock mode won't highlight the first character.
2909 (insert " Move to the session you want to recover,\n"
2910 " then type C-c C-c to select it.\n\n"
2911 " You can also delete some of these files;\n"
2912 " type d on a line to mark that file for deletion.\n\n"))))
2913 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2914 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish
))
2916 (defun recover-session-finish ()
2917 "Choose one saved session to recover auto-save files from.
2918 This command is used in the special Dired buffer created by
2919 \\[recover-session]."
2921 ;; Get the name of the session file to recover from.
2922 (let ((file (dired-get-filename))
2924 (buffer (get-buffer-create " *recover*")))
2926 (dired-do-flagged-delete t
)
2929 ;; Read in the auto-save-list file.
2932 (insert-file-contents file
)
2933 ;; Loop thru the text of that file
2934 ;; and get out the names of the files to recover.
2936 (let (thisfile autofile
)
2938 ;; This is a pair of lines for a non-file-visiting buffer.
2939 ;; Get the auto-save file name and manufacture
2940 ;; a "visited file name" from that.
2944 (buffer-substring-no-properties
2952 (file-name-nondirectory autofile
)
2954 (file-name-directory autofile
)))
2956 ;; This pair of lines is a file-visiting
2957 ;; buffer. Use the visited file name.
2960 (buffer-substring-no-properties
2961 (point) (progn (end-of-line) (point))))
2964 (buffer-substring-no-properties
2965 (point) (progn (end-of-line) (point))))
2967 ;; Ignore a file if its auto-save file does not exist now.
2968 (if (file-exists-p autofile
)
2969 (setq files
(cons thisfile files
)))))
2970 (setq files
(nreverse files
))
2971 ;; The file contains a pair of line for each auto-saved buffer.
2972 ;; The first line of the pair contains the visited file name
2973 ;; or is empty if the buffer was not visiting a file.
2974 ;; The second line is the auto-save file name.
2976 (map-y-or-n-p "Recover %s? "
2979 (save-excursion (recover-file file
))
2981 "Failed to recover `%s'" file
)))
2983 '("file" "files" "recover"))
2984 (message "No files can be recovered from this session now")))
2985 (kill-buffer buffer
))))
2987 (defun kill-some-buffers (&optional list
)
2988 "For each buffer in LIST, ask whether to kill it.
2989 LIST defaults to all existing live buffers."
2992 (setq list
(buffer-list)))
2994 (let* ((buffer (car list
))
2995 (name (buffer-name buffer
)))
2996 (and (not (string-equal name
""))
2997 (/= (aref name
0) ?
)
2999 (format "Buffer %s %s. Kill? "
3001 (if (buffer-modified-p buffer
)
3002 "HAS BEEN EDITED" "is unmodified")))
3003 (kill-buffer buffer
)))
3004 (setq list
(cdr list
))))
3006 (defun auto-save-mode (arg)
3007 "Toggle auto-saving of contents of current buffer.
3008 With prefix argument ARG, turn auto-saving on if positive, else off."
3010 (setq buffer-auto-save-file-name
3012 (or (not buffer-auto-save-file-name
)
3013 ;; If auto-save is off because buffer has shrunk,
3014 ;; then toggling should turn it on.
3015 (< buffer-saved-size
0))
3016 (or (eq arg t
) (listp arg
) (and (integerp arg
) (> arg
0))))
3017 (if (and buffer-file-name auto-save-visited-file-name
3018 (not buffer-read-only
))
3020 (make-auto-save-file-name))))
3021 ;; If -1 was stored here, to temporarily turn off saving,
3023 (and (< buffer-saved-size
0)
3024 (setq buffer-saved-size
0))
3026 (message "Auto-save %s (in this buffer)"
3027 (if buffer-auto-save-file-name
"on" "off")))
3028 buffer-auto-save-file-name
)
3030 (defun rename-auto-save-file ()
3031 "Adjust current buffer's auto save file name for current conditions.
3032 Also rename any existing auto save file, if it was made in this session."
3033 (let ((osave buffer-auto-save-file-name
))
3034 (setq buffer-auto-save-file-name
3035 (make-auto-save-file-name))
3036 (if (and osave buffer-auto-save-file-name
3037 (not (string= buffer-auto-save-file-name buffer-file-name
))
3038 (not (string= buffer-auto-save-file-name osave
))
3039 (file-exists-p osave
)
3040 (recent-auto-save-p))
3041 (rename-file osave buffer-auto-save-file-name t
))))
3043 (defun make-auto-save-file-name ()
3044 "Return file name to use for auto-saves of current buffer.
3045 Does not consider `auto-save-visited-file-name' as that variable is checked
3046 before calling this function. You can redefine this for customization.
3047 See also `auto-save-file-name-p'."
3048 (if buffer-file-name
3049 (if (and (eq system-type
'ms-dos
)
3050 (not (msdos-long-file-names)))
3051 (let ((fn (file-name-nondirectory buffer-file-name
)))
3052 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn
)
3053 (concat (file-name-directory buffer-file-name
)
3054 "#" (match-string 1 fn
)
3055 "." (match-string 3 fn
) "#"))
3056 (concat (file-name-directory buffer-file-name
)
3058 (file-name-nondirectory buffer-file-name
)
3061 ;; Deal with buffers that don't have any associated files. (Mail
3062 ;; mode tends to create a good number of these.)
3064 (let ((buffer-name (buffer-name))
3066 ;; Eliminate all slashes and backslashes by
3067 ;; replacing them with sequences that start with %.
3068 ;; Quote % also, to keep distinct names distinct.
3069 (while (string-match "[/\\%]" buffer-name limit
)
3070 (let* ((character (aref buffer-name
(match-beginning 0)))
3072 (cond ((eq character ?%
) "%%")
3073 ((eq character ?
/) "%+")
3074 ((eq character ?
\\) "%-"))))
3075 (setq buffer-name
(replace-match replacement t t buffer-name
))
3076 (setq limit
(1+ (match-end 0)))))
3077 ;; Generate the file name.
3079 (format "#%s#%s#" buffer-name
(make-temp-name ""))
3080 ;; Try a few alternative directories, to get one we can write it.
3082 ((file-writable-p default-directory
) default-directory
)
3083 ((file-writable-p "/var/tmp/") "/var/tmp/")
3086 (defun auto-save-file-name-p (filename)
3087 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
3088 FILENAME should lack slashes. You can redefine this for customization."
3089 (string-match "^#.*#$" filename
))
3091 (defun wildcard-to-regexp (wildcard)
3092 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
3093 The generated regexp will match a filename iff the filename
3094 matches that wildcard according to shell rules. Only wildcards known
3095 by `sh' are supported."
3096 (let* ((i (string-match "[[.*+\\^$?]" wildcard
))
3097 ;; Copy the initial run of non-special characters.
3098 (result (substring wildcard
0 i
))
3099 (len (length wildcard
)))
3100 ;; If no special characters, we're almost done.
3103 (let ((ch (aref wildcard i
))
3111 (eq (aref wildcard
(1+ i
)) ?\
]))
3113 ((eq ch ?\
[) ; [...] maps to regexp char class
3118 ((eq (aref wildcard i
) ?
!) ; [!...] -> [^...]
3121 (if (eq (aref wildcard i
) ?\
])
3126 ((eq (aref wildcard i
) ?^
)
3127 ;; Found "[^". Insert a `\0' character
3128 ;; (which cannot happen in a filename)
3129 ;; into the character class, so that `^'
3130 ;; is not the first character after `[',
3131 ;; and thus non-special in a regexp.
3135 ((eq (aref wildcard i
) ?\
])
3136 ;; I don't think `]' can appear in a
3137 ;; character class in a wildcard, but
3138 ;; let's be general here.
3143 (prog1 ; copy everything upto next `]'.
3146 (setq j
(string-match
3148 (setq i
(if j
(1- j
) (1- len
)))))))
3150 ((eq ch ?
*) "[^\000]*")
3154 ((eq ch ?
\\) "\\\\") ; probably cannot happen...
3155 ((eq ch ??
) "[^\000]")
3156 (t (char-to-string ch
)))))
3158 ;; Shell wildcards should match the entire filename,
3159 ;; not its part. Make the regexp say so.
3160 (concat "\\`" result
"\\'")))
3162 (defcustom list-directory-brief-switches
3163 (if (eq system-type
'vax-vms
) "" "-CF")
3164 "*Switches for list-directory to pass to `ls' for brief listing,"
3168 (defcustom list-directory-verbose-switches
3169 (if (eq system-type
'vax-vms
)
3170 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
3172 "*Switches for list-directory to pass to `ls' for verbose listing,"
3176 (defun file-expand-wildcards (pattern &optional full
)
3177 "Expand wildcard pattern PATTERN.
3178 This returns a list of file names which match the pattern.
3180 If PATTERN is written as an absolute relative file name,
3181 the values are absolute also.
3183 If PATTERN is written as a relative file name, it is interpreted
3184 relative to the current default directory, `default-directory'.
3185 The file names returned are normally also relative to the current
3186 default directory. However, if FULL is non-nil, they are absolute."
3187 (let* ((nondir (file-name-nondirectory pattern
))
3188 (dirpart (file-name-directory pattern
))
3189 ;; A list of all dirs that DIRPART specifies.
3190 ;; This can be more than one dir
3191 ;; if DIRPART contains wildcards.
3192 (dirs (if (and dirpart
(string-match "[[*?]" dirpart
))
3193 (mapcar 'file-name-as-directory
3194 (file-expand-wildcards (directory-file-name dirpart
)))
3198 (when (or (null (car dirs
)) ; Possible if DIRPART is not wild.
3199 (file-directory-p (directory-file-name (car dirs
))))
3200 (let ((this-dir-contents
3201 ;; Filter out "." and ".."
3203 (mapcar #'(lambda (name)
3204 (unless (string-match "\\`\\.\\.?\\'"
3205 (file-name-nondirectory name
))
3207 (directory-files (or (car dirs
) ".") full
3208 (wildcard-to-regexp nondir
))))))
3211 (if (and (car dirs
) (not full
))
3212 (mapcar (function (lambda (name) (concat (car dirs
) name
)))
3216 (setq dirs
(cdr dirs
)))
3219 (defun list-directory (dirname &optional verbose
)
3220 "Display a list of files in or matching DIRNAME, a la `ls'.
3221 DIRNAME is globbed by the shell if necessary.
3222 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
3223 Actions controlled by variables `list-directory-brief-switches'
3224 and `list-directory-verbose-switches'."
3225 (interactive (let ((pfx current-prefix-arg
))
3226 (list (read-file-name (if pfx
"List directory (verbose): "
3227 "List directory (brief): ")
3228 nil default-directory nil
)
3230 (let ((switches (if verbose list-directory-verbose-switches
3231 list-directory-brief-switches
)))
3232 (or dirname
(setq dirname default-directory
))
3233 (setq dirname
(expand-file-name dirname
))
3234 (with-output-to-temp-buffer "*Directory*"
3235 (buffer-disable-undo standard-output
)
3236 (princ "Directory ")
3240 (set-buffer "*Directory*")
3241 (setq default-directory
3242 (if (file-directory-p dirname
)
3243 (file-name-as-directory dirname
)
3244 (file-name-directory dirname
)))
3245 (let ((wildcard (not (file-directory-p dirname
))))
3246 (insert-directory dirname switches wildcard
(not wildcard
)))))))
3248 (defvar insert-directory-program
"ls"
3249 "Absolute or relative name of the `ls' program used by `insert-directory'.")
3252 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3253 ;; FULL-DIRECTORY-P is nil.
3254 ;; The single line of output must display FILE's name as it was
3255 ;; given, namely, an absolute path name.
3256 ;; - must insert exactly one line for each file if WILDCARD or
3257 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
3258 ;; before the file lines, plus optional text after the file lines.
3259 ;; Lines are delimited by "\n", so filenames containing "\n" are not
3261 ;; File lines should display the basename.
3262 ;; - must be consistent with
3263 ;; - functions dired-move-to-filename, (these two define what a file line is)
3264 ;; dired-move-to-end-of-filename,
3265 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
3266 ;; dired-insert-headerline
3267 ;; dired-after-subdir-garbage (defines what a "total" line is)
3268 ;; - variable dired-subdir-regexp
3269 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
3270 "Insert directory listing for FILE, formatted according to SWITCHES.
3271 Leaves point after the inserted text.
3272 SWITCHES may be a string of options, or a list of strings.
3273 Optional third arg WILDCARD means treat FILE as shell wildcard.
3274 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3275 switches do not contain `d', so that a full listing is expected.
3277 This works by running a directory listing program
3278 whose name is in the variable `insert-directory-program'.
3279 If WILDCARD, it also runs the shell specified by `shell-file-name'."
3280 ;; We need the directory in order to find the right handler.
3281 (let ((handler (find-file-name-handler (expand-file-name file
)
3282 'insert-directory
)))
3284 (funcall handler
'insert-directory file switches
3285 wildcard full-directory-p
)
3286 (if (eq system-type
'vax-vms
)
3287 (vms-read-directory file switches
(current-buffer))
3288 (let* ((coding-system-for-read
3289 (and enable-multibyte-characters
3290 (or file-name-coding-system
3291 default-file-name-coding-system
)))
3292 ;; This is to control encoding the arguments in call-process.
3293 (coding-system-for-write coding-system-for-read
)
3296 ;; Run ls in the directory of the file pattern we asked for.
3297 (let ((default-directory
3298 (if (file-name-absolute-p file
)
3299 (file-name-directory file
)
3300 (file-name-directory (expand-file-name file
))))
3301 (pattern (file-name-nondirectory file
))
3303 ;; Quote some characters that have special meanings in shells;
3304 ;; but don't quote the wildcards--we want them to be special.
3305 ;; We also currently don't quote the quoting characters
3306 ;; in case people want to use them explicitly to quote
3307 ;; wildcard characters.
3308 (while (string-match "[ \t\n;<>&|()#$]" pattern beg
)
3310 (concat (substring pattern
0 (match-beginning 0))
3312 (substring pattern
(match-beginning 0)))
3313 beg
(1+ (match-end 0))))
3314 (call-process shell-file-name nil t nil
3315 "-c" (concat "\\";; Disregard shell aliases!
3316 insert-directory-program
3318 (if (stringp switches
)
3320 (mapconcat 'identity switches
" "))
3323 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3324 ;; directory if FILE is a symbolic link.
3325 (apply 'call-process
3326 insert-directory-program nil t nil
3328 (if (listp switches
)
3329 (setq list switches
)
3330 (if (not (equal switches
""))
3332 ;; Split the switches at any spaces
3333 ;; so we can pass separate options as separate args.
3334 (while (string-match " " switches
)
3335 (setq list
(cons (substring switches
0 (match-beginning 0))
3337 switches
(substring switches
(match-end 0))))
3338 (setq list
(nreverse (cons switches list
))))))
3340 ;; Avoid lossage if FILE starts with `-'.
3343 (if (string-match "\\`~" file
)
3344 (setq file
(expand-file-name file
)))
3346 (if full-directory-p
3347 (concat (file-name-as-directory file
) ".")
3350 ;; We get here if ls failed.
3351 ;; Access the file to get a suitable error.
3352 (access-file file
"Reading directory")))))))
3354 (defvar kill-emacs-query-functions nil
3355 "Functions to call with no arguments to query about killing Emacs.
3356 If any of these functions returns nil, killing Emacs is cancelled.
3357 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3358 but `kill-emacs', the low level primitive, does not.
3359 See also `kill-emacs-hook'.")
3361 (defun save-buffers-kill-emacs (&optional arg
)
3362 "Offer to save each buffer, then kill this Emacs process.
3363 With prefix arg, silently save all file-visiting buffers, then kill."
3365 (save-some-buffers arg t
)
3366 (and (or (not (memq t
(mapcar (function
3367 (lambda (buf) (and (buffer-file-name buf
)
3368 (buffer-modified-p buf
))))
3370 (yes-or-no-p "Modified buffers exist; exit anyway? "))
3371 (or (not (fboundp 'process-list
))
3372 ;; process-list is not defined on VMS.
3373 (let ((processes (process-list))
3376 (and (memq (process-status (car processes
)) '(run stop open
))
3377 (let ((val (process-kill-without-query (car processes
))))
3378 (process-kill-without-query (car processes
) val
)
3381 (setq processes
(cdr processes
)))
3384 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
3385 ;; Query the user for other things, perhaps.
3386 (run-hook-with-args-until-failure 'kill-emacs-query-functions
)
3389 ;; We use /: as a prefix to "quote" a file name
3390 ;; so that magic file name handlers will not apply to it.
3392 (setq file-name-handler-alist
3393 (cons '("\\`/:" . file-name-non-special
)
3394 file-name-handler-alist
))
3396 ;; We depend on being the last handler on the list,
3397 ;; so that anything else which does need handling
3398 ;; has been handled already.
3399 ;; So it is safe for us to inhibit *all* magic file name handlers.
3401 (defun file-name-non-special (operation &rest arguments
)
3402 (let ((file-name-handler-alist nil
)
3404 (if (eq operation
'insert-directory
)
3405 (directory-file-name
3407 (unhandled-file-name-directory default-directory
)))
3409 ;; Get a list of the indices of the args which are file names.
3411 (cdr (or (assq operation
3412 ;; The first four are special because they
3413 ;; return a file name. We want to include the /:
3414 ;; in the return value.
3415 ;; So just avoid stripping it in the first place.
3416 '((expand-file-name . nil
)
3417 ;; `identity' means just return the first arg
3418 ;; as stripped of its quoting.
3419 (substitute-in-file-name . identity
)
3420 (file-name-directory . nil
)
3421 (file-name-as-directory . nil
)
3422 (directory-file-name . nil
)
3423 (file-name-completion 0 1)
3424 (file-name-all-completions 0 1)
3427 (make-symbolic-link 0 1)
3428 (add-name-to-file 0 1)))
3429 ;; For all other operations, treat the first argument only
3430 ;; as the file name.
3432 ;; Copy ARGUMENTS so we can replace elements in it.
3433 (arguments (copy-sequence arguments
)))
3434 ;; Strip off the /: from the file names that have this handler.
3436 (while (consp file-arg-indices
)
3437 (let ((pair (nthcdr (car file-arg-indices
) arguments
)))
3439 (string-match "\\`/:" (car pair
))
3441 (if (= (length (car pair
)) 2)
3443 (substring (car pair
) 2)))))
3444 (setq file-arg-indices
(cdr file-arg-indices
))))
3445 (if (eq file-arg-indices
'identity
)
3447 (apply operation arguments
))))
3449 (define-key ctl-x-map
"\C-f" 'find-file
)
3450 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
3451 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
3452 (define-key ctl-x-map
"\C-s" 'save-buffer
)
3453 (define-key ctl-x-map
"s" 'save-some-buffers
)
3454 (define-key ctl-x-map
"\C-w" 'write-file
)
3455 (define-key ctl-x-map
"i" 'insert-file
)
3456 (define-key esc-map
"~" 'not-modified
)
3457 (define-key ctl-x-map
"\C-d" 'list-directory
)
3458 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-emacs
)
3460 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
3461 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
3462 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
3463 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
3464 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
3466 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
3467 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
3468 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
3469 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
3471 ;;; files.el ends here