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