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