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