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