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