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