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