1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 93,
4 ;; 94, 95, 1996 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.
33 (defconst delete-auto-save-files t
34 "*Non-nil means delete auto-save file when a buffer is saved or killed.")
36 (defconst directory-abbrev-alist
38 "*Alist of abbreviations for file directories.
39 A list of elements of the form (FROM . TO), each meaning to replace
40 FROM with TO when it appears in a directory name. This replacement is
41 done when setting up the default directory of a newly visited file.
42 *Every* FROM string should start with `^'.
44 Do not use `~' in the TO strings.
45 They should be ordinary absolute directory names.
47 Use this feature when you have directories which you normally refer to
48 via absolute symbolic links. Make TO the name of the link, and FROM
49 the name it is linked to.")
51 ;;; Turn off backup files on VMS since it has version numbers.
52 (defconst make-backup-files
(not (eq system-type
'vax-vms
))
53 "*Non-nil means make a backup of a file the first time it is saved.
54 This can be done by renaming the file or by copying.
56 Renaming means that Emacs renames the existing file so that it is a
57 backup file, then writes the buffer into a new file. Any other names
58 that the old file had will now refer to the backup file. The new file
59 is owned by you and its group is defaulted.
61 Copying means that Emacs copies the existing file into the backup
62 file, then writes the buffer on top of the existing file. Any other
63 names that the old file had will now refer to the new (edited) file.
64 The file's owner and group are unchanged.
66 The choice of renaming or copying is controlled by the variables
67 `backup-by-copying', `backup-by-copying-when-linked' and
68 `backup-by-copying-when-mismatch'. See also `backup-inhibited'.")
70 ;; Do this so that local variables based on the file name
71 ;; are not overridden by the major mode.
72 (defvar backup-inhibited nil
73 "Non-nil means don't make a backup, regardless of the other parameters.
74 This variable is intended for use by making it local to a buffer.
75 But it is local only if you make it local.")
76 (put 'backup-inhibited
'permanent-local t
)
78 (defconst backup-by-copying nil
79 "*Non-nil means always use copying to create backup files.
80 See documentation of variable `make-backup-files'.")
82 (defconst backup-by-copying-when-linked nil
83 "*Non-nil means use copying to create backups for files with multiple names.
84 This causes the alternate names to refer to the latest version as edited.
85 This variable is relevant only if `backup-by-copying' is nil.")
87 (defconst backup-by-copying-when-mismatch nil
88 "*Non-nil means create backups by copying if this preserves owner or group.
89 Renaming may still be used (subject to control of other variables)
90 when it would not result in changing the owner or group of the file;
91 that is, for files which are owned by you and whose group matches
92 the default for a new file created there by you.
93 This variable is relevant only if `backup-by-copying' is nil.")
95 (defvar backup-enable-predicate
97 (or (< (length name
) 5)
98 (not (string-equal "/tmp/" (substring name
0 5)))))
99 "Predicate that looks at a file name and decides whether to make backups.
100 Called with an absolute file name as argument, it returns t to enable backup.")
102 (defconst buffer-offer-save nil
103 "*Non-nil in a buffer means offer to save the buffer on exit
104 even if the buffer is not visiting a file.
105 Automatically local in all buffers.")
106 (make-variable-buffer-local 'buffer-offer-save
)
108 (defconst find-file-existing-other-name t
109 "*Non-nil means find a file under alternative names, in existing buffers.
110 This means if any existing buffer is visiting the file you want
111 under another name, you get the existing buffer instead of a new buffer.")
113 (defconst find-file-visit-truename nil
114 "*Non-nil means visit a file under its truename.
115 The truename of a file is found by chasing all links
116 both at the file level and at the levels of the containing directories.")
118 (defvar buffer-file-number nil
119 "The device number and file number of the file visited in the current buffer.
120 The value is a list of the form (FILENUM DEVNUM).
121 This pair of numbers uniquely identifies the file.
122 If the buffer is visiting a new file, the value is nil.")
123 (make-variable-buffer-local 'buffer-file-number
)
124 (put 'buffer-file-number
'permanent-local t
)
126 (defvar buffer-file-numbers-unique
(not (memq system-type
'(windows-nt)))
127 "Non-nil means that buffer-file-number uniquely identifies files.")
129 (defconst file-precious-flag nil
130 "*Non-nil means protect against I/O errors while saving files.
131 Some modes set this non-nil in particular buffers.
133 This feature works by writing the new contents into a temporary file
134 and then renaming the temporary file to replace the original.
135 In this way, any I/O error in writing leaves the original untouched,
136 and there is never any instant where the file is nonexistent.
138 Note that this feature forces backups to be made by copying.
139 Yet, at the same time, saving a precious file
140 breaks any hard links between it and other files.")
142 (defvar version-control nil
143 "*Control use of version numbers for backup files.
144 t means make numeric backup versions unconditionally.
145 nil means make them for files that have some already.
146 `never' means do not make them.")
148 (defvar dired-kept-versions
2
149 "*When cleaning directory, number of versions to keep.")
151 (defvar delete-old-versions nil
152 "*If t, delete excess backup versions silently.
153 If nil, ask confirmation. Any other value prevents any trimming.")
155 (defvar kept-old-versions
2
156 "*Number of oldest versions to keep when a new numbered backup is made.")
158 (defvar kept-new-versions
2
159 "*Number of newest versions to keep when a new numbered backup is made.
160 Includes the new backup. Must be > 0")
162 (defconst require-final-newline nil
163 "*Value of t says silently ensure a file ends in a newline when it is saved.
164 Non-nil but not t says ask user whether to add a newline when there isn't one.
165 nil means don't add newlines.")
167 (defconst auto-save-default t
168 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
170 (defconst auto-save-visited-file-name nil
171 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
172 Normally auto-save files are written under other names.")
174 (defconst save-abbrevs nil
175 "*Non-nil means save word abbrevs too when files are saved.
176 Loading an abbrev file sets this to t.")
178 (defconst find-file-run-dired t
179 "*Non-nil says run dired if `find-file' is given the name of a directory.")
181 ;;;It is not useful to make this a local variable.
182 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
183 (defvar find-file-not-found-hooks nil
184 "List of functions to be called for `find-file' on nonexistent file.
185 These functions are called as soon as the error is detected.
186 `buffer-file-name' is already set up.
187 The functions are called in the order given until one of them returns non-nil.")
189 ;;;It is not useful to make this a local variable.
190 ;;;(put 'find-file-hooks 'permanent-local t)
191 (defvar find-file-hooks nil
192 "List of functions to be called after a buffer is loaded from a file.
193 The buffer's local variables (if any) will have been processed before the
194 functions are called.")
196 (defvar write-file-hooks nil
197 "List of functions to be called before writing out a buffer to a file.
198 If one of them returns non-nil, the file is considered already written
199 and the rest are not called.
200 These hooks are considered to pertain to the visited file.
201 So this list is cleared if you change the visited file name.
203 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
204 See also `write-contents-hooks'.")
205 ;;; However, in case someone does make it local...
206 (put 'write-file-hooks
'permanent-local t
)
208 (defvar local-write-file-hooks nil
209 "Just like `write-file-hooks', except intended for per-buffer use.
210 The functions in this list are called before the ones in
213 This variable is meant to be used for hooks that have to do with a
214 particular visited file. Therefore, it is a permanent local, so that
215 changing the major mode does not clear it. However, calling
216 `set-visited-file-name' does clear it.")
217 (make-variable-buffer-local 'local-write-file-hooks
)
218 (put 'local-write-file-hooks
'permanent-local t
)
220 (defvar write-contents-hooks nil
221 "List of functions to be called before writing out a buffer to a file.
222 If one of them returns non-nil, the file is considered already written
223 and the rest are not called.
225 This variable is meant to be used for hooks that pertain to the
226 buffer's contents, not to the particular visited file; thus,
227 `set-visited-file-name' does not clear this variable; but changing the
228 major mode does clear it.
230 This variable automatically becomes buffer-local whenever it is set.
231 If you use `add-hooks' to add elements to the list, use nil for the
234 See also `write-file-hooks'.")
235 (make-variable-buffer-local 'write-contents-hooks
)
237 (defconst enable-local-variables t
238 "*Control use of local-variables lists in files you visit.
239 The value can be t, nil or something else.
240 A value of t means local-variables lists are obeyed;
241 nil means they are ignored; anything else means query.
243 The command \\[normal-mode] always obeys local-variables lists
244 and ignores this variable.")
246 (defconst enable-local-eval
'maybe
247 "*Control processing of the \"variable\" `eval' in a file's local variables.
248 The value can be t, nil or something else.
249 A value of t means obey `eval' variables;
250 nil means ignore them; anything else means query.
252 The command \\[normal-mode] always obeys local-variables lists
253 and ignores this variable.")
255 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
256 (or (fboundp 'lock-buffer
)
257 (defalias 'lock-buffer
'ignore
))
258 (or (fboundp 'unlock-buffer
)
259 (defalias 'unlock-buffer
'ignore
))
260 (or (fboundp 'file-locked-p
)
261 (defalias 'file-locked-p
'ignore
))
263 ;; This hook function provides support for ange-ftp host name
264 ;; completion. It runs the usual ange-ftp hook, but only for
265 ;; completion operations. Having this here avoids the need
266 ;; to load ange-ftp when it's not really in use.
267 (defun ange-ftp-completion-hook-function (op &rest args
)
268 (if (memq op
'(file-name-completion file-name-all-completions
))
269 (apply 'ange-ftp-hook-function op args
)
270 (let ((inhibit-file-name-handlers
271 (cons 'ange-ftp-completion-hook-function
272 (and (eq inhibit-file-name-operation op
)
273 inhibit-file-name-handlers
)))
274 (inhibit-file-name-operation op
))
277 (defun convert-standard-filename (filename)
278 "Convert a standard file's name to something suitable for the current OS.
279 This function's standard definition is trivial; it just returns the argument.
280 However, on some systems, the function is redefined
281 with a definition that really does change some file names."
285 "Show the current default directory."
287 (message "Directory %s" default-directory
))
290 "Value of the CDPATH environment variable, as a list.
291 Not actually set up until the first time you you use it.")
293 (defvar path-separator
":"
294 "Character used to separate concatenated paths.")
296 (defun parse-colon-path (cd-path)
297 "Explode a colon-separated list of paths into a string list."
299 (let (cd-prefix cd-list
(cd-start 0) cd-colon
)
300 (setq cd-path
(concat cd-path path-separator
))
301 (while (setq cd-colon
(string-match path-separator cd-path cd-start
))
304 (list (if (= cd-start cd-colon
)
306 (substitute-in-file-name
307 (file-name-as-directory
308 (substring cd-path cd-start cd-colon
)))))))
309 (setq cd-start
(+ cd-colon
1)))
312 (defun cd-absolute (dir)
313 "Change current directory to given absolute file name DIR."
314 ;; Put the name into directory syntax now,
315 ;; because otherwise expand-file-name may give some bad results.
316 (if (not (eq system-type
'vax-vms
))
317 (setq dir
(file-name-as-directory dir
)))
318 (setq dir
(abbreviate-file-name (expand-file-name dir
)))
319 (if (not (file-directory-p dir
))
320 (error "%s is not a directory" dir
)
321 (if (file-executable-p dir
)
322 (setq default-directory dir
)
323 (error "Cannot cd to %s: Permission denied" dir
))))
326 "Make DIR become the current buffer's default directory.
327 If your environment includes a `CDPATH' variable, try each one of that
328 colon-separated list of directories when resolving a relative directory name."
330 (list (read-file-name "Change default directory: "
331 default-directory default-directory
332 (and (member cd-path
'(nil ("./")))
333 (null (getenv "CDPATH"))))))
334 (if (file-name-absolute-p dir
)
335 (cd-absolute (expand-file-name dir
))
337 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
338 (setq cd-path
(or trypath
(list "./")))))
339 (if (not (catch 'found
341 (function (lambda (x)
342 (let ((f (expand-file-name (concat x dir
))))
343 (if (file-directory-p f
)
346 (throw 'found t
))))))
349 (error "No such directory found via CDPATH environment variable"))))
351 (defun load-file (file)
352 "Load the Lisp file named FILE."
353 (interactive "fLoad file: ")
354 (load (expand-file-name file
) nil nil t
))
356 (defun load-library (library)
357 "Load the library named LIBRARY.
358 This is an interface to the function `load'."
359 (interactive "sLoad library: ")
362 (defun file-local-copy (file &optional buffer
)
363 "Copy the file FILE into a temporary file on this machine.
364 Returns the name of the local copy, or nil, if FILE is directly
366 (let ((handler (find-file-name-handler file
'file-local-copy
)))
368 (funcall handler
'file-local-copy file
)
371 (defun file-truename (filename &optional counter prev-dirs
)
372 "Return the truename of FILENAME, which should be absolute.
373 The truename of a file name is found by chasing symbolic links
374 both at the level of the file and at the level of the directories
375 containing it, until no links are left at any level.
377 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
378 Do not specify them in other calls."
379 ;; COUNTER can be a cons cell whose car is the count of how many more links
380 ;; to chase before getting an error.
381 ;; PREV-DIRS can be a cons cell whose car is an alist
382 ;; of truenames we've just recently computed.
384 ;; The last test looks dubious, maybe `+' is meant here? --simon.
385 (if (or (string= filename
"") (string= filename
"~")
386 (and (string= (substring filename
0 1) "~")
387 (string-match "~[^/]*" filename
)))
389 (setq filename
(expand-file-name filename
))
390 (if (string= filename
"")
391 (setq filename
"/"))))
392 (or counter
(setq counter
(list 100)))
394 ;; For speed, remove the ange-ftp completion handler from the list.
395 ;; We know it's not needed here.
396 ;; For even more speed, do this only on the outermost call.
397 (file-name-handler-alist
398 (if prev-dirs file-name-handler-alist
399 (let ((tem (copy-sequence file-name-handler-alist
)))
400 (delq (rassq 'ange-ftp-completion-hook-function tem
) tem
)))))
401 (or prev-dirs
(setq prev-dirs
(list nil
)))
402 ;; If this file directly leads to a link, process that iteratively
403 ;; so that we don't use lots of stack.
405 (setcar counter
(1- (car counter
)))
406 (if (< (car counter
) 0)
407 (error "Apparent cycle of symbolic links for %s" filename
))
408 (let ((handler (find-file-name-handler filename
'file-truename
)))
409 ;; For file name that has a special handler, call handler.
410 ;; This is so that ange-ftp can save time by doing a no-op.
412 (setq filename
(funcall handler
'file-truename filename
)
414 (let ((dir (or (file-name-directory filename
) default-directory
))
416 ;; Get the truename of the directory.
417 (setq dirfile
(directory-file-name dir
))
418 ;; If these are equal, we have the (or a) root directory.
419 (or (string= dir dirfile
)
420 ;; If this is the same dir we last got the truename for,
421 ;; save time--don't recalculate.
422 (if (assoc dir
(car prev-dirs
))
423 (setq dir
(cdr (assoc dir
(car prev-dirs
))))
425 (new (file-name-as-directory (file-truename dirfile counter prev-dirs
))))
426 (setcar prev-dirs
(cons (cons old new
) (car prev-dirs
)))
428 (if (equal ".." (file-name-nondirectory filename
))
430 (directory-file-name (file-name-directory (directory-file-name dir
)))
432 (if (equal "." (file-name-nondirectory filename
))
433 (setq filename
(directory-file-name dir
)
435 ;; Put it back on the file name.
436 (setq filename
(concat dir
(file-name-nondirectory filename
)))
437 ;; Is the file name the name of a link?
438 (setq target
(file-symlink-p filename
))
440 ;; Yes => chase that link, then start all over
441 ;; since the link may point to a directory name that uses links.
442 ;; We can't safely use expand-file-name here
443 ;; since target might look like foo/../bar where foo
444 ;; is itself a link. Instead, we handle . and .. above.
446 (if (file-name-absolute-p target
)
454 (defun file-chase-links (filename)
455 "Chase links in FILENAME until a name that is not a link.
456 Does not examine containing directories for links,
457 unlike `file-truename'."
458 (let (tem (count 100) (newname filename
))
459 (while (setq tem
(file-symlink-p newname
))
461 (error "Apparent cycle of symbolic links for %s" filename
))
462 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
463 (while (string-match "//+" tem
)
464 (setq tem
(concat (substring tem
0 (1+ (match-beginning 0)))
465 (substring tem
(match-end 0)))))
466 ;; Handle `..' by hand, since it needs to work in the
467 ;; target of any directory symlink.
468 ;; This code is not quite complete; it does not handle
469 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
470 (while (string-match "\\`\\.\\./" tem
)
471 (setq tem
(substring tem
3))
472 (setq newname
(file-name-as-directory
473 ;; Do the .. by hand.
476 ;; Chase links in the default dir of the symlink.
479 (file-name-directory newname
))))))))
480 (setq newname
(expand-file-name tem
(file-name-directory newname
)))
481 (setq count
(1- count
)))
484 (defun switch-to-buffer-other-window (buffer)
485 "Select buffer BUFFER in another window."
486 (interactive "BSwitch to buffer in other window: ")
487 (let ((pop-up-windows t
))
488 (pop-to-buffer buffer t
)))
490 (defun switch-to-buffer-other-frame (buffer)
491 "Switch to buffer BUFFER in another frame."
492 (interactive "BSwitch to buffer in other frame: ")
493 (let ((pop-up-frames t
))
494 (pop-to-buffer buffer t
)
495 (raise-frame (window-frame (selected-window)))))
497 (defun find-file (filename)
499 Switch to a buffer visiting file FILENAME,
500 creating one if none already exists."
501 (interactive "FFind file: ")
502 (switch-to-buffer (find-file-noselect filename
)))
504 (defun find-file-other-window (filename)
505 "Edit file FILENAME, in another window.
506 May create a new window, or reuse an existing one.
507 See the function `display-buffer'."
508 (interactive "FFind file in other window: ")
509 (switch-to-buffer-other-window (find-file-noselect filename
)))
511 (defun find-file-other-frame (filename)
512 "Edit file FILENAME, in another frame.
513 May create a new frame, or reuse an existing one.
514 See the function `display-buffer'."
515 (interactive "FFind file in other frame: ")
516 (switch-to-buffer-other-frame (find-file-noselect filename
)))
518 (defun find-file-read-only (filename)
519 "Edit file FILENAME but don't allow changes.
520 Like \\[find-file] but marks buffer as read-only.
521 Use \\[toggle-read-only] to permit editing."
522 (interactive "fFind file read-only: ")
524 (setq buffer-read-only t
)
527 (defun find-file-read-only-other-window (filename)
528 "Edit file FILENAME in another window but don't allow changes.
529 Like \\[find-file-other-window] but marks buffer as read-only.
530 Use \\[toggle-read-only] to permit editing."
531 (interactive "fFind file read-only other window: ")
532 (find-file-other-window filename
)
533 (setq buffer-read-only t
)
536 (defun find-file-read-only-other-frame (filename)
537 "Edit file FILENAME in another frame but don't allow changes.
538 Like \\[find-file-other-frame] but marks buffer as read-only.
539 Use \\[toggle-read-only] to permit editing."
540 (interactive "fFind file read-only other frame: ")
541 (find-file-other-frame filename
)
542 (setq buffer-read-only t
)
545 (defun find-alternate-file-other-window (filename)
546 "Find file FILENAME as a replacement for the file in the next window.
547 This command does not select that window."
549 (save-selected-window
551 (let ((file buffer-file-name
)
555 (setq file-name
(file-name-nondirectory file
)
556 file-dir
(file-name-directory file
)))
557 (list (read-file-name
558 "Find alternate file: " file-dir nil nil file-name
)))))
560 (find-file-other-window filename
)
561 (save-selected-window
563 (find-alternate-file filename
))))
565 (defun find-alternate-file (filename)
566 "Find file FILENAME, select its buffer, kill previous buffer.
567 If the current buffer now contains an empty file that you just visited
568 \(presumably by mistake), use this command to visit the file you really want."
570 (let ((file buffer-file-name
)
574 (setq file-name
(file-name-nondirectory file
)
575 file-dir
(file-name-directory file
)))
576 (list (read-file-name
577 "Find alternate file: " file-dir nil nil file-name
))))
578 (and (buffer-modified-p) (buffer-file-name)
579 ;; (not buffer-read-only)
580 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
583 (let ((obuf (current-buffer))
584 (ofile buffer-file-name
)
585 (onum buffer-file-number
)
586 (otrue buffer-file-truename
)
587 (oname (buffer-name)))
588 (if (get-buffer " **lose**")
589 (kill-buffer " **lose**"))
590 (rename-buffer " **lose**")
594 (setq buffer-file-name nil
)
595 (setq buffer-file-number nil
)
596 (setq buffer-file-truename nil
)
597 (find-file filename
))
598 (cond ((eq obuf
(current-buffer))
599 (setq buffer-file-name ofile
)
600 (setq buffer-file-number onum
)
601 (setq buffer-file-truename otrue
)
603 (rename-buffer oname
))))
604 (or (eq (current-buffer) obuf
)
605 (kill-buffer obuf
))))
607 (defun create-file-buffer (filename)
608 "Create a suitably named buffer for visiting FILENAME, and return it.
609 FILENAME (sans directory) is used unchanged if that name is free;
610 otherwise a string <2> or <3> or ... is appended to get an unused name."
611 (let ((lastname (file-name-nondirectory filename
)))
612 (if (string= lastname
"")
613 (setq lastname filename
))
614 (generate-new-buffer lastname
)))
616 (defun generate-new-buffer (name)
617 "Create and return a buffer with a name based on NAME.
618 Choose the buffer's name using `generate-new-buffer-name'."
619 (get-buffer-create (generate-new-buffer-name name
)))
621 (defconst automount-dir-prefix
"^/tmp_mnt/"
622 "Regexp to match the automounter prefix in a directory name.")
624 (defvar abbreviated-home-dir nil
625 "The user's homedir abbreviated according to `directory-abbrev-list'.")
627 (defun abbreviate-file-name (filename)
628 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
629 This also substitutes \"~\" for the user's home directory.
630 Type \\[describe-variable] directory-abbrev-alist RET for more information."
631 ;; Get rid of the prefixes added by the automounter.
632 (if (and automount-dir-prefix
633 (string-match automount-dir-prefix filename
)
634 (file-exists-p (file-name-directory
635 (substring filename
(1- (match-end 0))))))
636 (setq filename
(substring filename
(1- (match-end 0)))))
637 (let ((tail directory-abbrev-alist
))
638 ;; If any elt of directory-abbrev-alist matches this name,
639 ;; abbreviate accordingly.
641 (if (string-match (car (car tail
)) filename
)
643 (concat (cdr (car tail
)) (substring filename
(match-end 0)))))
644 (setq tail
(cdr tail
)))
645 ;; Compute and save the abbreviated homedir name.
646 ;; We defer computing this until the first time it's needed, to
647 ;; give time for directory-abbrev-alist to be set properly.
648 ;; We include a slash at the end, to avoid spurious matches
649 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
650 (or abbreviated-home-dir
651 (setq abbreviated-home-dir
652 (let ((abbreviated-home-dir "$foo"))
653 (concat "^" (abbreviate-file-name (expand-file-name "~"))
656 ;; If FILENAME starts with the abbreviated homedir,
657 ;; make it start with `~' instead.
658 (if (and (string-match abbreviated-home-dir filename
)
659 ;; If the home dir is just /, don't change it.
660 (not (and (= (match-end 0) 1)
661 (= (aref filename
0) ?
/)))
662 ;; MS-DOS root directories can come with a drive letter;
663 ;; Novell Netware allows drive letters beyond `Z:'.
664 (not (and (or (eq system-type
'ms-dos
)
665 (eq system-type
'windows-nt
))
667 (string-match "^[a-zA-`]:/$" filename
)))))
670 (substring filename
(match-beginning 1) (match-end 1))
671 (substring filename
(match-end 0)))))
674 (defvar find-file-not-true-dirname-list nil
675 "*List of logical names for which visiting shouldn't save the true dirname.
676 On VMS, when you visit a file using a logical name that searches a path,
677 you may or may not want the visited file name to record the specific
678 directory where the file was found. If you *do not* want that, add the logical
679 name to this list as a string.")
681 (defun find-buffer-visiting (filename)
682 "Return the buffer visiting file FILENAME (a string).
683 This is like `get-file-buffer', except that it checks for any buffer
684 visiting the same file, possibly under a different name.
685 If there is no such live buffer, return nil."
686 (let ((buf (get-file-buffer filename
))
687 (truename (abbreviate-file-name (file-truename filename
))))
689 (let ((list (buffer-list)) found
)
690 (while (and (not found
) list
)
692 (set-buffer (car list
))
693 (if (and buffer-file-name
694 (string= buffer-file-truename truename
))
695 (setq found
(car list
))))
696 (setq list
(cdr list
)))
698 (let ((number (nthcdr 10 (file-attributes truename
)))
699 (list (buffer-list)) found
)
700 (and buffer-file-numbers-unique
702 (while (and (not found
) list
)
704 (set-buffer (car list
))
705 (if (and buffer-file-name
706 (equal buffer-file-number number
)
707 ;; Verify this buffer's file number
708 ;; still belongs to its file.
709 (file-exists-p buffer-file-name
)
710 (equal (nthcdr 10 (file-attributes buffer-file-name
))
712 (setq found
(car list
))))
713 (setq list
(cdr list
))))
716 (defun insert-file-contents-literally (filename &optional visit beg end replace
)
717 "Like `insert-file-contents', q.v., but only reads in the file.
718 A buffer may be modified in several ways after reading into the buffer due
719 to advanced Emacs features, such as file-name-handlers, format decoding,
720 find-file-hooks, etc.
721 This function ensures that none of these modifications will take place."
722 (let ((file-name-handler-alist nil
)
724 (after-insert-file-functions nil
)
725 (find-buffer-file-type-function
726 (if (fboundp 'find-buffer-file-type
)
727 (symbol-function 'find-buffer-file-type
)
731 (fset 'find-buffer-file-type
(lambda (filename) t
))
732 (insert-file-contents filename visit beg end replace
))
733 (if find-buffer-file-type-function
734 (fset 'find-buffer-file-type find-buffer-file-type-function
)
735 (fmakunbound 'find-buffer-file-type
)))))
737 (defun find-file-noselect (filename &optional nowarn rawfile
)
738 "Read file FILENAME into a buffer and return the buffer.
739 If a buffer exists visiting FILENAME, return that one, but
740 verify that the file has not changed since visited or saved.
741 The buffer is not selected, just returned to the caller."
743 (abbreviate-file-name
744 (expand-file-name filename
)))
745 (if (file-directory-p filename
)
746 (if find-file-run-dired
747 (dired-noselect (if find-file-visit-truename
748 (abbreviate-file-name (file-truename filename
))
750 (error "%s is a directory" filename
))
751 (let* ((buf (get-file-buffer filename
))
752 (truename (abbreviate-file-name (file-truename filename
)))
753 (number (nthcdr 10 (file-attributes truename
)))
754 ;; Find any buffer for a file which has same truename.
755 (other (and (not buf
) (find-buffer-visiting filename
)))
757 ;; Let user know if there is a buffer with the same truename.
761 (string-equal filename
(buffer-file-name other
))
762 (message "%s and %s are the same file"
763 filename
(buffer-file-name other
)))
764 ;; Optionally also find that buffer.
765 (if (or find-file-existing-other-name find-file-visit-truename
)
769 (verify-visited-file-modtime buf
)
770 (cond ((not (file-exists-p filename
))
771 (error "File %s no longer exists!" filename
))
773 (if (string= (file-name-nondirectory filename
)
776 (if (buffer-modified-p buf
)
777 "File %s changed on disk. Discard your edits? "
778 "File %s changed on disk. Reread from disk? ")
779 (file-name-nondirectory filename
))
781 (if (buffer-modified-p buf
)
782 "File %s changed on disk. Discard your edits in %s? "
783 "File %s changed on disk. Reread from disk into %s? ")
784 (file-name-nondirectory filename
)
788 (revert-buffer t t
)))))
790 ;;; The truename stuff makes this obsolete.
791 ;;; (let* ((link-name (car (file-attributes filename)))
792 ;;; (linked-buf (and (stringp link-name)
793 ;;; (get-file-buffer link-name))))
794 ;;; (if (bufferp linked-buf)
795 ;;; (message "Symbolic link to file in buffer %s"
796 ;;; (buffer-name linked-buf))))
797 (setq buf
(create-file-buffer filename
))
798 (set-buffer-major-mode buf
)
803 (insert-file-contents-literally filename t
)
805 ;; Unconditionally set error
808 (insert-file-contents filename t
)
810 ;; Run find-file-not-found-hooks until one returns non-nil.
811 (or (run-hook-with-args-until-success 'find-file-not-found-hooks
)
812 ;; If they fail too, set error.
814 ;; Find the file's truename, and maybe use that as visited name.
815 (setq buffer-file-truename truename
)
816 (setq buffer-file-number number
)
817 ;; On VMS, we may want to remember which directory in a search list
818 ;; the file was found in.
819 (and (eq system-type
'vax-vms
)
821 (if (string-match ":" (file-name-directory filename
))
822 (setq logical
(substring (file-name-directory filename
)
823 0 (match-beginning 0))))
824 (not (member logical find-file-not-true-dirname-list
)))
825 (setq buffer-file-name buffer-file-truename
))
826 (if find-file-visit-truename
827 (setq buffer-file-name
829 (expand-file-name buffer-file-truename
))))
830 ;; Set buffer's default directory to that of the file.
831 (setq default-directory
(file-name-directory filename
))
832 ;; Turn off backup files for certain file names. Since
833 ;; this is a permanent local, the major mode won't eliminate it.
834 (and (not (funcall backup-enable-predicate buffer-file-name
))
836 (make-local-variable 'backup-inhibited
)
837 (setq backup-inhibited t
)))
840 (after-find-file error
(not nowarn
))
841 (setq buf
(current-buffer)))))
844 (defvar after-find-file-from-revert-buffer nil
)
846 (defun after-find-file (&optional error warn noauto
847 after-find-file-from-revert-buffer
849 "Called after finding a file and by the default revert function.
850 Sets buffer mode, parses local variables.
851 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
852 error in reading the file. WARN non-nil means warn if there
853 exists an auto-save file more recent than the visited file.
854 NOAUTO means don't mess with auto-save mode.
855 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
856 means this call was from `revert-buffer'.
857 Fifth arg NOMODES non-nil means don't alter the file's modes.
858 Finishes by calling the functions in `find-file-hooks'
859 unless NOMODES is non-nil."
860 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
865 (cond ((and error
(file-attributes buffer-file-name
))
866 (setq buffer-read-only t
)
867 "File exists, but cannot be read.")
868 ((not buffer-read-only
)
870 (file-newer-than-file-p (make-auto-save-file-name)
872 (format "%s has auto save data; consider M-x recover-file"
873 (file-name-nondirectory buffer-file-name
))
875 (if error
"(New file)" nil
)))
878 "Note: file is write protected")
879 ((file-attributes (directory-file-name default-directory
))
880 "File not found and directory write-protected")
881 ((file-exists-p (file-name-directory buffer-file-name
))
882 (setq buffer-read-only nil
))
884 (setq buffer-read-only nil
)
885 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name
))))
886 "Use M-x make-dir RET RET to create the directory"
887 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
891 (or not-serious
(sit-for 1 nil t
)))))
892 (if (and auto-save-default
(not noauto
))
897 (run-hooks 'find-file-hooks
)))
899 (defun normal-mode (&optional find-file
)
900 "Choose the major mode for this buffer automatically.
901 Also sets up any specified local variables of the file.
902 Uses the visited file name, the -*- line, and the local variables spec.
904 This function is called automatically from `find-file'. In that case,
905 we may set up specified local variables depending on the value of
906 `enable-local-variables': if it is t, we do; if it is nil, we don't;
907 otherwise, we query. `enable-local-variables' is ignored if you
908 run `normal-mode' explicitly."
910 (or find-file
(funcall (or default-major-mode
'fundamental-mode
)))
913 (error (message "File mode specification error: %s"
914 (prin1-to-string err
))))
916 (let ((enable-local-variables (or (not find-file
)
917 enable-local-variables
)))
918 (hack-local-variables))
919 (error (message "File local-variables error: %s"
920 (prin1-to-string err
)))))
922 (defvar auto-mode-alist
923 '(("\\.te?xt\\'" . text-mode
)
926 ("\\.tex\\'" . tex-mode
)
927 ("\\.ltx\\'" . latex-mode
)
928 ("\\.el\\'" . emacs-lisp-mode
)
929 ("\\.mm\\'" . nroff-mode
)
930 ("\\.me\\'" . nroff-mode
)
931 ("\\.ms\\'" . nroff-mode
)
932 ("\\.man\\'" . nroff-mode
)
933 ("\\.scm\\'" . scheme-mode
)
934 ("\\.l\\'" . lisp-mode
)
935 ("\\.lisp\\'" . lisp-mode
)
936 ("\\.f\\'" . fortran-mode
)
937 ("\\.F\\'" . fortran-mode
)
938 ("\\.for\\'" . fortran-mode
)
939 ("\\.p\\'" . pascal-mode
)
940 ("\\.pas\\'" . pascal-mode
)
941 ("\\.mss\\'" . scribe-mode
)
942 ("\\.ad[abs]\\'" . ada-mode
)
943 ("\\.icn\\'" . icon-mode
)
944 ("\\.pl\\'" . perl-mode
)
945 ("\\.pm\\'" . perl-mode
)
946 ("\\.cc\\'" . c
++-mode
)
947 ("\\.hh\\'" . c
++-mode
)
948 ("\\.C\\'" . c
++-mode
)
949 ("\\.H\\'" . c
++-mode
)
950 ("\\.cpp\\'" . c
++-mode
)
951 ("\\.cxx\\'" . c
++-mode
)
952 ("\\.hxx\\'" . c
++-mode
)
953 ("\\.c\\+\\+\\'" . c
++-mode
)
954 ("\\.h\\+\\+\\'" . c
++-mode
)
955 ("\\.java\\'" . java-mode
)
956 ("\\.mk\\'" . makefile-mode
)
957 ("\\(M\\|m\\|GNUm\\)akefile\\(.in\\)?\\'" . makefile-mode
)
958 ;;; Less common extensions come here
959 ;;; so more common ones above are found faster.
960 ("\\.texinfo\\'" . texinfo-mode
)
961 ("\\.te?xi\\'" . texinfo-mode
)
962 ("\\.s\\'" . asm-mode
)
963 ("\\.S\\'" . asm-mode
)
964 ("\\.asm\\'" . asm-mode
)
965 ("ChangeLog\\'" . change-log-mode
)
966 ("change.log\\'" . change-log-mode
)
967 ("changelo\\'" . change-log-mode
)
968 ("ChangeLog.[0-9]+\\'" . change-log-mode
)
969 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
970 ("\\.scm\\.[0-9]*\\'" . scheme-mode
)
971 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode
)
972 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode
)
973 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode
)
974 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode
)
975 ;;; The following should come after the ChangeLog pattern
976 ;;; for the sake of ChangeLog.1, etc.
977 ;;; and after the .scm.[0-9] pattern too.
978 ("\\.[12345678]\\'" . nroff-mode
)
979 ("\\.TeX\\'" . tex-mode
)
980 ("\\.sty\\'" . latex-mode
)
981 ("\\.cls\\'" . latex-mode
) ;LaTeX 2e class
982 ("\\.bbl\\'" . latex-mode
)
983 ("\\.bib\\'" . bibtex-mode
)
984 ("\\.article\\'" . text-mode
)
985 ("\\.letter\\'" . text-mode
)
986 ("\\.tcl\\'" . tcl-mode
)
987 ("\\.exp\\'" . tcl-mode
)
988 ("\\.itcl\\'" . tcl-mode
)
989 ("\\.itk\\'" . tcl-mode
)
990 ("\\.f90\\'" . f90-mode
)
991 ("\\.lsp\\'" . lisp-mode
)
992 ("\\.awk\\'" . awk-mode
)
993 ("\\.prolog\\'" . prolog-mode
)
994 ("\\.tar\\'" . tar-mode
)
995 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode
)
996 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\)\\'" . archive-mode
)
997 ;; Mailer puts message to be edited in
998 ;; /tmp/Re.... or Message
999 ("\\`/tmp/Re" . text-mode
)
1000 ("/Message[0-9]*\\'" . text-mode
)
1001 ("/drafts/[0-9]+\\'" . mh-letter-mode
)
1002 ;; some news reader is reported to use this
1003 ("\\`/tmp/fol/" . text-mode
)
1004 ("\\.y\\'" . c-mode
)
1005 ("\\.lex\\'" . c-mode
)
1006 ("\\.oak\\'" . scheme-mode
)
1007 ("\\.sgml?\\'" . sgml-mode
)
1008 ("\\.dtd\\'" . sgml-mode
)
1009 ("\\.s?html?\\'" . html-mode
)
1010 ;; .emacs following a directory delimiter
1011 ;; in either Unix or VMS syntax.
1012 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode
)
1013 ;; _emacs following a directory delimiter
1015 ("[:/]_emacs\\'" . emacs-lisp-mode
)
1016 ("\\.ml\\'" . lisp-mode
))
1018 Alist of filename patterns vs corresponding major mode functions.
1019 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1020 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1021 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1022 mode function to use. FUNCTION will be called, unless it is nil.
1024 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1025 calling FUNCTION (if it's not nil), we delete the suffix that matched
1026 REGEXP and search the list again for another match.")
1028 (defconst interpreter-mode-alist
1029 '(("perl" . perl-mode
)
1030 ("perl5" . perl-mode
)
1032 ("wishx" . tcl-mode
)
1034 ("tclsh" . tcl-mode
)
1039 ("scm" . scheme-mode
)
1057 ("tail" . text-mode
)
1058 ("more" . text-mode
)
1059 ("less" . text-mode
)
1061 "Alist mapping interpreter names to major modes.
1062 This alist applies to files whose first line starts with `#!'.
1063 Each element looks like (INTERPRETER . MODE).
1064 The car of each element is compared with
1065 the name of the interpreter specified in the first line.
1066 If it matches, mode MODE is selected.")
1068 (defconst inhibit-first-line-modes-regexps
'("\\.tar\\'" "\\.tgz\\'")
1069 "List of regexps; if one matches a file name, don't look for `-*-'.")
1071 (defconst inhibit-first-line-modes-suffixes nil
1072 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1073 When checking `inhibit-first-line-modes-regexps', we first discard
1074 from the end of the file name anything that matches one of these regexps.")
1076 (defvar user-init-file
1077 "" ; set by command-line
1078 "File name including directory of user's initialization file.")
1080 (defun set-auto-mode ()
1081 "Select major mode appropriate for current buffer.
1082 This checks for a -*- mode tag in the buffer's text,
1083 compares the filename against the entries in `auto-mode-alist',
1084 or checks the interpreter that runs this file against
1085 `interpreter-mode-alist'.
1087 It does not check for the `mode:' local variable in the
1088 Local Variables section of the file; for that, use `hack-local-variables'.
1090 If `enable-local-variables' is nil, this function does not check for a
1092 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1093 (let (beg end done modes
)
1095 (goto-char (point-min))
1096 (skip-chars-forward " \t\n")
1097 (and enable-local-variables
1098 ;; Don't look for -*- if this file name matches any
1099 ;; of the regexps in inhibit-first-line-modes-regexps.
1100 (let ((temp inhibit-first-line-modes-regexps
)
1101 (name (if buffer-file-name
1102 (file-name-sans-versions buffer-file-name
)
1104 (while (let ((sufs inhibit-first-line-modes-suffixes
))
1105 (while (and sufs
(not (string-match (car sufs
) name
)))
1106 (setq sufs
(cdr sufs
)))
1108 (setq name
(substring name
0 (match-beginning 0))))
1110 (not (string-match (car temp
) name
)))
1111 (setq temp
(cdr temp
)))
1113 (search-forward "-*-" (save-excursion
1114 ;; If the file begins with "#!"
1115 ;; (exec interpreter magic), look
1116 ;; for mode frobs in the first two
1117 ;; lines. You cannot necessarily
1118 ;; put them in the first line of
1119 ;; such a file without screwing up
1120 ;; the interpreter invocation.
1121 (end-of-line (and (looking-at "^#!") 2))
1124 (skip-chars-forward " \t")
1126 (search-forward "-*-"
1127 (save-excursion (end-of-line) (point))
1131 (skip-chars-backward " \t")
1134 (if (save-excursion (search-forward ":" end t
))
1135 ;; Find all specifications for the `mode:' variable
1136 ;; and execute them left to right.
1137 (while (let ((case-fold-search t
))
1138 (or (and (looking-at "mode:")
1139 (goto-char (match-end 0)))
1140 (re-search-forward "[ \t;]mode:" end t
)))
1141 (skip-chars-forward " \t")
1143 (if (search-forward ";" end t
)
1146 (skip-chars-backward " \t")
1147 (setq modes
(cons (intern (concat (downcase (buffer-substring beg
(point))) "-mode"))
1149 ;; Simple -*-MODE-*- case.
1150 (setq modes
(cons (intern (concat (downcase (buffer-substring beg end
))
1153 ;; If we found modes to use, invoke them now,
1154 ;; outside the save-excursion.
1156 (progn (mapcar 'funcall
(nreverse modes
))
1158 ;; If we didn't find a mode from a -*- line, try using the file name.
1159 (if (and (not done
) buffer-file-name
)
1160 (let ((name buffer-file-name
)
1162 ;; Remove backup-suffixes from file name.
1163 (setq name
(file-name-sans-versions name
))
1165 (setq keep-going nil
)
1166 (let ((alist auto-mode-alist
)
1168 ;; Find first matching alist entry.
1169 (let ((case-fold-search
1170 (memq system-type
'(vax-vms windows-nt
))))
1171 (while (and (not mode
) alist
)
1172 (if (string-match (car (car alist
)) name
)
1173 (if (and (consp (cdr (car alist
)))
1174 (nth 2 (car alist
)))
1176 (setq mode
(car (cdr (car alist
)))
1177 name
(substring name
0 (match-beginning 0))
1179 (setq mode
(cdr (car alist
))
1181 (setq alist
(cdr alist
))))
1184 ;; If we can't deduce a mode from the file name,
1185 ;; look for an interpreter specified in the first line.
1186 ;; As a special case, allow for things like "#!/bin/env perl",
1187 ;; which finds the interpreter anywhere in $PATH.
1190 (goto-char (point-min))
1191 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1192 (buffer-substring (match-beginning 2)
1196 ;; Map interpreter name to a mode.
1197 (setq elt
(assoc (file-name-nondirectory interpreter
)
1198 interpreter-mode-alist
))
1200 (funcall (cdr elt
)))))))))))
1202 (defun hack-local-variables-prop-line ()
1203 ;; Set local variables specified in the -*- line.
1204 ;; Ignore any specification for `mode:';
1205 ;; set-auto-mode should already have handled that.
1207 (goto-char (point-min))
1209 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1210 ;; Parse the -*- line into the `result' alist.
1211 (cond ((not (search-forward "-*-" end t
))
1212 ;; doesn't have one.
1214 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1215 ;; Simple form: "-*- MODENAME -*-". Already handled.
1218 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1219 ;; (last ";" is optional).
1221 (if (search-forward "-*-" end t
)
1222 (setq end
(- (point) 3))
1223 (error "-*- not terminated before end of line")))
1224 (while (< (point) end
)
1225 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1226 (error "malformed -*- line"))
1227 (goto-char (match-end 0))
1228 ;; There used to be a downcase here,
1229 ;; but the manual didn't say so,
1230 ;; and people want to set var names that aren't all lc.
1231 (let ((key (intern (buffer-substring
1234 (val (save-restriction
1235 (narrow-to-region (point) end
)
1236 (read (current-buffer)))))
1238 (setq result
(cons (cons key val
) result
)))
1239 (skip-chars-forward " \t;")))
1240 (setq result
(nreverse result
))))
1243 (or (eq enable-local-variables t
)
1244 (and enable-local-variables
1245 (save-window-excursion
1247 (switch-to-buffer (current-buffer))
1249 ;; If we fail to switch in the selected window,
1250 ;; it is probably a minibuffer.
1251 ;; So try another window.
1253 (switch-to-buffer-other-window (current-buffer))
1255 (switch-to-buffer-other-frame (current-buffer))))))
1256 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1257 (file-name-nondirectory buffer-file-name
)))))))
1258 (let ((enable-local-eval enable-local-eval
))
1260 (hack-one-local-variable (car (car result
)) (cdr (car result
)))
1261 (setq result
(cdr result
))))))))
1263 (defvar hack-local-variables-hook nil
1264 "Normal hook run after processing a file's local variables specs.
1265 Major modes can use this to examine user-specified local variables
1266 in order to initialize other data structure based on them.")
1268 (defun hack-local-variables ()
1269 "Parse and put into effect this buffer's local variables spec."
1270 (hack-local-variables-prop-line)
1271 ;; Look for "Local variables:" line in last page.
1273 (goto-char (point-max))
1274 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move
)
1275 (if (let ((case-fold-search t
))
1276 (and (search-forward "Local Variables:" nil t
)
1277 (or (eq enable-local-variables t
)
1278 (and enable-local-variables
1279 (save-window-excursion
1280 (switch-to-buffer (current-buffer))
1283 (set-window-start (selected-window) (point)))
1284 (y-or-n-p (format "Set local variables as specified at end of %s? "
1285 (if buffer-file-name
1286 (file-name-nondirectory
1289 (buffer-name))))))))))
1291 prefix prefixlen suffix beg
1292 (enable-local-eval enable-local-eval
))
1293 ;; The prefix is what comes before "local variables:" in its line.
1294 ;; The suffix is what comes after "local variables:" in its line.
1295 (skip-chars-forward " \t")
1297 (setq suffix
(buffer-substring (point)
1298 (progn (end-of-line) (point)))))
1299 (goto-char (match-beginning 0))
1302 (buffer-substring (point)
1303 (progn (beginning-of-line) (point)))))
1305 (if prefix
(setq prefixlen
(length prefix
)
1306 prefix
(regexp-quote prefix
)))
1307 (if suffix
(setq suffix
(concat (regexp-quote suffix
) "$")))
1309 ;; Look at next local variable spec.
1310 (if selective-display
(re-search-forward "[\n\C-m]")
1312 ;; Skip the prefix, if any.
1314 (if (looking-at prefix
)
1315 (forward-char prefixlen
)
1316 (error "Local variables entry is missing the prefix")))
1317 ;; Find the variable name; strip whitespace.
1318 (skip-chars-forward " \t")
1320 (skip-chars-forward "^:\n")
1321 (if (eolp) (error "Missing colon in local variables entry"))
1322 (skip-chars-backward " \t")
1323 (let* ((str (buffer-substring beg
(point)))
1326 ;; Setting variable named "end" means end of list.
1327 (if (string-equal (downcase str
) "end")
1329 ;; Otherwise read the variable value.
1330 (skip-chars-forward "^:")
1332 (setq val
(read (current-buffer)))
1333 (skip-chars-backward "\n")
1334 (skip-chars-forward " \t")
1335 (or (if suffix
(looking-at suffix
) (eolp))
1336 (error "Local variables entry is terminated incorrectly"))
1337 ;; Set the variable. "Variables" mode and eval are funny.
1338 (hack-one-local-variable var val
)))))))
1339 (run-hooks 'hack-local-variables-hook
))
1341 (defconst ignored-local-variables
1342 '(enable-local-eval)
1343 "Variables to be ignored in a file's local variable spec.")
1345 ;; Get confirmation before setting these variables as locals in a file.
1346 (put 'debugger
'risky-local-variable t
)
1347 (put 'enable-local-eval
'risky-local-variable t
)
1348 (put 'ignored-local-variables
'risky-local-variable t
)
1349 (put 'eval
'risky-local-variable t
)
1350 (put 'file-name-handler-alist
'risky-local-variable t
)
1351 (put 'minor-mode-map-alist
'risky-local-variable t
)
1352 (put 'after-load-alist
'risky-local-variable t
)
1353 (put 'buffer-file-name
'risky-local-variable t
)
1354 (put 'buffer-auto-save-file-name
'risky-local-variable t
)
1355 (put 'buffer-file-truename
'risky-local-variable t
)
1356 (put 'exec-path
'risky-local-variable t
)
1357 (put 'load-path
'risky-local-variable t
)
1358 (put 'exec-directory
'risky-local-variable t
)
1359 (put 'process-environment
'risky-local-variable t
)
1360 (put 'dabbrev-case-fold-search
'risky-local-variable t
)
1361 (put 'dabbrev-case-replace
'risky-local-variable t
)
1362 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1363 (put 'outline-level
'risky-local-variable t
)
1364 (put 'rmail-output-file-alist
'risky-local-variable t
)
1366 ;; This one is safe because the user gets to check it before it is used.
1367 (put 'compile-command
'safe-local-variable t
)
1369 (defun hack-one-local-variable-quotep (exp)
1370 (and (consp exp
) (eq (car exp
) 'quote
) (consp (cdr exp
))))
1372 ;; "Set" one variable in a local variables spec.
1373 ;; A few variable names are treated specially.
1374 (defun hack-one-local-variable (var val
)
1375 (cond ((eq var
'mode
)
1376 (funcall (intern (concat (downcase (symbol-name val
))
1378 ((memq var ignored-local-variables
)
1380 ;; "Setting" eval means either eval it or do nothing.
1381 ;; Likewise for setting hook variables.
1382 ((or (get var
'risky-local-variable
)
1384 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1386 (not (get var
'safe-local-variable
))))
1387 ;; Permit evalling a put of a harmless property.
1388 ;; if the args do nothing tricky.
1389 (if (or (and (eq var
'eval
)
1392 (hack-one-local-variable-quotep (nth 1 val
))
1393 (hack-one-local-variable-quotep (nth 2 val
))
1394 ;; Only allow safe values of lisp-indent-hook;
1396 (or (numberp (nth 3 val
))
1397 (equal (nth 3 val
) ''defun
))
1398 (memq (nth 1 (nth 2 val
))
1399 '(lisp-indent-hook)))
1400 ;; Permit eval if not root and user says ok.
1401 (and (not (zerop (user-uid)))
1402 (or (eq enable-local-eval t
)
1403 (and enable-local-eval
1404 (save-window-excursion
1405 (switch-to-buffer (current-buffer))
1408 (set-window-start (selected-window) (point)))
1409 (setq enable-local-eval
1410 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1411 (file-name-nondirectory buffer-file-name
)))))))))
1413 (save-excursion (eval val
))
1414 (make-local-variable var
)
1416 (message "Ignoring `eval:' in file's local variables")))
1417 ;; Ordinary variable, really set it.
1418 (t (make-local-variable var
)
1422 (defun set-visited-file-name (filename &optional no-query
)
1423 "Change name of file visited in current buffer to FILENAME.
1424 The next time the buffer is saved it will go in the newly specified file.
1425 nil or empty string as argument means make buffer not be visiting any file.
1426 Remember to delete the initial contents of the minibuffer
1427 if you wish to pass an empty string as the argument.
1429 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1430 confirmation in the case where the file FILENAME already exists."
1431 (interactive "FSet visited file name: ")
1432 (if (buffer-base-buffer)
1433 (error "An indirect buffer cannot visit a file"))
1437 (if (string-equal filename
"")
1439 (expand-file-name filename
))))
1442 (setq truename
(file-truename filename
))
1443 (if find-file-visit-truename
1444 (setq filename truename
))))
1445 (let ((buffer (and filename
(find-buffer-visiting filename
))))
1446 (and buffer
(not (eq buffer
(current-buffer)))
1448 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1451 (or (equal filename buffer-file-name
)
1453 (and filename
(lock-buffer filename
))
1455 (setq buffer-file-name filename
)
1456 (if filename
; make buffer name reflect filename.
1457 (let ((new-name (file-name-nondirectory buffer-file-name
)))
1458 (if (string= new-name
"")
1459 (error "Empty file name"))
1460 (if (eq system-type
'vax-vms
)
1461 (setq new-name
(downcase new-name
)))
1462 (setq default-directory
(file-name-directory buffer-file-name
))
1463 (or (string= new-name
(buffer-name))
1464 (rename-buffer new-name t
))))
1465 (setq buffer-backed-up nil
)
1466 (clear-visited-file-modtime)
1467 ;; Abbreviate the file names of the buffer.
1470 (setq buffer-file-truename
(abbreviate-file-name truename
))
1471 (if find-file-visit-truename
1472 (setq buffer-file-name buffer-file-truename
))))
1473 (setq buffer-file-number
1475 (nthcdr 10 (file-attributes buffer-file-name
))
1477 ;; write-file-hooks is normally used for things like ftp-find-file
1478 ;; that visit things that are not local files as if they were files.
1479 ;; Changing to visit an ordinary local file instead should flush the hook.
1480 (kill-local-variable 'write-file-hooks
)
1481 (kill-local-variable 'local-write-file-hooks
)
1482 (kill-local-variable 'revert-buffer-function
)
1483 (kill-local-variable 'backup-inhibited
)
1484 ;; If buffer was read-only because of version control,
1485 ;; that reason is gone now, so make it writable.
1487 (setq buffer-read-only nil
))
1488 (kill-local-variable 'vc-mode
)
1489 ;; Turn off backup files for certain file names.
1490 ;; Since this is a permanent local, the major mode won't eliminate it.
1491 (and (not (funcall backup-enable-predicate buffer-file-name
))
1493 (make-local-variable 'backup-inhibited
)
1494 (setq backup-inhibited t
)))
1495 (let ((oauto buffer-auto-save-file-name
))
1496 ;; If auto-save was not already on, turn it on if appropriate.
1497 (if (not buffer-auto-save-file-name
)
1498 (and buffer-file-name auto-save-default
1500 ;; If auto save is on, start using a new name.
1501 ;; We deliberately don't rename or delete the old auto save
1502 ;; for the old visited file name. This is because perhaps
1503 ;; the user wants to save the new state and then compare with the
1504 ;; previous state from the auto save file.
1505 (setq buffer-auto-save-file-name
1506 (make-auto-save-file-name)))
1507 ;; Rename the old auto save file if any.
1508 (and oauto buffer-auto-save-file-name
1509 (file-exists-p oauto
)
1510 (rename-file oauto buffer-auto-save-file-name t
)))
1511 (if buffer-file-name
1512 (set-buffer-modified-p t
)))
1514 (defun write-file (filename &optional confirm
)
1515 "Write current buffer into file FILENAME.
1516 Makes buffer visit that file, and marks it not modified.
1517 If the buffer is already visiting a file, you can specify
1518 a directory name as FILENAME, to write a file of the same
1519 old name in that directory.
1521 If optional second arg CONFIRM is non-nil,
1522 ask for confirmation for overwriting an existing file.
1523 Interactively, confirmation is required unless you supply a prefix argument."
1524 ;; (interactive "FWrite file: ")
1526 (list (if buffer-file-name
1527 (read-file-name "Write file: "
1529 (read-file-name "Write file: "
1530 (cdr (assq 'default-directory
1531 (buffer-local-variables)))
1532 nil nil
(buffer-name)))
1533 (not current-prefix-arg
)))
1534 (or (null filename
) (string-equal filename
"")
1536 ;; If arg is just a directory,
1537 ;; use same file name, but in that directory.
1538 (if (and (file-directory-p filename
) buffer-file-name
)
1539 (setq filename
(concat (file-name-as-directory filename
)
1540 (file-name-nondirectory buffer-file-name
))))
1542 (file-exists-p filename
)
1543 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename
))
1544 (error "Canceled")))
1545 (set-visited-file-name filename
)))
1546 (set-buffer-modified-p t
)
1549 (defun backup-buffer ()
1550 "Make a backup of the disk file visited by the current buffer, if appropriate.
1551 This is normally done before saving the buffer the first time.
1552 If the value is non-nil, it is the result of `file-modes' on the original
1553 file; this means that the caller, after saving the buffer, should change
1554 the modes of the new file to agree with the old modes."
1555 (if (and make-backup-files
(not backup-inhibited
)
1556 (not buffer-backed-up
)
1557 (file-exists-p buffer-file-name
)
1558 (memq (aref (elt (file-attributes buffer-file-name
) 8) 0)
1560 (let ((real-file-name buffer-file-name
)
1561 backup-info backupname targets setmodes
)
1562 ;; If specified name is a symbolic link, chase it to the target.
1563 ;; Thus we make the backups in the directory where the real file is.
1564 (setq real-file-name
(file-chase-links real-file-name
))
1565 (setq backup-info
(find-backup-file-name real-file-name
)
1566 backupname
(car backup-info
)
1567 targets
(cdr backup-info
))
1568 ;;; (if (file-directory-p buffer-file-name)
1569 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1572 (let ((delete-old-versions
1573 ;; If have old versions to maybe delete,
1574 ;; ask the user to confirm now, before doing anything.
1575 ;; But don't actually delete til later.
1577 (or (eq delete-old-versions t
) (eq delete-old-versions nil
))
1578 (or delete-old-versions
1579 (y-or-n-p (format "Delete excess backup versions of %s? "
1580 real-file-name
))))))
1581 ;; Actually write the back up file.
1583 (if (or file-precious-flag
1584 ; (file-symlink-p buffer-file-name)
1586 (and backup-by-copying-when-linked
1587 (> (file-nlinks real-file-name
) 1))
1588 (and backup-by-copying-when-mismatch
1589 (let ((attr (file-attributes real-file-name
)))
1591 (not (file-ownership-preserved-p real-file-name
))))))
1593 (copy-file real-file-name backupname t t
)
1595 ;; If copying fails because file BACKUPNAME
1596 ;; is not writable, delete that file and try again.
1597 (if (and (file-exists-p backupname
)
1598 (not (file-writable-p backupname
)))
1599 (delete-file backupname
))
1600 (copy-file real-file-name backupname t t
)))
1601 ;; rename-file should delete old backup.
1602 (rename-file real-file-name backupname t
)
1603 (setq setmodes
(file-modes backupname
)))
1605 ;; If trouble writing the backup, write it in ~.
1606 (setq backupname
(expand-file-name
1607 (convert-standard-filename
1609 (message "Cannot write backup file; backing up in %s"
1610 (file-name-nondirectory backupname
))
1613 (copy-file real-file-name backupname t t
)
1615 ;; If copying fails because file BACKUPNAME
1616 ;; is not writable, delete that file and try again.
1617 (if (and (file-exists-p backupname
)
1618 (not (file-writable-p backupname
)))
1619 (delete-file backupname
))
1620 (copy-file real-file-name backupname t t
)))))
1621 (setq buffer-backed-up t
)
1622 ;; Now delete the old versions, if desired.
1623 (if delete-old-versions
1626 (delete-file (car targets
))
1628 (setq targets
(cdr targets
))))
1630 (file-error nil
))))))
1632 (defun file-name-sans-versions (name &optional keep-backup-version
)
1633 "Return FILENAME sans backup versions or strings.
1634 This is a separate procedure so your site-init or startup file can
1636 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1637 we do not remove backup version numbers, only true file version numbers."
1638 (let ((handler (find-file-name-handler name
'file-name-sans-versions
)))
1640 (funcall handler
'file-name-sans-versions name keep-backup-version
)
1642 (if (eq system-type
'vax-vms
)
1643 ;; VMS version number is (a) semicolon, optional
1644 ;; sign, zero or more digits or (b) period, option
1645 ;; sign, zero or more digits, provided this is the
1646 ;; second period encountered outside of the
1647 ;; device/directory part of the file name.
1648 (or (string-match ";[-+]?[0-9]*\\'" name
)
1649 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1651 (match-beginning 1))
1653 (if keep-backup-version
1655 (or (string-match "\\.~[0-9.]+~\\'" name
)
1656 (string-match "~\\'" name
)
1657 (length name
))))))))
1659 (defun file-ownership-preserved-p (file)
1660 "Returns t if deleting FILE and rewriting it would preserve the owner."
1661 (let ((handler (find-file-name-handler file
'file-ownership-preserved-p
)))
1663 (funcall handler
'file-ownership-preserved-p file
)
1664 (let ((attributes (file-attributes file
)))
1665 ;; Return t if the file doesn't exist, since it's true that no
1666 ;; information would be lost by an (attempted) delete and create.
1667 (or (null attributes
)
1668 (= (nth 2 attributes
) (user-uid)))))))
1670 (defun file-name-sans-extension (filename)
1671 "Return FILENAME sans final \"extension\".
1672 The extension, in a file name, is the part that follows the last `.'."
1674 (let ((file (file-name-sans-versions (file-name-nondirectory filename
)))
1676 (if (string-match "\\.[^.]*\\'" file
)
1677 (if (setq directory
(file-name-directory filename
))
1678 (expand-file-name (substring file
0 (match-beginning 0))
1680 (substring file
0 (match-beginning 0)))
1683 (defun make-backup-file-name (file)
1684 "Create the non-numeric backup file name for FILE.
1685 This is a separate function so you can redefine it for customization."
1686 (if (and (eq system-type
'ms-dos
)
1687 (not (msdos-long-file-names)))
1688 (let ((fn (file-name-nondirectory file
)))
1689 (concat (file-name-directory file
)
1691 (and (string-match "\\`[^.]+\\'" fn
)
1692 (concat (match-string 0 fn
) ".~"))
1693 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn
)
1694 (concat (match-string 0 fn
) "~")))))
1697 (defun backup-file-name-p (file)
1698 "Return non-nil if FILE is a backup file name (numeric or not).
1699 This is a separate function so you can redefine it for customization.
1700 You may need to redefine `file-name-sans-versions' as well."
1701 (string-match "~\\'" file
))
1703 ;; This is used in various files.
1704 ;; The usage of bv-length is not very clean,
1705 ;; but I can't see a good alternative,
1706 ;; so as of now I am leaving it alone.
1707 (defun backup-extract-version (fn)
1708 "Given the name of a numeric backup file, return the backup number.
1709 Uses the free variable `bv-length', whose value should be
1710 the index in the name where the version number begins."
1711 (if (and (string-match "[0-9]+~$" fn bv-length
)
1712 (= (match-beginning 0) bv-length
))
1713 (string-to-int (substring fn bv-length -
1))
1716 ;; I believe there is no need to alter this behavior for VMS;
1717 ;; since backup files are not made on VMS, it should not get called.
1718 (defun find-backup-file-name (fn)
1719 "Find a file name for a backup file, and suggestions for deletions.
1720 Value is a list whose car is the name for the backup file
1721 and whose cdr is a list of old versions to consider deleting now.
1722 If the value is nil, don't make a backup."
1723 (let ((handler (find-file-name-handler fn
'find-backup-file-name
)))
1724 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1726 (funcall handler
'find-backup-file-name fn
)
1727 (if (eq version-control
'never
)
1728 (list (make-backup-file-name fn
))
1729 (let* ((base-versions (concat (file-name-nondirectory fn
) ".~"))
1730 (bv-length (length base-versions
))
1734 (deserve-versions-p nil
)
1735 (number-to-delete 0))
1737 (setq possibilities
(file-name-all-completions
1739 (file-name-directory fn
))
1740 versions
(sort (mapcar
1741 (function backup-extract-version
)
1744 high-water-mark
(apply 'max
0 versions
)
1745 deserve-versions-p
(or version-control
1746 (> high-water-mark
0))
1747 number-to-delete
(- (length versions
)
1748 kept-old-versions kept-new-versions -
1))
1750 (setq possibilities nil
)))
1751 (if (not deserve-versions-p
)
1752 (list (make-backup-file-name fn
))
1753 (cons (concat fn
".~" (int-to-string (1+ high-water-mark
)) "~")
1754 (if (and (> number-to-delete
0)
1755 ;; Delete nothing if there is overflow
1756 ;; in the number of versions to keep.
1757 (>= (+ kept-new-versions kept-old-versions -
1) 0))
1758 (mapcar (function (lambda (n)
1759 (concat fn
".~" (int-to-string n
) "~")))
1760 (let ((v (nthcdr kept-old-versions versions
)))
1761 (rplacd (nthcdr (1- number-to-delete
) v
) ())
1764 (defun file-nlinks (filename)
1765 "Return number of names file FILENAME has."
1766 (car (cdr (file-attributes filename
))))
1768 (defun file-relative-name (filename &optional directory
)
1769 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1770 (setq filename
(expand-file-name filename
)
1771 directory
(file-name-as-directory (expand-file-name
1772 (or directory default-directory
))))
1773 (let ((ancestor ""))
1774 (while (not (string-match (concat "^" (regexp-quote directory
)) filename
))
1775 (setq directory
(file-name-directory (substring directory
0 -
1))
1776 ancestor
(concat "../" ancestor
)))
1777 (concat ancestor
(substring filename
(match-end 0)))))
1779 (defun save-buffer (&optional args
)
1780 "Save current buffer in visited file if modified. Versions described below.
1781 By default, makes the previous version into a backup file
1782 if previously requested or if this is the first save.
1783 With 1 \\[universal-argument], marks this version
1784 to become a backup when the next save is done.
1785 With 2 \\[universal-argument]'s,
1786 unconditionally makes the previous version into a backup file.
1787 With 3 \\[universal-argument]'s, marks this version
1788 to become a backup when the next save is done,
1789 and unconditionally makes the previous version into a backup file.
1791 With argument of 0, never makes the previous version into a backup file.
1793 If a file's name is FOO, the names of its numbered backup versions are
1794 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1795 Numeric backups (rather than FOO~) will be made if value of
1796 `version-control' is not the atom `never' and either there are already
1797 numeric versions of the file being backed up, or `version-control' is
1799 We don't want excessive versions piling up, so there are variables
1800 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1801 and `kept-new-versions', which tells how many newest versions to keep.
1802 Defaults are 2 old versions and 2 new.
1803 `dired-kept-versions' controls dired's clean-directory (.) command.
1804 If `delete-old-versions' is nil, system will query user
1805 before trimming versions. Otherwise it does it silently."
1807 (let ((modp (buffer-modified-p))
1808 (large (> (buffer-size) 50000))
1809 (make-backup-files (or (and make-backup-files
(not (eq args
0)))
1810 (memq args
'(16 64)))))
1811 (and modp
(memq args
'(16 64)) (setq buffer-backed-up nil
))
1812 (if (and modp large
) (message "Saving file %s..." (buffer-file-name)))
1814 (and modp
(memq args
'(4 64)) (setq buffer-backed-up nil
))))
1816 (defun delete-auto-save-file-if-necessary (&optional force
)
1817 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1818 Normally delete only if the file was written by this Emacs since
1819 the last real save, but optional arg FORCE non-nil means delete anyway."
1820 (and buffer-auto-save-file-name delete-auto-save-files
1821 (not (string= buffer-file-name buffer-auto-save-file-name
))
1822 (or force
(recent-auto-save-p))
1825 (delete-file buffer-auto-save-file-name
)
1827 (set-buffer-auto-saved))))
1829 (defvar after-save-hook nil
1830 "Normal hook that is run after a buffer is saved to its file.")
1832 (defun basic-save-buffer ()
1833 "Save the current buffer in its visited file, if it has been modified.
1834 After saving the buffer, run `after-save-hook'."
1837 ;; In an indirect buffer, save its base buffer instead.
1838 (if (buffer-base-buffer)
1839 (set-buffer (buffer-base-buffer)))
1840 (if (buffer-modified-p)
1841 (let ((recent-save (recent-auto-save-p))
1842 setmodes tempsetmodes
)
1843 ;; On VMS, rename file and buffer to get rid of version number.
1844 (if (and (eq system-type
'vax-vms
)
1845 (not (string= buffer-file-name
1846 (file-name-sans-versions buffer-file-name
))))
1847 (let (buffer-new-name)
1848 ;; Strip VMS version number before save.
1849 (setq buffer-file-name
1850 (file-name-sans-versions buffer-file-name
))
1851 ;; Construct a (unique) buffer name to correspond.
1852 (let ((buf (create-file-buffer (downcase buffer-file-name
))))
1853 (setq buffer-new-name
(buffer-name buf
))
1855 (rename-buffer buffer-new-name
)))
1856 ;; If buffer has no file name, ask user for one.
1857 (or buffer-file-name
1860 (read-file-name "File to save in: ") nil
)))
1861 (and (file-exists-p filename
)
1862 (or (y-or-n-p (format "File `%s' exists; overwrite? "
1864 (error "Canceled")))
1865 (set-visited-file-name filename
)))
1866 (or (verify-visited-file-modtime (current-buffer))
1867 (not (file-exists-p buffer-file-name
))
1869 (format "%s has changed since visited or saved. Save anyway? "
1870 (file-name-nondirectory buffer-file-name
)))
1871 (error "Save not confirmed"))
1874 (and (> (point-max) 1)
1875 (/= (char-after (1- (point-max))) ?
\n)
1876 (not (and (eq selective-display t
)
1877 (= (char-after (1- (point-max))) ?
\r)))
1878 (or (eq require-final-newline t
)
1879 (and require-final-newline
1881 (format "Buffer %s does not end in newline. Add one? "
1884 (goto-char (point-max))
1886 (or (run-hook-with-args-until-success 'write-contents-hooks
)
1887 (run-hook-with-args-until-success 'local-write-file-hooks
)
1888 (run-hook-with-args-until-success 'write-file-hooks
)
1889 ;; If a hook returned t, file is already "written".
1890 ;; Otherwise, write it the usual way now.
1891 (setq setmodes
(basic-save-buffer-1)))
1892 (setq buffer-file-number
1893 (nthcdr 10 (file-attributes buffer-file-name
)))
1896 (set-file-modes buffer-file-name setmodes
)
1898 ;; If the auto-save file was recent before this command,
1900 (delete-auto-save-file-if-necessary recent-save
)
1901 ;; Support VC `implicit' locking.
1903 (run-hooks 'after-save-hook
))
1904 (message "(No changes need to be saved)"))))
1906 ;; This does the "real job" of writing a buffer into its visited file
1907 ;; and making a backup file. This is what is normally done
1908 ;; but inhibited if one of write-file-hooks returns non-nil.
1909 ;; It returns a value to store in setmodes.
1910 (defun basic-save-buffer-1 ()
1911 (let (tempsetmodes setmodes
)
1912 (if (not (file-writable-p buffer-file-name
))
1913 (let ((dir (file-name-directory buffer-file-name
)))
1914 (if (not (file-directory-p dir
))
1915 (error "%s is not a directory" dir
)
1916 (if (not (file-exists-p buffer-file-name
))
1917 (error "Directory %s write-protected" dir
)
1919 (format "File %s is write-protected; try to save anyway? "
1920 (file-name-nondirectory
1922 (setq tempsetmodes t
)
1923 (error "Attempt to save to a file which you aren't allowed to write"))))))
1924 (or buffer-backed-up
1925 (setq setmodes
(backup-buffer)))
1926 (let ((dir (file-name-directory buffer-file-name
)))
1927 (if (and file-precious-flag
1928 (file-writable-p dir
))
1929 ;; If file is precious, write temp name, then rename it.
1930 ;; This requires write access to the containing dir,
1931 ;; which is why we don't try it if we don't have that access.
1932 (let ((realname buffer-file-name
)
1933 tempname temp nogood i succeed
1934 (old-modtime (visited-file-modtime)))
1937 ;; Find the temporary name to write under.
1939 (setq tempname
(format
1940 (if (and (eq system-type
'ms-dos
)
1941 (not (msdos-long-file-names)))
1942 "%s#%d.tm#" ; MSDOS limits files to 8+3
1945 (setq nogood
(file-exists-p tempname
))
1948 (progn (clear-visited-file-modtime)
1949 (write-region (point-min) (point-max)
1950 tempname nil realname
1951 buffer-file-truename
)
1953 ;; If writing the temp file fails,
1954 ;; delete the temp file.
1957 (delete-file tempname
)
1958 (set-visited-file-modtime old-modtime
))))
1959 ;; Since we have created an entirely new file
1960 ;; and renamed it, make sure it gets the
1961 ;; right permission bits set.
1962 (setq setmodes
(file-modes buffer-file-name
))
1963 ;; We succeeded in writing the temp file,
1965 (rename-file tempname buffer-file-name t
))
1966 ;; If file not writable, see if we can make it writable
1967 ;; temporarily while we write it.
1968 ;; But no need to do so if we have just backed it up
1969 ;; (setmodes is set) because that says we're superseding.
1970 (cond ((and tempsetmodes
(not setmodes
))
1971 ;; Change the mode back, after writing.
1972 (setq setmodes
(file-modes buffer-file-name
))
1973 (set-file-modes buffer-file-name
511)))
1974 (write-region (point-min) (point-max)
1975 buffer-file-name nil t buffer-file-truename
)))
1978 (defun save-some-buffers (&optional arg exiting
)
1979 "Save some modified file-visiting buffers. Asks user about each one.
1980 Optional argument (the prefix) non-nil means save all with no questions.
1981 Optional second argument EXITING means ask about certain non-file buffers
1982 as well as about file buffers."
1984 (save-window-excursion
1985 (let* ((queried nil
)
1990 (and (buffer-modified-p buffer
)
1991 (not (buffer-base-buffer buffer
))
1993 (buffer-file-name buffer
)
1997 (and buffer-offer-save
(> (buffer-size) 0)))))
2001 (if (buffer-file-name buffer
)
2002 (format "Save file %s? "
2003 (buffer-file-name buffer
))
2004 (format "Save buffer %s? "
2005 (buffer-name buffer
)))))))
2011 '("buffer" "buffers" "save")
2012 (list (list ?\C-r
(lambda (buf)
2014 (setq view-exit-action
2016 (exit-recursive-edit)))
2018 ;; Return nil to ask about BUF again.
2020 "display the current buffer"))))
2022 (and save-abbrevs abbrevs-changed
2025 (y-or-n-p (format "Save abbrevs in %s? "
2027 (write-abbrev-file nil
))
2028 ;; Don't keep bothering user if he says no.
2029 (setq abbrevs-changed nil
)
2031 (or queried
(> files-done
0) abbrevs-done
2032 (message "(No files need saving)")))))
2034 (defun not-modified (&optional arg
)
2035 "Mark current buffer as unmodified, not needing to be saved.
2036 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2038 It is not a good idea to use this function in Lisp programs, because it
2039 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2041 (message (if arg
"Modification-flag set"
2042 "Modification-flag cleared"))
2043 (set-buffer-modified-p arg
))
2045 (defun toggle-read-only (&optional arg
)
2046 "Change whether this buffer is visiting its file read-only.
2047 With arg, set read-only iff arg is positive."
2049 (setq buffer-read-only
2051 (not buffer-read-only
)
2052 (> (prefix-numeric-value arg
) 0)))
2053 (force-mode-line-update))
2055 (defun insert-file (filename)
2056 "Insert contents of file FILENAME into buffer after point.
2057 Set mark after the inserted text.
2059 This function is meant for the user to run interactively.
2060 Don't call it from programs! Use `insert-file-contents' instead.
2061 \(Its calling sequence is different; see its documentation)."
2062 (interactive "*fInsert file: ")
2063 (if (file-directory-p filename
)
2064 (signal 'file-error
(list "Opening input file" "file is a directory"
2066 (let ((tem (insert-file-contents filename
)))
2067 (push-mark (+ (point) (car (cdr tem
))))))
2069 (defun append-to-file (start end filename
)
2070 "Append the contents of the region to the end of file FILENAME.
2071 When called from a function, expects three arguments,
2072 START, END and FILENAME. START and END are buffer positions
2073 saying what text to write."
2074 (interactive "r\nFAppend to file: ")
2075 (write-region start end filename t
))
2077 (defun file-newest-backup (filename)
2078 "Return most recent backup file for FILENAME or nil if no backups exist."
2079 (let* ((filename (expand-file-name filename
))
2080 (file (file-name-nondirectory filename
))
2081 (dir (file-name-directory filename
))
2082 (comp (file-name-all-completions file dir
))
2086 (setq tem
(car comp
)
2088 (cond ((and (backup-file-name-p tem
)
2089 (string= (file-name-sans-versions tem
) file
))
2090 (setq tem
(concat dir tem
))
2091 (if (or (null newest
)
2092 (file-newer-than-file-p tem newest
))
2093 (setq newest tem
)))))
2096 (defun rename-uniquely ()
2097 "Rename current buffer to a similar name not already taken.
2098 This function is useful for creating multiple shell process buffers
2099 or multiple mail buffers, etc."
2102 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2103 (not (and buffer-file-name
2104 (string= (buffer-name)
2105 (file-name-nondirectory
2106 buffer-file-name
)))))
2107 ;; If the existing buffer name has a <NNN>,
2108 ;; which isn't part of the file name (if any),
2109 ;; then get rid of that.
2110 (substring (buffer-name) 0 (match-beginning 0))
2112 (new-buf (generate-new-buffer base-name
))
2113 (name (buffer-name new-buf
)))
2114 (kill-buffer new-buf
)
2115 (rename-buffer name
)
2116 (force-mode-line-update))))
2118 (defun make-directory (dir &optional parents
)
2119 "Create the directory DIR and any nonexistent parent dirs.
2120 Interactively, the default choice of directory to create
2121 is the current default directory for file names.
2122 That is useful when you have visited a file in a nonexistent directory.
2124 Noninteractively, the second (optional) argument PARENTS says whether
2125 to create parent directories if they don't exist."
2127 (list (read-file-name "Make directory: " default-directory default-directory
2130 (let ((handler (find-file-name-handler dir
'make-directory
)))
2132 (funcall handler
'make-directory dir parents
)
2134 (make-directory-internal dir
)
2135 (let ((dir (directory-file-name (expand-file-name dir
)))
2137 (while (not (file-exists-p dir
))
2138 (setq create-list
(cons dir create-list
)
2139 dir
(directory-file-name (file-name-directory dir
))))
2141 (make-directory-internal (car create-list
))
2142 (setq create-list
(cdr create-list
))))))))
2144 (put 'revert-buffer-function
'permanent-local t
)
2145 (defvar revert-buffer-function nil
2146 "Function to use to revert this buffer, or nil to do the default.
2147 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2148 which are the arguments that `revert-buffer' received.")
2150 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
2151 (defvar revert-buffer-insert-file-contents-function nil
2152 "Function to use to insert contents when reverting this buffer.
2153 Gets two args, first the nominal file name to use,
2154 and second, t if reading the auto-save file.")
2156 (defvar before-revert-hook nil
2157 "Normal hook for `revert-buffer' to run before reverting.
2158 If `revert-buffer-function' is used to override the normal revert
2159 mechanism, this hook is not used.")
2161 (defvar after-revert-hook nil
2162 "Normal hook for `revert-buffer' to run after reverting.
2163 Note that the hook value that it runs is the value that was in effect
2164 before reverting; that makes a difference if you have buffer-local
2167 If `revert-buffer-function' is used to override the normal revert
2168 mechanism, this hook is not used.")
2170 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes
)
2171 "Replace the buffer text with the text of the visited file on disk.
2172 This undoes all changes since the file was visited or saved.
2173 With a prefix argument, offer to revert from latest auto-save file, if
2174 that is more recent than the visited file.
2176 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2177 to revert from the auto-save file when this is nil. Note that the
2178 sense of this argument is the reverse of the prefix argument, for the
2179 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2182 Optional second argument NOCONFIRM means don't ask for confirmation at
2185 Optional third argument PRESERVE-MODES non-nil means don't alter
2186 the files modes. Normally we reinitialize them using `normal-mode'.
2188 If the value of `revert-buffer-function' is non-nil, it is called to
2191 The default revert function runs the hook `before-revert-hook' at the
2192 beginning and `after-revert-hook' at the end."
2193 ;; I admit it's odd to reverse the sense of the prefix argument, but
2194 ;; there is a lot of code out there which assumes that the first
2195 ;; argument should be t to avoid consulting the auto-save file, and
2196 ;; there's no straightforward way to encourage authors to notice a
2197 ;; reversal of the argument sense. So I'm just changing the user
2198 ;; interface, but leaving the programmatic interface the same.
2199 (interactive (list (not current-prefix-arg
)))
2200 (if revert-buffer-function
2201 (funcall revert-buffer-function ignore-auto noconfirm
)
2202 (let* ((opoint (point))
2203 (auto-save-p (and (not ignore-auto
)
2204 (recent-auto-save-p)
2205 buffer-auto-save-file-name
2206 (file-readable-p buffer-auto-save-file-name
)
2208 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2209 (file-name (if auto-save-p
2210 buffer-auto-save-file-name
2212 (cond ((null file-name
)
2213 (error "Buffer does not seem to be associated with any file"))
2215 (yes-or-no-p (format "Revert buffer from file %s? "
2217 (run-hooks 'before-revert-hook
)
2218 ;; If file was backed up but has changed since,
2219 ;; we shd make another backup.
2220 (and (not auto-save-p
)
2221 (not (verify-visited-file-modtime (current-buffer)))
2222 (setq buffer-backed-up nil
))
2223 ;; Get rid of all undo records for this buffer.
2224 (or (eq buffer-undo-list t
)
2225 (setq buffer-undo-list nil
))
2226 ;; Effectively copy the after-revert-hook status,
2227 ;; since after-find-file will clobber it.
2228 (let ((global-hook (default-value 'after-revert-hook
))
2229 (local-hook-p (local-variable-p 'after-revert-hook
))
2230 (local-hook (and (local-variable-p 'after-revert-hook
)
2231 after-revert-hook
)))
2232 (let (buffer-read-only
2233 ;; Don't make undo records for the reversion.
2234 (buffer-undo-list t
))
2235 (if revert-buffer-insert-file-contents-function
2236 (funcall revert-buffer-insert-file-contents-function
2237 file-name auto-save-p
)
2238 (if (not (file-exists-p file-name
))
2239 (error "File %s no longer exists!" file-name
))
2240 ;; Bind buffer-file-name to nil
2241 ;; so that we don't try to lock the file.
2242 (let ((buffer-file-name nil
))
2246 (insert-file-contents file-name
(not auto-save-p
)
2248 (goto-char (min opoint
(point-max)))
2249 ;; Recompute the truename in case changes in symlinks
2250 ;; have changed the truename.
2251 (setq buffer-file-truename
2252 (abbreviate-file-name (file-truename buffer-file-name
)))
2253 (after-find-file nil nil t t preserve-modes
)
2254 ;; Run after-revert-hook as it was before we reverted.
2255 (setq-default revert-buffer-internal-hook global-hook
)
2258 (make-local-variable 'revert-buffer-internal-hook
)
2259 (setq revert-buffer-internal-hook local-hook
))
2260 (kill-local-variable 'revert-buffer-internal-hook
))
2261 (run-hooks 'revert-buffer-internal-hook
))
2264 (defun recover-file (file)
2265 "Visit file FILE, but get contents from its last auto-save file."
2266 ;; Actually putting the file name in the minibuffer should be used
2268 ;; Not just because users often use the default.
2269 (interactive "FRecover file: ")
2270 (setq file
(expand-file-name file
))
2271 (if (auto-save-file-name-p (file-name-nondirectory file
))
2272 (error "%s is an auto-save file" file
))
2273 (let ((file-name (let ((buffer-file-name file
))
2274 (make-auto-save-file-name))))
2275 (cond ((if (file-exists-p file
)
2276 (not (file-newer-than-file-p file-name file
))
2277 (not (file-exists-p file-name
)))
2278 (error "Auto-save file %s not current" file-name
))
2279 ((save-window-excursion
2280 (if (not (eq system-type
'vax-vms
))
2281 (with-output-to-temp-buffer "*Directory*"
2282 (buffer-disable-undo standard-output
)
2283 (call-process "ls" nil standard-output nil
2284 (if (file-symlink-p file
) "-lL" "-l")
2286 (yes-or-no-p (format "Recover auto save file %s? " file-name
)))
2287 (switch-to-buffer (find-file-noselect file t
))
2288 (let ((buffer-read-only nil
))
2290 (insert-file-contents file-name nil
))
2291 (after-find-file nil nil t
))
2292 (t (error "Recover-file cancelled.")))))
2294 (defun recover-session ()
2295 "Recover auto save files from a previous Emacs session.
2296 This command first displays a Dired buffer showing you the
2297 previous sessions that you could recover from.
2298 To choose one, move point to the proper line and then type C-c C-c.
2299 Then you'll be asked about a number of files to recover."
2301 (let ((ls-lisp-support-shell-wildcards t
))
2302 (dired (concat auto-save-list-file-prefix
"*")))
2303 (goto-char (point-min))
2304 (or (looking-at "Move to the session you want to recover,")
2305 (let ((inhibit-read-only t
))
2306 (insert "Move to the session you want to recover,\n"
2307 "then type C-c C-c to select it.\n\n"
2308 "You can also delete some of these files;\n"
2309 "type d on a line to mark that file for deletion.\n\n")))
2310 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2311 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish
))
2313 (defun recover-session-finish ()
2314 "Choose one saved session to recover auto-save files from.
2315 This command is used in the special Dired buffer created by
2316 \\[recover-session]."
2318 ;; Get the name of the session file to recover from.
2319 (let ((file (dired-get-filename))
2321 (buffer (get-buffer-create " *recover*")))
2322 (dired-do-flagged-delete t
)
2325 ;; Read in the auto-save-list file.
2328 (insert-file-contents file
)
2329 ;; Loop thru the text of that file
2330 ;; and get out the names of the files to recover.
2332 (let (thisfile autofile
)
2334 ;; This is a pair of lines for a non-file-visiting buffer.
2335 ;; Get the auto-save file name and manufacture
2336 ;; a "visited file name" from that.
2340 (buffer-substring-no-properties
2348 (file-name-nondirectory autofile
)
2350 (file-name-directory autofile
)))
2352 ;; This pair of lines is a file-visiting
2353 ;; buffer. Use the visited file name.
2356 (buffer-substring-no-properties
2357 (point) (progn (end-of-line) (point))))
2360 (buffer-substring-no-properties
2361 (point) (progn (end-of-line) (point))))
2363 ;; Ignore a file if its auto-save file does not exist now.
2364 (if (file-exists-p autofile
)
2365 (setq files
(cons thisfile files
)))))
2366 (setq files
(nreverse files
))
2367 ;; The file contains a pair of line for each auto-saved buffer.
2368 ;; The first line of the pair contains the visited file name
2369 ;; or is empty if the buffer was not visiting a file.
2370 ;; The second line is the auto-save file name.
2372 (map-y-or-n-p "Recover %s? "
2375 (save-excursion (recover-file file
))
2377 "Failed to recover `%s'" file
)))
2379 '("file" "files" "recover"))
2380 (message "No files can be recovered from this session now")))
2381 (kill-buffer buffer
))))
2383 (defun kill-some-buffers (&optional list
)
2384 "For each buffer in LIST, ask whether to kill it.
2385 LIST defaults to all existing live buffers."
2388 (setq list
(buffer-list)))
2390 (let* ((buffer (car list
))
2391 (name (buffer-name buffer
)))
2392 (and (not (string-equal name
""))
2393 (/= (aref name
0) ?
)
2395 (format "Buffer %s %s. Kill? "
2397 (if (buffer-modified-p buffer
)
2398 "HAS BEEN EDITED" "is unmodified")))
2399 (kill-buffer buffer
)))
2400 (setq list
(cdr list
))))
2402 (defun auto-save-mode (arg)
2403 "Toggle auto-saving of contents of current buffer.
2404 With prefix argument ARG, turn auto-saving on if positive, else off."
2406 (setq buffer-auto-save-file-name
2408 (or (not buffer-auto-save-file-name
)
2409 ;; If autosave is off because buffer has shrunk,
2410 ;; then toggling should turn it on.
2411 (< buffer-saved-size
0))
2412 (or (eq arg t
) (listp arg
) (and (integerp arg
) (> arg
0))))
2413 (if (and buffer-file-name auto-save-visited-file-name
2414 (not buffer-read-only
))
2416 (make-auto-save-file-name))))
2417 ;; If -1 was stored here, to temporarily turn off saving,
2419 (and (< buffer-saved-size
0)
2420 (setq buffer-saved-size
0))
2422 (message "Auto-save %s (in this buffer)"
2423 (if buffer-auto-save-file-name
"on" "off")))
2424 buffer-auto-save-file-name
)
2426 (defun rename-auto-save-file ()
2427 "Adjust current buffer's auto save file name for current conditions.
2428 Also rename any existing auto save file, if it was made in this session."
2429 (let ((osave buffer-auto-save-file-name
))
2430 (setq buffer-auto-save-file-name
2431 (make-auto-save-file-name))
2432 (if (and osave buffer-auto-save-file-name
2433 (not (string= buffer-auto-save-file-name buffer-file-name
))
2434 (not (string= buffer-auto-save-file-name osave
))
2435 (file-exists-p osave
)
2436 (recent-auto-save-p))
2437 (rename-file osave buffer-auto-save-file-name t
))))
2439 (defun make-auto-save-file-name ()
2440 "Return file name to use for auto-saves of current buffer.
2441 Does not consider `auto-save-visited-file-name' as that variable is checked
2442 before calling this function. You can redefine this for customization.
2443 See also `auto-save-file-name-p'."
2444 (if buffer-file-name
2445 (if (and (eq system-type
'ms-dos
)
2446 (not (msdos-long-file-names)))
2447 (let ((fn (file-name-nondirectory buffer-file-name
)))
2448 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn
)
2449 (concat (file-name-directory buffer-file-name
)
2450 "#" (match-string 1 fn
)
2451 "." (match-string 3 fn
) "#"))
2452 (concat (file-name-directory buffer-file-name
)
2454 (file-name-nondirectory buffer-file-name
)
2457 ;; Deal with buffers that don't have any associated files. (Mail
2458 ;; mode tends to create a good number of these.)
2460 (let ((buffer-name (buffer-name))
2462 ;; Use technique from Sebastian Kremer's auto-save
2463 ;; package to turn slashes into \\!. This ensures that
2464 ;; the auto-save buffer name is unique.
2466 (while (string-match "[/\\]" buffer-name limit
)
2467 (setq buffer-name
(concat (substring buffer-name
0 (match-beginning 0))
2468 (if (string= (substring buffer-name
2474 (substring buffer-name
(match-end 0))))
2475 (setq limit
(1+ (match-end 0))))
2476 ;; Generate the file name.
2478 (format "#%s#%s#" buffer-name
(make-temp-name ""))
2479 ;; Try a few alternative directories, to get one we can write it.
2481 ((file-writable-p default-directory
) default-directory
)
2482 ((file-writable-p "/var/tmp/") "/var/tmp/")
2485 (defun auto-save-file-name-p (filename)
2486 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2487 FILENAME should lack slashes. You can redefine this for customization."
2488 (string-match "^#.*#$" filename
))
2490 (defun wildcard-to-regexp (wildcard)
2491 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2492 The generated regexp will match a filename iff the filename
2493 matches that wildcard according to shell rules. Only wildcards known
2494 by `sh' are supported."
2495 (let* ((i (string-match "[[.*+\\^$?]" wildcard
))
2496 ;; Copy the initial run of non-special characters.
2497 (result (substring wildcard
0 i
))
2498 (len (length wildcard
)))
2499 ;; If no special characters, we're almost done.
2502 (let ((ch (aref wildcard i
))
2508 ((eq ch ?\
[) ; [...] maps to regexp char class
2513 ((eq (aref wildcard i
) ?
!) ; [!...] -> [^...]
2516 (if (eq (aref wildcard i
) ?\
])
2521 ((eq (aref wildcard i
) ?^
)
2522 ;; Found "[^". Insert a `\0' character
2523 ;; (which cannot happen in a filename)
2524 ;; into the character class, so that `^'
2525 ;; is not the first character after `[',
2526 ;; and thus non-special in a regexp.
2530 ((eq (aref wildcard i
) ?\
])
2531 ;; I don't think `]' can appear in a
2532 ;; character class in a wildcard, but
2533 ;; let's be general here.
2538 (prog1 ; copy everything upto next `]'.
2541 (setq j
(string-match
2543 (setq i
(if j
(1- j
) (1- len
)))))))
2545 ((eq ch ?
*) "[^\000]*")
2549 ((eq ch ?
\\) "\\\\") ; probably cannot happen...
2550 ((eq ch ??
) "[^\000]")
2551 (t (char-to-string ch
)))))
2553 ;; Shell wildcards should match the entire filename,
2554 ;; not its part. Make the regexp say so.
2555 (concat "\\`" result
"\\'")))
2557 (defconst list-directory-brief-switches
2558 (if (eq system-type
'vax-vms
) "" "-CF")
2559 "*Switches for list-directory to pass to `ls' for brief listing,")
2561 (defconst list-directory-verbose-switches
2562 (if (eq system-type
'vax-vms
)
2563 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2565 "*Switches for list-directory to pass to `ls' for verbose listing,")
2567 (defun list-directory (dirname &optional verbose
)
2568 "Display a list of files in or matching DIRNAME, a la `ls'.
2569 DIRNAME is globbed by the shell if necessary.
2570 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2571 Actions controlled by variables `list-directory-brief-switches'
2572 and `list-directory-verbose-switches'."
2573 (interactive (let ((pfx current-prefix-arg
))
2574 (list (read-file-name (if pfx
"List directory (verbose): "
2575 "List directory (brief): ")
2576 nil default-directory nil
)
2578 (let ((switches (if verbose list-directory-verbose-switches
2579 list-directory-brief-switches
)))
2580 (or dirname
(setq dirname default-directory
))
2581 (setq dirname
(expand-file-name dirname
))
2582 (with-output-to-temp-buffer "*Directory*"
2583 (buffer-disable-undo standard-output
)
2584 (princ "Directory ")
2588 (set-buffer "*Directory*")
2589 (setq default-directory
2590 (if (file-directory-p dirname
)
2591 (file-name-as-directory dirname
)
2592 (file-name-directory dirname
)))
2593 (let ((wildcard (not (file-directory-p dirname
))))
2594 (insert-directory dirname switches wildcard
(not wildcard
)))))))
2596 (defvar insert-directory-program
"ls"
2597 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2600 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2601 ;; FULL-DIRECTORY-P is nil.
2602 ;; The single line of output must display FILE's name as it was
2603 ;; given, namely, an absolute path name.
2604 ;; - must insert exactly one line for each file if WILDCARD or
2605 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2606 ;; before the file lines, plus optional text after the file lines.
2607 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2609 ;; File lines should display the basename.
2610 ;; - must be consistent with
2611 ;; - functions dired-move-to-filename, (these two define what a file line is)
2612 ;; dired-move-to-end-of-filename,
2613 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2614 ;; dired-insert-headerline
2615 ;; dired-after-subdir-garbage (defines what a "total" line is)
2616 ;; - variable dired-subdir-regexp
2617 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
2618 "Insert directory listing for FILE, formatted according to SWITCHES.
2619 Leaves point after the inserted text.
2620 SWITCHES may be a string of options, or a list of strings.
2621 Optional third arg WILDCARD means treat FILE as shell wildcard.
2622 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2623 switches do not contain `d', so that a full listing is expected.
2625 This works by running a directory listing program
2626 whose name is in the variable `insert-directory-program'.
2627 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2628 ;; We need the directory in order to find the right handler.
2629 (let ((handler (find-file-name-handler (expand-file-name file
)
2630 'insert-directory
)))
2632 (funcall handler
'insert-directory file switches
2633 wildcard full-directory-p
)
2634 (if (eq system-type
'vax-vms
)
2635 (vms-read-directory file switches
(current-buffer))
2638 ;; Run ls in the directory of the file pattern we asked for.
2639 (let ((default-directory
2640 (if (file-name-absolute-p file
)
2641 (file-name-directory file
)
2642 (file-name-directory (expand-file-name file
))))
2643 (pattern (file-name-nondirectory file
))
2645 ;; Quote some characters that have special meanings in shells;
2646 ;; but don't quote the wildcards--we want them to be special.
2647 ;; We also currently don't quote the quoting characters
2648 ;; in case people want to use them explicitly to quote
2649 ;; wildcard characters.
2650 (while (string-match "[ \t\n;<>&|()#$]" pattern beg
)
2652 (concat (substring pattern
0 (match-beginning 0))
2654 (substring pattern
(match-beginning 0)))
2655 beg
(1+ (match-end 0))))
2656 (call-process shell-file-name nil t nil
2657 "-c" (concat "\\" ;; Disregard shell aliases!
2658 insert-directory-program
2660 (if (stringp switches
)
2662 (mapconcat 'identity switches
" "))
2665 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2666 ;; directory if FILE is a symbolic link.
2667 (apply 'call-process
2668 insert-directory-program nil t nil
2670 (if (listp switches
)
2671 (setq list switches
)
2672 (if (not (equal switches
""))
2674 ;; Split the switches at any spaces
2675 ;; so we can pass separate options as separate args.
2676 (while (string-match " " switches
)
2677 (setq list
(cons (substring switches
0 (match-beginning 0))
2679 switches
(substring switches
(match-end 0))))
2680 (setq list
(nreverse (cons switches list
))))))
2683 (if full-directory-p
2684 (concat (file-name-as-directory file
) ".")
2686 ;; We get here if ls failed.
2687 ;; Access the file to get a suitable error.
2688 (access-file file
"Reading directory"))))))
2690 (defvar kill-emacs-query-functions nil
2691 "Functions to call with no arguments to query about killing Emacs.
2692 If any of these functions returns nil, killing Emacs is cancelled.
2693 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2694 but `kill-emacs', the low level primitive, does not.
2695 See also `kill-emacs-hook'.")
2697 (defun save-buffers-kill-emacs (&optional arg
)
2698 "Offer to save each buffer, then kill this Emacs process.
2699 With prefix arg, silently save all file-visiting buffers, then kill."
2701 (save-some-buffers arg t
)
2702 (and (or (not (memq t
(mapcar (function
2703 (lambda (buf) (and (buffer-file-name buf
)
2704 (buffer-modified-p buf
))))
2706 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2707 (or (not (fboundp 'process-list
))
2708 ;; process-list is not defined on VMS.
2709 (let ((processes (process-list))
2712 (and (memq (process-status (car processes
)) '(run stop open
))
2713 (let ((val (process-kill-without-query (car processes
))))
2714 (process-kill-without-query (car processes
) val
)
2717 (setq processes
(cdr processes
)))
2719 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2720 ;; Query the user for other things, perhaps.
2721 (run-hook-with-args-until-failure 'kill-emacs-query-functions
)
2724 (define-key ctl-x-map
"\C-f" 'find-file
)
2725 (define-key ctl-x-map
"\C-q" 'toggle-read-only
)
2726 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
2727 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
2728 (define-key ctl-x-map
"\C-s" 'save-buffer
)
2729 (define-key ctl-x-map
"s" 'save-some-buffers
)
2730 (define-key ctl-x-map
"\C-w" 'write-file
)
2731 (define-key ctl-x-map
"i" 'insert-file
)
2732 (define-key esc-map
"~" 'not-modified
)
2733 (define-key ctl-x-map
"\C-d" 'list-directory
)
2734 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-emacs
)
2736 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
2737 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
2738 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
2739 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
2740 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
2742 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
2743 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
2744 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
2745 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
2747 ;;; files.el ends here