(auto-mode-alist): Add ".mf" and ".mp" for meta-mode.el.
[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"))
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
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
803 (defun insert-file-contents-literally (filename &optional visit beg end replace)
804 "Like `insert-file-contents', q.v., but only reads in the file.
805 A buffer may be modified in several ways after reading into the buffer due
806 to advanced Emacs features, such as file-name-handlers, format decoding,
807 find-file-hooks, etc.
808 This function ensures that none of these modifications will take place.
809
810 This function does not work for remote files, because it turns off
811 file name handlers and remote file access uses a file name handler."
812 (let ((file-name-handler-alist nil)
813 (format-alist nil)
814 (after-insert-file-functions nil)
815 (find-buffer-file-type-function
816 (if (fboundp 'find-buffer-file-type)
817 (symbol-function 'find-buffer-file-type)
818 nil)))
819 (unwind-protect
820 (progn
821 (fset 'find-buffer-file-type (lambda (filename) t))
822 (insert-file-contents filename visit beg end replace))
823 (if find-buffer-file-type-function
824 (fset 'find-buffer-file-type find-buffer-file-type-function)
825 (fmakunbound 'find-buffer-file-type)))))
826
827 (defun find-file-noselect (filename &optional nowarn rawfile)
828 "Read file FILENAME into a buffer and return the buffer.
829 If a buffer exists visiting FILENAME, return that one, but
830 verify that the file has not changed since visited or saved.
831 The buffer is not selected, just returned to the caller.
832 Optional first arg NOWARN non-nil means suppress any warning messages.
833 Optional second arg RAWFILE non-nil means the file is read literally"
834 (setq filename
835 (abbreviate-file-name
836 (expand-file-name filename)))
837 (if (file-directory-p filename)
838 (if find-file-run-dired
839 (dired-noselect (if find-file-visit-truename
840 (abbreviate-file-name (file-truename filename))
841 filename))
842 (error "%s is a directory" filename))
843 (let* ((buf (get-file-buffer filename))
844 (truename (abbreviate-file-name (file-truename filename)))
845 (number (nthcdr 10 (file-attributes truename)))
846 ;; Find any buffer for a file which has same truename.
847 (other (and (not buf) (find-buffer-visiting filename)))
848 error)
849 ;; Let user know if there is a buffer with the same truename.
850 (if other
851 (progn
852 (or nowarn
853 (string-equal filename (buffer-file-name other))
854 (message "%s and %s are the same file"
855 filename (buffer-file-name other)))
856 ;; Optionally also find that buffer.
857 (if (or find-file-existing-other-name find-file-visit-truename)
858 (setq buf other))))
859 (if buf
860 (or nowarn
861 (verify-visited-file-modtime buf)
862 (cond ((not (file-exists-p filename))
863 (error "File %s no longer exists!" filename))
864 ;; Certain files should be reverted automatically
865 ;; if they have changed on disk and not in the buffer.
866 ((and (not (buffer-modified-p buf))
867 (let ((tail revert-without-query)
868 (found nil))
869 (while tail
870 (if (string-match (car tail) filename)
871 (setq found t))
872 (setq tail (cdr tail)))
873 found))
874 (with-current-buffer buf
875 (message "Reverting file %s..." filename)
876 (revert-buffer t t)
877 (message "Reverting file %s...done" filename)))
878 ((yes-or-no-p
879 (if (string= (file-name-nondirectory filename)
880 (buffer-name buf))
881 (format
882 (if (buffer-modified-p buf)
883 "File %s changed on disk. Discard your edits? "
884 "File %s changed on disk. Reread from disk? ")
885 (file-name-nondirectory filename))
886 (format
887 (if (buffer-modified-p buf)
888 "File %s changed on disk. Discard your edits in %s? "
889 "File %s changed on disk. Reread from disk into %s? ")
890 (file-name-nondirectory filename)
891 (buffer-name buf))))
892 (with-current-buffer buf
893 (revert-buffer t t)))))
894 (save-excursion
895 ;;; The truename stuff makes this obsolete.
896 ;;; (let* ((link-name (car (file-attributes filename)))
897 ;;; (linked-buf (and (stringp link-name)
898 ;;; (get-file-buffer link-name))))
899 ;;; (if (bufferp linked-buf)
900 ;;; (message "Symbolic link to file in buffer %s"
901 ;;; (buffer-name linked-buf))))
902 (setq buf (create-file-buffer filename))
903 (set-buffer-major-mode buf)
904 (set-buffer buf)
905 (erase-buffer)
906 (if rawfile
907 (condition-case ()
908 (insert-file-contents-literally filename t)
909 (file-error
910 ;; Unconditionally set error
911 (setq error t)))
912 (condition-case ()
913 (insert-file-contents filename t)
914 (file-error
915 ;; Run find-file-not-found-hooks until one returns non-nil.
916 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
917 ;; If they fail too, set error.
918 (setq error t)))))
919 ;; Find the file's truename, and maybe use that as visited name.
920 (setq buffer-file-truename truename)
921 (setq buffer-file-number number)
922 ;; On VMS, we may want to remember which directory in a search list
923 ;; the file was found in.
924 (and (eq system-type 'vax-vms)
925 (let (logical)
926 (if (string-match ":" (file-name-directory filename))
927 (setq logical (substring (file-name-directory filename)
928 0 (match-beginning 0))))
929 (not (member logical find-file-not-true-dirname-list)))
930 (setq buffer-file-name buffer-file-truename))
931 (if find-file-visit-truename
932 (setq buffer-file-name
933 (setq filename
934 (expand-file-name buffer-file-truename))))
935 ;; Set buffer's default directory to that of the file.
936 (setq default-directory (file-name-directory filename))
937 ;; Turn off backup files for certain file names. Since
938 ;; this is a permanent local, the major mode won't eliminate it.
939 (and (not (funcall backup-enable-predicate buffer-file-name))
940 (progn
941 (make-local-variable 'backup-inhibited)
942 (setq backup-inhibited t)))
943 (if rawfile
944 nil
945 (after-find-file error (not nowarn))
946 (setq buf (current-buffer)))))
947 buf)))
948
949 (defun find-file-literally (filename)
950 "Visit file FILENAME with no conversion of any kind.
951 Format conversion and character code conversion are both disabled,
952 and multibyte characters are disabled in the resulting buffer.
953 Automatic uncompression is also disabled."
954 (interactive "FFind file literally: ")
955 (let ((coding-system-for-read 'no-conversion)
956 (coding-system-for-write 'no-conversion)
957 (auto-mode-alist (copy-sequence auto-mode-alist))
958 (jka-compr-compression-info-list nil)
959 (format-alist nil)
960 (after-insert-file-functions nil)
961 tail)
962 ;; Turn off use of tar-mode and archive-mode
963 ;; for this one file. (We copied auto-mode-alist above
964 ;; so as not to alter it permanently.)
965 (setq tail auto-mode-alist)
966 (while tail
967 (if (memq (cdr (car tail)) '(tar-mode archive-mode))
968 (setq auto-mode-alist (delq (car tail) auto-mode-alist)))
969 (setq tail (cdr tail)))
970 (prog1
971 (find-file filename)
972 (setq enable-multibyte-characters nil))))
973 \f
974 (defvar after-find-file-from-revert-buffer nil)
975
976 (defun after-find-file (&optional error warn noauto
977 after-find-file-from-revert-buffer
978 nomodes)
979 "Called after finding a file and by the default revert function.
980 Sets buffer mode, parses local variables.
981 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
982 error in reading the file. WARN non-nil means warn if there
983 exists an auto-save file more recent than the visited file.
984 NOAUTO means don't mess with auto-save mode.
985 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
986 means this call was from `revert-buffer'.
987 Fifth arg NOMODES non-nil means don't alter the file's modes.
988 Finishes by calling the functions in `find-file-hooks'
989 unless NOMODES is non-nil."
990 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
991 (if noninteractive
992 nil
993 (let* (not-serious
994 (msg
995 (cond ((and error (file-attributes buffer-file-name))
996 (setq buffer-read-only t)
997 "File exists, but cannot be read.")
998 ((not buffer-read-only)
999 (if (and warn
1000 (file-newer-than-file-p (make-auto-save-file-name)
1001 buffer-file-name))
1002 (format "%s has auto save data; consider M-x recover-file"
1003 (file-name-nondirectory buffer-file-name))
1004 (setq not-serious t)
1005 (if error "(New file)" nil)))
1006 ((not error)
1007 (setq not-serious t)
1008 "Note: file is write protected")
1009 ((file-attributes (directory-file-name default-directory))
1010 "File not found and directory write-protected")
1011 ((file-exists-p (file-name-directory buffer-file-name))
1012 (setq buffer-read-only nil))
1013 (t
1014 (setq buffer-read-only nil)
1015 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1016 "Use M-x make-dir RET RET to create the directory"
1017 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
1018 (if msg
1019 (progn
1020 (message msg)
1021 (or not-serious (sit-for 1 nil t)))))
1022 (if (and auto-save-default (not noauto))
1023 (auto-save-mode t)))
1024 (if nomodes
1025 nil
1026 (normal-mode t)
1027 (if (and buffer-read-only view-read-only
1028 (not (eq (get major-mode 'mode-class) 'special)))
1029 (view-mode-enter))
1030 (run-hooks 'find-file-hooks)))
1031
1032 (defun normal-mode (&optional find-file)
1033 "Choose the major mode for this buffer automatically.
1034 Also sets up any specified local variables of the file.
1035 Uses the visited file name, the -*- line, and the local variables spec.
1036
1037 This function is called automatically from `find-file'. In that case,
1038 we may set up specified local variables depending on the value of
1039 `enable-local-variables': if it is t, we do; if it is nil, we don't;
1040 otherwise, we query. `enable-local-variables' is ignored if you
1041 run `normal-mode' explicitly."
1042 (interactive)
1043 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1044 (condition-case err
1045 (set-auto-mode)
1046 (error (message "File mode specification error: %s"
1047 (prin1-to-string err))))
1048 (condition-case err
1049 (let ((enable-local-variables (or (not find-file)
1050 enable-local-variables)))
1051 (hack-local-variables))
1052 (error (message "File local-variables error: %s"
1053 (prin1-to-string err)))))
1054
1055 (defvar auto-mode-alist
1056 '(("\\.te?xt\\'" . text-mode)
1057 ("\\.c\\'" . c-mode)
1058 ("\\.h\\'" . c-mode)
1059 ("\\.tex\\'" . tex-mode)
1060 ("\\.ltx\\'" . latex-mode)
1061 ("\\.el\\'" . emacs-lisp-mode)
1062 ("\\.mm\\'" . nroff-mode)
1063 ("\\.me\\'" . nroff-mode)
1064 ("\\.ms\\'" . nroff-mode)
1065 ("\\.man\\'" . nroff-mode)
1066 ("\\.scm\\'" . scheme-mode)
1067 ("\\.l\\'" . lisp-mode)
1068 ("\\.lisp\\'" . lisp-mode)
1069 ("\\.f\\'" . fortran-mode)
1070 ("\\.F\\'" . fortran-mode)
1071 ("\\.for\\'" . fortran-mode)
1072 ("\\.p\\'" . pascal-mode)
1073 ("\\.pas\\'" . pascal-mode)
1074 ("\\.ad[abs]\\'" . ada-mode)
1075 ("\\.pl\\'" . perl-mode)
1076 ("\\.pm\\'" . perl-mode)
1077 ("\\.s?html?\\'" . html-mode)
1078 ("\\.cc\\'" . c++-mode)
1079 ("\\.hh\\'" . c++-mode)
1080 ("\\.hpp\\'" . c++-mode)
1081 ("\\.C\\'" . c++-mode)
1082 ("\\.H\\'" . c++-mode)
1083 ("\\.cpp\\'" . c++-mode)
1084 ("\\.cxx\\'" . c++-mode)
1085 ("\\.hxx\\'" . c++-mode)
1086 ("\\.c\\+\\+\\'" . c++-mode)
1087 ("\\.h\\+\\+\\'" . c++-mode)
1088 ("\\.m\\'" . objc-mode)
1089 ("\\.java\\'" . java-mode)
1090 ("\\.mk\\'" . makefile-mode)
1091 ("\\(M\\|m\\|GNUm\\)akefile\\(.in\\)?\\'" . makefile-mode)
1092 ;;; Less common extensions come here
1093 ;;; so more common ones above are found faster.
1094 ("\\.texinfo\\'" . texinfo-mode)
1095 ("\\.te?xi\\'" . texinfo-mode)
1096 ("\\.s\\'" . asm-mode)
1097 ("\\.S\\'" . asm-mode)
1098 ("\\.asm\\'" . asm-mode)
1099 ("ChangeLog\\'" . change-log-mode)
1100 ("change.log\\'" . change-log-mode)
1101 ("changelo\\'" . change-log-mode)
1102 ("ChangeLog.[0-9]+\\'" . change-log-mode)
1103 ;; for MSDOS and MS-Windows (which are case-insensitive)
1104 ("changelog\\'" . change-log-mode)
1105 ("changelog.[0-9]+\\'" . change-log-mode)
1106 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1107 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
1108 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
1109 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1110 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1111 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
1112 ;;; The following should come after the ChangeLog pattern
1113 ;;; for the sake of ChangeLog.1, etc.
1114 ;;; and after the .scm.[0-9] pattern too.
1115 ("\\.[12345678]\\'" . nroff-mode)
1116 ("\\.TeX\\'" . tex-mode)
1117 ("\\.sty\\'" . latex-mode)
1118 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
1119 ("\\.clo\\'" . latex-mode) ;LaTeX 2e class option
1120 ("\\.bbl\\'" . latex-mode)
1121 ("\\.bib\\'" . bibtex-mode)
1122 ("\\.mf\\'" . metafont-mode)
1123 ("\\.mp\\'" . metapost-mode)
1124 ("\\.article\\'" . text-mode)
1125 ("\\.letter\\'" . text-mode)
1126 ("\\.tcl\\'" . tcl-mode)
1127 ("\\.exp\\'" . tcl-mode)
1128 ("\\.itcl\\'" . tcl-mode)
1129 ("\\.itk\\'" . tcl-mode)
1130 ("\\.icn\\'" . icon-mode)
1131 ("\\.sim\\'" . simula-mode)
1132 ("\\.mss\\'" . scribe-mode)
1133 ("\\.f90\\'" . f90-mode)
1134 ("\\.lsp\\'" . lisp-mode)
1135 ("\\.awk\\'" . awk-mode)
1136 ("\\.prolog\\'" . prolog-mode)
1137 ("\\.tar\\'" . tar-mode)
1138 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode)
1139 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\)\\'" . archive-mode)
1140 ;; Mailer puts message to be edited in
1141 ;; /tmp/Re.... or Message
1142 ("\\`/tmp/Re" . text-mode)
1143 ("/Message[0-9]*\\'" . text-mode)
1144 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1145 ;; some news reader is reported to use this
1146 ("\\`/tmp/fol/" . text-mode)
1147 ("\\.y\\'" . c-mode)
1148 ("\\.lex\\'" . c-mode)
1149 ("\\.oak\\'" . scheme-mode)
1150 ("\\.sgml?\\'" . sgml-mode)
1151 ("\\.dtd\\'" . sgml-mode)
1152 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
1153 ;; .emacs following a directory delimiter
1154 ;; in Unix, MSDOG or VMS syntax.
1155 ("[]>:/\\]\\..*emacs\\'" . emacs-lisp-mode)
1156 ;; _emacs following a directory delimiter
1157 ;; in MsDos syntax
1158 ("[:/]_emacs\\'" . emacs-lisp-mode)
1159 ("\\.ml\\'" . lisp-mode))
1160 "\
1161 Alist of filename patterns vs corresponding major mode functions.
1162 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1163 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1164 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1165 mode function to use. FUNCTION will be called, unless it is nil.
1166
1167 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1168 calling FUNCTION (if it's not nil), we delete the suffix that matched
1169 REGEXP and search the list again for another match.")
1170
1171 (defvar interpreter-mode-alist
1172 '(("perl" . perl-mode)
1173 ("perl5" . perl-mode)
1174 ("wish" . tcl-mode)
1175 ("wishx" . tcl-mode)
1176 ("tcl" . tcl-mode)
1177 ("tclsh" . tcl-mode)
1178 ("awk" . awk-mode)
1179 ("mawk" . awk-mode)
1180 ("nawk" . awk-mode)
1181 ("gawk" . awk-mode)
1182 ("scm" . scheme-mode)
1183 ("ash" . sh-mode)
1184 ("bash" . sh-mode)
1185 ("csh" . sh-mode)
1186 ("dtksh" . sh-mode)
1187 ("es" . sh-mode)
1188 ("itcsh" . sh-mode)
1189 ("jsh" . sh-mode)
1190 ("ksh" . sh-mode)
1191 ("oash" . sh-mode)
1192 ("pdksh" . sh-mode)
1193 ("rc" . sh-mode)
1194 ("sh" . sh-mode)
1195 ("sh5" . sh-mode)
1196 ("tcsh" . sh-mode)
1197 ("wksh" . sh-mode)
1198 ("wsh" . sh-mode)
1199 ("zsh" . sh-mode)
1200 ("tail" . text-mode)
1201 ("more" . text-mode)
1202 ("less" . text-mode)
1203 ("pg" . text-mode))
1204 "Alist mapping interpreter names to major modes.
1205 This alist applies to files whose first line starts with `#!'.
1206 Each element looks like (INTERPRETER . MODE).
1207 The car of each element is compared with
1208 the name of the interpreter specified in the first line.
1209 If it matches, mode MODE is selected.")
1210
1211 (defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
1212 "List of regexps; if one matches a file name, don't look for `-*-'.")
1213
1214 (defvar inhibit-first-line-modes-suffixes nil
1215 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1216 When checking `inhibit-first-line-modes-regexps', we first discard
1217 from the end of the file name anything that matches one of these regexps.")
1218
1219 (defvar user-init-file
1220 "" ; set by command-line
1221 "File name including directory of user's initialization file.")
1222
1223 (defun set-auto-mode (&optional just-from-file-name)
1224 "Select major mode appropriate for current buffer.
1225 This checks for a -*- mode tag in the buffer's text,
1226 compares the filename against the entries in `auto-mode-alist',
1227 or checks the interpreter that runs this file against
1228 `interpreter-mode-alist'.
1229
1230 It does not check for the `mode:' local variable in the
1231 Local Variables section of the file; for that, use `hack-local-variables'.
1232
1233 If `enable-local-variables' is nil, this function does not check for a
1234 -*- mode tag.
1235
1236 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1237 then we do not set anything but the major mode,
1238 and we don't even do that unless it would come from the file name."
1239 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1240 (let (beg end done modes)
1241 (save-excursion
1242 (goto-char (point-min))
1243 (skip-chars-forward " \t\n")
1244 (and enable-local-variables
1245 ;; Don't look for -*- if this file name matches any
1246 ;; of the regexps in inhibit-first-line-modes-regexps.
1247 (let ((temp inhibit-first-line-modes-regexps)
1248 (name (if buffer-file-name
1249 (file-name-sans-versions buffer-file-name)
1250 (buffer-name))))
1251 (while (let ((sufs inhibit-first-line-modes-suffixes))
1252 (while (and sufs (not (string-match (car sufs) name)))
1253 (setq sufs (cdr sufs)))
1254 sufs)
1255 (setq name (substring name 0 (match-beginning 0))))
1256 (while (and temp
1257 (not (string-match (car temp) name)))
1258 (setq temp (cdr temp)))
1259 (not temp))
1260 (search-forward "-*-" (save-excursion
1261 ;; If the file begins with "#!"
1262 ;; (exec interpreter magic), look
1263 ;; for mode frobs in the first two
1264 ;; lines. You cannot necessarily
1265 ;; put them in the first line of
1266 ;; such a file without screwing up
1267 ;; the interpreter invocation.
1268 (end-of-line (and (looking-at "^#!") 2))
1269 (point)) t)
1270 (progn
1271 (skip-chars-forward " \t")
1272 (setq beg (point))
1273 (search-forward "-*-"
1274 (save-excursion (end-of-line) (point))
1275 t))
1276 (progn
1277 (forward-char -3)
1278 (skip-chars-backward " \t")
1279 (setq end (point))
1280 (goto-char beg)
1281 (if (save-excursion (search-forward ":" end t))
1282 ;; Find all specifications for the `mode:' variable
1283 ;; and execute them left to right.
1284 (while (let ((case-fold-search t))
1285 (or (and (looking-at "mode:")
1286 (goto-char (match-end 0)))
1287 (re-search-forward "[ \t;]mode:" end t)))
1288 (skip-chars-forward " \t")
1289 (setq beg (point))
1290 (if (search-forward ";" end t)
1291 (forward-char -1)
1292 (goto-char end))
1293 (skip-chars-backward " \t")
1294 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1295 modes)))
1296 ;; Simple -*-MODE-*- case.
1297 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1298 "-mode"))
1299 modes))))))
1300 ;; If we found modes to use, invoke them now,
1301 ;; outside the save-excursion.
1302 (when modes
1303 (unless just-from-file-name
1304 (mapcar 'funcall (nreverse modes)))
1305 (setq done t))
1306 ;; If we didn't find a mode from a -*- line, try using the file name.
1307 (if (and (not done) buffer-file-name)
1308 (let ((name buffer-file-name)
1309 (keep-going t))
1310 ;; Remove backup-suffixes from file name.
1311 (setq name (file-name-sans-versions name))
1312 (while keep-going
1313 (setq keep-going nil)
1314 (let ((alist auto-mode-alist)
1315 (mode nil))
1316 ;; Find first matching alist entry.
1317 (let ((case-fold-search
1318 (memq system-type '(vax-vms windows-nt))))
1319 (while (and (not mode) alist)
1320 (if (string-match (car (car alist)) name)
1321 (if (and (consp (cdr (car alist)))
1322 (nth 2 (car alist)))
1323 (progn
1324 (setq mode (car (cdr (car alist)))
1325 name (substring name 0 (match-beginning 0))
1326 keep-going t))
1327 (setq mode (cdr (car alist))
1328 keep-going nil)))
1329 (setq alist (cdr alist))))
1330 (if mode
1331 (funcall mode)
1332 ;; If we can't deduce a mode from the file name,
1333 ;; look for an interpreter specified in the first line.
1334 ;; As a special case, allow for things like "#!/bin/env perl",
1335 ;; which finds the interpreter anywhere in $PATH.
1336 (let ((interpreter
1337 (save-excursion
1338 (goto-char (point-min))
1339 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1340 (buffer-substring (match-beginning 2)
1341 (match-end 2))
1342 "")))
1343 elt)
1344 ;; Map interpreter name to a mode.
1345 (setq elt (assoc (file-name-nondirectory interpreter)
1346 interpreter-mode-alist))
1347 (unless just-from-file-name
1348 (if elt
1349 (funcall (cdr elt))))))))))))
1350
1351 (defun hack-local-variables-prop-line ()
1352 ;; Set local variables specified in the -*- line.
1353 ;; Ignore any specification for `mode:';
1354 ;; set-auto-mode should already have handled that.
1355 (save-excursion
1356 (goto-char (point-min))
1357 (let ((result nil)
1358 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1359 ;; Parse the -*- line into the `result' alist.
1360 (cond ((not (search-forward "-*-" end t))
1361 ;; doesn't have one.
1362 nil)
1363 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1364 ;; Simple form: "-*- MODENAME -*-". Already handled.
1365 nil)
1366 (t
1367 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1368 ;; (last ";" is optional).
1369 (save-excursion
1370 (if (search-forward "-*-" end t)
1371 (setq end (- (point) 3))
1372 (error "-*- not terminated before end of line")))
1373 (while (< (point) end)
1374 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1375 (error "malformed -*- line"))
1376 (goto-char (match-end 0))
1377 ;; There used to be a downcase here,
1378 ;; but the manual didn't say so,
1379 ;; and people want to set var names that aren't all lc.
1380 (let ((key (intern (buffer-substring
1381 (match-beginning 1)
1382 (match-end 1))))
1383 (val (save-restriction
1384 (narrow-to-region (point) end)
1385 (read (current-buffer)))))
1386 ;; It is traditional to ignore
1387 ;; case when checking for `mode' in set-auto-mode,
1388 ;; so we must do that here as well.
1389 ;; That is inconsistent, but we're stuck with it.
1390 (or (equal (downcase (symbol-name key)) "mode")
1391 (setq result (cons (cons key val) result)))
1392 (skip-chars-forward " \t;")))
1393 (setq result (nreverse result))))
1394
1395 (if (and result
1396 (or (eq enable-local-variables t)
1397 (and enable-local-variables
1398 (save-window-excursion
1399 (condition-case nil
1400 (switch-to-buffer (current-buffer))
1401 (error
1402 ;; If we fail to switch in the selected window,
1403 ;; it is probably a minibuffer.
1404 ;; So try another window.
1405 (condition-case nil
1406 (switch-to-buffer-other-window (current-buffer))
1407 (error
1408 (switch-to-buffer-other-frame (current-buffer))))))
1409 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1410 (file-name-nondirectory buffer-file-name)))))))
1411 (let ((enable-local-eval enable-local-eval))
1412 (while result
1413 (hack-one-local-variable (car (car result)) (cdr (car result)))
1414 (setq result (cdr result))))))))
1415
1416 (defvar hack-local-variables-hook nil
1417 "Normal hook run after processing a file's local variables specs.
1418 Major modes can use this to examine user-specified local variables
1419 in order to initialize other data structure based on them.")
1420
1421 (defun hack-local-variables (&optional mode-only)
1422 "Parse and put into effect this buffer's local variables spec.
1423 If MODE-ONLY is non-nil, all we do is check whether the major mode
1424 is specified, returning t if it is specified."
1425 (unless mode-only
1426 (hack-local-variables-prop-line))
1427 ;; Look for "Local variables:" line in last page.
1428 (let (mode-specified)
1429 (save-excursion
1430 (goto-char (point-max))
1431 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1432 (if (let ((case-fold-search t))
1433 (and (search-forward "Local Variables:" nil t)
1434 (or (eq enable-local-variables t)
1435 mode-only
1436 (and enable-local-variables
1437 (save-window-excursion
1438 (switch-to-buffer (current-buffer))
1439 (save-excursion
1440 (beginning-of-line)
1441 (set-window-start (selected-window) (point)))
1442 (y-or-n-p (format "Set local variables as specified at end of %s? "
1443 (if buffer-file-name
1444 (file-name-nondirectory
1445 buffer-file-name)
1446 (concat "buffer "
1447 (buffer-name))))))))))
1448 (let ((continue t)
1449 prefix prefixlen suffix beg
1450 mode-specified
1451 (enable-local-eval enable-local-eval))
1452 ;; The prefix is what comes before "local variables:" in its line.
1453 ;; The suffix is what comes after "local variables:" in its line.
1454 (skip-chars-forward " \t")
1455 (or (eolp)
1456 (setq suffix (buffer-substring (point)
1457 (progn (end-of-line) (point)))))
1458 (goto-char (match-beginning 0))
1459 (or (bolp)
1460 (setq prefix
1461 (buffer-substring (point)
1462 (progn (beginning-of-line) (point)))))
1463
1464 (if prefix (setq prefixlen (length prefix)
1465 prefix (regexp-quote prefix)))
1466 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1467 (while continue
1468 ;; Look at next local variable spec.
1469 (if selective-display (re-search-forward "[\n\C-m]")
1470 (forward-line 1))
1471 ;; Skip the prefix, if any.
1472 (if prefix
1473 (if (looking-at prefix)
1474 (forward-char prefixlen)
1475 (error "Local variables entry is missing the prefix")))
1476 ;; Find the variable name; strip whitespace.
1477 (skip-chars-forward " \t")
1478 (setq beg (point))
1479 (skip-chars-forward "^:\n")
1480 (if (eolp) (error "Missing colon in local variables entry"))
1481 (skip-chars-backward " \t")
1482 (let* ((str (buffer-substring beg (point)))
1483 (var (read str))
1484 val)
1485 ;; Setting variable named "end" means end of list.
1486 (if (string-equal (downcase str) "end")
1487 (setq continue nil)
1488 ;; Otherwise read the variable value.
1489 (skip-chars-forward "^:")
1490 (forward-char 1)
1491 (setq val (read (current-buffer)))
1492 (skip-chars-backward "\n")
1493 (skip-chars-forward " \t")
1494 (or (if suffix (looking-at suffix) (eolp))
1495 (error "Local variables entry is terminated incorrectly"))
1496 (if mode-only
1497 (if (eq var 'mode)
1498 (setq mode-specified t))
1499 ;; Set the variable. "Variables" mode and eval are funny.
1500 (hack-one-local-variable var val))))))))
1501 (unless mode-only
1502 (run-hooks 'hack-local-variables-hook))
1503 mode-specified))
1504
1505 (defvar ignored-local-variables
1506 '(enable-local-eval)
1507 "Variables to be ignored in a file's local variable spec.")
1508
1509 ;; Get confirmation before setting these variables as locals in a file.
1510 (put 'debugger 'risky-local-variable t)
1511 (put 'enable-local-eval 'risky-local-variable t)
1512 (put 'ignored-local-variables 'risky-local-variable t)
1513 (put 'eval 'risky-local-variable t)
1514 (put 'file-name-handler-alist 'risky-local-variable t)
1515 (put 'minor-mode-map-alist 'risky-local-variable t)
1516 (put 'after-load-alist 'risky-local-variable t)
1517 (put 'buffer-file-name 'risky-local-variable t)
1518 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1519 (put 'buffer-file-truename 'risky-local-variable t)
1520 (put 'exec-path 'risky-local-variable t)
1521 (put 'load-path 'risky-local-variable t)
1522 (put 'exec-directory 'risky-local-variable t)
1523 (put 'process-environment 'risky-local-variable t)
1524 (put 'dabbrev-case-fold-search 'risky-local-variable t)
1525 (put 'dabbrev-case-replace 'risky-local-variable t)
1526 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1527 (put 'outline-level 'risky-local-variable t)
1528 (put 'rmail-output-file-alist 'risky-local-variable t)
1529
1530 ;; This one is safe because the user gets to check it before it is used.
1531 (put 'compile-command 'safe-local-variable t)
1532
1533 (defun hack-one-local-variable-quotep (exp)
1534 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1535
1536 ;; "Set" one variable in a local variables spec.
1537 ;; A few variable names are treated specially.
1538 (defun hack-one-local-variable (var val)
1539 (cond ((eq var 'mode)
1540 (funcall (intern (concat (downcase (symbol-name val))
1541 "-mode"))))
1542 ((memq var ignored-local-variables)
1543 nil)
1544 ;; "Setting" eval means either eval it or do nothing.
1545 ;; Likewise for setting hook variables.
1546 ((or (get var 'risky-local-variable)
1547 (and
1548 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1549 (symbol-name var))
1550 (not (get var 'safe-local-variable))))
1551 ;; Permit evalling a put of a harmless property.
1552 ;; if the args do nothing tricky.
1553 (if (or (and (eq var 'eval)
1554 (consp val)
1555 (eq (car val) 'put)
1556 (hack-one-local-variable-quotep (nth 1 val))
1557 (hack-one-local-variable-quotep (nth 2 val))
1558 ;; Only allow safe values of lisp-indent-hook;
1559 ;; not functions.
1560 (or (numberp (nth 3 val))
1561 (equal (nth 3 val) ''defun))
1562 (memq (nth 1 (nth 2 val))
1563 '(lisp-indent-hook)))
1564 ;; Permit eval if not root and user says ok.
1565 (and (not (zerop (user-uid)))
1566 (or (eq enable-local-eval t)
1567 (and enable-local-eval
1568 (save-window-excursion
1569 (switch-to-buffer (current-buffer))
1570 (save-excursion
1571 (beginning-of-line)
1572 (set-window-start (selected-window) (point)))
1573 (setq enable-local-eval
1574 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1575 (file-name-nondirectory buffer-file-name)))))))))
1576 (if (eq var 'eval)
1577 (save-excursion (eval val))
1578 (make-local-variable var)
1579 (set var val))
1580 (message "Ignoring `eval:' in file's local variables")))
1581 ;; Ordinary variable, really set it.
1582 (t (make-local-variable var)
1583 (set var val))))
1584
1585 \f
1586 (defcustom change-major-mode-with-file-name t
1587 "*Non-nil means \\[write-file] should set the major mode from the file name.
1588 However, the mode will not be changed if
1589 \(1) a local variables list or the `-*-' line specifies a major mode, or
1590 \(2) the current major mode is a \"special\" mode,
1591 \ not suitable for ordinary files, or
1592 \(3) the new file name does not particularly specify any mode."
1593 :type 'boolean
1594 :group 'editing-basics)
1595
1596 (defun set-visited-file-name (filename &optional no-query along-with-file)
1597 "Change name of file visited in current buffer to FILENAME.
1598 The next time the buffer is saved it will go in the newly specified file.
1599 nil or empty string as argument means make buffer not be visiting any file.
1600 Remember to delete the initial contents of the minibuffer
1601 if you wish to pass an empty string as the argument.
1602
1603 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1604 confirmation in the case where another buffer is already visiting FILENAME.
1605
1606 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1607 the old visited file has been renamed to the new name FILENAME."
1608 (interactive "FSet visited file name: ")
1609 (if (buffer-base-buffer)
1610 (error "An indirect buffer cannot visit a file"))
1611 (let (truename)
1612 (if filename
1613 (setq filename
1614 (if (string-equal filename "")
1615 nil
1616 (expand-file-name filename))))
1617 (if filename
1618 (progn
1619 (setq truename (file-truename filename))
1620 (if find-file-visit-truename
1621 (setq filename truename))))
1622 (let ((buffer (and filename (find-buffer-visiting filename))))
1623 (and buffer (not (eq buffer (current-buffer)))
1624 (not no-query)
1625 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1626 filename)))
1627 (error "Aborted")))
1628 (or (equal filename buffer-file-name)
1629 (progn
1630 (and filename (lock-buffer filename))
1631 (unlock-buffer)))
1632 (setq buffer-file-name filename)
1633 (if filename ; make buffer name reflect filename.
1634 (let ((new-name (file-name-nondirectory buffer-file-name)))
1635 (if (string= new-name "")
1636 (error "Empty file name"))
1637 (if (eq system-type 'vax-vms)
1638 (setq new-name (downcase new-name)))
1639 (setq default-directory (file-name-directory buffer-file-name))
1640 (or (string= new-name (buffer-name))
1641 (rename-buffer new-name t))))
1642 (setq buffer-backed-up nil)
1643 (or along-with-file
1644 (clear-visited-file-modtime))
1645 ;; Abbreviate the file names of the buffer.
1646 (if truename
1647 (progn
1648 (setq buffer-file-truename (abbreviate-file-name truename))
1649 (if find-file-visit-truename
1650 (setq buffer-file-name buffer-file-truename))))
1651 (setq buffer-file-number
1652 (if filename
1653 (nthcdr 10 (file-attributes buffer-file-name))
1654 nil)))
1655 ;; write-file-hooks is normally used for things like ftp-find-file
1656 ;; that visit things that are not local files as if they were files.
1657 ;; Changing to visit an ordinary local file instead should flush the hook.
1658 (kill-local-variable 'write-file-hooks)
1659 (kill-local-variable 'local-write-file-hooks)
1660 (kill-local-variable 'revert-buffer-function)
1661 (kill-local-variable 'backup-inhibited)
1662 ;; If buffer was read-only because of version control,
1663 ;; that reason is gone now, so make it writable.
1664 (if vc-mode
1665 (setq buffer-read-only nil))
1666 (kill-local-variable 'vc-mode)
1667 ;; Turn off backup files for certain file names.
1668 ;; Since this is a permanent local, the major mode won't eliminate it.
1669 (and (not (funcall backup-enable-predicate buffer-file-name))
1670 (progn
1671 (make-local-variable 'backup-inhibited)
1672 (setq backup-inhibited t)))
1673 (let ((oauto buffer-auto-save-file-name))
1674 ;; If auto-save was not already on, turn it on if appropriate.
1675 (if (not buffer-auto-save-file-name)
1676 (and buffer-file-name auto-save-default
1677 (auto-save-mode t))
1678 ;; If auto save is on, start using a new name.
1679 ;; We deliberately don't rename or delete the old auto save
1680 ;; for the old visited file name. This is because perhaps
1681 ;; the user wants to save the new state and then compare with the
1682 ;; previous state from the auto save file.
1683 (setq buffer-auto-save-file-name
1684 (make-auto-save-file-name)))
1685 ;; Rename the old auto save file if any.
1686 (and oauto buffer-auto-save-file-name
1687 (file-exists-p oauto)
1688 (rename-file oauto buffer-auto-save-file-name t)))
1689 (and buffer-file-name
1690 (not along-with-file)
1691 (set-buffer-modified-p t))
1692 ;; Update the major mode, if the file name determines it.
1693 (condition-case nil
1694 ;; Don't change the mode if it is special.
1695 (or (not change-major-mode-with-file-name)
1696 (get major-mode 'mode-class)
1697 ;; Don't change the mode if the local variable list specifies it.
1698 (hack-local-variables t)
1699 (set-auto-mode t))
1700 (error nil)))
1701
1702 (defun write-file (filename &optional confirm)
1703 "Write current buffer into file FILENAME.
1704 Makes buffer visit that file, and marks it not modified.
1705 If the buffer is already visiting a file, you can specify
1706 a directory name as FILENAME, to write a file of the same
1707 old name in that directory.
1708
1709 If optional second arg CONFIRM is non-nil,
1710 ask for confirmation for overwriting an existing file.
1711 Interactively, confirmation is required unless you supply a prefix argument."
1712 ;; (interactive "FWrite file: ")
1713 (interactive
1714 (list (if buffer-file-name
1715 (read-file-name "Write file: "
1716 nil nil nil nil)
1717 (read-file-name "Write file: "
1718 (cdr (assq 'default-directory
1719 (buffer-local-variables)))
1720 nil nil (buffer-name)))
1721 (not current-prefix-arg)))
1722 (or (null filename) (string-equal filename "")
1723 (progn
1724 ;; If arg is just a directory,
1725 ;; use same file name, but in that directory.
1726 (if (and (file-directory-p filename) buffer-file-name)
1727 (setq filename (concat (file-name-as-directory filename)
1728 (file-name-nondirectory buffer-file-name))))
1729 (and confirm
1730 (file-exists-p filename)
1731 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1732 (error "Canceled")))
1733 (set-visited-file-name filename (not confirm))))
1734 (set-buffer-modified-p t)
1735 (save-buffer))
1736 \f
1737 (defun backup-buffer ()
1738 "Make a backup of the disk file visited by the current buffer, if appropriate.
1739 This is normally done before saving the buffer the first time.
1740 If the value is non-nil, it is the result of `file-modes' on the original
1741 file; this means that the caller, after saving the buffer, should change
1742 the modes of the new file to agree with the old modes.
1743
1744 A backup may be done by renaming or by copying; see documentation of
1745 variable `make-backup-files'. If it's done by renaming, then the file is
1746 no longer accessible under its old name."
1747 (if (and make-backup-files (not backup-inhibited)
1748 (not buffer-backed-up)
1749 (file-exists-p buffer-file-name)
1750 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1751 '(?- ?l)))
1752 (let ((real-file-name buffer-file-name)
1753 backup-info backupname targets setmodes)
1754 ;; If specified name is a symbolic link, chase it to the target.
1755 ;; Thus we make the backups in the directory where the real file is.
1756 (setq real-file-name (file-chase-links real-file-name))
1757 (setq backup-info (find-backup-file-name real-file-name)
1758 backupname (car backup-info)
1759 targets (cdr backup-info))
1760 ;;; (if (file-directory-p buffer-file-name)
1761 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1762 (if backup-info
1763 (condition-case ()
1764 (let ((delete-old-versions
1765 ;; If have old versions to maybe delete,
1766 ;; ask the user to confirm now, before doing anything.
1767 ;; But don't actually delete til later.
1768 (and targets
1769 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1770 (or delete-old-versions
1771 (y-or-n-p (format "Delete excess backup versions of %s? "
1772 real-file-name))))))
1773 ;; Actually write the back up file.
1774 (condition-case ()
1775 (if (or file-precious-flag
1776 ; (file-symlink-p buffer-file-name)
1777 backup-by-copying
1778 (and backup-by-copying-when-linked
1779 (> (file-nlinks real-file-name) 1))
1780 (and backup-by-copying-when-mismatch
1781 (let ((attr (file-attributes real-file-name)))
1782 (or (nth 9 attr)
1783 (not (file-ownership-preserved-p real-file-name))))))
1784 (condition-case ()
1785 (copy-file real-file-name backupname t t)
1786 (file-error
1787 ;; If copying fails because file BACKUPNAME
1788 ;; is not writable, delete that file and try again.
1789 (if (and (file-exists-p backupname)
1790 (not (file-writable-p backupname)))
1791 (delete-file backupname))
1792 (copy-file real-file-name backupname t t)))
1793 ;; rename-file should delete old backup.
1794 (rename-file real-file-name backupname t)
1795 (setq setmodes (file-modes backupname)))
1796 (file-error
1797 ;; If trouble writing the backup, write it in ~.
1798 (setq backupname (expand-file-name
1799 (convert-standard-filename
1800 "~/%backup%~")))
1801 (message "Cannot write backup file; backing up in %s"
1802 (file-name-nondirectory backupname))
1803 (sleep-for 1)
1804 (condition-case ()
1805 (copy-file real-file-name backupname t t)
1806 (file-error
1807 ;; If copying fails because file BACKUPNAME
1808 ;; is not writable, delete that file and try again.
1809 (if (and (file-exists-p backupname)
1810 (not (file-writable-p backupname)))
1811 (delete-file backupname))
1812 (copy-file real-file-name backupname t t)))))
1813 (setq buffer-backed-up t)
1814 ;; Now delete the old versions, if desired.
1815 (if delete-old-versions
1816 (while targets
1817 (condition-case ()
1818 (delete-file (car targets))
1819 (file-error nil))
1820 (setq targets (cdr targets))))
1821 setmodes)
1822 (file-error nil))))))
1823
1824 (defun file-name-sans-versions (name &optional keep-backup-version)
1825 "Return FILENAME sans backup versions or strings.
1826 This is a separate procedure so your site-init or startup file can
1827 redefine it.
1828 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1829 we do not remove backup version numbers, only true file version numbers."
1830 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1831 (if handler
1832 (funcall handler 'file-name-sans-versions name keep-backup-version)
1833 (substring name 0
1834 (if (eq system-type 'vax-vms)
1835 ;; VMS version number is (a) semicolon, optional
1836 ;; sign, zero or more digits or (b) period, option
1837 ;; sign, zero or more digits, provided this is the
1838 ;; second period encountered outside of the
1839 ;; device/directory part of the file name.
1840 (or (string-match ";[-+]?[0-9]*\\'" name)
1841 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1842 name)
1843 (match-beginning 1))
1844 (length name))
1845 (if keep-backup-version
1846 (length name)
1847 (or (string-match "\\.~[0-9.]+~\\'" name)
1848 (string-match "~\\'" name)
1849 (length name))))))))
1850
1851 (defun file-ownership-preserved-p (file)
1852 "Returns t if deleting FILE and rewriting it would preserve the owner."
1853 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1854 (if handler
1855 (funcall handler 'file-ownership-preserved-p file)
1856 (let ((attributes (file-attributes file)))
1857 ;; Return t if the file doesn't exist, since it's true that no
1858 ;; information would be lost by an (attempted) delete and create.
1859 (or (null attributes)
1860 (= (nth 2 attributes) (user-uid)))))))
1861
1862 (defun file-name-sans-extension (filename)
1863 "Return FILENAME sans final \"extension\".
1864 The extension, in a file name, is the part that follows the last `.'."
1865 (save-match-data
1866 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1867 directory)
1868 (if (string-match "\\.[^.]*\\'" file)
1869 (if (setq directory (file-name-directory filename))
1870 (expand-file-name (substring file 0 (match-beginning 0))
1871 directory)
1872 (substring file 0 (match-beginning 0)))
1873 filename))))
1874
1875 (defun file-name-extension (filename &optional period)
1876 "Return FILENAME's final \"extension\".
1877 The extension, in a file name, is the part that follows the last `.'.
1878 Return nil for extensionless file names such as `foo'.
1879 Return the empty string for file names such as `foo.'.
1880
1881 If PERIOD is non-nil, then the returned value includes the period
1882 that delimits the extension, and if FILENAME has no extension,
1883 the value is \"\"."
1884 (save-match-data
1885 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
1886 (if (string-match "\\.[^.]*\\'" file)
1887 (substring file (+ (match-beginning 0) (if period 0 1)))
1888 (if period
1889 "")))))
1890
1891 (defun make-backup-file-name (file)
1892 "Create the non-numeric backup file name for FILE.
1893 This is a separate function so you can redefine it for customization."
1894 (if (and (eq system-type 'ms-dos)
1895 (not (msdos-long-file-names)))
1896 (let ((fn (file-name-nondirectory file)))
1897 (concat (file-name-directory file)
1898 (or
1899 (and (string-match "\\`[^.]+\\'" fn)
1900 (concat (match-string 0 fn) ".~"))
1901 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
1902 (concat (match-string 0 fn) "~")))))
1903 (concat file "~")))
1904
1905 (defun backup-file-name-p (file)
1906 "Return non-nil if FILE is a backup file name (numeric or not).
1907 This is a separate function so you can redefine it for customization.
1908 You may need to redefine `file-name-sans-versions' as well."
1909 (string-match "~\\'" file))
1910
1911 (defvar backup-extract-version-start)
1912
1913 ;; This is used in various files.
1914 ;; The usage of bv-length is not very clean,
1915 ;; but I can't see a good alternative,
1916 ;; so as of now I am leaving it alone.
1917 (defun backup-extract-version (fn)
1918 "Given the name of a numeric backup file, return the backup number.
1919 Uses the free variable `backup-extract-version-start', whose value should be
1920 the index in the name where the version number begins."
1921 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
1922 (= (match-beginning 0) backup-extract-version-start))
1923 (string-to-int (substring fn backup-extract-version-start -1))
1924 0))
1925
1926 ;; I believe there is no need to alter this behavior for VMS;
1927 ;; since backup files are not made on VMS, it should not get called.
1928 (defun find-backup-file-name (fn)
1929 "Find a file name for a backup file, and suggestions for deletions.
1930 Value is a list whose car is the name for the backup file
1931 and whose cdr is a list of old versions to consider deleting now.
1932 If the value is nil, don't make a backup."
1933 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
1934 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1935 (if handler
1936 (funcall handler 'find-backup-file-name fn)
1937 (if (eq version-control 'never)
1938 (list (make-backup-file-name fn))
1939 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1940 (backup-extract-version-start (length base-versions))
1941 possibilities
1942 (versions nil)
1943 (high-water-mark 0)
1944 (deserve-versions-p nil)
1945 (number-to-delete 0))
1946 (condition-case ()
1947 (setq possibilities (file-name-all-completions
1948 base-versions
1949 (file-name-directory fn))
1950 versions (sort (mapcar
1951 (function backup-extract-version)
1952 possibilities)
1953 '<)
1954 high-water-mark (apply 'max 0 versions)
1955 deserve-versions-p (or version-control
1956 (> high-water-mark 0))
1957 number-to-delete (- (length versions)
1958 kept-old-versions kept-new-versions -1))
1959 (file-error
1960 (setq possibilities nil)))
1961 (if (not deserve-versions-p)
1962 (list (make-backup-file-name fn))
1963 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1964 (if (and (> number-to-delete 0)
1965 ;; Delete nothing if there is overflow
1966 ;; in the number of versions to keep.
1967 (>= (+ kept-new-versions kept-old-versions -1) 0))
1968 (mapcar (function (lambda (n)
1969 (concat fn ".~" (int-to-string n) "~")))
1970 (let ((v (nthcdr kept-old-versions versions)))
1971 (rplacd (nthcdr (1- number-to-delete) v) ())
1972 v))))))))))
1973
1974 (defun file-nlinks (filename)
1975 "Return number of names file FILENAME has."
1976 (car (cdr (file-attributes filename))))
1977
1978 (defun file-relative-name (filename &optional directory)
1979 "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
1980 This function returns a relative file name which is equivalent to FILENAME
1981 when used with that default directory as the default.
1982 If this is impossible (which can happen on MSDOS and Windows
1983 when the file name and directory use different drive names)
1984 then it returns FILENAME."
1985 (save-match-data
1986 (let ((fname (expand-file-name filename)))
1987 (setq directory (file-name-as-directory
1988 (expand-file-name (or directory default-directory))))
1989 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
1990 ;; drive names, they can't be relative, so return the absolute name.
1991 (if (and (or (eq system-type 'ms-dos)
1992 (eq system-type 'windows-nt))
1993 (not (string-equal (substring fname 0 2)
1994 (substring directory 0 2))))
1995 filename
1996 (let ((ancestor ".")
1997 (fname-dir (file-name-as-directory fname)))
1998 (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
1999 (not (string-match (concat "^" (regexp-quote directory)) fname)))
2000 (setq directory (file-name-directory (substring directory 0 -1))
2001 ancestor (if (equal ancestor ".")
2002 ".."
2003 (concat "../" ancestor))))
2004 ;; Now ancestor is empty, or .., or ../.., etc.
2005 (if (string-match (concat "^" (regexp-quote directory)) fname)
2006 ;; We matched within FNAME's directory part.
2007 ;; Add the rest of FNAME onto ANCESTOR.
2008 (let ((rest (substring fname (match-end 0))))
2009 (if (and (equal ancestor ".")
2010 (not (equal rest "")))
2011 ;; But don't bother with ANCESTOR if it would give us `./'.
2012 rest
2013 (concat (file-name-as-directory ancestor) rest)))
2014 ;; We matched FNAME's directory equivalent.
2015 ancestor))))))
2016 \f
2017 (defun save-buffer (&optional args)
2018 "Save current buffer in visited file if modified. Versions described below.
2019 By default, makes the previous version into a backup file
2020 if previously requested or if this is the first save.
2021 With 1 \\[universal-argument], marks this version
2022 to become a backup when the next save is done.
2023 With 2 \\[universal-argument]'s,
2024 unconditionally makes the previous version into a backup file.
2025 With 3 \\[universal-argument]'s, marks this version
2026 to become a backup when the next save is done,
2027 and unconditionally makes the previous version into a backup file.
2028
2029 With argument of 0, never makes the previous version into a backup file.
2030
2031 If a file's name is FOO, the names of its numbered backup versions are
2032 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2033 Numeric backups (rather than FOO~) will be made if value of
2034 `version-control' is not the atom `never' and either there are already
2035 numeric versions of the file being backed up, or `version-control' is
2036 non-nil.
2037 We don't want excessive versions piling up, so there are variables
2038 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2039 and `kept-new-versions', which tells how many newest versions to keep.
2040 Defaults are 2 old versions and 2 new.
2041 `dired-kept-versions' controls dired's clean-directory (.) command.
2042 If `delete-old-versions' is nil, system will query user
2043 before trimming versions. Otherwise it does it silently."
2044 (interactive "p")
2045 (let ((modp (buffer-modified-p))
2046 (large (> (buffer-size) 50000))
2047 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2048 (memq args '(16 64)))))
2049 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2050 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
2051 (basic-save-buffer)
2052 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2053
2054 (defun delete-auto-save-file-if-necessary (&optional force)
2055 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2056 Normally delete only if the file was written by this Emacs since
2057 the last real save, but optional arg FORCE non-nil means delete anyway."
2058 (and buffer-auto-save-file-name delete-auto-save-files
2059 (not (string= buffer-file-name buffer-auto-save-file-name))
2060 (or force (recent-auto-save-p))
2061 (progn
2062 (condition-case ()
2063 (delete-file buffer-auto-save-file-name)
2064 (file-error nil))
2065 (set-buffer-auto-saved))))
2066
2067 (defvar after-save-hook nil
2068 "Normal hook that is run after a buffer is saved to its file.")
2069
2070 (defun basic-save-buffer ()
2071 "Save the current buffer in its visited file, if it has been modified.
2072 After saving the buffer, run `after-save-hook'."
2073 (interactive)
2074 (save-excursion
2075 ;; In an indirect buffer, save its base buffer instead.
2076 (if (buffer-base-buffer)
2077 (set-buffer (buffer-base-buffer)))
2078 (if (buffer-modified-p)
2079 (let ((recent-save (recent-auto-save-p))
2080 setmodes tempsetmodes)
2081 ;; On VMS, rename file and buffer to get rid of version number.
2082 (if (and (eq system-type 'vax-vms)
2083 (not (string= buffer-file-name
2084 (file-name-sans-versions buffer-file-name))))
2085 (let (buffer-new-name)
2086 ;; Strip VMS version number before save.
2087 (setq buffer-file-name
2088 (file-name-sans-versions buffer-file-name))
2089 ;; Construct a (unique) buffer name to correspond.
2090 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2091 (setq buffer-new-name (buffer-name buf))
2092 (kill-buffer buf))
2093 (rename-buffer buffer-new-name)))
2094 ;; If buffer has no file name, ask user for one.
2095 (or buffer-file-name
2096 (let ((filename
2097 (expand-file-name
2098 (read-file-name "File to save in: ") nil)))
2099 (and (file-exists-p filename)
2100 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2101 filename))
2102 (error "Canceled")))
2103 (set-visited-file-name filename)))
2104 (or (verify-visited-file-modtime (current-buffer))
2105 (not (file-exists-p buffer-file-name))
2106 (yes-or-no-p
2107 (format "%s has changed since visited or saved. Save anyway? "
2108 (file-name-nondirectory buffer-file-name)))
2109 (error "Save not confirmed"))
2110 (save-restriction
2111 (widen)
2112 (and (> (point-max) 1)
2113 (/= (char-after (1- (point-max))) ?\n)
2114 (not (and (eq selective-display t)
2115 (= (char-after (1- (point-max))) ?\r)))
2116 (or (eq require-final-newline t)
2117 (and require-final-newline
2118 (y-or-n-p
2119 (format "Buffer %s does not end in newline. Add one? "
2120 (buffer-name)))))
2121 (save-excursion
2122 (goto-char (point-max))
2123 (insert ?\n)))
2124 (or (run-hook-with-args-until-success 'write-contents-hooks)
2125 (run-hook-with-args-until-success 'local-write-file-hooks)
2126 (run-hook-with-args-until-success 'write-file-hooks)
2127 ;; If a hook returned t, file is already "written".
2128 ;; Otherwise, write it the usual way now.
2129 (setq setmodes (basic-save-buffer-1)))
2130 (setq buffer-file-number
2131 (nthcdr 10 (file-attributes buffer-file-name)))
2132 (if setmodes
2133 (condition-case ()
2134 (set-file-modes buffer-file-name setmodes)
2135 (error nil))))
2136 ;; If the auto-save file was recent before this command,
2137 ;; delete it now.
2138 (delete-auto-save-file-if-necessary recent-save)
2139 ;; Support VC `implicit' locking.
2140 (vc-after-save)
2141 (run-hooks 'after-save-hook))
2142 (message "(No changes need to be saved)"))))
2143
2144 ;; This does the "real job" of writing a buffer into its visited file
2145 ;; and making a backup file. This is what is normally done
2146 ;; but inhibited if one of write-file-hooks returns non-nil.
2147 ;; It returns a value to store in setmodes.
2148 (defun basic-save-buffer-1 ()
2149 (let (tempsetmodes setmodes)
2150 (if (not (file-writable-p buffer-file-name))
2151 (let ((dir (file-name-directory buffer-file-name)))
2152 (if (not (file-directory-p dir))
2153 (if (file-exists-p dir)
2154 (error "%s is not a directory" dir)
2155 (error "%s: no such directory"))
2156 (if (not (file-exists-p buffer-file-name))
2157 (error "Directory %s write-protected" dir)
2158 (if (yes-or-no-p
2159 (format "File %s is write-protected; try to save anyway? "
2160 (file-name-nondirectory
2161 buffer-file-name)))
2162 (setq tempsetmodes t)
2163 (error "Attempt to save to a file which you aren't allowed to write"))))))
2164 (or buffer-backed-up
2165 (setq setmodes (backup-buffer)))
2166 (let ((dir (file-name-directory buffer-file-name)))
2167 (if (and file-precious-flag
2168 (file-writable-p dir))
2169 ;; If file is precious, write temp name, then rename it.
2170 ;; This requires write access to the containing dir,
2171 ;; which is why we don't try it if we don't have that access.
2172 (let ((realname buffer-file-name)
2173 tempname temp nogood i succeed
2174 (old-modtime (visited-file-modtime)))
2175 (setq i 0)
2176 (setq nogood t)
2177 ;; Find the temporary name to write under.
2178 (while nogood
2179 (setq tempname (format
2180 (if (and (eq system-type 'ms-dos)
2181 (not (msdos-long-file-names)))
2182 "%s#%d.tm#" ; MSDOS limits files to 8+3
2183 "%s#tmp#%d")
2184 dir i))
2185 (setq nogood (file-exists-p tempname))
2186 (setq i (1+ i)))
2187 (unwind-protect
2188 (progn (clear-visited-file-modtime)
2189 (write-region (point-min) (point-max)
2190 tempname nil realname
2191 buffer-file-truename)
2192 (setq succeed t))
2193 ;; If writing the temp file fails,
2194 ;; delete the temp file.
2195 (or succeed
2196 (progn
2197 (delete-file tempname)
2198 (set-visited-file-modtime old-modtime))))
2199 ;; Since we have created an entirely new file
2200 ;; and renamed it, make sure it gets the
2201 ;; right permission bits set.
2202 (setq setmodes (file-modes buffer-file-name))
2203 ;; We succeeded in writing the temp file,
2204 ;; so rename it.
2205 (rename-file tempname buffer-file-name t))
2206 ;; If file not writable, see if we can make it writable
2207 ;; temporarily while we write it.
2208 ;; But no need to do so if we have just backed it up
2209 ;; (setmodes is set) because that says we're superseding.
2210 (cond ((and tempsetmodes (not setmodes))
2211 ;; Change the mode back, after writing.
2212 (setq setmodes (file-modes buffer-file-name))
2213 (set-file-modes buffer-file-name 511)))
2214 (write-region (point-min) (point-max)
2215 buffer-file-name nil t buffer-file-truename)))
2216 setmodes))
2217
2218 (defun save-some-buffers (&optional arg exiting)
2219 "Save some modified file-visiting buffers. Asks user about each one.
2220 Optional argument (the prefix) non-nil means save all with no questions.
2221 Optional second argument EXITING means ask about certain non-file buffers
2222 as well as about file buffers."
2223 (interactive "P")
2224 (save-window-excursion
2225 (let* ((queried nil)
2226 (files-done
2227 (map-y-or-n-p
2228 (function
2229 (lambda (buffer)
2230 (and (buffer-modified-p buffer)
2231 (not (buffer-base-buffer buffer))
2232 (or
2233 (buffer-file-name buffer)
2234 (and exiting
2235 (progn
2236 (set-buffer buffer)
2237 (and buffer-offer-save (> (buffer-size) 0)))))
2238 (if arg
2239 t
2240 (setq queried t)
2241 (if (buffer-file-name buffer)
2242 (format "Save file %s? "
2243 (buffer-file-name buffer))
2244 (format "Save buffer %s? "
2245 (buffer-name buffer)))))))
2246 (function
2247 (lambda (buffer)
2248 (set-buffer buffer)
2249 (save-buffer)))
2250 (buffer-list)
2251 '("buffer" "buffers" "save")
2252 (list (list ?\C-r (lambda (buf)
2253 (view-buffer buf
2254 (function
2255 (lambda (ignore)
2256 (exit-recursive-edit))))
2257 (recursive-edit)
2258 ;; Return nil to ask about BUF again.
2259 nil)
2260 "display the current buffer"))))
2261 (abbrevs-done
2262 (and save-abbrevs abbrevs-changed
2263 (progn
2264 (if (or arg
2265 (y-or-n-p (format "Save abbrevs in %s? "
2266 abbrev-file-name)))
2267 (write-abbrev-file nil))
2268 ;; Don't keep bothering user if he says no.
2269 (setq abbrevs-changed nil)
2270 t))))
2271 (or queried (> files-done 0) abbrevs-done
2272 (message "(No files need saving)")))))
2273 \f
2274 (defun not-modified (&optional arg)
2275 "Mark current buffer as unmodified, not needing to be saved.
2276 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2277
2278 It is not a good idea to use this function in Lisp programs, because it
2279 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2280 (interactive "P")
2281 (message (if arg "Modification-flag set"
2282 "Modification-flag cleared"))
2283 (set-buffer-modified-p arg))
2284
2285 (defun toggle-read-only (&optional arg)
2286 "Change whether this buffer is visiting its file read-only.
2287 With arg, set read-only iff arg is positive.
2288 If visiting file read-only and `view-read-only' is non-nil, enter view mode."
2289 (interactive "P")
2290 (cond
2291 ((and arg (if (> (prefix-numeric-value arg) 0) buffer-read-only
2292 (not buffer-read-only))) ; If buffer-read-only is set correctly,
2293 nil) ; do nothing.
2294 ;; Toggle.
2295 ((and buffer-read-only view-mode)
2296 (View-exit-and-edit)) ; Must leave view mode.
2297 ((and (not buffer-read-only) view-read-only
2298 (not (eq (get major-mode 'mode-class) 'special)))
2299 (view-mode-enter))
2300 (t (setq buffer-read-only (not buffer-read-only))
2301 (force-mode-line-update))))
2302
2303 (defun insert-file (filename)
2304 "Insert contents of file FILENAME into buffer after point.
2305 Set mark after the inserted text.
2306
2307 This function is meant for the user to run interactively.
2308 Don't call it from programs! Use `insert-file-contents' instead.
2309 \(Its calling sequence is different; see its documentation)."
2310 (interactive "*fInsert file: ")
2311 (if (file-directory-p filename)
2312 (signal 'file-error (list "Opening input file" "file is a directory"
2313 filename)))
2314 (let ((tem (insert-file-contents filename)))
2315 (push-mark (+ (point) (car (cdr tem))))))
2316
2317 (defun append-to-file (start end filename)
2318 "Append the contents of the region to the end of file FILENAME.
2319 When called from a function, expects three arguments,
2320 START, END and FILENAME. START and END are buffer positions
2321 saying what text to write.
2322 A prefix argument enables user to specify the coding-system interactively."
2323 (interactive "r\nFAppend to file: ")
2324 (write-region start end filename t))
2325
2326 (defun file-newest-backup (filename)
2327 "Return most recent backup file for FILENAME or nil if no backups exist."
2328 (let* ((filename (expand-file-name filename))
2329 (file (file-name-nondirectory filename))
2330 (dir (file-name-directory filename))
2331 (comp (file-name-all-completions file dir))
2332 (newest nil)
2333 tem)
2334 (while comp
2335 (setq tem (car comp)
2336 comp (cdr comp))
2337 (cond ((and (backup-file-name-p tem)
2338 (string= (file-name-sans-versions tem) file))
2339 (setq tem (concat dir tem))
2340 (if (or (null newest)
2341 (file-newer-than-file-p tem newest))
2342 (setq newest tem)))))
2343 newest))
2344
2345 (defun rename-uniquely ()
2346 "Rename current buffer to a similar name not already taken.
2347 This function is useful for creating multiple shell process buffers
2348 or multiple mail buffers, etc."
2349 (interactive)
2350 (save-match-data
2351 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2352 (not (and buffer-file-name
2353 (string= (buffer-name)
2354 (file-name-nondirectory
2355 buffer-file-name)))))
2356 ;; If the existing buffer name has a <NNN>,
2357 ;; which isn't part of the file name (if any),
2358 ;; then get rid of that.
2359 (substring (buffer-name) 0 (match-beginning 0))
2360 (buffer-name)))
2361 (new-buf (generate-new-buffer base-name))
2362 (name (buffer-name new-buf)))
2363 (kill-buffer new-buf)
2364 (rename-buffer name)
2365 (force-mode-line-update))))
2366
2367 (defun make-directory (dir &optional parents)
2368 "Create the directory DIR and any nonexistent parent dirs.
2369 Interactively, the default choice of directory to create
2370 is the current default directory for file names.
2371 That is useful when you have visited a file in a nonexistent directory.
2372
2373 Noninteractively, the second (optional) argument PARENTS says whether
2374 to create parent directories if they don't exist."
2375 (interactive
2376 (list (read-file-name "Make directory: " default-directory default-directory
2377 nil nil)
2378 t))
2379 (let ((handler (find-file-name-handler dir 'make-directory)))
2380 (if handler
2381 (funcall handler 'make-directory dir parents)
2382 (if (not parents)
2383 (make-directory-internal dir)
2384 (let ((dir (directory-file-name (expand-file-name dir)))
2385 create-list)
2386 (while (not (file-exists-p dir))
2387 (setq create-list (cons dir create-list)
2388 dir (directory-file-name (file-name-directory dir))))
2389 (while create-list
2390 (make-directory-internal (car create-list))
2391 (setq create-list (cdr create-list))))))))
2392 \f
2393 (put 'revert-buffer-function 'permanent-local t)
2394 (defvar revert-buffer-function nil
2395 "Function to use to revert this buffer, or nil to do the default.
2396 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2397 which are the arguments that `revert-buffer' received.")
2398
2399 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2400 (defvar revert-buffer-insert-file-contents-function nil
2401 "Function to use to insert contents when reverting this buffer.
2402 Gets two args, first the nominal file name to use,
2403 and second, t if reading the auto-save file.")
2404
2405 (defvar before-revert-hook nil
2406 "Normal hook for `revert-buffer' to run before reverting.
2407 If `revert-buffer-function' is used to override the normal revert
2408 mechanism, this hook is not used.")
2409
2410 (defvar after-revert-hook nil
2411 "Normal hook for `revert-buffer' to run after reverting.
2412 Note that the hook value that it runs is the value that was in effect
2413 before reverting; that makes a difference if you have buffer-local
2414 hook functions.
2415
2416 If `revert-buffer-function' is used to override the normal revert
2417 mechanism, this hook is not used.")
2418
2419 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2420 "Replace current buffer text with the text of the visited file on disk.
2421 This undoes all changes since the file was visited or saved.
2422 With a prefix argument, offer to revert from latest auto-save file, if
2423 that is more recent than the visited file.
2424
2425 This command also works for special buffers that contain text which
2426 doesn't come from a file, but reflects some other data base instead:
2427 for example, Dired buffers and buffer-list buffers. In these cases,
2428 it reconstructs the buffer contents from the appropriate data base.
2429
2430 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2431 to revert from the auto-save file when this is nil. Note that the
2432 sense of this argument is the reverse of the prefix argument, for the
2433 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2434 to nil.
2435
2436 Optional second argument NOCONFIRM means don't ask for confirmation at
2437 all.
2438
2439 Optional third argument PRESERVE-MODES non-nil means don't alter
2440 the files modes. Normally we reinitialize them using `normal-mode'.
2441
2442 If the value of `revert-buffer-function' is non-nil, it is called to
2443 do all the work for this command. Otherwise, the hooks
2444 `before-revert-hook' and `after-revert-hook' are run at the beginning
2445 and the end, and if `revert-buffer-insert-file-contents-function' is
2446 non-nil, it is called instead of rereading visited file contents."
2447
2448 ;; I admit it's odd to reverse the sense of the prefix argument, but
2449 ;; there is a lot of code out there which assumes that the first
2450 ;; argument should be t to avoid consulting the auto-save file, and
2451 ;; there's no straightforward way to encourage authors to notice a
2452 ;; reversal of the argument sense. So I'm just changing the user
2453 ;; interface, but leaving the programmatic interface the same.
2454 (interactive (list (not current-prefix-arg)))
2455 (if revert-buffer-function
2456 (funcall revert-buffer-function ignore-auto noconfirm)
2457 (let* ((opoint (point))
2458 (auto-save-p (and (not ignore-auto)
2459 (recent-auto-save-p)
2460 buffer-auto-save-file-name
2461 (file-readable-p buffer-auto-save-file-name)
2462 (y-or-n-p
2463 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2464 (file-name (if auto-save-p
2465 buffer-auto-save-file-name
2466 buffer-file-name)))
2467 (cond ((null file-name)
2468 (error "Buffer does not seem to be associated with any file"))
2469 ((or noconfirm
2470 (and (not (buffer-modified-p))
2471 (let ((tail revert-without-query)
2472 (found nil))
2473 (while tail
2474 (if (string-match (car tail) file-name)
2475 (setq found t))
2476 (setq tail (cdr tail)))
2477 found))
2478 (yes-or-no-p (format "Revert buffer from file %s? "
2479 file-name)))
2480 (run-hooks 'before-revert-hook)
2481 ;; If file was backed up but has changed since,
2482 ;; we shd make another backup.
2483 (and (not auto-save-p)
2484 (not (verify-visited-file-modtime (current-buffer)))
2485 (setq buffer-backed-up nil))
2486 ;; Get rid of all undo records for this buffer.
2487 (or (eq buffer-undo-list t)
2488 (setq buffer-undo-list nil))
2489 ;; Effectively copy the after-revert-hook status,
2490 ;; since after-find-file will clobber it.
2491 (let ((global-hook (default-value 'after-revert-hook))
2492 (local-hook-p (local-variable-p 'after-revert-hook))
2493 (local-hook (and (local-variable-p 'after-revert-hook)
2494 after-revert-hook)))
2495 (let (buffer-read-only
2496 ;; Don't make undo records for the reversion.
2497 (buffer-undo-list t))
2498 (if revert-buffer-insert-file-contents-function
2499 (funcall revert-buffer-insert-file-contents-function
2500 file-name auto-save-p)
2501 (if (not (file-exists-p file-name))
2502 (error "File %s no longer exists!" file-name))
2503 ;; Bind buffer-file-name to nil
2504 ;; so that we don't try to lock the file.
2505 (let ((buffer-file-name nil))
2506 (or auto-save-p
2507 (unlock-buffer)))
2508 (widen)
2509 (insert-file-contents file-name (not auto-save-p)
2510 nil nil t)))
2511 (goto-char (min opoint (point-max)))
2512 ;; Recompute the truename in case changes in symlinks
2513 ;; have changed the truename.
2514 (setq buffer-file-truename
2515 (abbreviate-file-name (file-truename buffer-file-name)))
2516 (after-find-file nil nil t t preserve-modes)
2517 ;; Run after-revert-hook as it was before we reverted.
2518 (setq-default revert-buffer-internal-hook global-hook)
2519 (if local-hook-p
2520 (progn
2521 (make-local-variable 'revert-buffer-internal-hook)
2522 (setq revert-buffer-internal-hook local-hook))
2523 (kill-local-variable 'revert-buffer-internal-hook))
2524 (run-hooks 'revert-buffer-internal-hook))
2525 t)))))
2526
2527 (defun recover-file (file)
2528 "Visit file FILE, but get contents from its last auto-save file."
2529 ;; Actually putting the file name in the minibuffer should be used
2530 ;; only rarely.
2531 ;; Not just because users often use the default.
2532 (interactive "FRecover file: ")
2533 (setq file (expand-file-name file))
2534 (if (auto-save-file-name-p (file-name-nondirectory file))
2535 (error "%s is an auto-save file" file))
2536 (let ((file-name (let ((buffer-file-name file))
2537 (make-auto-save-file-name))))
2538 (cond ((if (file-exists-p file)
2539 (not (file-newer-than-file-p file-name file))
2540 (not (file-exists-p file-name)))
2541 (error "Auto-save file %s not current" file-name))
2542 ((save-window-excursion
2543 (if (not (eq system-type 'vax-vms))
2544 (with-output-to-temp-buffer "*Directory*"
2545 (buffer-disable-undo standard-output)
2546 (call-process "ls" nil standard-output nil
2547 (if (file-symlink-p file) "-lL" "-l")
2548 file file-name)))
2549 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2550 (switch-to-buffer (find-file-noselect file t))
2551 (let ((buffer-read-only nil)
2552 ;; Auto-saved file shoule be read without any code conversion.
2553 (coding-system-for-read 'no-conversion))
2554 (erase-buffer)
2555 (insert-file-contents file-name nil))
2556 (after-find-file nil nil t))
2557 (t (error "Recover-file cancelled")))))
2558
2559 (defun recover-session ()
2560 "Recover auto save files from a previous Emacs session.
2561 This command first displays a Dired buffer showing you the
2562 previous sessions that you could recover from.
2563 To choose one, move point to the proper line and then type C-c C-c.
2564 Then you'll be asked about a number of files to recover."
2565 (interactive)
2566 (if (null auto-save-list-file-prefix)
2567 (error "You set `auto-save-list-file-prefix' to disable making session files"))
2568 (let ((ls-lisp-support-shell-wildcards t))
2569 (dired (concat auto-save-list-file-prefix "*")
2570 (concat dired-listing-switches "t")))
2571 (goto-char (point-min))
2572 (or (looking-at "Move to the session you want to recover,")
2573 (let ((inhibit-read-only t))
2574 (insert "Move to the session you want to recover,\n"
2575 "then type C-c C-c to select it.\n\n"
2576 "You can also delete some of these files;\n"
2577 "type d on a line to mark that file for deletion.\n\n")))
2578 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2579 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2580
2581 (defun recover-session-finish ()
2582 "Choose one saved session to recover auto-save files from.
2583 This command is used in the special Dired buffer created by
2584 \\[recover-session]."
2585 (interactive)
2586 ;; Get the name of the session file to recover from.
2587 (let ((file (dired-get-filename))
2588 files
2589 (buffer (get-buffer-create " *recover*")))
2590 (dired-do-flagged-delete t)
2591 (unwind-protect
2592 (save-excursion
2593 ;; Read in the auto-save-list file.
2594 (set-buffer buffer)
2595 (erase-buffer)
2596 (insert-file-contents file)
2597 ;; Loop thru the text of that file
2598 ;; and get out the names of the files to recover.
2599 (while (not (eobp))
2600 (let (thisfile autofile)
2601 (if (eolp)
2602 ;; This is a pair of lines for a non-file-visiting buffer.
2603 ;; Get the auto-save file name and manufacture
2604 ;; a "visited file name" from that.
2605 (progn
2606 (forward-line 1)
2607 (setq autofile
2608 (buffer-substring-no-properties
2609 (point)
2610 (save-excursion
2611 (end-of-line)
2612 (point))))
2613 (setq thisfile
2614 (expand-file-name
2615 (substring
2616 (file-name-nondirectory autofile)
2617 1 -1)
2618 (file-name-directory autofile)))
2619 (forward-line 1))
2620 ;; This pair of lines is a file-visiting
2621 ;; buffer. Use the visited file name.
2622 (progn
2623 (setq thisfile
2624 (buffer-substring-no-properties
2625 (point) (progn (end-of-line) (point))))
2626 (forward-line 1)
2627 (setq autofile
2628 (buffer-substring-no-properties
2629 (point) (progn (end-of-line) (point))))
2630 (forward-line 1)))
2631 ;; Ignore a file if its auto-save file does not exist now.
2632 (if (file-exists-p autofile)
2633 (setq files (cons thisfile files)))))
2634 (setq files (nreverse files))
2635 ;; The file contains a pair of line for each auto-saved buffer.
2636 ;; The first line of the pair contains the visited file name
2637 ;; or is empty if the buffer was not visiting a file.
2638 ;; The second line is the auto-save file name.
2639 (if files
2640 (map-y-or-n-p "Recover %s? "
2641 (lambda (file)
2642 (condition-case nil
2643 (save-excursion (recover-file file))
2644 (error
2645 "Failed to recover `%s'" file)))
2646 files
2647 '("file" "files" "recover"))
2648 (message "No files can be recovered from this session now")))
2649 (kill-buffer buffer))))
2650
2651 (defun kill-some-buffers (&optional list)
2652 "For each buffer in LIST, ask whether to kill it.
2653 LIST defaults to all existing live buffers."
2654 (interactive)
2655 (if (null list)
2656 (setq list (buffer-list)))
2657 (while list
2658 (let* ((buffer (car list))
2659 (name (buffer-name buffer)))
2660 (and (not (string-equal name ""))
2661 (/= (aref name 0) ? )
2662 (yes-or-no-p
2663 (format "Buffer %s %s. Kill? "
2664 name
2665 (if (buffer-modified-p buffer)
2666 "HAS BEEN EDITED" "is unmodified")))
2667 (kill-buffer buffer)))
2668 (setq list (cdr list))))
2669 \f
2670 (defun auto-save-mode (arg)
2671 "Toggle auto-saving of contents of current buffer.
2672 With prefix argument ARG, turn auto-saving on if positive, else off."
2673 (interactive "P")
2674 (setq buffer-auto-save-file-name
2675 (and (if (null arg)
2676 (or (not buffer-auto-save-file-name)
2677 ;; If autosave is off because buffer has shrunk,
2678 ;; then toggling should turn it on.
2679 (< buffer-saved-size 0))
2680 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2681 (if (and buffer-file-name auto-save-visited-file-name
2682 (not buffer-read-only))
2683 buffer-file-name
2684 (make-auto-save-file-name))))
2685 ;; If -1 was stored here, to temporarily turn off saving,
2686 ;; turn it back on.
2687 (and (< buffer-saved-size 0)
2688 (setq buffer-saved-size 0))
2689 (if (interactive-p)
2690 (message "Auto-save %s (in this buffer)"
2691 (if buffer-auto-save-file-name "on" "off")))
2692 buffer-auto-save-file-name)
2693
2694 (defun rename-auto-save-file ()
2695 "Adjust current buffer's auto save file name for current conditions.
2696 Also rename any existing auto save file, if it was made in this session."
2697 (let ((osave buffer-auto-save-file-name))
2698 (setq buffer-auto-save-file-name
2699 (make-auto-save-file-name))
2700 (if (and osave buffer-auto-save-file-name
2701 (not (string= buffer-auto-save-file-name buffer-file-name))
2702 (not (string= buffer-auto-save-file-name osave))
2703 (file-exists-p osave)
2704 (recent-auto-save-p))
2705 (rename-file osave buffer-auto-save-file-name t))))
2706
2707 (defun make-auto-save-file-name ()
2708 "Return file name to use for auto-saves of current buffer.
2709 Does not consider `auto-save-visited-file-name' as that variable is checked
2710 before calling this function. You can redefine this for customization.
2711 See also `auto-save-file-name-p'."
2712 (if buffer-file-name
2713 (if (and (eq system-type 'ms-dos)
2714 (not (msdos-long-file-names)))
2715 (let ((fn (file-name-nondirectory buffer-file-name)))
2716 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
2717 (concat (file-name-directory buffer-file-name)
2718 "#" (match-string 1 fn)
2719 "." (match-string 3 fn) "#"))
2720 (concat (file-name-directory buffer-file-name)
2721 "#"
2722 (file-name-nondirectory buffer-file-name)
2723 "#"))
2724
2725 ;; Deal with buffers that don't have any associated files. (Mail
2726 ;; mode tends to create a good number of these.)
2727
2728 (let ((buffer-name (buffer-name))
2729 (limit 0))
2730 ;; Eliminate all slashes and backslashes by
2731 ;; replacing them with sequences that start with %.
2732 ;; Quote % also, to keep distinct names distinct.
2733 (while (string-match "[/\\%]" buffer-name limit)
2734 (let* ((character (aref buffer-name (match-beginning 0)))
2735 (replacement
2736 (cond ((eq character ?%) "%%")
2737 ((eq character ?/) "%+")
2738 ((eq character ?\\) "%-"))))
2739 (setq buffer-name (replace-match replacement t t buffer-name))
2740 (setq limit (1+ (match-end 0)))))
2741 ;; Generate the file name.
2742 (expand-file-name
2743 (format "#%s#%s#" buffer-name (make-temp-name ""))
2744 ;; Try a few alternative directories, to get one we can write it.
2745 (cond
2746 ((file-writable-p default-directory) default-directory)
2747 ((file-writable-p "/var/tmp/") "/var/tmp/")
2748 ("~/"))))))
2749
2750 (defun auto-save-file-name-p (filename)
2751 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2752 FILENAME should lack slashes. You can redefine this for customization."
2753 (string-match "^#.*#$" filename))
2754 \f
2755 (defun wildcard-to-regexp (wildcard)
2756 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2757 The generated regexp will match a filename iff the filename
2758 matches that wildcard according to shell rules. Only wildcards known
2759 by `sh' are supported."
2760 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2761 ;; Copy the initial run of non-special characters.
2762 (result (substring wildcard 0 i))
2763 (len (length wildcard)))
2764 ;; If no special characters, we're almost done.
2765 (if i
2766 (while (< i len)
2767 (let ((ch (aref wildcard i))
2768 j)
2769 (setq
2770 result
2771 (concat result
2772 (cond
2773 ((and (eq ch ?\[)
2774 (< (1+ i) len)
2775 (eq (aref wildcard (1+ i)) ?\]))
2776 "\\[")
2777 ((eq ch ?\[) ; [...] maps to regexp char class
2778 (progn
2779 (setq i (1+ i))
2780 (concat
2781 (cond
2782 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2783 (progn
2784 (setq i (1+ i))
2785 (if (eq (aref wildcard i) ?\])
2786 (progn
2787 (setq i (1+ i))
2788 "[^]")
2789 "[^")))
2790 ((eq (aref wildcard i) ?^)
2791 ;; Found "[^". Insert a `\0' character
2792 ;; (which cannot happen in a filename)
2793 ;; into the character class, so that `^'
2794 ;; is not the first character after `[',
2795 ;; and thus non-special in a regexp.
2796 (progn
2797 (setq i (1+ i))
2798 "[\000^"))
2799 ((eq (aref wildcard i) ?\])
2800 ;; I don't think `]' can appear in a
2801 ;; character class in a wildcard, but
2802 ;; let's be general here.
2803 (progn
2804 (setq i (1+ i))
2805 "[]"))
2806 (t "["))
2807 (prog1 ; copy everything upto next `]'.
2808 (substring wildcard
2809 i
2810 (setq j (string-match
2811 "]" wildcard i)))
2812 (setq i (if j (1- j) (1- len)))))))
2813 ((eq ch ?.) "\\.")
2814 ((eq ch ?*) "[^\000]*")
2815 ((eq ch ?+) "\\+")
2816 ((eq ch ?^) "\\^")
2817 ((eq ch ?$) "\\$")
2818 ((eq ch ?\\) "\\\\") ; probably cannot happen...
2819 ((eq ch ??) "[^\000]")
2820 (t (char-to-string ch)))))
2821 (setq i (1+ i)))))
2822 ;; Shell wildcards should match the entire filename,
2823 ;; not its part. Make the regexp say so.
2824 (concat "\\`" result "\\'")))
2825 \f
2826 (defcustom list-directory-brief-switches
2827 (if (eq system-type 'vax-vms) "" "-CF")
2828 "*Switches for list-directory to pass to `ls' for brief listing,"
2829 :type 'string
2830 :group 'dired)
2831
2832 (defcustom list-directory-verbose-switches
2833 (if (eq system-type 'vax-vms)
2834 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2835 "-l")
2836 "*Switches for list-directory to pass to `ls' for verbose listing,"
2837 :type 'string
2838 :group 'dired)
2839
2840 (defun list-directory (dirname &optional verbose)
2841 "Display a list of files in or matching DIRNAME, a la `ls'.
2842 DIRNAME is globbed by the shell if necessary.
2843 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2844 Actions controlled by variables `list-directory-brief-switches'
2845 and `list-directory-verbose-switches'."
2846 (interactive (let ((pfx current-prefix-arg))
2847 (list (read-file-name (if pfx "List directory (verbose): "
2848 "List directory (brief): ")
2849 nil default-directory nil)
2850 pfx)))
2851 (let ((switches (if verbose list-directory-verbose-switches
2852 list-directory-brief-switches)))
2853 (or dirname (setq dirname default-directory))
2854 (setq dirname (expand-file-name dirname))
2855 (with-output-to-temp-buffer "*Directory*"
2856 (buffer-disable-undo standard-output)
2857 (princ "Directory ")
2858 (princ dirname)
2859 (terpri)
2860 (save-excursion
2861 (set-buffer "*Directory*")
2862 (setq default-directory
2863 (if (file-directory-p dirname)
2864 (file-name-as-directory dirname)
2865 (file-name-directory dirname)))
2866 (let ((wildcard (not (file-directory-p dirname))))
2867 (insert-directory dirname switches wildcard (not wildcard)))))))
2868
2869 (defvar insert-directory-program "ls"
2870 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2871
2872 ;; insert-directory
2873 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2874 ;; FULL-DIRECTORY-P is nil.
2875 ;; The single line of output must display FILE's name as it was
2876 ;; given, namely, an absolute path name.
2877 ;; - must insert exactly one line for each file if WILDCARD or
2878 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2879 ;; before the file lines, plus optional text after the file lines.
2880 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2881 ;; allowed.
2882 ;; File lines should display the basename.
2883 ;; - must be consistent with
2884 ;; - functions dired-move-to-filename, (these two define what a file line is)
2885 ;; dired-move-to-end-of-filename,
2886 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2887 ;; dired-insert-headerline
2888 ;; dired-after-subdir-garbage (defines what a "total" line is)
2889 ;; - variable dired-subdir-regexp
2890 (defun insert-directory (file switches &optional wildcard full-directory-p)
2891 "Insert directory listing for FILE, formatted according to SWITCHES.
2892 Leaves point after the inserted text.
2893 SWITCHES may be a string of options, or a list of strings.
2894 Optional third arg WILDCARD means treat FILE as shell wildcard.
2895 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2896 switches do not contain `d', so that a full listing is expected.
2897
2898 This works by running a directory listing program
2899 whose name is in the variable `insert-directory-program'.
2900 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2901 ;; We need the directory in order to find the right handler.
2902 (let ((handler (find-file-name-handler (expand-file-name file)
2903 'insert-directory)))
2904 (if handler
2905 (funcall handler 'insert-directory file switches
2906 wildcard full-directory-p)
2907 (if (eq system-type 'vax-vms)
2908 (vms-read-directory file switches (current-buffer))
2909 (or (= 0
2910 (if wildcard
2911 ;; Run ls in the directory of the file pattern we asked for.
2912 (let ((default-directory
2913 (if (file-name-absolute-p file)
2914 (file-name-directory file)
2915 (file-name-directory (expand-file-name file))))
2916 (pattern (file-name-nondirectory file))
2917 (beg 0))
2918 ;; Quote some characters that have special meanings in shells;
2919 ;; but don't quote the wildcards--we want them to be special.
2920 ;; We also currently don't quote the quoting characters
2921 ;; in case people want to use them explicitly to quote
2922 ;; wildcard characters.
2923 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
2924 (setq pattern
2925 (concat (substring pattern 0 (match-beginning 0))
2926 "\\"
2927 (substring pattern (match-beginning 0)))
2928 beg (1+ (match-end 0))))
2929 (call-process shell-file-name nil t nil
2930 "-c" (concat "\\" ;; Disregard shell aliases!
2931 insert-directory-program
2932 " -d "
2933 (if (stringp switches)
2934 switches
2935 (mapconcat 'identity switches " "))
2936 " -- "
2937 pattern)))
2938 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2939 ;; directory if FILE is a symbolic link.
2940 (apply 'call-process
2941 insert-directory-program nil t nil
2942 (let (list)
2943 (if (listp switches)
2944 (setq list switches)
2945 (if (not (equal switches ""))
2946 (progn
2947 ;; Split the switches at any spaces
2948 ;; so we can pass separate options as separate args.
2949 (while (string-match " " switches)
2950 (setq list (cons (substring switches 0 (match-beginning 0))
2951 list)
2952 switches (substring switches (match-end 0))))
2953 (setq list (nreverse (cons switches list))))))
2954 (append list
2955 ;; Avoid lossage if FILE starts with `-'.
2956 '("--")
2957 (list
2958 (if full-directory-p
2959 (concat (file-name-as-directory file) ".")
2960 file)))))))
2961 ;; We get here if ls failed.
2962 ;; Access the file to get a suitable error.
2963 (access-file file "Reading directory"))))))
2964
2965 (defvar kill-emacs-query-functions nil
2966 "Functions to call with no arguments to query about killing Emacs.
2967 If any of these functions returns nil, killing Emacs is cancelled.
2968 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2969 but `kill-emacs', the low level primitive, does not.
2970 See also `kill-emacs-hook'.")
2971
2972 (defun save-buffers-kill-emacs (&optional arg)
2973 "Offer to save each buffer, then kill this Emacs process.
2974 With prefix arg, silently save all file-visiting buffers, then kill."
2975 (interactive "P")
2976 (save-some-buffers arg t)
2977 (and (or (not (memq t (mapcar (function
2978 (lambda (buf) (and (buffer-file-name buf)
2979 (buffer-modified-p buf))))
2980 (buffer-list))))
2981 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2982 (or (not (fboundp 'process-list))
2983 ;; process-list is not defined on VMS.
2984 (let ((processes (process-list))
2985 active)
2986 (while processes
2987 (and (memq (process-status (car processes)) '(run stop open))
2988 (let ((val (process-kill-without-query (car processes))))
2989 (process-kill-without-query (car processes) val)
2990 val)
2991 (setq active t))
2992 (setq processes (cdr processes)))
2993 (or (not active)
2994 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2995 ;; Query the user for other things, perhaps.
2996 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
2997 (kill-emacs)))
2998 \f
2999 ;; We use /: as a prefix to "quote" a file name
3000 ;; so that magic file name handlers will not apply to it.
3001
3002 (setq file-name-handler-alist
3003 (cons '("\\`/:" . file-name-non-special)
3004 file-name-handler-alist))
3005
3006 ;; We depend on being the last handler on the list,
3007 ;; so that anything else which does need handling
3008 ;; has been handled already.
3009 ;; So it is safe for us to inhibit *all* magic file name handlers.
3010
3011 (defun file-name-non-special (operation &rest arguments)
3012 (let ((file-name-handler-alist nil)
3013 ;; Get a list of the indices of the args which are file names.
3014 (file-arg-indices
3015 (cdr (or (assq operation
3016 ;; The first four are special because they
3017 ;; return a file name. We want to include the /:
3018 ;; in the return value.
3019 ;; So just avoid stripping it in the first place.
3020 '((expand-file-name . nil)
3021 ;; `identity' means just return the first arg
3022 ;; as stripped of its quoting.
3023 (substitute-in-file-name . identity)
3024 (file-name-directory . nil)
3025 (file-name-as-directory . nil)
3026 (directory-file-name . nil)
3027 (file-name-completion 0 1)
3028 (file-name-all-completions 0 1)
3029 (rename-file 0 1)
3030 (copy-file 0 1)
3031 (make-symbolic-link 0 1)
3032 (add-name-to-file 0 1)))
3033 ;; For all other operations, treat the first argument only
3034 ;; as the file name.
3035 '(nil 0))))
3036 ;; Copy ARGUMENTS so we can replace elements in it.
3037 (arguments (copy-sequence arguments)))
3038 ;; Strip off the /: from the file names that have this handler.
3039 (save-match-data
3040 (while (consp file-arg-indices)
3041 (and (nth (car file-arg-indices) arguments)
3042 (string-match "\\`/:" (nth (car file-arg-indices) arguments))
3043 (setcar (nthcdr (car file-arg-indices) arguments)
3044 (substring (nth (car file-arg-indices) arguments) 2)))
3045 (setq file-arg-indices (cdr file-arg-indices))))
3046 (if (eq file-arg-indices 'identity)
3047 (car arguments)
3048 (apply operation arguments))))
3049 \f
3050 (define-key ctl-x-map "\C-f" 'find-file)
3051 (define-key ctl-x-map "\C-r" 'find-file-read-only)
3052 (define-key ctl-x-map "\C-v" 'find-alternate-file)
3053 (define-key ctl-x-map "\C-s" 'save-buffer)
3054 (define-key ctl-x-map "s" 'save-some-buffers)
3055 (define-key ctl-x-map "\C-w" 'write-file)
3056 (define-key ctl-x-map "i" 'insert-file)
3057 (define-key esc-map "~" 'not-modified)
3058 (define-key ctl-x-map "\C-d" 'list-directory)
3059 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3060
3061 (define-key ctl-x-4-map "f" 'find-file-other-window)
3062 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3063 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3064 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
3065 (define-key ctl-x-4-map "\C-o" 'display-buffer)
3066
3067 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3068 (define-key ctl-x-5-map "f" 'find-file-other-frame)
3069 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3070 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
3071
3072 ;;; files.el ends here