(ediff-toggle-read-only,ediff-read-file-name):
[emacs.git] / lisp / files.el
blobe9f9ed30c2879369f292108e7d8da6b0eb557124
1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 93, 94, 1995 Free Software Foundation, Inc.
5 ;; Maintainer: FSF
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23 ;;; Commentary:
25 ;; Defines most of Emacs's file- and directory-handling functions,
26 ;; including basic file visiting, backup generation, link handling,
27 ;; ITS-id version control, load- and write-hook handling, and the like.
29 ;;; Code:
31 (defconst delete-auto-save-files t
32 "*Non-nil means delete auto-save file when a buffer is saved or killed.")
34 (defconst directory-abbrev-alist
35 nil
36 "*Alist of abbreviations for file directories.
37 A list of elements of the form (FROM . TO), each meaning to replace
38 FROM with TO when it appears in a directory name. This replacement is
39 done when setting up the default directory of a newly visited file.
40 *Every* FROM string should start with `^'.
42 Do not use `~' in the TO strings.
43 They should be ordinary absolute directory names.
45 Use this feature when you have directories which you normally refer to
46 via absolute symbolic links. Make TO the name of the link, and FROM
47 the name it is linked to.")
49 ;;; Turn off backup files on VMS since it has version numbers.
50 (defconst make-backup-files (not (eq system-type 'vax-vms))
51 "*Non-nil means make a backup of a file the first time it is saved.
52 This can be done by renaming the file or by copying.
54 Renaming means that Emacs renames the existing file so that it is a
55 backup file, then writes the buffer into a new file. Any other names
56 that the old file had will now refer to the backup file. The new file
57 is owned by you and its group is defaulted.
59 Copying means that Emacs copies the existing file into the backup
60 file, then writes the buffer on top of the existing file. Any other
61 names that the old file had will now refer to the new (edited) file.
62 The file's owner and group are unchanged.
64 The choice of renaming or copying is controlled by the variables
65 `backup-by-copying', `backup-by-copying-when-linked' and
66 `backup-by-copying-when-mismatch'. See also `backup-inhibited'.")
68 ;; Do this so that local variables based on the file name
69 ;; are not overridden by the major mode.
70 (defvar backup-inhibited nil
71 "Non-nil means don't make a backup, regardless of the other parameters.
72 This variable is intended for use by making it local to a buffer.
73 But it is local only if you make it local.")
74 (put 'backup-inhibited 'permanent-local t)
76 (defconst backup-by-copying nil
77 "*Non-nil means always use copying to create backup files.
78 See documentation of variable `make-backup-files'.")
80 (defconst backup-by-copying-when-linked nil
81 "*Non-nil means use copying to create backups for files with multiple names.
82 This causes the alternate names to refer to the latest version as edited.
83 This variable is relevant only if `backup-by-copying' is nil.")
85 (defconst backup-by-copying-when-mismatch nil
86 "*Non-nil means create backups by copying if this preserves owner or group.
87 Renaming may still be used (subject to control of other variables)
88 when it would not result in changing the owner or group of the file;
89 that is, for files which are owned by you and whose group matches
90 the default for a new file created there by you.
91 This variable is relevant only if `backup-by-copying' is nil.")
93 (defvar backup-enable-predicate
94 '(lambda (name)
95 (or (< (length name) 5)
96 (not (string-equal "/tmp/" (substring name 0 5)))))
97 "Predicate that looks at a file name and decides whether to make backups.
98 Called with an absolute file name as argument, it returns t to enable backup.")
100 (defconst buffer-offer-save nil
101 "*Non-nil in a buffer means offer to save the buffer on exit
102 even if the buffer is not visiting a file.
103 Automatically local in all buffers.")
104 (make-variable-buffer-local 'buffer-offer-save)
106 (defconst find-file-existing-other-name nil
107 "*Non-nil means find a file under alternative names, in existing buffers.
108 This means if any existing buffer is visiting the file you want
109 under another name, you get the existing buffer instead of a new buffer.")
111 (defconst find-file-visit-truename nil
112 "*Non-nil means visit a file under its truename.
113 The truename of a file is found by chasing all links
114 both at the file level and at the levels of the containing directories.")
116 (defvar buffer-file-number nil
117 "The device number and file number of the file visited in the current buffer.
118 The value is a list of the form (FILENUM DEVNUM).
119 This pair of numbers uniquely identifies the file.
120 If the buffer is visiting a new file, the value is nil.")
121 (make-variable-buffer-local 'buffer-file-number)
122 (put 'buffer-file-number 'permanent-local t)
124 (defconst file-precious-flag nil
125 "*Non-nil means protect against I/O errors while saving files.
126 Some modes set this non-nil in particular buffers.
128 This feature works by writing the new contents into a temporary file
129 and then renaming the temporary file to replace the original.
130 In this way, any I/O error in writing leaves the original untouched,
131 and there is never any instant where the file is nonexistent.
133 Note that this feature forces backups to be made by copying.
134 Yet, at the same time, saving a precious file
135 breaks any hard links between it and other files.")
137 (defvar version-control nil
138 "*Control use of version numbers for backup files.
139 t means make numeric backup versions unconditionally.
140 nil means make them for files that have some already.
141 `never' means do not make them.")
143 (defvar dired-kept-versions 2
144 "*When cleaning directory, number of versions to keep.")
146 (defvar delete-old-versions nil
147 "*If t, delete excess backup versions silently.
148 If nil, ask confirmation. Any other value prevents any trimming.")
150 (defvar kept-old-versions 2
151 "*Number of oldest versions to keep when a new numbered backup is made.")
153 (defvar kept-new-versions 2
154 "*Number of newest versions to keep when a new numbered backup is made.
155 Includes the new backup. Must be > 0")
157 (defconst require-final-newline nil
158 "*Value of t says silently ensure a file ends in a newline when it is saved.
159 Non-nil but not t says ask user whether to add a newline when there isn't one.
160 nil means don't add newlines.")
162 (defconst auto-save-default t
163 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
165 (defconst auto-save-visited-file-name nil
166 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
167 Normally auto-save files are written under other names.")
169 (defconst save-abbrevs nil
170 "*Non-nil means save word abbrevs too when files are saved.
171 Loading an abbrev file sets this to t.")
173 (defconst find-file-run-dired t
174 "*Non-nil says run dired if `find-file' is given the name of a directory.")
176 ;;;It is not useful to make this a local variable.
177 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
178 (defvar find-file-not-found-hooks nil
179 "List of functions to be called for `find-file' on nonexistent file.
180 These functions are called as soon as the error is detected.
181 `buffer-file-name' is already set up.
182 The functions are called in the order given until one of them returns non-nil.")
184 ;;;It is not useful to make this a local variable.
185 ;;;(put 'find-file-hooks 'permanent-local t)
186 (defvar find-file-hooks nil
187 "List of functions to be called after a buffer is loaded from a file.
188 The buffer's local variables (if any) will have been processed before the
189 functions are called.")
191 (defvar write-file-hooks nil
192 "List of functions to be called before writing out a buffer to a file.
193 If one of them returns non-nil, the file is considered already written
194 and the rest are not called.
195 These hooks are considered to pertain to the visited file.
196 So this list is cleared if you change the visited file name.
197 See also `write-contents-hooks'.
198 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.")
199 ;;; However, in case someone does make it local...
200 (put 'write-file-hooks 'permanent-local t)
202 (defvar local-write-file-hooks nil
203 "Just like `write-file-hooks', except intended for per-buffer use.
204 The functions in this list are called before the ones in
205 `write-file-hooks'.")
206 (make-variable-buffer-local 'local-write-file-hooks)
207 (put 'local-write-file-hooks 'permanent-local t)
209 (defvar write-contents-hooks nil
210 "List of functions to be called before writing out a buffer to a file.
211 If one of them returns non-nil, the file is considered already written
212 and the rest are not called.
213 These hooks are considered to pertain to the buffer's contents,
214 not to the particular visited file; thus, `set-visited-file-name' does
215 not clear this variable, but changing the major mode does clear it.
216 See also `write-file-hooks'.")
218 (defconst enable-local-variables t
219 "*Control use of local-variables lists in files you visit.
220 The value can be t, nil or something else.
221 A value of t means local-variables lists are obeyed;
222 nil means they are ignored; anything else means query.
224 The command \\[normal-mode] always obeys local-variables lists
225 and ignores this variable.")
227 (defconst enable-local-eval 'maybe
228 "*Control processing of the \"variable\" `eval' in a file's local variables.
229 The value can be t, nil or something else.
230 A value of t means obey `eval' variables;
231 nil means ignore them; anything else means query.
233 The command \\[normal-mode] always obeys local-variables lists
234 and ignores this variable.")
236 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
237 (or (fboundp 'lock-buffer)
238 (defalias 'lock-buffer 'ignore))
239 (or (fboundp 'unlock-buffer)
240 (defalias 'unlock-buffer 'ignore))
242 ;; This hook function provides support for ange-ftp host name
243 ;; completion. It runs the usual ange-ftp hook, but only for
244 ;; completion operations. Having this here avoids the need
245 ;; to load ange-ftp when it's not really in use.
246 (defun ange-ftp-completion-hook-function (op &rest args)
247 (if (memq op '(file-name-completion file-name-all-completions))
248 (apply 'ange-ftp-hook-function op args)
249 (let ((inhibit-file-name-handlers
250 (cons 'ange-ftp-completion-hook-function
251 (and (eq inhibit-file-name-operation op)
252 inhibit-file-name-handlers)))
253 (inhibit-file-name-operation op))
254 (apply op args))))
256 (defun pwd ()
257 "Show the current default directory."
258 (interactive nil)
259 (message "Directory %s" default-directory))
261 (defvar cd-path nil
262 "Value of the CDPATH environment variable, as a list.
263 Not actually set up until the first time you you use it.")
265 (defvar path-separator ":"
266 "Character used to separate concatenated paths.")
268 (defun parse-colon-path (cd-path)
269 "Explode a colon-separated list of paths into a string list."
270 (and cd-path
271 (let (cd-prefix cd-list (cd-start 0) cd-colon)
272 (setq cd-path (concat cd-path path-separator))
273 (while (setq cd-colon (string-match path-separator cd-path cd-start))
274 (setq cd-list
275 (nconc cd-list
276 (list (if (= cd-start cd-colon)
278 (substitute-in-file-name
279 (file-name-as-directory
280 (substring cd-path cd-start cd-colon)))))))
281 (setq cd-start (+ cd-colon 1)))
282 cd-list)))
284 (defun cd-absolute (dir)
285 "Change current directory to given absolute file name DIR."
286 ;; Put the name into directory syntax now,
287 ;; because otherwise expand-file-name may give some bad results.
288 (if (not (eq system-type 'vax-vms))
289 (setq dir (file-name-as-directory dir)))
290 (setq dir (abbreviate-file-name (expand-file-name dir)))
291 (if (not (file-directory-p dir))
292 (error "%s is not a directory" dir)
293 (if (file-executable-p dir)
294 (setq default-directory dir)
295 (error "Cannot cd to %s: Permission denied" dir))))
297 (defun cd (dir)
298 "Make DIR become the current buffer's default directory.
299 If your environment includes a `CDPATH' variable, try each one of that
300 colon-separated list of directories when resolving a relative directory name."
301 (interactive
302 (list (read-file-name "Change default directory: "
303 default-directory default-directory
304 (and (member cd-path '(nil ("./")))
305 (null (getenv "CDPATH"))))))
306 (if (file-name-absolute-p dir)
307 (cd-absolute (expand-file-name dir))
308 (if (null cd-path)
309 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
310 (setq cd-path (or trypath (list "./")))))
311 (if (not (catch 'found
312 (mapcar
313 (function (lambda (x)
314 (let ((f (expand-file-name (concat x dir))))
315 (if (file-directory-p f)
316 (progn
317 (cd-absolute f)
318 (throw 'found t))))))
319 cd-path)
320 nil))
321 (error "No such directory found via CDPATH environment variable"))))
323 (defun load-file (file)
324 "Load the Lisp file named FILE."
325 (interactive "fLoad file: ")
326 (load (expand-file-name file) nil nil t))
328 (defun load-library (library)
329 "Load the library named LIBRARY.
330 This is an interface to the function `load'."
331 (interactive "sLoad library: ")
332 (load library))
334 (defun file-local-copy (file &optional buffer)
335 "Copy the file FILE into a temporary file on this machine.
336 Returns the name of the local copy, or nil, if FILE is directly
337 accessible."
338 (let ((handler (find-file-name-handler file 'file-local-copy)))
339 (if handler
340 (funcall handler 'file-local-copy file)
341 nil)))
343 (defun file-truename (filename &optional counter prev-dirs)
344 "Return the truename of FILENAME, which should be absolute.
345 The truename of a file name is found by chasing symbolic links
346 both at the level of the file and at the level of the directories
347 containing it, until no links are left at any level.
349 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
350 Do not specify them in other calls."
351 ;; COUNTER can be a cons cell whose car is the count of how many more links
352 ;; to chase before getting an error.
353 ;; PREV-DIRS can be a cons cell whose car is an alist
354 ;; of truenames we've just recently computed.
356 ;; The last test looks dubious, maybe `+' is meant here? --simon.
357 (if (or (string= filename "") (string= filename "~")
358 (and (string= (substring filename 0 1) "~")
359 (string-match "~[^/]*" filename)))
360 (progn
361 (setq filename (expand-file-name filename))
362 (if (string= filename "")
363 (setq filename "/"))))
364 (or counter (setq counter (list 100)))
365 (let (done
366 ;; For speed, remove the ange-ftp completion handler from the list.
367 ;; We know it's not needed here.
368 ;; For even more speed, do this only on the outermost call.
369 (file-name-handler-alist
370 (if prev-dirs file-name-handler-alist
371 (let ((tem (copy-sequence file-name-handler-alist)))
372 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
373 (or prev-dirs (setq prev-dirs (list nil)))
374 ;; If this file directly leads to a link, process that iteratively
375 ;; so that we don't use lots of stack.
376 (while (not done)
377 (setcar counter (1- (car counter)))
378 (if (< (car counter) 0)
379 (error "Apparent cycle of symbolic links for %s" filename))
380 (let ((handler (find-file-name-handler filename 'file-truename)))
381 ;; For file name that has a special handler, call handler.
382 ;; This is so that ange-ftp can save time by doing a no-op.
383 (if handler
384 (setq filename (funcall handler 'file-truename filename)
385 done t)
386 (let ((dir (or (file-name-directory filename) default-directory))
387 target dirfile)
388 ;; Get the truename of the directory.
389 (setq dirfile (directory-file-name dir))
390 ;; If these are equal, we have the (or a) root directory.
391 (or (string= dir dirfile)
392 ;; If this is the same dir we last got the truename for,
393 ;; save time--don't recalculate.
394 (if (assoc dir (car prev-dirs))
395 (setq dir (cdr (assoc dir (car prev-dirs))))
396 (let ((old dir)
397 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
398 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
399 (setq dir new))))
400 (if (equal ".." (file-name-nondirectory filename))
401 (setq filename
402 (directory-file-name (file-name-directory (directory-file-name dir)))
403 done t)
404 (if (equal "." (file-name-nondirectory filename))
405 (setq filename (directory-file-name dir)
406 done t)
407 ;; Put it back on the file name.
408 (setq filename (concat dir (file-name-nondirectory filename)))
409 ;; Is the file name the name of a link?
410 (setq target (file-symlink-p filename))
411 (if target
412 ;; Yes => chase that link, then start all over
413 ;; since the link may point to a directory name that uses links.
414 ;; We can't safely use expand-file-name here
415 ;; since target might look like foo/../bar where foo
416 ;; is itself a link. Instead, we handle . and .. above.
417 (setq filename
418 (if (file-name-absolute-p target)
419 target
420 (concat dir target))
421 done nil)
422 ;; No, we are done!
423 (setq done t))))))))
424 filename))
426 (defun file-chase-links (filename)
427 "Chase links in FILENAME until a name that is not a link.
428 Does not examine containing directories for links,
429 unlike `file-truename'."
430 (let (tem (count 100) (newname filename))
431 (while (setq tem (file-symlink-p newname))
432 (if (= count 0)
433 (error "Apparent cycle of symbolic links for %s" filename))
434 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
435 (while (string-match "//+" tem)
436 (setq tem (concat (substring tem 0 (1+ (match-beginning 0)))
437 (substring tem (match-end 0)))))
438 ;; Handle `..' by hand, since it needs to work in the
439 ;; target of any directory symlink.
440 ;; This code is not quite complete; it does not handle
441 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
442 (while (string-match "\\`\\.\\./" tem)
443 (setq tem (substring tem 3))
444 (setq newname (file-name-as-directory
445 ;; Do the .. by hand.
446 (directory-file-name
447 (file-name-directory
448 ;; Chase links in the default dir of the symlink.
449 (file-chase-links
450 (directory-file-name
451 (file-name-directory newname))))))))
452 (setq newname (expand-file-name tem (file-name-directory newname)))
453 (setq count (1- count)))
454 newname))
456 (defun switch-to-buffer-other-window (buffer)
457 "Select buffer BUFFER in another window."
458 (interactive "BSwitch to buffer in other window: ")
459 (let ((pop-up-windows t))
460 (pop-to-buffer buffer t)))
462 (defun switch-to-buffer-other-frame (buffer)
463 "Switch to buffer BUFFER in another frame."
464 (interactive "BSwitch to buffer in other frame: ")
465 (let ((pop-up-frames t))
466 (pop-to-buffer buffer t)
467 (raise-frame (window-frame (selected-window)))))
469 (defun find-file (filename)
470 "Edit file FILENAME.
471 Switch to a buffer visiting file FILENAME,
472 creating one if none already exists."
473 (interactive "FFind file: ")
474 (switch-to-buffer (find-file-noselect filename)))
476 (defun find-file-other-window (filename)
477 "Edit file FILENAME, in another window.
478 May create a new window, or reuse an existing one.
479 See the function `display-buffer'."
480 (interactive "FFind file in other window: ")
481 (switch-to-buffer-other-window (find-file-noselect filename)))
483 (defun find-file-other-frame (filename)
484 "Edit file FILENAME, in another frame.
485 May create a new frame, or reuse an existing one.
486 See the function `display-buffer'."
487 (interactive "FFind file in other frame: ")
488 (switch-to-buffer-other-frame (find-file-noselect filename)))
490 (defun find-file-read-only (filename)
491 "Edit file FILENAME but don't allow changes.
492 Like \\[find-file] but marks buffer as read-only.
493 Use \\[toggle-read-only] to permit editing."
494 (interactive "fFind file read-only: ")
495 (find-file filename)
496 (setq buffer-read-only t)
497 (current-buffer))
499 (defun find-file-read-only-other-window (filename)
500 "Edit file FILENAME in another window but don't allow changes.
501 Like \\[find-file-other-window] but marks buffer as read-only.
502 Use \\[toggle-read-only] to permit editing."
503 (interactive "fFind file read-only other window: ")
504 (find-file-other-window filename)
505 (setq buffer-read-only t)
506 (current-buffer))
508 (defun find-file-read-only-other-frame (filename)
509 "Edit file FILENAME in another frame but don't allow changes.
510 Like \\[find-file-other-frame] but marks buffer as read-only.
511 Use \\[toggle-read-only] to permit editing."
512 (interactive "fFind file read-only other frame: ")
513 (find-file-other-frame filename)
514 (setq buffer-read-only t)
515 (current-buffer))
517 (defun find-alternate-file (filename)
518 "Find file FILENAME, select its buffer, kill previous buffer.
519 If the current buffer now contains an empty file that you just visited
520 \(presumably by mistake), use this command to visit the file you really want."
521 (interactive
522 (let ((file buffer-file-name)
523 (file-name nil)
524 (file-dir nil))
525 (and file
526 (setq file-name (file-name-nondirectory file)
527 file-dir (file-name-directory file)))
528 (list (read-file-name
529 "Find alternate file: " file-dir nil nil file-name))))
530 (and (buffer-modified-p) (buffer-file-name)
531 ;; (not buffer-read-only)
532 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
533 (buffer-name))))
534 (error "Aborted"))
535 (let ((obuf (current-buffer))
536 (ofile buffer-file-name)
537 (onum buffer-file-number)
538 (otrue buffer-file-truename)
539 (oname (buffer-name)))
540 (if (get-buffer " **lose**")
541 (kill-buffer " **lose**"))
542 (rename-buffer " **lose**")
543 (setq buffer-file-name nil)
544 (setq buffer-file-number nil)
545 (setq buffer-file-truename nil)
546 (unwind-protect
547 (progn
548 (unlock-buffer)
549 (find-file filename))
550 (cond ((eq obuf (current-buffer))
551 (setq buffer-file-name ofile)
552 (setq buffer-file-number onum)
553 (setq buffer-file-truename otrue)
554 (lock-buffer)
555 (rename-buffer oname))))
556 (or (eq (current-buffer) obuf)
557 (kill-buffer obuf))))
559 (defun create-file-buffer (filename)
560 "Create a suitably named buffer for visiting FILENAME, and return it.
561 FILENAME (sans directory) is used unchanged if that name is free;
562 otherwise a string <2> or <3> or ... is appended to get an unused name."
563 (let ((lastname (file-name-nondirectory filename)))
564 (if (string= lastname "")
565 (setq lastname filename))
566 (generate-new-buffer lastname)))
568 (defun generate-new-buffer (name)
569 "Create and return a buffer with a name based on NAME.
570 Choose the buffer's name using `generate-new-buffer-name'."
571 (get-buffer-create (generate-new-buffer-name name)))
573 (defconst automount-dir-prefix "^/tmp_mnt/"
574 "Regexp to match the automounter prefix in a directory name.")
576 (defvar abbreviated-home-dir nil
577 "The user's homedir abbreviated according to `directory-abbrev-list'.")
579 (defun abbreviate-file-name (filename)
580 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
581 This also substitutes \"~\" for the user's home directory.
582 Type \\[describe-variable] directory-abbrev-alist RET for more information."
583 ;; Get rid of the prefixes added by the automounter.
584 (if (and (string-match automount-dir-prefix filename)
585 (file-exists-p (file-name-directory
586 (substring filename (1- (match-end 0))))))
587 (setq filename (substring filename (1- (match-end 0)))))
588 (let ((tail directory-abbrev-alist))
589 ;; If any elt of directory-abbrev-alist matches this name,
590 ;; abbreviate accordingly.
591 (while tail
592 (if (string-match (car (car tail)) filename)
593 (setq filename
594 (concat (cdr (car tail)) (substring filename (match-end 0)))))
595 (setq tail (cdr tail)))
596 ;; Compute and save the abbreviated homedir name.
597 ;; We defer computing this until the first time it's needed, to
598 ;; give time for directory-abbrev-alist to be set properly.
599 ;; We include a slash at the end, to avoid spurious matches
600 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
601 (or abbreviated-home-dir
602 (setq abbreviated-home-dir
603 (let ((abbreviated-home-dir "$foo"))
604 (concat "^" (abbreviate-file-name (expand-file-name "~"))
605 "\\(/\\|$\\)"))))
607 ;; If FILENAME starts with the abbreviated homedir,
608 ;; make it start with `~' instead.
609 (if (and (string-match abbreviated-home-dir filename)
610 ;; If the home dir is just /, don't change it.
611 (not (and (= (match-end 0) 1)
612 (= (aref filename 0) ?/)))
613 (not (and (or (eq system-type 'ms-dos)
614 (eq system-type 'windows-nt))
615 (save-match-data
616 (string-match "^[a-zA-Z]:/$" filename)))))
617 (setq filename
618 (concat "~"
619 (substring filename (match-beginning 1) (match-end 1))
620 (substring filename (match-end 0)))))
621 filename))
623 (defvar find-file-not-true-dirname-list nil
624 "*List of logical names for which visiting shouldn't save the true dirname.
625 On VMS, when you visit a file using a logical name that searches a path,
626 you may or may not want the visited file name to record the specific
627 directory where the file was found. If you *do not* want that, add the logical
628 name to this list as a string.")
630 (defun find-buffer-visiting (filename)
631 "Return the buffer visiting file FILENAME (a string).
632 This is like `get-file-buffer', except that it checks for any buffer
633 visiting the same file, possibly under a different name.
634 If there is no such live buffer, return nil."
635 (let ((buf (get-file-buffer filename))
636 (truename (abbreviate-file-name (file-truename filename))))
637 (or buf
638 (let ((list (buffer-list)) found)
639 (while (and (not found) list)
640 (save-excursion
641 (set-buffer (car list))
642 (if (and buffer-file-name
643 (string= buffer-file-truename truename))
644 (setq found (car list))))
645 (setq list (cdr list)))
646 found)
647 (let ((number (nthcdr 10 (file-attributes truename)))
648 (list (buffer-list)) found)
649 (and number
650 (while (and (not found) list)
651 (save-excursion
652 (set-buffer (car list))
653 (if (and buffer-file-name
654 (equal buffer-file-number number)
655 ;; Verify this buffer's file number
656 ;; still belongs to its file.
657 (file-exists-p buffer-file-name)
658 (equal (nthcdr 10 (file-attributes buffer-file-name))
659 number))
660 (setq found (car list))))
661 (setq list (cdr list))))
662 found))))
664 (defun insert-file-contents-literally (filename &optional visit beg end replace)
665 "Like `insert-file-contents', q.v., but only reads in the file.
666 A buffer may be modified in several ways after reading into the buffer due
667 to advanced Emacs features, such as file-name-handlers, format decoding,
668 find-file-hooks, etc.
669 This function ensures that none of these modifications will take place."
670 (let ((file-name-handler-alist nil)
671 (format-alist nil)
672 (after-insert-file-functions nil)
673 (find-buffer-file-type-function
674 (if (fboundp 'find-buffer-file-type)
675 (symbol-function 'find-buffer-file-type)
676 nil)))
677 (unwind-protect
678 (progn
679 (fset 'find-buffer-file-type (lambda (filename) t))
680 (insert-file-contents filename visit beg end replace))
681 (if find-buffer-file-type-function
682 (fset 'find-buffer-file-type find-buffer-file-type-function)
683 (fmakunbound 'find-buffer-file-type)))))
685 (defun find-file-noselect (filename &optional nowarn rawfile)
686 "Read file FILENAME into a buffer and return the buffer.
687 If a buffer exists visiting FILENAME, return that one, but
688 verify that the file has not changed since visited or saved.
689 The buffer is not selected, just returned to the caller."
690 (setq filename
691 (abbreviate-file-name
692 (expand-file-name filename)))
693 (if (file-directory-p filename)
694 (if find-file-run-dired
695 (dired-noselect filename)
696 (error "%s is a directory." filename))
697 (let* ((buf (get-file-buffer filename))
698 (truename (abbreviate-file-name (file-truename filename)))
699 (number (nthcdr 10 (file-attributes truename)))
700 ;; Find any buffer for a file which has same truename.
701 (other (and (not buf) (find-buffer-visiting filename)))
702 error)
703 ;; Let user know if there is a buffer with the same truename.
704 (if other
705 (progn
706 (or nowarn
707 (string-equal filename (buffer-file-name other))
708 (message "%s and %s are the same file"
709 filename (buffer-file-name other)))
710 ;; Optionally also find that buffer.
711 (if (or find-file-existing-other-name find-file-visit-truename)
712 (setq buf other))))
713 (if buf
714 (or nowarn
715 (verify-visited-file-modtime buf)
716 (cond ((not (file-exists-p filename))
717 (error "File %s no longer exists!" filename))
718 ((yes-or-no-p
719 (if (string= (file-name-nondirectory filename)
720 (buffer-name buf))
721 (format
722 (if (buffer-modified-p buf)
723 "File %s changed on disk. Discard your edits? "
724 "File %s changed on disk. Reread from disk? ")
725 (file-name-nondirectory filename))
726 (format
727 (if (buffer-modified-p buf)
728 "File %s changed on disk. Discard your edits in %s? "
729 "File %s changed on disk. Reread from disk into %s? ")
730 (file-name-nondirectory filename)
731 (buffer-name buf))))
732 (save-excursion
733 (set-buffer buf)
734 (revert-buffer t t)))))
735 (save-excursion
736 ;;; The truename stuff makes this obsolete.
737 ;;; (let* ((link-name (car (file-attributes filename)))
738 ;;; (linked-buf (and (stringp link-name)
739 ;;; (get-file-buffer link-name))))
740 ;;; (if (bufferp linked-buf)
741 ;;; (message "Symbolic link to file in buffer %s"
742 ;;; (buffer-name linked-buf))))
743 (setq buf (create-file-buffer filename))
744 (set-buffer-major-mode buf)
745 (set-buffer buf)
746 (erase-buffer)
747 (if rawfile
748 (condition-case ()
749 (insert-file-contents-literally filename t)
750 (file-error
751 ;; Unconditionally set error
752 (setq error t)))
753 (condition-case ()
754 (insert-file-contents filename t)
755 (file-error
756 ;; Run find-file-not-found-hooks until one returns non-nil.
757 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
758 ;; If they fail too, set error.
759 (setq error t)))))
760 ;; Find the file's truename, and maybe use that as visited name.
761 (setq buffer-file-truename truename)
762 (setq buffer-file-number number)
763 ;; On VMS, we may want to remember which directory in a search list
764 ;; the file was found in.
765 (and (eq system-type 'vax-vms)
766 (let (logical)
767 (if (string-match ":" (file-name-directory filename))
768 (setq logical (substring (file-name-directory filename)
769 0 (match-beginning 0))))
770 (not (member logical find-file-not-true-dirname-list)))
771 (setq buffer-file-name buffer-file-truename))
772 (if find-file-visit-truename
773 (setq buffer-file-name
774 (setq filename
775 (expand-file-name buffer-file-truename))))
776 ;; Set buffer's default directory to that of the file.
777 (setq default-directory (file-name-directory filename))
778 ;; Turn off backup files for certain file names. Since
779 ;; this is a permanent local, the major mode won't eliminate it.
780 (and (not (funcall backup-enable-predicate buffer-file-name))
781 (progn
782 (make-local-variable 'backup-inhibited)
783 (setq backup-inhibited t)))
784 (if rawfile
786 (after-find-file error (not nowarn)))))
787 buf)))
789 (defvar after-find-file-from-revert-buffer nil)
791 (defun after-find-file (&optional error warn noauto
792 after-find-file-from-revert-buffer)
793 "Called after finding a file and by the default revert function.
794 Sets buffer mode, parses local variables.
795 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
796 error in reading the file. WARN non-nil means warn if there
797 exists an auto-save file more recent than the visited file.
798 NOAUTO means don't mess with auto-save mode.
799 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
800 means this call was from `revert-buffer'.
801 Finishes by calling the functions in `find-file-hooks'."
802 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
803 (if noninteractive
805 (let* (not-serious
806 (msg
807 (cond ((and error (file-attributes buffer-file-name))
808 (setq buffer-read-only t)
809 "File exists, but cannot be read.")
810 ((not buffer-read-only)
811 (if (and warn
812 (file-newer-than-file-p (make-auto-save-file-name)
813 buffer-file-name))
814 "Auto save file is newer; consider M-x recover-file"
815 (setq not-serious t)
816 (if error "(New file)" nil)))
817 ((not error)
818 (setq not-serious t)
819 "Note: file is write protected")
820 ((file-attributes (directory-file-name default-directory))
821 "File not found and directory write-protected")
822 ((file-exists-p (file-name-directory buffer-file-name))
823 (setq buffer-read-only nil))
825 (setq buffer-read-only nil)
826 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
827 "Use M-x make-dir RET RET to create the directory"
828 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
829 (if msg
830 (progn
831 (message msg)
832 (or not-serious (sit-for 1 nil t)))))
833 (if (and auto-save-default (not noauto))
834 (auto-save-mode t)))
835 (normal-mode t)
836 (run-hooks 'find-file-hooks))
838 (defun normal-mode (&optional find-file)
839 "Choose the major mode for this buffer automatically.
840 Also sets up any specified local variables of the file.
841 Uses the visited file name, the -*- line, and the local variables spec.
843 This function is called automatically from `find-file'. In that case,
844 we may set up specified local variables depending on the value of
845 `enable-local-variables': if it is t, we do; if it is nil, we don't;
846 otherwise, we query. `enable-local-variables' is ignored if you
847 run `normal-mode' explicitly."
848 (interactive)
849 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
850 (condition-case err
851 (set-auto-mode)
852 (error (message "File mode specification error: %s"
853 (prin1-to-string err))))
854 (condition-case err
855 (let ((enable-local-variables (or (not find-file)
856 enable-local-variables)))
857 (hack-local-variables))
858 (error (message "File local-variables error: %s"
859 (prin1-to-string err)))))
861 (defvar auto-mode-alist (mapcar 'purecopy
862 '(("\\.text\\'" . text-mode)
863 ("\\.c\\'" . c-mode)
864 ("\\.h\\'" . c-mode)
865 ("\\.tex\\'" . tex-mode)
866 ("\\.ltx\\'" . latex-mode)
867 ("\\.el\\'" . emacs-lisp-mode)
868 ("\\.mm\\'" . nroff-mode)
869 ("\\.me\\'" . nroff-mode)
870 ("\\.ms\\'" . nroff-mode)
871 ("\\.man\\'" . nroff-mode)
872 ("\\.scm\\'" . scheme-mode)
873 ("\\.l\\'" . lisp-mode)
874 ("\\.lisp\\'" . lisp-mode)
875 ("\\.f\\'" . fortran-mode)
876 ("\\.for\\'" . fortran-mode)
877 ("\\.p\\'" . pascal-mode)
878 ("\\.pas\\'" . pascal-mode)
879 ("\\.mss\\'" . scribe-mode)
880 ("\\.ad[abs]\\'" . ada-mode)
881 ("\\.icn\\'" . icon-mode)
882 ("\\.pl\\'" . perl-mode)
883 ("\\.cc\\'" . c++-mode)
884 ("\\.hh\\'" . c++-mode)
885 ("\\.C\\'" . c++-mode)
886 ("\\.H\\'" . c++-mode)
887 ("\\.cpp\\'" . c++-mode)
888 ("\\.cxx\\'" . c++-mode)
889 ("\\.hxx\\'" . c++-mode)
890 ("\\.c\\+\\+\\'" . c++-mode)
891 ("\\.h\\+\\+\\'" . c++-mode)
892 ("\\.mk\\'" . makefile-mode)
893 ("[Mm]akefile\\(.in\\)?\\'" . makefile-mode)
894 ;;; Less common extensions come here
895 ;;; so more common ones above are found faster.
896 ("\\.texinfo\\'" . texinfo-mode)
897 ("\\.texi\\'" . texinfo-mode)
898 ("\\.s\\'" . asm-mode)
899 ("ChangeLog\\'" . change-log-mode)
900 ("change.log\\'" . change-log-mode)
901 ("changelo\\'" . change-log-mode)
902 ("ChangeLog.[0-9]+\\'" . change-log-mode)
903 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
904 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
905 ;;; The following should come after the ChangeLog pattern
906 ;;; for the sake of ChangeLog.1, etc.
907 ;;; and after the .scm.[0-9] pattern too.
908 ("\\.[12345678]\\'" . nroff-mode)
909 ("\\.TeX\\'" . tex-mode)
910 ("\\.sty\\'" . latex-mode)
911 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
912 ("\\.bbl\\'" . latex-mode)
913 ("\\.bib\\'" . bibtex-mode)
914 ("\\.article\\'" . text-mode)
915 ("\\.letter\\'" . text-mode)
916 ("\\.tcl\\'" . tcl-mode)
917 ("\\.f90\\'" . f90-mode)
918 ("\\.lsp\\'" . lisp-mode)
919 ("\\.awk\\'" . awk-mode)
920 ("\\.prolog\\'" . prolog-mode)
921 ("\\.tar\\'" . tar-mode)
922 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode)
923 ;; Mailer puts message to be edited in
924 ;; /tmp/Re.... or Message
925 ("^/tmp/Re" . text-mode)
926 ("/Message[0-9]*\\'" . text-mode)
927 ("/drafts/[0-9]+\\'" . mh-letter-mode)
928 ;; some news reader is reported to use this
929 ("^/tmp/fol/" . text-mode)
930 ("\\.y\\'" . c-mode)
931 ("\\.lex\\'" . c-mode)
932 ("\\.oak\\'" . scheme-mode)
933 ("\\.sgm\\'" . sgml-mode)
934 ("\\.sgml\\'" . sgml-mode)
935 ("\\.dtd\\'" . sgml-mode)
936 ;; .emacs following a directory delimiter
937 ;; in either Unix or VMS syntax.
938 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
939 ;; _emacs following a directory delimiter
940 ;; in MsDos syntax
941 ("[:/]_emacs\\'" . emacs-lisp-mode)
942 ("\\.ml\\'" . lisp-mode)))
944 Alist of filename patterns vs corresponding major mode functions.
945 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
946 \(NON-NIL stands for anything that is not nil; the value does not matter.)
947 Visiting a file whose name matches REGEXP specifies FUNCTION as the
948 mode function to use. FUNCTION will be called, unless it is nil.
950 If the element has the form (REGEXP FUNCTION NON-NIL), then after
951 calling FUNCTION (if it's not nil), we delete the suffix that matched
952 REGEXP and search the list again for another match.")
954 (defconst interpreter-mode-alist
955 '(("perl" . perl-mode)
956 ("wish" . tcl-mode)
957 ("wishx" . tcl-mode)
958 ("tcl" . tcl-mode)
959 ("tclsh" . tcl-mode)
960 ("awk" . awk-mode)
961 ("nawk" . awk-mode)
962 ("gawk" . awk-mode)
963 ("scm" . scheme-mode))
964 "Alist mapping interpreter names to major modes.
965 This alist applies to files whose first line starts with `#!'.
966 Each element looks like (INTERPRETER . MODE).
967 The car of each element is compared with
968 the name of the interpreter specified in the first line.
969 If it matches, mode MODE is selected.")
971 (defconst inhibit-first-line-modes-regexps '("\\.tar\\'")
972 "List of regexps; if one matches a file name, don't look for `-*-'.")
974 (defconst inhibit-first-line-modes-suffixes nil
975 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
976 When checking `inhibit-first-line-modes-regexps', we first discard
977 from the end of the file name anything that matches one of these regexps.")
979 (defvar user-init-file
980 "" ; set by command-line
981 "File name including directory of user's initialization file.")
983 (defun set-auto-mode ()
984 "Select major mode appropriate for current buffer.
985 This checks for a -*- mode tag in the buffer's text,
986 compares the filename against the entries in `auto-mode-alist',
987 or checks the interpreter that runs this file against
988 `interpreter-mode-alist'.
990 It does not check for the `mode:' local variable in the
991 Local Variables section of the file; for that, use `hack-local-variables'.
993 If `enable-local-variables' is nil, this function does not check for a
994 -*- mode tag."
995 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
996 (let (beg end done)
997 (save-excursion
998 (goto-char (point-min))
999 (skip-chars-forward " \t\n")
1000 (and enable-local-variables
1001 ;; Don't look for -*- if this file name matches any
1002 ;; of the regexps in inhibit-first-line-modes-regexps.
1003 (let ((temp inhibit-first-line-modes-regexps)
1004 (name (if buffer-file-name
1005 (file-name-sans-versions buffer-file-name)
1006 (buffer-name))))
1007 (while (let ((sufs inhibit-first-line-modes-suffixes))
1008 (while (and sufs (not (string-match (car sufs) name)))
1009 (setq sufs (cdr sufs)))
1010 sufs)
1011 (setq name (substring name 0 (match-beginning 0))))
1012 (while (and temp
1013 (not (string-match (car temp) name)))
1014 (setq temp (cdr temp)))
1015 (not temp))
1016 (search-forward "-*-" (save-excursion
1017 ;; If the file begins with "#!"
1018 ;; (exec interpreter magic), look
1019 ;; for mode frobs in the first two
1020 ;; lines. You cannot necessarily
1021 ;; put them in the first line of
1022 ;; such a file without screwing up
1023 ;; the interpreter invocation.
1024 (end-of-line (and (looking-at "^#!") 2))
1025 (point)) t)
1026 (progn
1027 (skip-chars-forward " \t")
1028 (setq beg (point))
1029 (search-forward "-*-"
1030 (save-excursion (end-of-line) (point))
1032 (progn
1033 (forward-char -3)
1034 (skip-chars-backward " \t")
1035 (setq end (point))
1036 (goto-char beg)
1037 (if (save-excursion (search-forward ":" end t))
1038 ;; Find all specifications for the `mode:' variable
1039 ;; and execute them left to right.
1040 (while (let ((case-fold-search t))
1041 (or (and (looking-at "mode:")
1042 (goto-char (match-end 0)))
1043 (re-search-forward "[ \t;]mode:" end t)))
1044 (skip-chars-forward " \t")
1045 (setq beg (point))
1046 (if (search-forward ";" end t)
1047 (forward-char -1)
1048 (goto-char end))
1049 (skip-chars-backward " \t")
1050 (funcall (intern (concat (downcase (buffer-substring beg (point))) "-mode")))
1051 (setq done t))
1052 ;; Simple -*-MODE-*- case.
1053 (funcall (intern (concat (downcase (buffer-substring beg end)) "-mode")))
1054 (setq done t))))
1055 ;; If we didn't find a mode from a -*- line, try using the file name.
1056 (if (and (not done) buffer-file-name)
1057 (let ((name buffer-file-name)
1058 (keep-going t))
1059 ;; Remove backup-suffixes from file name.
1060 (setq name (file-name-sans-versions name))
1061 (while keep-going
1062 (setq keep-going nil)
1063 (let ((alist auto-mode-alist)
1064 (mode nil))
1065 ;; Find first matching alist entry.
1066 (let ((case-fold-search
1067 (memq system-type '(vax-vms windows-nt))))
1068 (while (and (not mode) alist)
1069 (if (string-match (car (car alist)) name)
1070 (if (and (consp (cdr (car alist)))
1071 (nth 2 (car alist)))
1072 (progn
1073 (setq mode (car (cdr (car alist)))
1074 name (substring name 0 (match-beginning 0))
1075 keep-going t))
1076 (setq mode (cdr (car alist))
1077 keep-going nil)))
1078 (setq alist (cdr alist))))
1079 (if mode
1080 (funcall mode)
1081 ;; If we can't deduce a mode from the file name,
1082 ;; look for an interpreter specified in the first line.
1083 (let ((interpreter
1084 (save-excursion
1085 (goto-char (point-min))
1086 (if (looking-at "#! *\\([^ \t\n]+\\)")
1087 (buffer-substring (match-beginning 1)
1088 (match-end 1))
1089 "")))
1090 elt)
1091 ;; Map interpreter name to a mode.
1092 (setq elt (assoc (file-name-nondirectory interpreter)
1093 interpreter-mode-alist))
1094 (if elt
1095 (funcall (cdr elt))))))))))))
1097 (defun hack-local-variables-prop-line ()
1098 ;; Set local variables specified in the -*- line.
1099 ;; Ignore any specification for `mode:';
1100 ;; set-auto-mode should already have handled that.
1101 (save-excursion
1102 (goto-char (point-min))
1103 (let ((result nil)
1104 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1105 ;; Parse the -*- line into the `result' alist.
1106 (cond ((not (search-forward "-*-" end t))
1107 ;; doesn't have one.
1108 nil)
1109 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1110 ;; Simple form: "-*- MODENAME -*-". Already handled.
1111 nil)
1113 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1114 ;; (last ";" is optional).
1115 (save-excursion
1116 (if (search-forward "-*-" end t)
1117 (setq end (- (point) 3))
1118 (error "-*- not terminated before end of line")))
1119 (while (< (point) end)
1120 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1121 (error "malformed -*- line"))
1122 (goto-char (match-end 0))
1123 ;; There used to be a downcase here,
1124 ;; but the manual didn't say so,
1125 ;; and people want to set var names that aren't all lc.
1126 (let ((key (intern (buffer-substring
1127 (match-beginning 1)
1128 (match-end 1))))
1129 (val (save-restriction
1130 (narrow-to-region (point) end)
1131 (read (current-buffer)))))
1132 (or (eq key 'mode)
1133 (setq result (cons (cons key val) result)))
1134 (skip-chars-forward " \t;")))
1135 (setq result (nreverse result))))
1137 (if (and result
1138 (or (eq enable-local-variables t)
1139 (and enable-local-variables
1140 (save-window-excursion
1141 (condition-case nil
1142 (switch-to-buffer (current-buffer))
1143 (error
1144 ;; If we fail to switch in the selected window,
1145 ;; it is probably a minibuffer.
1146 ;; So try another window.
1147 (condition-case nil
1148 (switch-to-buffer-other-window (current-buffer))
1149 (error
1150 (switch-to-buffer-other-frame (current-buffer))))))
1151 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1152 (file-name-nondirectory buffer-file-name)))))))
1153 (while result
1154 (hack-one-local-variable (car (car result)) (cdr (car result)))
1155 (setq result (cdr result)))))))
1157 (defvar hack-local-variables-hook nil
1158 "Normal hook run after processing a file's local variables specs.
1159 Major modes can use this to examine user-specified local variables
1160 in order to initialize other data structure based on them.")
1162 (defun hack-local-variables ()
1163 "Parse and put into effect this buffer's local variables spec."
1164 (hack-local-variables-prop-line)
1165 ;; Look for "Local variables:" line in last page.
1166 (save-excursion
1167 (goto-char (point-max))
1168 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1169 (if (let ((case-fold-search t))
1170 (and (search-forward "Local Variables:" nil t)
1171 (or (eq enable-local-variables t)
1172 (and enable-local-variables
1173 (save-window-excursion
1174 (switch-to-buffer (current-buffer))
1175 (save-excursion
1176 (beginning-of-line)
1177 (set-window-start (selected-window) (point)))
1178 (y-or-n-p (format "Set local variables as specified at end of %s? "
1179 (if buffer-file-name
1180 (file-name-nondirectory
1181 buffer-file-name)
1182 (concat "buffer "
1183 (buffer-name))))))))))
1184 (let ((continue t)
1185 prefix prefixlen suffix beg
1186 (enable-local-eval enable-local-eval))
1187 ;; The prefix is what comes before "local variables:" in its line.
1188 ;; The suffix is what comes after "local variables:" in its line.
1189 (skip-chars-forward " \t")
1190 (or (eolp)
1191 (setq suffix (buffer-substring (point)
1192 (progn (end-of-line) (point)))))
1193 (goto-char (match-beginning 0))
1194 (or (bolp)
1195 (setq prefix
1196 (buffer-substring (point)
1197 (progn (beginning-of-line) (point)))))
1199 (if prefix (setq prefixlen (length prefix)
1200 prefix (regexp-quote prefix)))
1201 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1202 (while continue
1203 ;; Look at next local variable spec.
1204 (if selective-display (re-search-forward "[\n\C-m]")
1205 (forward-line 1))
1206 ;; Skip the prefix, if any.
1207 (if prefix
1208 (if (looking-at prefix)
1209 (forward-char prefixlen)
1210 (error "Local variables entry is missing the prefix")))
1211 ;; Find the variable name; strip whitespace.
1212 (skip-chars-forward " \t")
1213 (setq beg (point))
1214 (skip-chars-forward "^:\n")
1215 (if (eolp) (error "Missing colon in local variables entry"))
1216 (skip-chars-backward " \t")
1217 (let* ((str (buffer-substring beg (point)))
1218 (var (read str))
1219 val)
1220 ;; Setting variable named "end" means end of list.
1221 (if (string-equal (downcase str) "end")
1222 (setq continue nil)
1223 ;; Otherwise read the variable value.
1224 (skip-chars-forward "^:")
1225 (forward-char 1)
1226 (setq val (read (current-buffer)))
1227 (skip-chars-backward "\n")
1228 (skip-chars-forward " \t")
1229 (or (if suffix (looking-at suffix) (eolp))
1230 (error "Local variables entry is terminated incorrectly"))
1231 ;; Set the variable. "Variables" mode and eval are funny.
1232 (hack-one-local-variable var val)))))))
1233 (run-hooks 'hack-local-variables-hook))
1235 (defconst ignored-local-variables
1236 '(enable-local-eval)
1237 "Variables to be ignored in a file's local variable spec.")
1239 ;; Get confirmation before setting these variables as locals in a file.
1240 (put 'debugger 'risky-local-variable t)
1241 (put 'enable-local-eval 'risky-local-variable t)
1242 (put 'ignored-local-variables 'risky-local-variable t)
1243 (put 'eval 'risky-local-variable t)
1244 (put 'file-name-handler-alist 'risky-local-variable t)
1245 (put 'minor-mode-map-alist 'risky-local-variable t)
1246 (put 'after-load-alist 'risky-local-variable t)
1247 (put 'buffer-file-name 'risky-local-variable t)
1248 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1249 (put 'buffer-file-truename 'risky-local-variable t)
1250 (put 'exec-path 'risky-local-variable t)
1251 (put 'load-path 'risky-local-variable t)
1252 (put 'exec-directory 'risky-local-variable t)
1253 (put 'process-environment 'risky-local-variable t)
1254 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1255 (put 'outline-level 'risky-local-variable t)
1256 (put 'rmail-output-file-alist 'risky-local-variable t)
1258 ;; This one is safe because the user gets to check it before it is used.
1259 (put 'compile-command 'safe-local-variable t)
1261 (defun hack-one-local-variable-quotep (exp)
1262 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1264 ;; "Set" one variable in a local variables spec.
1265 ;; A few variable names are treated specially.
1266 (defun hack-one-local-variable (var val)
1267 (cond ((eq var 'mode)
1268 (funcall (intern (concat (downcase (symbol-name val))
1269 "-mode"))))
1270 ((memq var ignored-local-variables)
1271 nil)
1272 ;; "Setting" eval means either eval it or do nothing.
1273 ;; Likewise for setting hook variables.
1274 ((or (get var 'risky-local-variable)
1275 (and
1276 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1277 (symbol-name var))
1278 (not (get var 'safe-local-variable))))
1279 ;; Permit evaling a put of a harmless property
1280 ;; if the args do nothing tricky.
1281 (if (or (and (eq var 'eval)
1282 (consp val)
1283 (eq (car val) 'put)
1284 (hack-one-local-variable-quotep (nth 1 val))
1285 (hack-one-local-variable-quotep (nth 2 val))
1286 ;; Only allow safe values of lisp-indent-hook;
1287 ;; not functions.
1288 (or (numberp (nth 3 val))
1289 (equal (nth 3 val) ''defun))
1290 (memq (nth 1 (nth 2 val))
1291 '(lisp-indent-hook)))
1292 ;; Permit eval if not root and user says ok.
1293 (and (not (zerop (user-uid)))
1294 (or (eq enable-local-eval t)
1295 (and enable-local-eval
1296 (save-window-excursion
1297 (switch-to-buffer (current-buffer))
1298 (save-excursion
1299 (beginning-of-line)
1300 (set-window-start (selected-window) (point)))
1301 (setq enable-local-eval
1302 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1303 (file-name-nondirectory buffer-file-name)))))))))
1304 (if (eq var 'eval)
1305 (save-excursion (eval val))
1306 (make-local-variable var)
1307 (set var val))
1308 (message "Ignoring `eval:' in file's local variables")))
1309 ;; Ordinary variable, really set it.
1310 (t (make-local-variable var)
1311 (set var val))))
1314 (defun set-visited-file-name (filename)
1315 "Change name of file visited in current buffer to FILENAME.
1316 The next time the buffer is saved it will go in the newly specified file.
1317 nil or empty string as argument means make buffer not be visiting any file.
1318 Remember to delete the initial contents of the minibuffer
1319 if you wish to pass an empty string as the argument."
1320 (interactive "FSet visited file name: ")
1321 (if (buffer-base-buffer)
1322 (error "An indirect buffer cannot visit a file"))
1323 (let (truename)
1324 (if filename
1325 (setq filename
1326 (if (string-equal filename "")
1328 (expand-file-name filename))))
1329 (if filename
1330 (progn
1331 (setq truename (file-truename filename))
1332 (if find-file-visit-truename
1333 ;; Do not use the abbreviated filename, because
1334 ;; write-region will reset it to the expanded filename
1335 (setq filename truename))))
1336 (or (equal filename buffer-file-name)
1337 (progn
1338 (and filename (lock-buffer filename))
1339 (unlock-buffer)))
1340 (setq buffer-file-name filename)
1341 (if filename ; make buffer name reflect filename.
1342 (let ((new-name (file-name-nondirectory buffer-file-name)))
1343 (if (string= new-name "")
1344 (error "Empty file name"))
1345 (if (eq system-type 'vax-vms)
1346 (setq new-name (downcase new-name)))
1347 (setq default-directory (file-name-directory buffer-file-name))
1348 (or (string= new-name (buffer-name))
1349 (rename-buffer new-name t))))
1350 (setq buffer-backed-up nil)
1351 (clear-visited-file-modtime)
1352 (if truename
1353 (setq buffer-file-truename (abbreviate-file-name truename)))
1354 (setq buffer-file-number
1355 (if filename
1356 (nth 10 (file-attributes buffer-file-name))
1357 nil)))
1358 ;; write-file-hooks is normally used for things like ftp-find-file
1359 ;; that visit things that are not local files as if they were files.
1360 ;; Changing to visit an ordinary local file instead should flush the hook.
1361 (kill-local-variable 'write-file-hooks)
1362 (kill-local-variable 'local-write-file-hooks)
1363 (kill-local-variable 'revert-buffer-function)
1364 (kill-local-variable 'backup-inhibited)
1365 ;; If buffer was read-only because of version control,
1366 ;; that reason is gone now, so make it writable.
1367 (if vc-mode
1368 (setq buffer-read-only nil))
1369 (kill-local-variable 'vc-mode)
1370 ;; Turn off backup files for certain file names.
1371 ;; Since this is a permanent local, the major mode won't eliminate it.
1372 (and (not (funcall backup-enable-predicate buffer-file-name))
1373 (progn
1374 (make-local-variable 'backup-inhibited)
1375 (setq backup-inhibited t)))
1376 (let ((oauto buffer-auto-save-file-name))
1377 ;; If auto-save was not already on, turn it on if appropriate.
1378 (if (not buffer-auto-save-file-name)
1379 (and buffer-file-name auto-save-default
1380 (auto-save-mode t))
1381 ;; If auto save is on, start using a new name.
1382 ;; We deliberately don't rename or delete the old auto save
1383 ;; for the old visited file name. This is because perhaps
1384 ;; the user wants to save the new state and then compare with the
1385 ;; previous state from the auto save file.
1386 (setq buffer-auto-save-file-name
1387 (make-auto-save-file-name)))
1388 ;; Rename the old auto save file if any.
1389 (and oauto buffer-auto-save-file-name
1390 (file-exists-p oauto)
1391 (rename-file oauto buffer-auto-save-file-name t)))
1392 (if buffer-file-name
1393 (set-buffer-modified-p t)))
1395 (defun write-file (filename &optional confirm)
1396 "Write current buffer into file FILENAME.
1397 Makes buffer visit that file, and marks it not modified.
1398 If the buffer is already visiting a file, you can specify
1399 a directory name as FILENAME, to write a file of the same
1400 old name in that directory.
1401 If optional second arg CONFIRM is non-nil,
1402 ask for confirmation for overwriting an existing file."
1403 ;; (interactive "FWrite file: ")
1404 (interactive
1405 (list (if buffer-file-name
1406 (read-file-name "Write file: "
1407 nil nil nil nil)
1408 (read-file-name "Write file: "
1409 (cdr (assq 'default-directory
1410 (buffer-local-variables)))
1411 nil nil (buffer-name)))
1413 (or (null filename) (string-equal filename "")
1414 (progn
1415 ;; If arg is just a directory,
1416 ;; use same file name, but in that directory.
1417 (if (and (file-directory-p filename) buffer-file-name)
1418 (setq filename (concat (file-name-as-directory filename)
1419 (file-name-nondirectory buffer-file-name))))
1420 (and confirm
1421 (file-exists-p filename)
1422 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1423 (error "Canceled")))
1424 (set-visited-file-name filename)))
1425 (set-buffer-modified-p t)
1426 (save-buffer))
1428 (defun backup-buffer ()
1429 "Make a backup of the disk file visited by the current buffer, if appropriate.
1430 This is normally done before saving the buffer the first time.
1431 If the value is non-nil, it is the result of `file-modes' on the original
1432 file; this means that the caller, after saving the buffer, should change
1433 the modes of the new file to agree with the old modes."
1434 (if (and make-backup-files (not backup-inhibited)
1435 (not buffer-backed-up)
1436 (file-exists-p buffer-file-name)
1437 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1438 '(?- ?l)))
1439 (let ((real-file-name buffer-file-name)
1440 backup-info backupname targets setmodes)
1441 ;; If specified name is a symbolic link, chase it to the target.
1442 ;; Thus we make the backups in the directory where the real file is.
1443 (setq real-file-name (file-chase-links real-file-name))
1444 (setq backup-info (find-backup-file-name real-file-name)
1445 backupname (car backup-info)
1446 targets (cdr backup-info))
1447 ;;; (if (file-directory-p buffer-file-name)
1448 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1449 (if backup-info
1450 (condition-case ()
1451 (let ((delete-old-versions
1452 ;; If have old versions to maybe delete,
1453 ;; ask the user to confirm now, before doing anything.
1454 ;; But don't actually delete til later.
1455 (and targets
1456 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1457 (or delete-old-versions
1458 (y-or-n-p (format "Delete excess backup versions of %s? "
1459 real-file-name))))))
1460 ;; Actually write the back up file.
1461 (condition-case ()
1462 (if (or file-precious-flag
1463 ; (file-symlink-p buffer-file-name)
1464 backup-by-copying
1465 (and backup-by-copying-when-linked
1466 (> (file-nlinks real-file-name) 1))
1467 (and backup-by-copying-when-mismatch
1468 (let ((attr (file-attributes real-file-name)))
1469 (or (nth 9 attr)
1470 (not (file-ownership-preserved-p real-file-name))))))
1471 (condition-case ()
1472 (copy-file real-file-name backupname t t)
1473 (file-error
1474 ;; If copying fails because file BACKUPNAME
1475 ;; is not writable, delete that file and try again.
1476 (if (and (file-exists-p backupname)
1477 (not (file-writable-p backupname)))
1478 (delete-file backupname))
1479 (copy-file real-file-name backupname t t)))
1480 ;; rename-file should delete old backup.
1481 (rename-file real-file-name backupname t)
1482 (setq setmodes (file-modes backupname)))
1483 (file-error
1484 ;; If trouble writing the backup, write it in ~.
1485 (setq backupname (expand-file-name "~/%backup%~"))
1486 (message "Cannot write backup file; backing up in ~/%%backup%%~")
1487 (sleep-for 1)
1488 (condition-case ()
1489 (copy-file real-file-name backupname t t)
1490 (file-error
1491 ;; If copying fails because file BACKUPNAME
1492 ;; is not writable, delete that file and try again.
1493 (if (and (file-exists-p backupname)
1494 (not (file-writable-p backupname)))
1495 (delete-file backupname))
1496 (copy-file real-file-name backupname t t)))))
1497 (setq buffer-backed-up t)
1498 ;; Now delete the old versions, if desired.
1499 (if delete-old-versions
1500 (while targets
1501 (condition-case ()
1502 (delete-file (car targets))
1503 (file-error nil))
1504 (setq targets (cdr targets))))
1505 setmodes)
1506 (file-error nil))))))
1508 (defun file-name-sans-versions (name &optional keep-backup-version)
1509 "Return FILENAME sans backup versions or strings.
1510 This is a separate procedure so your site-init or startup file can
1511 redefine it.
1512 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1513 we do not remove backup version numbers, only true file version numbers."
1514 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1515 (if handler
1516 (funcall handler 'file-name-sans-versions name keep-backup-version)
1517 (substring name 0
1518 (if (eq system-type 'vax-vms)
1519 ;; VMS version number is (a) semicolon, optional
1520 ;; sign, zero or more digits or (b) period, option
1521 ;; sign, zero or more digits, provided this is the
1522 ;; second period encountered outside of the
1523 ;; device/directory part of the file name.
1524 (or (string-match ";[-+]?[0-9]*\\'" name)
1525 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1526 name)
1527 (match-beginning 1))
1528 (length name))
1529 (if keep-backup-version
1530 (length name)
1531 (or (string-match "\\.~[0-9.]+~\\'" name)
1532 (string-match "~\\'" name)
1533 (length name))))))))
1535 (defun file-ownership-preserved-p (file)
1536 "Returns t if deleting FILE and rewriting it would preserve the owner."
1537 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1538 (if handler
1539 (funcall handler 'file-ownership-preserved-p file)
1540 (let ((attributes (file-attributes file)))
1541 ;; Return t if the file doesn't exist, since it's true that no
1542 ;; information would be lost by an (attempted) delete and create.
1543 (or (null attributes)
1544 (= (nth 2 attributes) (user-uid)))))))
1546 (defun file-name-sans-extension (filename)
1547 "Return FILENAME sans final \"extension\".
1548 The extension, in a file name, is the part that follows the last `.'."
1549 (save-match-data
1550 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1551 directory)
1552 (if (string-match "\\.[^.]*\\'" file)
1553 (if (setq directory (file-name-directory filename))
1554 (expand-file-name (substring file 0 (match-beginning 0))
1555 directory)
1556 (substring file 0 (match-beginning 0)))
1557 filename))))
1559 (defun make-backup-file-name (file)
1560 "Create the non-numeric backup file name for FILE.
1561 This is a separate function so you can redefine it for customization."
1562 (if (eq system-type 'ms-dos)
1563 (let ((fn (file-name-nondirectory file)))
1564 (concat (file-name-directory file)
1565 (if (string-match "\\([^.]*\\)\\(\\..*\\)?" fn)
1566 (substring fn 0 (match-end 1)))
1567 ".bak"))
1568 (concat file "~")))
1570 (defun backup-file-name-p (file)
1571 "Return non-nil if FILE is a backup file name (numeric or not).
1572 This is a separate function so you can redefine it for customization.
1573 You may need to redefine `file-name-sans-versions' as well."
1574 (if (eq system-type 'ms-dos)
1575 (string-match "\\.bak$" file)
1576 (string-match "~$" file)))
1578 ;; This is used in various files.
1579 ;; The usage of bv-length is not very clean,
1580 ;; but I can't see a good alternative,
1581 ;; so as of now I am leaving it alone.
1582 (defun backup-extract-version (fn)
1583 "Given the name of a numeric backup file, return the backup number.
1584 Uses the free variable `bv-length', whose value should be
1585 the index in the name where the version number begins."
1586 (if (and (string-match "[0-9]+~$" fn bv-length)
1587 (= (match-beginning 0) bv-length))
1588 (string-to-int (substring fn bv-length -1))
1591 ;; I believe there is no need to alter this behavior for VMS;
1592 ;; since backup files are not made on VMS, it should not get called.
1593 (defun find-backup-file-name (fn)
1594 "Find a file name for a backup file, and suggestions for deletions.
1595 Value is a list whose car is the name for the backup file
1596 and whose cdr is a list of old versions to consider deleting now.
1597 If the value is nil, don't make a backup."
1598 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
1599 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1600 (if handler
1601 (funcall handler 'find-backup-file-name fn)
1602 (if (eq version-control 'never)
1603 (list (make-backup-file-name fn))
1604 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1605 (bv-length (length base-versions))
1606 possibilities
1607 (versions nil)
1608 (high-water-mark 0)
1609 (deserve-versions-p nil)
1610 (number-to-delete 0))
1611 (condition-case ()
1612 (setq possibilities (file-name-all-completions
1613 base-versions
1614 (file-name-directory fn))
1615 versions (sort (mapcar
1616 (function backup-extract-version)
1617 possibilities)
1619 high-water-mark (apply 'max 0 versions)
1620 deserve-versions-p (or version-control
1621 (> high-water-mark 0))
1622 number-to-delete (- (length versions)
1623 kept-old-versions kept-new-versions -1))
1624 (file-error
1625 (setq possibilities nil)))
1626 (if (not deserve-versions-p)
1627 (list (make-backup-file-name fn))
1628 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1629 (if (and (> number-to-delete 0)
1630 ;; Delete nothing if there is overflow
1631 ;; in the number of versions to keep.
1632 (>= (+ kept-new-versions kept-old-versions -1) 0))
1633 (mapcar (function (lambda (n)
1634 (concat fn ".~" (int-to-string n) "~")))
1635 (let ((v (nthcdr kept-old-versions versions)))
1636 (rplacd (nthcdr (1- number-to-delete) v) ())
1637 v))))))))))
1639 (defun file-nlinks (filename)
1640 "Return number of names file FILENAME has."
1641 (car (cdr (file-attributes filename))))
1643 (defun file-relative-name (filename &optional directory)
1644 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1645 (setq filename (expand-file-name filename)
1646 directory (file-name-as-directory (expand-file-name
1647 (or directory default-directory))))
1648 (let ((ancestor ""))
1649 (while (not (string-match (concat "^" (regexp-quote directory)) filename))
1650 (setq directory (file-name-directory (substring directory 0 -1))
1651 ancestor (concat "../" ancestor)))
1652 (concat ancestor (substring filename (match-end 0)))))
1654 (defun save-buffer (&optional args)
1655 "Save current buffer in visited file if modified. Versions described below.
1656 By default, makes the previous version into a backup file
1657 if previously requested or if this is the first save.
1658 With 1 or 3 \\[universal-argument]'s, marks this version
1659 to become a backup when the next save is done.
1660 With 2 or 3 \\[universal-argument]'s,
1661 unconditionally makes the previous version into a backup file.
1662 With argument of 0, never makes the previous version into a backup file.
1664 If a file's name is FOO, the names of its numbered backup versions are
1665 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1666 Numeric backups (rather than FOO~) will be made if value of
1667 `version-control' is not the atom `never' and either there are already
1668 numeric versions of the file being backed up, or `version-control' is
1669 non-nil.
1670 We don't want excessive versions piling up, so there are variables
1671 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1672 and `kept-new-versions', which tells how many newest versions to keep.
1673 Defaults are 2 old versions and 2 new.
1674 `dired-kept-versions' controls dired's clean-directory (.) command.
1675 If `delete-old-versions' is nil, system will query user
1676 before trimming versions. Otherwise it does it silently."
1677 (interactive "p")
1678 (let ((modp (buffer-modified-p))
1679 (large (> (buffer-size) 50000))
1680 (make-backup-files (or (and make-backup-files (not (eq args 0)))
1681 (memq args '(16 64)))))
1682 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
1683 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
1684 (basic-save-buffer)
1685 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
1687 (defun delete-auto-save-file-if-necessary (&optional force)
1688 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1689 Normally delete only if the file was written by this Emacs since
1690 the last real save, but optional arg FORCE non-nil means delete anyway."
1691 (and buffer-auto-save-file-name delete-auto-save-files
1692 (not (string= buffer-file-name buffer-auto-save-file-name))
1693 (or force (recent-auto-save-p))
1694 (progn
1695 (condition-case ()
1696 (delete-file buffer-auto-save-file-name)
1697 (file-error nil))
1698 (set-buffer-auto-saved))))
1700 (defvar after-save-hook nil
1701 "Normal hook that is run after a buffer is saved to its file.")
1703 (defun basic-save-buffer ()
1704 "Save the current buffer in its visited file, if it has been modified.
1705 After saving the buffer, run `after-save-hook'."
1706 (interactive)
1707 (save-excursion
1708 ;; In an indirect buffer, save its base buffer instead.
1709 (if (buffer-base-buffer)
1710 (set-buffer (buffer-base-buffer)))
1711 (if (buffer-modified-p)
1712 (let ((recent-save (recent-auto-save-p))
1713 setmodes tempsetmodes)
1714 ;; On VMS, rename file and buffer to get rid of version number.
1715 (if (and (eq system-type 'vax-vms)
1716 (not (string= buffer-file-name
1717 (file-name-sans-versions buffer-file-name))))
1718 (let (buffer-new-name)
1719 ;; Strip VMS version number before save.
1720 (setq buffer-file-name
1721 (file-name-sans-versions buffer-file-name))
1722 ;; Construct a (unique) buffer name to correspond.
1723 (let ((buf (create-file-buffer (downcase buffer-file-name))))
1724 (setq buffer-new-name (buffer-name buf))
1725 (kill-buffer buf))
1726 (rename-buffer buffer-new-name)))
1727 ;; If buffer has no file name, ask user for one.
1728 (or buffer-file-name
1729 (let ((filename
1730 (expand-file-name
1731 (read-file-name "File to save in: ") nil)))
1732 (and (file-exists-p filename)
1733 (or (y-or-n-p (format "File `%s' exists; overwrite? "
1734 filename))
1735 (error "Canceled")))
1736 (set-visited-file-name filename)))
1737 (or (verify-visited-file-modtime (current-buffer))
1738 (not (file-exists-p buffer-file-name))
1739 (yes-or-no-p
1740 (format "%s has changed since visited or saved. Save anyway? "
1741 (file-name-nondirectory buffer-file-name)))
1742 (error "Save not confirmed"))
1743 (save-restriction
1744 (widen)
1745 (and (> (point-max) 1)
1746 (/= (char-after (1- (point-max))) ?\n)
1747 (not (and (eq selective-display t)
1748 (= (char-after (1- (point-max))) ?\r)))
1749 (or (eq require-final-newline t)
1750 (and require-final-newline
1751 (y-or-n-p
1752 (format "Buffer %s does not end in newline. Add one? "
1753 (buffer-name)))))
1754 (save-excursion
1755 (goto-char (point-max))
1756 (insert ?\n)))
1757 (or (run-hook-with-args-until-success 'write-contents-hooks)
1758 (run-hook-with-args-until-success 'local-write-file-hooks)
1759 (run-hook-with-args-until-success 'write-file-hooks)
1760 ;; If a hook returned t, file is already "written".
1761 ;; Otherwise, write it the usual way now.
1762 (setq setmodes (basic-save-buffer-1)))
1763 (setq buffer-file-number (nth 10 (file-attributes buffer-file-name)))
1764 (if setmodes
1765 (condition-case ()
1766 (set-file-modes buffer-file-name setmodes)
1767 (error nil))))
1768 ;; If the auto-save file was recent before this command,
1769 ;; delete it now.
1770 (delete-auto-save-file-if-necessary recent-save)
1771 ;; Support VC `implicit' locking.
1772 (vc-after-save)
1773 (run-hooks 'after-save-hook))
1774 (message "(No changes need to be saved)"))))
1776 ;; This does the "real job" of writing a buffer into its visited file
1777 ;; and making a backup file. This is what is normally done
1778 ;; but inhibited if one of write-file-hooks returns non-nil.
1779 ;; It returns a value to store in setmodes.
1780 (defun basic-save-buffer-1 ()
1781 (let (tempsetmodes setmodes)
1782 (if (not (file-writable-p buffer-file-name))
1783 (let ((dir (file-name-directory buffer-file-name)))
1784 (if (not (file-directory-p dir))
1785 (error "%s is not a directory" dir)
1786 (if (not (file-exists-p buffer-file-name))
1787 (error "Directory %s write-protected" dir)
1788 (if (yes-or-no-p
1789 (format "File %s is write-protected; try to save anyway? "
1790 (file-name-nondirectory
1791 buffer-file-name)))
1792 (setq tempsetmodes t)
1793 (error "Attempt to save to a file which you aren't allowed to write"))))))
1794 (or buffer-backed-up
1795 (setq setmodes (backup-buffer)))
1796 (let ((dir (file-name-directory buffer-file-name)))
1797 (if (and file-precious-flag
1798 (file-writable-p dir))
1799 ;; If file is precious, write temp name, then rename it.
1800 ;; This requires write access to the containing dir,
1801 ;; which is why we don't try it if we don't have that access.
1802 (let ((realname buffer-file-name)
1803 tempname temp nogood i succeed
1804 (old-modtime (visited-file-modtime)))
1805 (setq i 0)
1806 (setq nogood t)
1807 ;; Find the temporary name to write under.
1808 (while nogood
1809 (setq tempname (format "%s#tmp#%d" dir i))
1810 (setq nogood (file-exists-p tempname))
1811 (setq i (1+ i)))
1812 (unwind-protect
1813 (progn (clear-visited-file-modtime)
1814 (write-region (point-min) (point-max)
1815 tempname nil realname
1816 buffer-file-truename)
1817 (setq succeed t))
1818 ;; If writing the temp file fails,
1819 ;; delete the temp file.
1820 (or succeed
1821 (progn
1822 (delete-file tempname)
1823 (set-visited-file-modtime old-modtime))))
1824 ;; Since we have created an entirely new file
1825 ;; and renamed it, make sure it gets the
1826 ;; right permission bits set.
1827 (setq setmodes (file-modes buffer-file-name))
1828 ;; We succeeded in writing the temp file,
1829 ;; so rename it.
1830 (rename-file tempname buffer-file-name t))
1831 ;; If file not writable, see if we can make it writable
1832 ;; temporarily while we write it.
1833 ;; But no need to do so if we have just backed it up
1834 ;; (setmodes is set) because that says we're superseding.
1835 (cond ((and tempsetmodes (not setmodes))
1836 ;; Change the mode back, after writing.
1837 (setq setmodes (file-modes buffer-file-name))
1838 (set-file-modes buffer-file-name 511)))
1839 (write-region (point-min) (point-max)
1840 buffer-file-name nil t buffer-file-truename)))
1841 setmodes))
1843 (defun save-some-buffers (&optional arg exiting)
1844 "Save some modified file-visiting buffers. Asks user about each one.
1845 Optional argument (the prefix) non-nil means save all with no questions.
1846 Optional second argument EXITING means ask about certain non-file buffers
1847 as well as about file buffers."
1848 (interactive "P")
1849 (save-window-excursion
1850 (let ((files-done
1851 (map-y-or-n-p
1852 (function
1853 (lambda (buffer)
1854 (and (buffer-modified-p buffer)
1855 (not (buffer-base-buffer buffer))
1857 (buffer-file-name buffer)
1858 (and exiting
1859 (progn
1860 (set-buffer buffer)
1861 (and buffer-offer-save (> (buffer-size) 0)))))
1862 (if arg
1864 (if (buffer-file-name buffer)
1865 (format "Save file %s? "
1866 (buffer-file-name buffer))
1867 (format "Save buffer %s? "
1868 (buffer-name buffer)))))))
1869 (function
1870 (lambda (buffer)
1871 (set-buffer buffer)
1872 (save-buffer)))
1873 (buffer-list)
1874 '("buffer" "buffers" "save")
1875 (list (list ?\C-r (lambda (buf)
1876 (view-buffer buf)
1877 (setq view-exit-action
1878 '(lambda (ignore)
1879 (exit-recursive-edit)))
1880 (recursive-edit)
1881 ;; Return nil to ask about BUF again.
1882 nil)
1883 "display the current buffer"))))
1884 (abbrevs-done
1885 (and save-abbrevs abbrevs-changed
1886 (progn
1887 (if (or arg
1888 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
1889 (write-abbrev-file nil))
1890 ;; Don't keep bothering user if he says no.
1891 (setq abbrevs-changed nil)
1892 t))))
1893 (or (> files-done 0) abbrevs-done
1894 (message "(No files need saving)")))))
1896 (defun not-modified (&optional arg)
1897 "Mark current buffer as unmodified, not needing to be saved.
1898 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
1900 It is not a good idea to use this function in Lisp programs, because it
1901 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
1902 (interactive "P")
1903 (message (if arg "Modification-flag set"
1904 "Modification-flag cleared"))
1905 (set-buffer-modified-p arg))
1907 (defun toggle-read-only (&optional arg)
1908 "Change whether this buffer is visiting its file read-only.
1909 With arg, set read-only iff arg is positive."
1910 (interactive "P")
1911 (setq buffer-read-only
1912 (if (null arg)
1913 (not buffer-read-only)
1914 (> (prefix-numeric-value arg) 0)))
1915 (force-mode-line-update))
1917 (defun insert-file (filename)
1918 "Insert contents of file FILENAME into buffer after point.
1919 Set mark after the inserted text.
1921 This function is meant for the user to run interactively.
1922 Don't call it from programs! Use `insert-file-contents' instead.
1923 \(Its calling sequence is different; see its documentation)."
1924 (interactive "*fInsert file: ")
1925 (if (file-directory-p filename)
1926 (signal 'file-error (list "Opening input file" "file is a directory"
1927 filename)))
1928 (let ((tem (insert-file-contents filename)))
1929 (push-mark (+ (point) (car (cdr tem))))))
1931 (defun append-to-file (start end filename)
1932 "Append the contents of the region to the end of file FILENAME.
1933 When called from a function, expects three arguments,
1934 START, END and FILENAME. START and END are buffer positions
1935 saying what text to write."
1936 (interactive "r\nFAppend to file: ")
1937 (write-region start end filename t))
1939 (defun file-newest-backup (filename)
1940 "Return most recent backup file for FILENAME or nil if no backups exist."
1941 (let* ((filename (expand-file-name filename))
1942 (file (file-name-nondirectory filename))
1943 (dir (file-name-directory filename))
1944 (comp (file-name-all-completions file dir))
1945 newest)
1946 (while comp
1947 (setq file (concat dir (car comp))
1948 comp (cdr comp))
1949 (if (and (backup-file-name-p file)
1950 (or (null newest) (file-newer-than-file-p file newest)))
1951 (setq newest file)))
1952 newest))
1954 (defun rename-uniquely ()
1955 "Rename current buffer to a similar name not already taken.
1956 This function is useful for creating multiple shell process buffers
1957 or multiple mail buffers, etc."
1958 (interactive)
1959 (save-match-data
1960 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
1961 (not (and buffer-file-name
1962 (string= (buffer-name)
1963 (file-name-nondirectory
1964 buffer-file-name)))))
1965 ;; If the existing buffer name has a <NNN>,
1966 ;; which isn't part of the file name (if any),
1967 ;; then get rid of that.
1968 (substring (buffer-name) 0 (match-beginning 0))
1969 (buffer-name)))
1970 (new-buf (generate-new-buffer base-name))
1971 (name (buffer-name new-buf)))
1972 (kill-buffer new-buf)
1973 (rename-buffer name)
1974 (force-mode-line-update))))
1976 (defun make-directory (dir &optional parents)
1977 "Create the directory DIR and any nonexistent parent dirs.
1978 Interactively, the default choice of directory to create
1979 is the current default directory for file names.
1980 That is useful when you have visited a file in a nonexistint directory.
1982 Noninteractively, the second (optional) argument PARENTS says whether
1983 to create parent directories if they don't exist."
1984 (interactive
1985 (list (read-file-name "Make directory: " default-directory default-directory
1986 nil nil)
1988 (let ((handler (find-file-name-handler dir 'make-directory)))
1989 (if handler
1990 (funcall handler 'make-directory dir parents)
1991 (if (not parents)
1992 (make-directory-internal dir)
1993 (let ((dir (directory-file-name (expand-file-name dir)))
1994 create-list)
1995 (while (not (file-exists-p dir))
1996 (setq create-list (cons dir create-list)
1997 dir (directory-file-name (file-name-directory dir))))
1998 (while create-list
1999 (make-directory-internal (car create-list))
2000 (setq create-list (cdr create-list))))))))
2002 (put 'revert-buffer-function 'permanent-local t)
2003 (defvar revert-buffer-function nil
2004 "Function to use to revert this buffer, or nil to do the default.
2005 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2006 which are the arguments that `revert-buffer' received.")
2008 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2009 (defvar revert-buffer-insert-file-contents-function nil
2010 "Function to use to insert contents when reverting this buffer.
2011 Gets two args, first the nominal file name to use,
2012 and second, t if reading the auto-save file.")
2014 (defvar before-revert-hook nil
2015 "Normal hook for `revert-buffer' to run before reverting.
2016 If `revert-buffer-function' is used to override the normal revert
2017 mechanism, this hook is not used.")
2019 (defvar after-revert-hook nil
2020 "Normal hook for `revert-buffer' to run after reverting.
2021 Note that the hook value that it runs is the value that was in effect
2022 before reverting; that makes a difference if you have buffer-local
2023 hook functions.
2025 If `revert-buffer-function' is used to override the normal revert
2026 mechanism, this hook is not used.")
2028 (defun revert-buffer (&optional ignore-auto noconfirm)
2029 "Replace the buffer text with the text of the visited file on disk.
2030 This undoes all changes since the file was visited or saved.
2031 With a prefix argument, offer to revert from latest auto-save file, if
2032 that is more recent than the visited file.
2034 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2035 to revert from the auto-save file when this is nil. Note that the
2036 sense of this argument is the reverse of the prefix argument, for the
2037 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2038 to nil.
2040 Optional second argument NOCONFIRM means don't ask for confirmation at
2041 all.
2043 If the value of `revert-buffer-function' is non-nil, it is called to
2044 do the work.
2046 The default revert function runs the hook `before-revert-hook' at the
2047 beginning and `after-revert-hook' at the end."
2048 ;; I admit it's odd to reverse the sense of the prefix argument, but
2049 ;; there is a lot of code out there which assumes that the first
2050 ;; argument should be t to avoid consulting the auto-save file, and
2051 ;; there's no straightforward way to encourage authors to notice a
2052 ;; reversal of the argument sense. So I'm just changing the user
2053 ;; interface, but leaving the programmatic interface the same.
2054 (interactive (list (not current-prefix-arg)))
2055 (if revert-buffer-function
2056 (funcall revert-buffer-function ignore-auto noconfirm)
2057 (let* ((opoint (point))
2058 (auto-save-p (and (not ignore-auto)
2059 (recent-auto-save-p)
2060 buffer-auto-save-file-name
2061 (file-readable-p buffer-auto-save-file-name)
2062 (y-or-n-p
2063 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2064 (file-name (if auto-save-p
2065 buffer-auto-save-file-name
2066 buffer-file-name)))
2067 (cond ((null file-name)
2068 (error "Buffer does not seem to be associated with any file"))
2069 ((or noconfirm
2070 (yes-or-no-p (format "Revert buffer from file %s? "
2071 file-name)))
2072 (run-hooks 'before-revert-hook)
2073 ;; If file was backed up but has changed since,
2074 ;; we shd make another backup.
2075 (and (not auto-save-p)
2076 (not (verify-visited-file-modtime (current-buffer)))
2077 (setq buffer-backed-up nil))
2078 ;; Get rid of all undo records for this buffer.
2079 (or (eq buffer-undo-list t)
2080 (setq buffer-undo-list nil))
2081 ;; Effectively copy the after-revert-hook status,
2082 ;; since after-find-file will clobber it.
2083 (let ((global-hook (default-value 'after-revert-hook))
2084 (local-hook-p (local-variable-p 'after-revert-hook))
2085 (local-hook (and (local-variable-p 'after-revert-hook)
2086 after-revert-hook)))
2087 (let (buffer-read-only
2088 ;; Don't make undo records for the reversion.
2089 (buffer-undo-list t))
2090 (if revert-buffer-insert-file-contents-function
2091 (funcall revert-buffer-insert-file-contents-function
2092 file-name auto-save-p)
2093 (if (not (file-exists-p file-name))
2094 (error "File %s no longer exists!" file-name))
2095 ;; Bind buffer-file-name to nil
2096 ;; so that we don't try to lock the file.
2097 (let ((buffer-file-name nil))
2098 (or auto-save-p
2099 (unlock-buffer)))
2100 (widen)
2101 (insert-file-contents file-name (not auto-save-p)
2102 nil nil t)))
2103 (goto-char (min opoint (point-max)))
2104 ;; Recompute the truename in case changes in symlinks
2105 ;; have changed the truename.
2106 (setq buffer-file-truename
2107 (abbreviate-file-name (file-truename buffer-file-name)))
2108 (after-find-file nil nil t t)
2109 ;; Run after-revert-hook as it was before we reverted.
2110 (setq-default revert-buffer-internal-hook global-hook)
2111 (if local-hook-p
2112 (progn
2113 (make-local-variable 'revert-buffer-internal-hook)
2114 (setq revert-buffer-internal-hook local-hook))
2115 (kill-local-variable 'revert-buffer-internal-hook))
2116 (run-hooks 'revert-buffer-internal-hook))
2117 t)))))
2119 (defun recover-file (file)
2120 "Visit file FILE, but get contents from its last auto-save file."
2121 ;; Actually putting the file name in the minibuffer should be used
2122 ;; only rarely.
2123 ;; Not just because users often use the default.
2124 (interactive "fRecover file: ")
2125 (setq file (expand-file-name file))
2126 (if (auto-save-file-name-p (file-name-nondirectory file))
2127 (error "%s is an auto-save file" file))
2128 (let ((file-name (let ((buffer-file-name file))
2129 (make-auto-save-file-name))))
2130 (cond ((if (file-exists-p file)
2131 (not (file-newer-than-file-p file-name file))
2132 (not (file-exists-p file-name)))
2133 (error "Auto-save file %s not current" file-name))
2134 ((save-window-excursion
2135 (if (not (eq system-type 'vax-vms))
2136 (with-output-to-temp-buffer "*Directory*"
2137 (buffer-disable-undo standard-output)
2138 (call-process "ls" nil standard-output nil
2139 (if (file-symlink-p file) "-lL" "-l")
2140 file file-name)))
2141 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2142 (switch-to-buffer (find-file-noselect file t))
2143 (let ((buffer-read-only nil))
2144 (erase-buffer)
2145 (insert-file-contents file-name nil))
2146 (after-find-file nil nil t))
2147 (t (error "Recover-file cancelled.")))))
2149 (defun recover-session ()
2150 "Recover auto save files from a previous Emacs session.
2151 This command first displays a Dired buffer showing you the
2152 previous sessions that you could recover from.
2153 To choose one, move point to the proper line and then type C-c C-c.
2154 Then you'll be asked about a number of files to recover."
2155 (interactive)
2156 (dired (concat auto-save-list-file-prefix "*"))
2157 (goto-char (point-min))
2158 (or (looking-at "Move to the session you want to recover,")
2159 (let ((inhibit-read-only t))
2160 (insert "Move to the session you want to recover,\n"
2161 "then type C-c C-c to select it.\n\n"
2162 "You can also delete some of these files;\n"
2163 "type d on a line to mark that file for deletion.\n\n")))
2164 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2165 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2167 (defun recover-session-finish ()
2168 "Choose one saved session to recover auto-save files from.
2169 This command is used in the special Dired buffer created by
2170 \\[recover-session]."
2171 (interactive)
2172 ;; Get the name of the session file to recover from.
2173 (let ((file (dired-get-filename))
2174 files
2175 (buffer (get-buffer-create " *recover*")))
2176 (dired-do-flagged-delete t)
2177 (unwind-protect
2178 (save-excursion
2179 ;; Read in the auto-save-list file.
2180 (set-buffer buffer)
2181 (erase-buffer)
2182 (insert-file-contents file)
2183 ;; Loop thru the text of that file
2184 ;; and get out the names of the files to recover.
2185 (while (not (eobp))
2186 (let (thisfile autofile)
2187 (if (eolp)
2188 ;; This is a pair of lines for a non-file-visiting buffer.
2189 ;; Get the auto-save file name and manufacture
2190 ;; a "visited file name" from that.
2191 (progn
2192 (forward-line 1)
2193 (setq autofile
2194 (buffer-substring-no-properties
2195 (point)
2196 (save-excursion
2197 (end-of-line)
2198 (point))))
2199 (setq thisfile
2200 (expand-file-name
2201 (substring
2202 (file-name-nondirectory autofile)
2203 1 -1)
2204 (file-name-directory autofile)))
2205 (forward-line 1))
2206 ;; This pair of lines is a file-visiting
2207 ;; buffer. Use the visited file name.
2208 (progn
2209 (setq thisfile
2210 (buffer-substring-no-properties
2211 (point) (progn (end-of-line) (point))))
2212 (forward-line 1)
2213 (setq autofile
2214 (buffer-substring-no-properties
2215 (point) (progn (end-of-line) (point))))
2216 (forward-line 1)))
2217 ;; Ignore a file if its auto-save file does not exist now.
2218 (if (file-exists-p autofile)
2219 (setq files (cons thisfile files)))))
2220 (setq files (nreverse files))
2221 ;; The file contains a pair of line for each auto-saved buffer.
2222 ;; The first line of the pair contains the visited file name
2223 ;; or is empty if the buffer was not visiting a file.
2224 ;; The second line is the auto-save file name.
2225 (if files
2226 (map-y-or-n-p "Recover %s? "
2227 (lambda (file)
2228 (condition-case nil
2229 (save-excursion (recover-file file))
2230 (error
2231 "Failed to recover `%s'" file)))
2232 files
2233 '("file" "files" "recover"))
2234 (message "No files can be recovered from this session now")))
2235 (kill-buffer buffer))))
2237 (defun kill-some-buffers ()
2238 "For each buffer, ask whether to kill it."
2239 (interactive)
2240 (let ((list (buffer-list)))
2241 (while list
2242 (let* ((buffer (car list))
2243 (name (buffer-name buffer)))
2244 (and (not (string-equal name ""))
2245 (/= (aref name 0) ? )
2246 (yes-or-no-p
2247 (format "Buffer %s %s. Kill? "
2248 name
2249 (if (buffer-modified-p buffer)
2250 "HAS BEEN EDITED" "is unmodified")))
2251 (kill-buffer buffer)))
2252 (setq list (cdr list)))))
2254 (defun auto-save-mode (arg)
2255 "Toggle auto-saving of contents of current buffer.
2256 With prefix argument ARG, turn auto-saving on if positive, else off."
2257 (interactive "P")
2258 (setq buffer-auto-save-file-name
2259 (and (if (null arg)
2260 (or (not buffer-auto-save-file-name)
2261 ;; If autosave is off because buffer has shrunk,
2262 ;; then toggling should turn it on.
2263 (< buffer-saved-size 0))
2264 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2265 (if (and buffer-file-name auto-save-visited-file-name
2266 (not buffer-read-only))
2267 buffer-file-name
2268 (make-auto-save-file-name))))
2269 ;; If -1 was stored here, to temporarily turn off saving,
2270 ;; turn it back on.
2271 (and (< buffer-saved-size 0)
2272 (setq buffer-saved-size 0))
2273 (if (interactive-p)
2274 (message "Auto-save %s (in this buffer)"
2275 (if buffer-auto-save-file-name "on" "off")))
2276 buffer-auto-save-file-name)
2278 (defun rename-auto-save-file ()
2279 "Adjust current buffer's auto save file name for current conditions.
2280 Also rename any existing auto save file, if it was made in this session."
2281 (let ((osave buffer-auto-save-file-name))
2282 (setq buffer-auto-save-file-name
2283 (make-auto-save-file-name))
2284 (if (and osave buffer-auto-save-file-name
2285 (not (string= buffer-auto-save-file-name buffer-file-name))
2286 (not (string= buffer-auto-save-file-name osave))
2287 (file-exists-p osave)
2288 (recent-auto-save-p))
2289 (rename-file osave buffer-auto-save-file-name t))))
2291 (defun make-auto-save-file-name ()
2292 "Return file name to use for auto-saves of current buffer.
2293 Does not consider `auto-save-visited-file-name' as that variable is checked
2294 before calling this function. You can redefine this for customization.
2295 See also `auto-save-file-name-p'."
2296 (if buffer-file-name
2297 (concat (file-name-directory buffer-file-name)
2299 (file-name-nondirectory buffer-file-name)
2300 "#")
2302 ;; Deal with buffers that don't have any associated files. (Mail
2303 ;; mode tends to create a good number of these.)
2305 (let ((buffer-name (buffer-name))
2306 (limit 0))
2307 ;; Use technique from Sebastian Kremer's auto-save
2308 ;; package to turn slashes into \\!. This ensures that
2309 ;; the auto-save buffer name is unique.
2311 (while (string-match "[/\\]" buffer-name limit)
2312 (setq buffer-name (concat (substring buffer-name 0 (match-beginning 0))
2313 (if (string= (substring buffer-name
2314 (match-beginning 0)
2315 (match-end 0))
2316 "/")
2317 "\\!"
2318 "\\\\")
2319 (substring buffer-name (match-end 0))))
2320 (setq limit (1+ (match-end 0))))
2322 (expand-file-name (format "#%s#%s#" buffer-name (make-temp-name ""))))))
2324 (defun auto-save-file-name-p (filename)
2325 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2326 FILENAME should lack slashes. You can redefine this for customization."
2327 (string-match "^#.*#$" filename))
2329 (defconst list-directory-brief-switches
2330 (if (eq system-type 'vax-vms) "" "-CF")
2331 "*Switches for list-directory to pass to `ls' for brief listing,")
2333 (defconst list-directory-verbose-switches
2334 (if (eq system-type 'vax-vms)
2335 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2336 "-l")
2337 "*Switches for list-directory to pass to `ls' for verbose listing,")
2339 (defun list-directory (dirname &optional verbose)
2340 "Display a list of files in or matching DIRNAME, a la `ls'.
2341 DIRNAME is globbed by the shell if necessary.
2342 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2343 Actions controlled by variables `list-directory-brief-switches'
2344 and `list-directory-verbose-switches'."
2345 (interactive (let ((pfx current-prefix-arg))
2346 (list (read-file-name (if pfx "List directory (verbose): "
2347 "List directory (brief): ")
2348 nil default-directory nil)
2349 pfx)))
2350 (let ((switches (if verbose list-directory-verbose-switches
2351 list-directory-brief-switches)))
2352 (or dirname (setq dirname default-directory))
2353 (setq dirname (expand-file-name dirname))
2354 (with-output-to-temp-buffer "*Directory*"
2355 (buffer-disable-undo standard-output)
2356 (princ "Directory ")
2357 (princ dirname)
2358 (terpri)
2359 (save-excursion
2360 (set-buffer "*Directory*")
2361 (setq default-directory (file-name-directory dirname))
2362 (let ((wildcard (not (file-directory-p dirname))))
2363 (insert-directory dirname switches wildcard (not wildcard)))))))
2365 (defvar insert-directory-program "ls"
2366 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2368 ;; insert-directory
2369 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2370 ;; FULL-DIRECTORY-P is nil.
2371 ;; The single line of output must display FILE's name as it was
2372 ;; given, namely, an absolute path name.
2373 ;; - must insert exactly one line for each file if WILDCARD or
2374 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2375 ;; before the file lines, plus optional text after the file lines.
2376 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2377 ;; allowed.
2378 ;; File lines should display the basename.
2379 ;; - must be consistent with
2380 ;; - functions dired-move-to-filename, (these two define what a file line is)
2381 ;; dired-move-to-end-of-filename,
2382 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2383 ;; dired-insert-headerline
2384 ;; dired-after-subdir-garbage (defines what a "total" line is)
2385 ;; - variable dired-subdir-regexp
2386 (defun insert-directory (file switches &optional wildcard full-directory-p)
2387 "Insert directory listing for FILE, formatted according to SWITCHES.
2388 Leaves point after the inserted text.
2389 SWITCHES may be a string of options, or a list of strings.
2390 Optional third arg WILDCARD means treat FILE as shell wildcard.
2391 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2392 switches do not contain `d', so that a full listing is expected.
2394 This works by running a directory listing program
2395 whose name is in the variable `insert-directory-program'.
2396 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2397 ;; We need the directory in order to find the right handler.
2398 (let ((handler (find-file-name-handler (expand-file-name file)
2399 'insert-directory)))
2400 (if handler
2401 (funcall handler 'insert-directory file switches
2402 wildcard full-directory-p)
2403 (if (eq system-type 'vax-vms)
2404 (vms-read-directory file switches (current-buffer))
2405 (if wildcard
2406 ;; Run ls in the directory of the file pattern we asked for.
2407 (let ((default-directory
2408 (if (file-name-absolute-p file)
2409 (file-name-directory file)
2410 (file-name-directory (expand-file-name file))))
2411 (pattern (file-name-nondirectory file))
2412 (beg 0))
2413 ;; Quote some characters that have special meanings in shells;
2414 ;; but don't quote the wildcards--we want them to be special.
2415 ;; We also currently don't quote the quoting characters
2416 ;; in case people want to use them explicitly to quote
2417 ;; wildcard characters.
2418 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
2419 (setq pattern
2420 (concat (substring pattern 0 (match-beginning 0))
2421 "\\"
2422 (substring pattern (match-beginning 0)))
2423 beg (1+ (match-end 0))))
2424 (call-process shell-file-name nil t nil
2425 "-c" (concat "\\" ;; Disregard shell aliases!
2426 insert-directory-program
2427 " -d "
2428 (if (stringp switches)
2429 switches
2430 (mapconcat 'identity switches " "))
2432 pattern)))
2433 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2434 ;; directory if FILE is a symbolic link.
2435 (apply 'call-process
2436 insert-directory-program nil t nil
2437 (let (list)
2438 (if (listp switches)
2439 (setq list switches)
2440 (if (not (equal switches ""))
2441 (progn
2442 ;; Split the switches at any spaces
2443 ;; so we can pass separate options as separate args.
2444 (while (string-match " " switches)
2445 (setq list (cons (substring switches 0 (match-beginning 0))
2446 list)
2447 switches (substring switches (match-end 0))))
2448 (setq list (cons switches list)))))
2449 (append list
2450 (list
2451 (if full-directory-p
2452 (concat (file-name-as-directory file) ".")
2453 file))))))))))
2455 (defvar kill-emacs-query-functions nil
2456 "Functions to call with no arguments to query about killing Emacs.
2457 If any of these functions returns nil, killing Emacs is cancelled.
2458 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2459 but `kill-emacs', the low level primitive, does not.
2460 See also `kill-emacs-hook'.")
2462 (defun save-buffers-kill-emacs (&optional arg)
2463 "Offer to save each buffer, then kill this Emacs process.
2464 With prefix arg, silently save all file-visiting buffers, then kill."
2465 (interactive "P")
2466 (save-some-buffers arg t)
2467 (and (or (not (memq t (mapcar (function
2468 (lambda (buf) (and (buffer-file-name buf)
2469 (buffer-modified-p buf))))
2470 (buffer-list))))
2471 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2472 (or (not (fboundp 'process-list))
2473 ;; process-list is not defined on VMS.
2474 (let ((processes (process-list))
2475 active)
2476 (while processes
2477 (and (memq (process-status (car processes)) '(run stop open))
2478 (let ((val (process-kill-without-query (car processes))))
2479 (process-kill-without-query (car processes) val)
2480 val)
2481 (setq active t))
2482 (setq processes (cdr processes)))
2483 (or (not active)
2484 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2485 ;; Query the user for other things, perhaps.
2486 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
2487 (kill-emacs)))
2489 (define-key ctl-x-map "\C-f" 'find-file)
2490 (define-key ctl-x-map "\C-q" 'toggle-read-only)
2491 (define-key ctl-x-map "\C-r" 'find-file-read-only)
2492 (define-key ctl-x-map "\C-v" 'find-alternate-file)
2493 (define-key ctl-x-map "\C-s" 'save-buffer)
2494 (define-key ctl-x-map "s" 'save-some-buffers)
2495 (define-key ctl-x-map "\C-w" 'write-file)
2496 (define-key ctl-x-map "i" 'insert-file)
2497 (define-key esc-map "~" 'not-modified)
2498 (define-key ctl-x-map "\C-d" 'list-directory)
2499 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
2501 (define-key ctl-x-4-map "f" 'find-file-other-window)
2502 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
2503 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
2504 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
2505 (define-key ctl-x-4-map "\C-o" 'display-buffer)
2507 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
2508 (define-key ctl-x-5-map "f" 'find-file-other-frame)
2509 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
2510 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
2512 ;;; files.el ends here