typo
[bpt/emacs.git] / lisp / files.el
CommitLineData
c0274f38
ER
1;;; files.el --- file input and output commands for Emacs
2
e5cb26a8
SM
3;; Copyright (C) 1985, 1986, 1987, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4;; 1999, 2000, 2001, 2002, 2003, 2004, 2005 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
564af258 45Note that the auto-save file will not be deleted if the buffer is killed
92631216 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 70
5c6d31a4 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
ffc0e1ca
AS
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
ffc0e1ca
AS
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
ffc0e1ca 136(defvar backup-enable-predicate 'normal-backup-enable-predicate
b4da00e9 137 "Predicate that looks at a file name and decides whether to make backups.
37193ee6 138Called with an absolute file name as argument, it returns t to enable backup.")
b4da00e9 139
21540597 140(defcustom buffer-offer-save nil
ffc0e1ca
AS
141 "*Non-nil in a buffer means always offer to save buffer on exit.
142Do so even if the buffer is not visiting a file.
21540597
RS
143Automatically local in all buffers."
144 :type 'boolean
145 :group 'backup)
b4da00e9
RM
146(make-variable-buffer-local 'buffer-offer-save)
147
21540597 148(defcustom find-file-existing-other-name t
f3e23606
RS
149 "*Non-nil means find a file under alternative names, in existing buffers.
150This means if any existing buffer is visiting the file you want
21540597
RS
151under another name, you get the existing buffer instead of a new buffer."
152 :type 'boolean
153 :group 'find-file)
f3e23606 154
21540597 155(defcustom find-file-visit-truename nil
f3e23606
RS
156 "*Non-nil means visit a file under its truename.
157The truename of a file is found by chasing all links
21540597
RS
158both at the file level and at the levels of the containing directories."
159 :type 'boolean
160 :group 'find-file)
f3e23606 161
db8c4866 162(defcustom revert-without-query
d7fa5aa2 163 nil
ebeb898f
RS
164 "*Specify which files should be reverted without query.
165The value is a list of regular expressions.
166If the file name matches one of these regular expressions,
db8c4866 167then `revert-buffer' reverts the file without querying
21540597 168if the file has changed on disk and you have not edited the buffer."
a0d809f2 169 :type '(repeat regexp)
21540597 170 :group 'find-file)
ebeb898f 171
f3e23606
RS
172(defvar buffer-file-number nil
173 "The device number and file number of the file visited in the current buffer.
174The value is a list of the form (FILENUM DEVNUM).
175This pair of numbers uniquely identifies the file.
176If the buffer is visiting a new file, the value is nil.")
177(make-variable-buffer-local 'buffer-file-number)
178(put 'buffer-file-number 'permanent-local t)
179
de88363f
RS
180(defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
181 "Non-nil means that buffer-file-number uniquely identifies files.")
182
e554eeb7
RS
183(defvar buffer-file-read-only nil
184 "Non-nil if visited file was read-only when visited.")
185(make-variable-buffer-local 'buffer-file-read-only)
186
388d6ab5 187(defcustom temporary-file-directory
eb61b61b
RS
188 (file-name-as-directory
189 (cond ((memq system-type '(ms-dos windows-nt))
190 (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
191 ((memq system-type '(vax-vms axp-vms))
192 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
193 (t
194 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
388d6ab5
RS
195 "The directory for writing temporary files."
196 :group 'files
197 :type 'directory)
eb61b61b 198
388d6ab5 199(defcustom small-temporary-file-directory
eb61b61b
RS
200 (if (eq system-type 'ms-dos) (getenv "TMPDIR"))
201 "The directory for writing small temporary files.
202If non-nil, this directory is used instead of `temporary-file-directory'
203by programs that create small temporary files. This is for systems that
388d6ab5
RS
204have fast storage with limited space, such as a RAM disk."
205 :group 'files
bab6eadb 206 :type '(choice (const nil) directory))
eb61b61b
RS
207
208;; The system null device. (Should reference NULL_DEVICE from C.)
209(defvar null-device "/dev/null" "The system null device.")
210
30966847
EZ
211(defvar file-name-invalid-regexp
212 (cond ((and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
9959c16e 213 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
30966847 214 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
edfc7f25 215 "[\000-\031]\\|" ; control characters
30966847
EZ
216 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
217 "\\(/[^/.]+\\.[^/.]*\\.\\)")) ; more than a single dot
c60ee5e7 218 ((memq system-type '(ms-dos windows-nt cygwin))
9959c16e 219 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
106a57a4 220 "[|<>\"?*\000-\031]")) ; invalid characters
30966847
EZ
221 (t "[\000]"))
222 "Regexp recognizing file names which aren't allowed by the filesystem.")
223
21540597 224(defcustom file-precious-flag nil
b4da00e9 225 "*Non-nil means protect against I/O errors while saving files.
560f4415 226Some modes set this non-nil in particular buffers.
4b7271c1
KH
227
228This feature works by writing the new contents into a temporary file
229and then renaming the temporary file to replace the original.
230In this way, any I/O error in writing leaves the original untouched,
231and there is never any instant where the file is nonexistent.
232
233Note that this feature forces backups to be made by copying.
560f4415 234Yet, at the same time, saving a precious file
21540597
RS
235breaks any hard links between it and other files."
236 :type 'boolean
237 :group 'backup)
b4da00e9 238
21540597 239(defcustom version-control nil
b4da00e9
RM
240 "*Control use of version numbers for backup files.
241t means make numeric backup versions unconditionally.
242nil means make them for files that have some already.
21540597 243`never' means do not make them."
e48807d1
AS
244 :type '(choice (const :tag "Never" never)
245 (const :tag "If existing" nil)
246 (other :tag "Always" t))
21540597
RS
247 :group 'backup
248 :group 'vc)
249
250(defcustom dired-kept-versions 2
251 "*When cleaning directory, number of versions to keep."
252 :type 'integer
253 :group 'backup
254 :group 'dired)
255
256(defcustom delete-old-versions nil
de7d5e1b 257 "*If t, delete excess backup versions silently.
21540597
RS
258If nil, ask confirmation. Any other value prevents any trimming."
259 :type '(choice (const :tag "Delete" t)
260 (const :tag "Ask" nil)
e48807d1 261 (other :tag "Leave" other))
21540597
RS
262 :group 'backup)
263
264(defcustom kept-old-versions 2
265 "*Number of oldest versions to keep when a new numbered backup is made."
266 :type 'integer
267 :group 'backup)
268
269(defcustom kept-new-versions 2
b4da00e9 270 "*Number of newest versions to keep when a new numbered backup is made.
21540597
RS
271Includes the new backup. Must be > 0"
272 :type 'integer
273 :group 'backup)
b4da00e9 274
21540597 275(defcustom require-final-newline nil
f4206092
RS
276 "*Whether to add a newline automatically at the end of the file.
277
278A value of t means do this only when the file is about to be saved.
279A value of `visit' means do this right after the file is visited.
280A value of `visit-save' means do it at both of those times.
281Any other non-nil value means ask user whether to add a newline, when saving.
282nil means don't add newlines.
283
284Certain major modes set this locally to the value obtained
285from `mode-require-final-newline'."
286 :type '(choice (const :tag "When visiting" visit)
287 (const :tag "When saving" t)
288 (const :tag "When visiting or saving" visit-save)
289 (const :tag "Never" nil)
e48807d1 290 (other :tag "Ask" ask))
21540597 291 :group 'editing-basics)
b4da00e9 292
f4206092 293(defcustom mode-require-final-newline t
5e9961be 294 "*Whether to add a newline at end of file, in certain major modes.
f4206092
RS
295Those modes set `require-final-newline' to this value when you enable them.
296They do so because they are used for files that are supposed
297to end in newlines, and the question is how to arrange that.
298
299A value of t means do this only when the file is about to be saved.
300A value of `visit' means do this right after the file is visited.
301A value of `visit-save' means do it at both of those times.
5e9961be 302Any other non-nil value means ask user whether to add a newline, when saving.
44dce0fb 303nil means do not add newlines when saving.
5e9961be 304
99374611 305If you set this to nil, you must be careful to manually add a final newline
44dce0fb 306whenever you save a file that really needs one."
f4206092
RS
307 :type '(choice (const :tag "When visiting" visit)
308 (const :tag "When saving" t)
309 (const :tag "When visiting or saving" visit-save)
576ceeb3
LT
310 (other :tag "Ask" ask)
311 (const :tag "Don't add newlines" nil))
f4206092 312 :group 'editing-basics
bf247b6e 313 :version "22.1")
f4206092 314
21540597
RS
315(defcustom auto-save-default t
316 "*Non-nil says by default do auto-saving of every file-visiting buffer."
317 :type 'boolean
318 :group 'auto-save)
b4da00e9 319
21540597 320(defcustom auto-save-visited-file-name nil
b4da00e9 321 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
21540597
RS
322Normally auto-save files are written under other names."
323 :type 'boolean
324 :group 'auto-save)
b4da00e9 325
ffc0e1ca 326(defcustom auto-save-file-name-transforms
b1e5937c 327 `(("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'"
747981b0
EZ
328 ;; Don't put "\\2" inside expand-file-name, since it will be
329 ;; transformed to "/2" on DOS/Windows.
a0b60c33 330 ,(concat temporary-file-directory "\\2") t))
ffc0e1ca 331 "*Transforms to apply to buffer file name before making auto-save file name.
a0b60c33 332Each transform is a list (REGEXP REPLACEMENT UNIQUIFY):
ffc0e1ca
AS
333REGEXP is a regular expression to match against the file name.
334If it matches, `replace-match' is used to replace the
335matching part with REPLACEMENT.
a0b60c33 336If the optional element UNIQUIFY is non-nil, the auto-save file name is
36236b72 337constructed by taking the directory part of the replaced file-name,
a0b60c33
GM
338concatenated with the buffer file name with all directory separators
339changed to `!' to prevent clashes. This will not work
340correctly if your filesystem truncates the resulting name.
341
ffc0e1ca
AS
342All the transforms in the list are tried, in the order they are listed.
343When one transform applies, its result is final;
344no further transforms are tried.
345
a2899d6c
KG
346The default value is set up to put the auto-save file into the
347temporary directory (see the variable `temporary-file-directory') for
a0b60c33
GM
348editing a remote file.
349
350On MS-DOS filesystems without long names this variable is always
351ignored."
ffc0e1ca 352 :group 'auto-save
a0b60c33
GM
353 :type '(repeat (list (string :tag "Regexp") (string :tag "Replacement")
354 (boolean :tag "Uniquify")))
ffc0e1ca
AS
355 :version "21.1")
356
88b36776 357(defcustom save-abbrevs t
02c6a1cc
EZ
358 "*Non-nil means save word abbrevs too when files are saved.
359If `silently', don't ask the user before saving."
360 :type '(choice (const t) (const nil) (const silently))
21540597 361 :group 'abbrev)
b4da00e9 362
21540597 363(defcustom find-file-run-dired t
ffc0e1ca
AS
364 "*Non-nil means allow `find-file' to visit directories.
365To visit the directory, `find-file' runs `find-directory-functions'."
21540597
RS
366 :type 'boolean
367 :group 'find-file)
b4da00e9 368
ffc0e1ca
AS
369(defcustom find-directory-functions '(cvs-dired-noselect dired-noselect)
370 "*List of functions to try in sequence to visit a directory.
371Each function is called with the directory name as the sole argument
372and should return either a buffer or nil."
373 :type '(hook :options (cvs-dired-noselect dired-noselect))
374 :group 'find-file)
375
92966e6f
RS
376;;;It is not useful to make this a local variable.
377;;;(put 'find-file-not-found-hooks 'permanent-local t)
0370fe77 378(defvar find-file-not-found-functions nil
b4da00e9
RM
379 "List of functions to be called for `find-file' on nonexistent file.
380These functions are called as soon as the error is detected.
ffc0e1ca 381Variable `buffer-file-name' is already set up.
b4da00e9 382The functions are called in the order given until one of them returns non-nil.")
0370fe77
SM
383(defvaralias 'find-file-not-found-hooks 'find-file-not-found-functions)
384(make-obsolete-variable
bf247b6e 385 'find-file-not-found-hooks 'find-file-not-found-functions "22.1")
b4da00e9 386
92966e6f
RS
387;;;It is not useful to make this a local variable.
388;;;(put 'find-file-hooks 'permanent-local t)
564af258 389(defcustom find-file-hook nil
b4da00e9
RM
390 "List of functions to be called after a buffer is loaded from a file.
391The buffer's local variables (if any) will have been processed before the
564af258
DL
392functions are called."
393 :group 'find-file
394 :type 'hook
395 :options '(auto-insert)
bf247b6e 396 :version "22.1")
0370fe77 397(defvaralias 'find-file-hooks 'find-file-hook)
bf247b6e 398(make-obsolete-variable 'find-file-hooks 'find-file-hook "22.1")
b4da00e9 399
0370fe77 400(defvar write-file-functions nil
b4da00e9
RM
401 "List of functions to be called before writing out a buffer to a file.
402If one of them returns non-nil, the file is considered already written
8c0e7b73
JB
403and the rest are not called.
404These hooks are considered to pertain to the visited file.
0370fe77
SM
405So any buffer-local binding of this variable is discarded if you change
406the visited file name with \\[set-visited-file-name], but not when you
407change the major mode.
408
0eb0202f
LT
409This hook is not run if any of the functions in
410`write-contents-functions' returns non-nil. Both hooks pertain
411to how to save a buffer to file, for instance, choosing a suitable
412coding system and setting mode bits. (See Info
413node `(elisp)Saving Buffers'.) To perform various checks or
414updates before the buffer is saved, use `before-save-hook' .")
0370fe77
SM
415(put 'write-file-functions 'permanent-local t)
416(defvaralias 'write-file-hooks 'write-file-functions)
bf247b6e 417(make-obsolete-variable 'write-file-hooks 'write-file-functions "22.1")
0370fe77
SM
418
419(defvar local-write-file-hooks nil)
b19f1da4
BF
420(make-variable-buffer-local 'local-write-file-hooks)
421(put 'local-write-file-hooks 'permanent-local t)
bf247b6e 422(make-obsolete-variable 'local-write-file-hooks 'write-file-functions "22.1")
8c0e7b73 423
0370fe77 424(defvar write-contents-functions nil
8c0e7b73
JB
425 "List of functions to be called before writing out a buffer to a file.
426If one of them returns non-nil, the file is considered already written
7dd11b37
LH
427and the rest are not called and neither are the functions in
428`write-file-functions'.
f82966e4
KH
429
430This variable is meant to be used for hooks that pertain to the
431buffer's contents, not to the particular visited file; thus,
432`set-visited-file-name' does not clear this variable; but changing the
693f800d
RS
433major mode does clear it.
434
0eb0202f
LT
435For hooks that _do_ pertain to the particular visited file, use
436`write-file-functions'. Both this variable and
437`write-file-functions' relate to how a buffer is saved to file.
438To perform various checks or updates before the buffer is saved,
439use `before-save-hook'.")
0370fe77
SM
440(make-variable-buffer-local 'write-contents-functions)
441(defvaralias 'write-contents-hooks 'write-contents-functions)
bf247b6e 442(make-obsolete-variable 'write-contents-hooks 'write-contents-functions "22.1")
b4da00e9 443
21540597 444(defcustom enable-local-variables t
93a2702d 445 "*Control use of local variables in files you visit.
b4da00e9 446The value can be t, nil or something else.
93a2702d 447A value of t means file local variables specifications are obeyed;
b4da00e9 448nil means they are ignored; anything else means query.
aa5fcebf
KH
449This variable also controls use of major modes specified in
450a -*- line.
b4da00e9 451
aa5fcebf
KH
452The command \\[normal-mode], when used interactively,
453always obeys file local variable specifications and the -*- line,
454and ignores this variable."
21540597
RS
455 :type '(choice (const :tag "Obey" t)
456 (const :tag "Ignore" nil)
e48807d1 457 (other :tag "Query" other))
21540597 458 :group 'find-file)
b4da00e9 459
da09b92b
RS
460(defvar local-enable-local-variables t
461 "Like `enable-local-variables' but meant for buffer-local bindings.
aa5fcebf 462The meaningful values are nil and non-nil. The default is non-nil.
da09b92b 463If a major mode sets this to nil, buffer-locally, then any local
aa5fcebf
KH
464variables list in the file will be ignored.
465
466This variable does not affect the use of major modes
467specified in a -*- line.")
da09b92b 468
21540597 469(defcustom enable-local-eval 'maybe
d207b766
RS
470 "*Control processing of the \"variable\" `eval' in a file's local variables.
471The value can be t, nil or something else.
472A value of t means obey `eval' variables;
e0b2a2d9 473nil means ignore them; anything else means query."
21540597
RS
474 :type '(choice (const :tag "Obey" t)
475 (const :tag "Ignore" nil)
e48807d1 476 (other :tag "Query" other))
21540597 477 :group 'find-file)
b4da00e9
RM
478
479;; Avoid losing in versions where CLASH_DETECTION is disabled.
480(or (fboundp 'lock-buffer)
231c4e10 481 (defalias 'lock-buffer 'ignore))
b4da00e9 482(or (fboundp 'unlock-buffer)
231c4e10 483 (defalias 'unlock-buffer 'ignore))
a7305f6e
RS
484(or (fboundp 'file-locked-p)
485 (defalias 'file-locked-p 'ignore))
93fe0a35 486
cb211eb2 487(defcustom view-read-only nil
4c91443d
RS
488 "*Non-nil means buffers visiting files read-only do so in view mode.
489In fact, this means that all read-only buffers normally have
490View mode enabled, including buffers that are read-only because
491you visit a file you cannot alter, and buffers you make read-only
492using \\[toggle-read-only]."
cb211eb2
SM
493 :type 'boolean
494 :group 'view)
2a9fe1e2 495
1aa8fe46 496(put 'ange-ftp-completion-hook-function 'safe-magic t)
93fe0a35 497(defun ange-ftp-completion-hook-function (op &rest args)
ffc0e1ca
AS
498 "Provides support for ange-ftp host name completion.
499Runs the usual ange-ftp hook, but only for completion operations."
500 ;; Having this here avoids the need to load ange-ftp when it's not
501 ;; really in use.
93fe0a35
RS
502 (if (memq op '(file-name-completion file-name-all-completions))
503 (apply 'ange-ftp-hook-function op args)
57e81f57
RS
504 (let ((inhibit-file-name-handlers
505 (cons 'ange-ftp-completion-hook-function
506 (and (eq inhibit-file-name-operation op)
507 inhibit-file-name-handlers)))
508 (inhibit-file-name-operation op))
93fe0a35 509 (apply op args))))
567c1ca9
RS
510
511(defun convert-standard-filename (filename)
a576d8e2 512 "Convert a standard file's name to something suitable for the OS.
915b0bf0
JB
513This means to guarantee valid names and perhaps to canonicalize
514certain patterns.
515
516This function's standard definition is trivial; it just returns
517the argument. However, on Windows and DOS, replace invalid
518characters. On DOS, make sure to obey the 8.3 limitations. On
519Windows, turn Cygwin names into native names, and also turn
520slashes into backslashes if the shell requires it (see
a576d8e2
LT
521`w32-shell-dos-semantics').
522
523See Info node `(elisp)Standard File Names' for more details."
567c1ca9 524 filename)
5d4d17b8
KS
525
526(defun read-directory-name (prompt &optional dir default-dirname mustmatch initial)
527 "Read directory name, prompting with PROMPT and completing in directory DIR.
528Value is not expanded---you must call `expand-file-name' yourself.
25802eac
LT
529Default name to DEFAULT-DIRNAME if user exits with the same
530non-empty string that was inserted by this function.
44dce0fb
RS
531 (If DEFAULT-DIRNAME is omitted, DIR combined with INITIAL is used,
532 or just DIR if INITIAL is nil.)
25802eac
LT
533If the user exits with an empty minibuffer, this function returns
534an empty string. (This can only happen if the user erased the
535pre-inserted contents or if `insert-default-directory' is nil.)
5d4d17b8
KS
536Fourth arg MUSTMATCH non-nil means require existing directory's name.
537 Non-nil and non-t means also require confirmation after completion.
538Fifth arg INITIAL specifies text to start with.
25802eac
LT
539DIR should be an absolute directory name. It defaults to
540the value of `default-directory'."
5d4d17b8
KS
541 (unless dir
542 (setq dir default-directory))
543 (unless default-dirname
36236b72 544 (setq default-dirname
5d4d17b8 545 (if initial (concat dir initial) default-directory)))
44dce0fb
RS
546 (read-file-name prompt dir (or default-dirname
547 (if initial (expand-file-name initial dir)
548 dir))
549 mustmatch initial
5d4d17b8
KS
550 'file-directory-p))
551
b4da00e9
RM
552\f
553(defun pwd ()
554 "Show the current default directory."
555 (interactive nil)
556 (message "Directory %s" default-directory))
557
231c4e10
ER
558(defvar cd-path nil
559 "Value of the CDPATH environment variable, as a list.
9ee45b2c 560Not actually set up until the first time you use it.")
231c4e10
ER
561
562(defun parse-colon-path (cd-path)
ae135939 563 "Explode a search path into a list of directory names.
c5994cfa
JB
564Directories are separated by occurrences of `path-separator'
565\(which is colon in GNU and GNU-like systems)."
ffc0e1ca 566 ;; We could use split-string here.
231c4e10 567 (and cd-path
818286f4 568 (let (cd-list (cd-start 0) cd-colon)
306faa42
RS
569 (setq cd-path (concat cd-path path-separator))
570 (while (setq cd-colon (string-match path-separator cd-path cd-start))
231c4e10 571 (setq cd-list
9daefb36 572 (nconc cd-list
c52e4104
RS
573 (list (if (= cd-start cd-colon)
574 nil
575 (substitute-in-file-name
e33e80e4
RS
576 (file-name-as-directory
577 (substring cd-path cd-start cd-colon)))))))
231c4e10
ER
578 (setq cd-start (+ cd-colon 1)))
579 cd-list)))
580
581(defun cd-absolute (dir)
30c5ce9c 582 "Change current directory to given absolute file name DIR."
f4a0f59b
RS
583 ;; Put the name into directory syntax now,
584 ;; because otherwise expand-file-name may give some bad results.
b4da00e9
RM
585 (if (not (eq system-type 'vax-vms))
586 (setq dir (file-name-as-directory dir)))
f4a0f59b 587 (setq dir (abbreviate-file-name (expand-file-name dir)))
b4da00e9 588 (if (not (file-directory-p dir))
83c6f446
RS
589 (if (file-exists-p dir)
590 (error "%s is not a directory" dir)
31c691c1 591 (error "%s: no such directory" dir))
b4da00e9
RM
592 (if (file-executable-p dir)
593 (setq default-directory dir)
9daefb36 594 (error "Cannot cd to %s: Permission denied" dir))))
b4da00e9 595
231c4e10
ER
596(defun cd (dir)
597 "Make DIR become the current buffer's default directory.
ae135939
JB
598If your environment includes a `CDPATH' variable, try each one of
599that list of directories (separated by occurrences of
c5994cfa
JB
600`path-separator') when resolving a relative directory name.
601The path separator is colon in GNU and GNU-like systems."
dac4ea74 602 (interactive
5d4d17b8 603 (list (read-directory-name "Change default directory: "
2121cd9c
RM
604 default-directory default-directory
605 (and (member cd-path '(nil ("./")))
606 (null (getenv "CDPATH"))))))
30c5ce9c
RS
607 (if (file-name-absolute-p dir)
608 (cd-absolute (expand-file-name dir))
609 (if (null cd-path)
610 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
611 (setq cd-path (or trypath (list "./")))))
612 (if (not (catch 'found
613 (mapcar
614 (function (lambda (x)
615 (let ((f (expand-file-name (concat x dir))))
616 (if (file-directory-p f)
617 (progn
618 (cd-absolute f)
619 (throw 'found t))))))
620 cd-path)
621 nil))
622 (error "No such directory found via CDPATH environment variable"))))
231c4e10 623
b4da00e9
RM
624(defun load-file (file)
625 "Load the Lisp file named FILE."
58195faa
DL
626 ;; This is a case where .elc makes a lot of sense.
627 (interactive (list (let ((completion-ignored-extensions
9ab80679 628 (remove ".elc" completion-ignored-extensions)))
58195faa
DL
629 (read-file-name "Load file: "))))
630 (load (expand-file-name file) nil nil t))
b4da00e9 631
38eea7c7
SM
632(defun locate-file (filename path &optional suffixes predicate)
633 "Search for FILENAME through PATH.
634If SUFFIXES is non-nil, it should be a list of suffixes to append to
635file name when searching. If SUFFIXES is nil, it is equivalent to '(\"\").
636If non-nil, PREDICATE is used instead of `file-readable-p'.
e6f0ff92
RS
637PREDICATE can also be an integer to pass to the `access' system call,
638in which case file-name handlers are ignored. This usage is deprecated.
639
640For compatibility, PREDICATE can also be one of the symbols
641`executable', `readable', `writable', or `exists', or a list of
642one or more of those symbols."
38eea7c7
SM
643 (if (and predicate (symbolp predicate) (not (functionp predicate)))
644 (setq predicate (list predicate)))
645 (when (and (consp predicate) (not (functionp predicate)))
646 (setq predicate
647 (logior (if (memq 'executable predicate) 1 0)
648 (if (memq 'writable predicate) 2 0)
649 (if (memq 'readable predicate) 4 0))))
650 (locate-file-internal filename path suffixes predicate))
651
652(defun locate-file-completion (string path-and-suffixes action)
653 "Do completion for file names passed to `locate-file'.
654PATH-AND-SUFFIXES is a pair of lists (DIRECTORIES . SUFFIXES)."
2c3d8820 655 (if (file-name-absolute-p string)
38eea7c7 656 (read-file-name-internal string nil action)
2c3d8820 657 (let ((names nil)
38eea7c7 658 (suffix (concat (regexp-opt (cdr path-and-suffixes) t) "\\'"))
2c3d8820 659 (string-dir (file-name-directory string)))
38eea7c7 660 (dolist (dir (car path-and-suffixes))
f2440e42
RS
661 (unless dir
662 (setq dir default-directory))
2c3d8820
SM
663 (if string-dir (setq dir (expand-file-name string-dir dir)))
664 (when (file-directory-p dir)
665 (dolist (file (file-name-all-completions
666 (file-name-nondirectory string) dir))
667 (push (if string-dir (concat string-dir file) file) names)
668 (when (string-match suffix file)
669 (setq file (substring file 0 (match-beginning 0)))
670 (push (if string-dir (concat string-dir file) file) names)))))
0370fe77
SM
671 (cond
672 ((eq action t) (all-completions string names))
673 ((null action) (try-completion string names))
674 (t (test-completion string names))))))
2c3d8820 675
b4da00e9
RM
676(defun load-library (library)
677 "Load the library named LIBRARY.
678This is an interface to the function `load'."
38eea7c7
SM
679 (interactive
680 (list (completing-read "Load library: "
681 'locate-file-completion
682 (cons load-path load-suffixes))))
b4da00e9 683 (load library))
5d68c2c2 684
ff7affeb 685(defun file-remote-p (file)
3f788773
KG
686 "Test whether FILE specifies a location on a remote system.
687Return an identification of the system if the location is indeed
688remote. The identification of the system may comprise a method
689to access the system and its hostname, amongst other things.
690
691For example, the filename \"/user@host:/foo\" specifies a location
692on the system \"/user@host:\"."
04621aaa 693 (let ((handler (find-file-name-handler file 'file-remote-p)))
ff7affeb 694 (if handler
04621aaa
MA
695 (funcall handler 'file-remote-p file)
696 nil)))
ff7affeb 697
ffc0e1ca 698(defun file-local-copy (file)
5d68c2c2
RS
699 "Copy the file FILE into a temporary file on this machine.
700Returns the name of the local copy, or nil, if FILE is directly
701accessible."
ffc0e1ca
AS
702 ;; This formerly had an optional BUFFER argument that wasn't used by
703 ;; anything.
6eaebaa2 704 (let ((handler (find-file-name-handler file 'file-local-copy)))
5d68c2c2
RS
705 (if handler
706 (funcall handler 'file-local-copy file)
707 nil)))
f3e23606 708
05ef1cda 709(defun file-truename (filename &optional counter prev-dirs)
f3e23606
RS
710 "Return the truename of FILENAME, which should be absolute.
711The truename of a file name is found by chasing symbolic links
712both at the level of the file and at the level of the directories
05ef1cda
RS
713containing it, until no links are left at any level.
714
89bf74f8 715\(fn FILENAME)" ;; Don't document the optional arguments.
b9963e32
JB
716 ;; COUNTER and PREV-DIRS are only used in recursive calls.
717 ;; COUNTER can be a cons cell whose car is the count of how many
718 ;; more links to chase before getting an error.
05ef1cda
RS
719 ;; PREV-DIRS can be a cons cell whose car is an alist
720 ;; of truenames we've just recently computed.
f2440e42
RS
721 (cond ((or (string= filename "") (string= filename "~"))
722 (setq filename (expand-file-name filename))
723 (if (string= filename "")
724 (setq filename "/")))
725 ((and (string= (substring filename 0 1) "~")
726 (string-match "~[^/]*/?" filename))
727 (let ((first-part
728 (substring filename 0 (match-end 0)))
729 (rest (substring filename (match-end 0))))
730 (setq filename (concat (expand-file-name first-part) rest)))))
731
05ef1cda 732 (or counter (setq counter (list 100)))
b505828b
RS
733 (let (done
734 ;; For speed, remove the ange-ftp completion handler from the list.
735 ;; We know it's not needed here.
736 ;; For even more speed, do this only on the outermost call.
737 (file-name-handler-alist
738 (if prev-dirs file-name-handler-alist
739 (let ((tem (copy-sequence file-name-handler-alist)))
740 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
741 (or prev-dirs (setq prev-dirs (list nil)))
b1667e6c
GV
742
743 ;; andrewi@harlequin.co.uk - none of the following code (except for
744 ;; invoking the file-name handler) currently applies on Windows
745 ;; (ie. there are no native symlinks), but there is an issue with
746 ;; case differences being ignored by the OS, and short "8.3 DOS"
747 ;; name aliases existing for all files. (The short names are not
748 ;; reported by directory-files, but can be used to refer to files.)
749 ;; It seems appropriate for file-truename to resolve these issues in
750 ;; the most natural way, which on Windows is to call the function
751 ;; `w32-long-file-name' - this returns the exact name of a file as
752 ;; it is stored on disk (expanding short name aliases with the full
753 ;; name in the process).
754 (if (eq system-type 'windows-nt)
06dd5ef7 755 (let ((handler (find-file-name-handler filename 'file-truename)))
b1667e6c
GV
756 ;; For file name that has a special handler, call handler.
757 ;; This is so that ange-ftp can save time by doing a no-op.
758 (if handler
759 (setq filename (funcall handler 'file-truename filename))
760 ;; If filename contains a wildcard, newname will be the old name.
06dd5ef7 761 (unless (string-match "[[*?]" filename)
5b373bd3
JB
762 ;; If filename exists, use the long name
763 (setq filename (or (w32-long-file-name filename) filename))))
b1667e6c
GV
764 (setq done t)))
765
05ef1cda
RS
766 ;; If this file directly leads to a link, process that iteratively
767 ;; so that we don't use lots of stack.
768 (while (not done)
769 (setcar counter (1- (car counter)))
770 (if (< (car counter) 0)
771 (error "Apparent cycle of symbolic links for %s" filename))
772 (let ((handler (find-file-name-handler filename 'file-truename)))
773 ;; For file name that has a special handler, call handler.
774 ;; This is so that ange-ftp can save time by doing a no-op.
775 (if handler
776 (setq filename (funcall handler 'file-truename filename)
777 done t)
fb145562 778 (let ((dir (or (file-name-directory filename) default-directory))
05ef1cda
RS
779 target dirfile)
780 ;; Get the truename of the directory.
781 (setq dirfile (directory-file-name dir))
782 ;; If these are equal, we have the (or a) root directory.
783 (or (string= dir dirfile)
784 ;; If this is the same dir we last got the truename for,
785 ;; save time--don't recalculate.
786 (if (assoc dir (car prev-dirs))
787 (setq dir (cdr (assoc dir (car prev-dirs))))
788 (let ((old dir)
789 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
790 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
791 (setq dir new))))
792 (if (equal ".." (file-name-nondirectory filename))
793 (setq filename
794 (directory-file-name (file-name-directory (directory-file-name dir)))
795 done t)
796 (if (equal "." (file-name-nondirectory filename))
797 (setq filename (directory-file-name dir)
798 done t)
799 ;; Put it back on the file name.
800 (setq filename (concat dir (file-name-nondirectory filename)))
801 ;; Is the file name the name of a link?
802 (setq target (file-symlink-p filename))
803 (if target
804 ;; Yes => chase that link, then start all over
805 ;; since the link may point to a directory name that uses links.
806 ;; We can't safely use expand-file-name here
807 ;; since target might look like foo/../bar where foo
808 ;; is itself a link. Instead, we handle . and .. above.
809 (setq filename
810 (if (file-name-absolute-p target)
811 target
812 (concat dir target))
813 done nil)
814 ;; No, we are done!
815 (setq done t))))))))
816 filename))
5dbfdacd 817
302fcc98 818(defun file-chase-links (filename &optional limit)
5dadeb29 819 "Chase links in FILENAME until a name that is not a link.
302fcc98
RS
820Unlike `file-truename', this does not check whether a parent
821directory name is a symbolic link.
822If the optional argument LIMIT is a number,
823it means chase no more than that many links and then stop."
824 (let (tem (newname filename)
92464ae6 825 (count 0))
302fcc98
RS
826 (while (and (or (null limit) (< count limit))
827 (setq tem (file-symlink-p newname)))
9695aac6 828 (save-match-data
92464ae6 829 (if (and (null limit) (= count 100))
9695aac6
RS
830 (error "Apparent cycle of symbolic links for %s" filename))
831 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
832 (while (string-match "//+" tem)
833 (setq tem (replace-match "/" nil nil tem)))
834 ;; Handle `..' by hand, since it needs to work in the
835 ;; target of any directory symlink.
836 ;; This code is not quite complete; it does not handle
837 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
838 (while (string-match "\\`\\.\\./" tem)
839 (setq tem (substring tem 3))
840 (setq newname (expand-file-name newname))
841 ;; Chase links in the default dir of the symlink.
842 (setq newname
843 (file-chase-links
844 (directory-file-name (file-name-directory newname))))
845 ;; Now find the parent of that dir.
846 (setq newname (file-name-directory newname)))
847 (setq newname (expand-file-name tem (file-name-directory newname)))
92464ae6 848 (setq count (1+ count))))
5dadeb29 849 newname))
9bdbd98e
KH
850
851(defun recode-file-name (file coding new-coding &optional ok-if-already-exists)
852 "Change the encoding of FILE's name from CODING to NEW-CODING.
853The value is a new name of FILE.
854Signals a `file-already-exists' error if a file of the new name
855already exists unless optional third argument OK-IF-ALREADY-EXISTS
856is non-nil. A number as third arg means request confirmation if
857the new name already exists. This is what happens in interactive
858use with M-x."
859 (interactive
860 (let ((default-coding (or file-name-coding-system
861 default-file-name-coding-system))
862 (filename (read-file-name "Recode filename: " nil nil t))
863 from-coding to-coding)
864 (if (and default-coding
865 ;; We provide the default coding only when it seems that
866 ;; the filename is correctly decoded by the default
867 ;; coding.
868 (let ((charsets (find-charset-string filename)))
869 (and (not (memq 'eight-bit-control charsets))
870 (not (memq 'eight-bit-graphic charsets)))))
871 (setq from-coding (read-coding-system
872 (format "Recode filename %s from (default %s): "
873 filename default-coding)
874 default-coding))
875 (setq from-coding (read-coding-system
876 (format "Recode filename %s from: " filename))))
cdec2ad7 877
9bdbd98e
KH
878 ;; We provide the default coding only when a user is going to
879 ;; change the encoding not from the default coding.
880 (if (eq from-coding default-coding)
881 (setq to-coding (read-coding-system
882 (format "Recode filename %s from %s to: "
883 filename from-coding)))
884 (setq to-coding (read-coding-system
885 (format "Recode filename %s from %s to (default %s): "
886 filename from-coding default-coding)
887 default-coding)))
888 (list filename from-coding to-coding)))
889
890 (let* ((default-coding (or file-name-coding-system
891 default-file-name-coding-system))
892 ;; FILE should have been decoded by DEFAULT-CODING.
893 (encoded (encode-coding-string file default-coding))
894 (newname (decode-coding-string encoded coding))
895 (new-encoded (encode-coding-string newname new-coding))
896 ;; Suppress further encoding.
897 (file-name-coding-system nil)
898 (default-file-name-coding-system nil)
899 (locale-coding-system nil))
900 (rename-file encoded new-encoded ok-if-already-exists)
901 newname))
b4da00e9 902\f
467ff692
RS
903(defun switch-to-buffer-other-window (buffer &optional norecord)
904 "Select buffer BUFFER in another window.
839857c7
LT
905If BUFFER does not identify an existing buffer, then this function
906creates a buffer with that name.
907
908When called from Lisp, BUFFER can be a buffer, a string \(a buffer name),
909or nil. If BUFFER is nil, then this function chooses a buffer
910using `other-buffer'.
467ff692 911Optional second arg NORECORD non-nil means
4c6a4739 912do not put this buffer at the front of the list of recently selected ones.
839857c7 913This function returns the buffer it switched to.
4c6a4739
EZ
914
915This uses the function `display-buffer' as a subroutine; see its
916documentation for additional customization information."
b4da00e9 917 (interactive "BSwitch to buffer in other window: ")
cf44b9b7
RS
918 (let ((pop-up-windows t)
919 ;; Don't let these interfere.
920 same-window-buffer-names same-window-regexps)
467ff692 921 (pop-to-buffer buffer t norecord)))
b4da00e9 922
467ff692
RS
923(defun switch-to-buffer-other-frame (buffer &optional norecord)
924 "Switch to buffer BUFFER in another frame.
925Optional second arg NORECORD non-nil means
4c6a4739
EZ
926do not put this buffer at the front of the list of recently selected ones.
927
928This uses the function `display-buffer' as a subroutine; see its
929documentation for additional customization information."
f98955ea 930 (interactive "BSwitch to buffer in other frame: ")
cf44b9b7
RS
931 (let ((pop-up-frames t)
932 same-window-buffer-names same-window-regexps)
467ff692 933 (pop-to-buffer buffer t norecord)
336b7f41 934 (raise-frame (window-frame (selected-window)))))
5bbbceb1 935
a49a58f9
RS
936(defvar find-file-default nil
937 "Used within `find-file-read-args'.")
938
a42e7db0
SM
939(defmacro minibuffer-with-setup-hook (fun &rest body)
940 "Add FUN to `minibuffer-setup-hook' while executing BODY.
941BODY should use the minibuffer at most once.
942Recursive uses of the minibuffer will not be affected."
943 (declare (indent 1) (debug t))
944 (let ((hook (make-symbol "setup-hook")))
44dce0fb
RS
945 `(let (,hook)
946 (setq ,hook
947 (lambda ()
948 ;; Clear out this hook so it does not interfere
949 ;; with any recursive minibuffer usage.
950 (remove-hook 'minibuffer-setup-hook ,hook)
951 (,fun)))
a42e7db0
SM
952 (unwind-protect
953 (progn
954 (add-hook 'minibuffer-setup-hook ,hook)
955 ,@body)
956 (remove-hook 'minibuffer-setup-hook ,hook)))))
957
05a7cb3d 958(defun find-file-read-args (prompt mustmatch)
e6f0ff92
RS
959 (list (let ((find-file-default
960 (and buffer-file-name
a42e7db0
SM
961 (abbreviate-file-name buffer-file-name))))
962 (minibuffer-with-setup-hook
963 (lambda () (setq minibuffer-default find-file-default))
964 (read-file-name prompt nil default-directory mustmatch)))
b2a26f4e 965 t))
e6f0ff92 966
243ce842 967(defun find-file (filename &optional wildcards)
b4da00e9
RM
968 "Edit file FILENAME.
969Switch to a buffer visiting file FILENAME,
243ce842 970creating one if none already exists.
e6f0ff92
RS
971Interactively, the default if you just type RET is the current directory,
972but the visited file name is available through the minibuffer history:
973type M-n to pull it into the minibuffer.
974
243ce842 975Interactively, or if WILDCARDS is non-nil in a call from Lisp,
91174d63
RS
976expand wildcards (if any) and visit multiple files. You can
977suppress wildcard expansion by setting `find-file-wildcards'.
978
979To visit a file without any kind of conversion and without
980automatically choosing a major mode, use \\[find-file-literally]."
a9d6a617 981 (interactive (find-file-read-args "Find file: " nil))
5b8ed07b
RS
982 (let ((value (find-file-noselect filename nil nil wildcards)))
983 (if (listp value)
984 (mapcar 'switch-to-buffer (nreverse value))
985 (switch-to-buffer value))))
82d0954a 986
243ce842 987(defun find-file-other-window (filename &optional wildcards)
b4da00e9
RM
988 "Edit file FILENAME, in another window.
989May create a new window, or reuse an existing one.
243ce842 990See the function `display-buffer'.
e6f0ff92
RS
991
992Interactively, the default if you just type RET is the current directory,
993but the visited file name is available through the minibuffer history:
994type M-n to pull it into the minibuffer.
995
243ce842
RS
996Interactively, or if WILDCARDS is non-nil in a call from Lisp,
997expand wildcards (if any) and visit multiple files."
05a7cb3d 998 (interactive (find-file-read-args "Find file in other window: " nil))
5b8ed07b
RS
999 (let ((value (find-file-noselect filename nil nil wildcards)))
1000 (if (listp value)
1001 (progn
1002 (setq value (nreverse value))
a9d6a617
JL
1003 (cons (switch-to-buffer-other-window (car value))
1004 (mapcar 'switch-to-buffer (cdr value))))
5b8ed07b 1005 (switch-to-buffer-other-window value))))
243ce842
RS
1006
1007(defun find-file-other-frame (filename &optional wildcards)
f98955ea
JB
1008 "Edit file FILENAME, in another frame.
1009May create a new frame, or reuse an existing one.
243ce842 1010See the function `display-buffer'.
e6f0ff92
RS
1011
1012Interactively, the default if you just type RET is the current directory,
1013but the visited file name is available through the minibuffer history:
1014type M-n to pull it into the minibuffer.
1015
243ce842
RS
1016Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1017expand wildcards (if any) and visit multiple files."
05a7cb3d 1018 (interactive (find-file-read-args "Find file in other frame: " nil))
5b8ed07b
RS
1019 (let ((value (find-file-noselect filename nil nil wildcards)))
1020 (if (listp value)
1021 (progn
1022 (setq value (nreverse value))
a9d6a617
JL
1023 (cons (switch-to-buffer-other-frame (car value))
1024 (mapcar 'switch-to-buffer (cdr value))))
5b8ed07b 1025 (switch-to-buffer-other-frame value))))
243ce842 1026
46bfc73b
JD
1027(defun find-file-existing (filename &optional wildcards)
1028 "Edit the existing file FILENAME.
1029Like \\[find-file] but only allow files that exists."
1030 (interactive (find-file-read-args "Find existing file: " t))
1031 (unless (file-exists-p filename) (error "%s does not exist" filename))
1032 (find-file filename wildcards)
1033 (current-buffer))
1034
243ce842 1035(defun find-file-read-only (filename &optional wildcards)
b4da00e9 1036 "Edit file FILENAME but don't allow changes.
e6f0ff92 1037Like \\[find-file] but marks buffer as read-only.
b4da00e9 1038Use \\[toggle-read-only] to permit editing."
a9d6a617
JL
1039 (interactive (find-file-read-args "Find file read-only: " nil))
1040 (unless (or (and wildcards find-file-wildcards
1041 (not (string-match "\\`/:" filename))
1042 (string-match "[[*?]" filename))
1043 (file-exists-p filename))
1044 (error "%s does not exist" filename))
1045 (let ((value (find-file filename wildcards)))
1046 (mapc (lambda (b) (with-current-buffer b (toggle-read-only 1)))
1047 (if (listp value) value (list value)))
1048 value))
b4da00e9 1049
243ce842 1050(defun find-file-read-only-other-window (filename &optional wildcards)
b4da00e9
RM
1051 "Edit file FILENAME in another window but don't allow changes.
1052Like \\[find-file-other-window] but marks buffer as read-only.
1053Use \\[toggle-read-only] to permit editing."
a9d6a617
JL
1054 (interactive (find-file-read-args "Find file read-only other window: " nil))
1055 (unless (or (and wildcards find-file-wildcards
1056 (not (string-match "\\`/:" filename))
1057 (string-match "[[*?]" filename))
1058 (file-exists-p filename))
1059 (error "%s does not exist" filename))
1060 (let ((value (find-file-other-window filename wildcards)))
1061 (mapc (lambda (b) (with-current-buffer b (toggle-read-only 1)))
1062 (if (listp value) value (list value)))
1063 value))
b4da00e9 1064
243ce842 1065(defun find-file-read-only-other-frame (filename &optional wildcards)
f98955ea
JB
1066 "Edit file FILENAME in another frame but don't allow changes.
1067Like \\[find-file-other-frame] but marks buffer as read-only.
5bbbceb1 1068Use \\[toggle-read-only] to permit editing."
a9d6a617
JL
1069 (interactive (find-file-read-args "Find file read-only other frame: " nil))
1070 (unless (or (and wildcards find-file-wildcards
1071 (not (string-match "\\`/:" filename))
1072 (string-match "[[*?]" filename))
1073 (file-exists-p filename))
1074 (error "%s does not exist" filename))
1075 (let ((value (find-file-other-frame filename wildcards)))
1076 (mapc (lambda (b) (with-current-buffer b (toggle-read-only 1)))
1077 (if (listp value) value (list value)))
1078 value))
1079
1080(defun find-alternate-file-other-window (filename &optional wildcards)
60eaf370 1081 "Find file FILENAME as a replacement for the file in the next window.
a9d6a617
JL
1082This command does not select that window.
1083
1084Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1085expand wildcards (if any) and replace the file with multiple files."
60eaf370
RS
1086 (interactive
1087 (save-selected-window
1088 (other-window 1)
1089 (let ((file buffer-file-name)
1090 (file-name nil)
1091 (file-dir nil))
1092 (and file
1093 (setq file-name (file-name-nondirectory file)
1094 file-dir (file-name-directory file)))
1095 (list (read-file-name
a9d6a617
JL
1096 "Find alternate file: " file-dir nil nil file-name)
1097 t))))
60eaf370 1098 (if (one-window-p)
a9d6a617 1099 (find-file-other-window filename wildcards)
60eaf370
RS
1100 (save-selected-window
1101 (other-window 1)
a9d6a617 1102 (find-alternate-file filename wildcards))))
60eaf370 1103
a9d6a617 1104(defun find-alternate-file (filename &optional wildcards)
b4da00e9
RM
1105 "Find file FILENAME, select its buffer, kill previous buffer.
1106If the current buffer now contains an empty file that you just visited
a9d6a617
JL
1107\(presumably by mistake), use this command to visit the file you really want.
1108
1109Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1110expand wildcards (if any) and replace the file with multiple files."
b4da00e9
RM
1111 (interactive
1112 (let ((file buffer-file-name)
1113 (file-name nil)
1114 (file-dir nil))
1115 (and file
1116 (setq file-name (file-name-nondirectory file)
1117 file-dir (file-name-directory file)))
a61f59b4 1118 (list (read-file-name
a9d6a617
JL
1119 "Find alternate file: " file-dir nil nil file-name)
1120 t)))
63fabbb4
RS
1121 (unless (run-hook-with-args-until-failure 'kill-buffer-query-functions)
1122 (error "Aborted"))
1123 (when (and (buffer-modified-p) (buffer-file-name))
1124 (if (yes-or-no-p (format "Buffer %s is modified; save it first? "
1125 (buffer-name)))
1126 (save-buffer)
1127 (unless (yes-or-no-p "Kill and replace the buffer without saving it? ")
1128 (error "Aborted"))))
b4da00e9
RM
1129 (let ((obuf (current-buffer))
1130 (ofile buffer-file-name)
8bb27285 1131 (onum buffer-file-number)
37c58ca6 1132 (odir dired-directory)
8bb27285 1133 (otrue buffer-file-truename)
b4da00e9 1134 (oname (buffer-name)))
baf9b8c4
RS
1135 (if (get-buffer " **lose**")
1136 (kill-buffer " **lose**"))
b4da00e9 1137 (rename-buffer " **lose**")
b4da00e9
RM
1138 (unwind-protect
1139 (progn
1140 (unlock-buffer)
7906c044
RS
1141 ;; This prevents us from finding the same buffer
1142 ;; if we specified the same file again.
a4ad4d96
RS
1143 (setq buffer-file-name nil)
1144 (setq buffer-file-number nil)
1145 (setq buffer-file-truename nil)
7906c044
RS
1146 ;; Likewise for dired buffers.
1147 (setq dired-directory nil)
a9d6a617 1148 (find-file filename wildcards))
63fabbb4
RS
1149 (when (eq obuf (current-buffer))
1150 ;; This executes if find-file gets an error
1151 ;; and does not really find anything.
1152 ;; We put things back as they were.
1153 ;; If find-file actually finds something, we kill obuf below.
1154 (setq buffer-file-name ofile)
1155 (setq buffer-file-number onum)
1156 (setq buffer-file-truename otrue)
7906c044 1157 (setq dired-directory odir)
63fabbb4
RS
1158 (lock-buffer)
1159 (rename-buffer oname)))
1160 (unless (eq (current-buffer) obuf)
d97a9ff3
RS
1161 (with-current-buffer obuf
1162 ;; We already asked; don't ask again.
1163 (let ((kill-buffer-query-functions))
1164 (kill-buffer obuf))))))
9b8ef27d 1165\f
b4da00e9
RM
1166(defun create-file-buffer (filename)
1167 "Create a suitably named buffer for visiting FILENAME, and return it.
1168FILENAME (sans directory) is used unchanged if that name is free;
1169otherwise a string <2> or <3> or ... is appended to get an unused name."
1170 (let ((lastname (file-name-nondirectory filename)))
1171 (if (string= lastname "")
1172 (setq lastname filename))
1173 (generate-new-buffer lastname)))
1174
5bbbceb1
JB
1175(defun generate-new-buffer (name)
1176 "Create and return a buffer with a name based on NAME.
29165787 1177Choose the buffer's name using `generate-new-buffer-name'."
5bbbceb1
JB
1178 (get-buffer-create (generate-new-buffer-name name)))
1179
ffc0e1ca
AS
1180(defcustom automount-dir-prefix "^/tmp_mnt/"
1181 "Regexp to match the automounter prefix in a directory name."
1182 :group 'files
1183 :type 'regexp)
e373f201 1184
ffb3a4db 1185(defvar abbreviated-home-dir nil
ffc0e1ca 1186 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
ffb3a4db 1187
5bbbceb1 1188(defun abbreviate-file-name (filename)
29165787 1189 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
b69a0de9 1190This also substitutes \"~\" for the user's home directory and
5baabf7b 1191removes automounter prefixes (see the variable `automount-dir-prefix')."
e373f201 1192 ;; Get rid of the prefixes added by the automounter.
a8f34fc0
RS
1193 (if (and automount-dir-prefix
1194 (string-match automount-dir-prefix filename)
e373f201
JB
1195 (file-exists-p (file-name-directory
1196 (substring filename (1- (match-end 0))))))
1197 (setq filename (substring filename (1- (match-end 0)))))
5bbbceb1 1198 (let ((tail directory-abbrev-alist))
ffb3a4db
RS
1199 ;; If any elt of directory-abbrev-alist matches this name,
1200 ;; abbreviate accordingly.
5bbbceb1
JB
1201 (while tail
1202 (if (string-match (car (car tail)) filename)
1203 (setq filename
1204 (concat (cdr (car tail)) (substring filename (match-end 0)))))
1205 (setq tail (cdr tail)))
ffb3a4db
RS
1206 ;; Compute and save the abbreviated homedir name.
1207 ;; We defer computing this until the first time it's needed, to
1208 ;; give time for directory-abbrev-alist to be set properly.
e98dda89
RS
1209 ;; We include a slash at the end, to avoid spurious matches
1210 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
ffb3a4db
RS
1211 (or abbreviated-home-dir
1212 (setq abbreviated-home-dir
1213 (let ((abbreviated-home-dir "$foo"))
3a8a836d
RS
1214 (concat "^" (abbreviate-file-name (expand-file-name "~"))
1215 "\\(/\\|$\\)"))))
76d5492b 1216
ffb3a4db
RS
1217 ;; If FILENAME starts with the abbreviated homedir,
1218 ;; make it start with `~' instead.
ca33ccb5
RS
1219 (if (and (string-match abbreviated-home-dir filename)
1220 ;; If the home dir is just /, don't change it.
1221 (not (and (= (match-end 0) 1)
288201bd 1222 (= (aref filename 0) ?/)))
567c1ca9
RS
1223 ;; MS-DOS root directories can come with a drive letter;
1224 ;; Novell Netware allows drive letters beyond `Z:'.
76d5492b 1225 (not (and (or (eq system-type 'ms-dos)
c60ee5e7 1226 (eq system-type 'cygwin)
c32d49e8 1227 (eq system-type 'windows-nt))
288201bd 1228 (save-match-data
567c1ca9 1229 (string-match "^[a-zA-`]:/$" filename)))))
5bbbceb1 1230 (setq filename
28dbf501 1231 (concat "~"
3a8a836d 1232 (substring filename (match-beginning 1) (match-end 1))
28dbf501 1233 (substring filename (match-end 0)))))
5bbbceb1
JB
1234 filename))
1235
21540597 1236(defcustom find-file-not-true-dirname-list nil
1770543d
RS
1237 "*List of logical names for which visiting shouldn't save the true dirname.
1238On VMS, when you visit a file using a logical name that searches a path,
1239you may or may not want the visited file name to record the specific
1240directory where the file was found. If you *do not* want that, add the logical
21540597
RS
1241name to this list as a string."
1242 :type '(repeat (string :tag "Name"))
1243 :group 'find-file)
1770543d 1244
3a64a3cf 1245(defun find-buffer-visiting (filename &optional predicate)
138c44f6
KH
1246 "Return the buffer visiting file FILENAME (a string).
1247This is like `get-file-buffer', except that it checks for any buffer
1248visiting the same file, possibly under a different name.
a1b0c2a7
RS
1249If PREDICATE is non-nil, only buffers satisfying it are eligible,
1250and others are ignored.
138c44f6 1251If there is no such live buffer, return nil."
3a64a3cf
JB
1252 (let ((predicate (or predicate #'identity))
1253 (truename (abbreviate-file-name (file-truename filename))))
1254 (or (let ((buf (get-file-buffer filename)))
1255 (when (and buf (funcall predicate buf)) buf))
1256 (let ((list (buffer-list)) found)
1257 (while (and (not found) list)
1258 (save-excursion
1259 (set-buffer (car list))
1260 (if (and buffer-file-name
1261 (string= buffer-file-truename truename)
1262 (funcall predicate (current-buffer)))
1263 (setq found (car list))))
1264 (setq list (cdr list)))
1265 found)
1266 (let* ((attributes (file-attributes truename))
1267 (number (nthcdr 10 attributes))
1268 (list (buffer-list)) found)
1269 (and buffer-file-numbers-unique
1270 number
1271 (while (and (not found) list)
1272 (with-current-buffer (car list)
1273 (if (and buffer-file-name
1274 (equal buffer-file-number number)
1275 ;; Verify this buffer's file number
1276 ;; still belongs to its file.
1277 (file-exists-p buffer-file-name)
1278 (equal (file-attributes buffer-file-truename)
1279 attributes)
1280 (funcall predicate (current-buffer)))
1281 (setq found (car list))))
1282 (setq list (cdr list))))
1283 found))))
9b8ef27d 1284\f
5de148a2
RS
1285(defcustom find-file-wildcards t
1286 "*Non-nil means file-visiting commands should handle wildcards.
1287For example, if you specify `*.c', that would visit all the files
1288whose names match the pattern."
1289 :group 'files
3957c982 1290 :version "20.4"
5de148a2
RS
1291 :type 'boolean)
1292
ffc0e1ca
AS
1293(defcustom find-file-suppress-same-file-warnings nil
1294 "*Non-nil means suppress warning messages for symlinked files.
1295When nil, Emacs prints a warning when visiting a file that is already
1296visited, but with a different name. Setting this option to t
1297suppresses this warning."
1298 :group 'files
1299 :version "21.1"
1300 :type 'boolean)
1301
818286f4 1302(defcustom large-file-warning-threshold 10000000
5d648479
JPW
1303 "Maximum size of file above which a confirmation is requested.
1304When nil, never request confirmation."
1305 :group 'files
1306 :group 'find-file
bf247b6e 1307 :version "22.1"
5d648479 1308 :type '(choice integer (const :tag "Never request confirmation" nil)))
818286f4 1309
243ce842 1310(defun find-file-noselect (filename &optional nowarn rawfile wildcards)
b4da00e9
RM
1311 "Read file FILENAME into a buffer and return the buffer.
1312If a buffer exists visiting FILENAME, return that one, but
1313verify that the file has not changed since visited or saved.
82d0954a
KH
1314The buffer is not selected, just returned to the caller.
1315Optional first arg NOWARN non-nil means suppress any warning messages.
243ce842
RS
1316Optional second arg RAWFILE non-nil means the file is read literally.
1317Optional third arg WILDCARDS non-nil means do wildcard processing
5b8ed07b 1318and visit all the matching files. When wildcards are actually
a9d6a617
JL
1319used and expanded, return a list of buffers that are visiting
1320the various files."
e373f201
JB
1321 (setq filename
1322 (abbreviate-file-name
1323 (expand-file-name filename)))
b4da00e9 1324 (if (file-directory-p filename)
ffc0e1ca
AS
1325 (or (and find-file-run-dired
1326 (run-hook-with-args-until-success
1327 'find-directory-functions
1328 (if find-file-visit-truename
1329 (abbreviate-file-name (file-truename filename))
1330 filename)))
1331 (error "%s is a directory" filename))
243ce842
RS
1332 (if (and wildcards
1333 find-file-wildcards
f91fe604 1334 (not (string-match "\\`/:" filename))
5de148a2 1335 (string-match "[[*?]" filename))
ffc0e1ca
AS
1336 (let ((files (condition-case nil
1337 (file-expand-wildcards filename t)
1338 (error (list filename))))
5de148a2 1339 (find-file-wildcards nil))
f91fe604 1340 (if (null files)
ffc0e1ca 1341 (find-file-noselect filename)
648ec2ff 1342 (mapcar #'find-file-noselect files)))
5de148a2
RS
1343 (let* ((buf (get-file-buffer filename))
1344 (truename (abbreviate-file-name (file-truename filename)))
818286f4
SM
1345 (attributes (file-attributes truename))
1346 (number (nthcdr 10 attributes))
5de148a2
RS
1347 ;; Find any buffer for a file which has same truename.
1348 (other (and (not buf) (find-buffer-visiting filename))))
1349 ;; Let user know if there is a buffer with the same truename.
1350 (if other
1351 (progn
1352 (or nowarn
ffc0e1ca 1353 find-file-suppress-same-file-warnings
5de148a2
RS
1354 (string-equal filename (buffer-file-name other))
1355 (message "%s and %s are the same file"
1356 filename (buffer-file-name other)))
1357 ;; Optionally also find that buffer.
1358 (if (or find-file-existing-other-name find-file-visit-truename)
1359 (setq buf other))))
818286f4
SM
1360 ;; Check to see if the file looks uncommonly large.
1361 (when (and large-file-warning-threshold (nth 7 attributes)
1362 ;; Don't ask again if we already have the file or
1363 ;; if we're asked to be quiet.
1364 (not (or buf nowarn))
1365 (> (nth 7 attributes) large-file-warning-threshold)
1366 (not (y-or-n-p
1367 (format "File %s is large (%sMB), really open? "
1368 (file-name-nondirectory filename)
1369 (/ (nth 7 attributes) 1048576)))))
1370 (error "Aborted"))
5de148a2
RS
1371 (if buf
1372 ;; We are using an existing buffer.
1373 (progn
1374 (or nowarn
1375 (verify-visited-file-modtime buf)
1376 (cond ((not (file-exists-p filename))
1377 (error "File %s no longer exists!" filename))
1378 ;; Certain files should be reverted automatically
1379 ;; if they have changed on disk and not in the buffer.
1380 ((and (not (buffer-modified-p buf))
1381 (let ((tail revert-without-query)
1382 (found nil))
1383 (while tail
1384 (if (string-match (car tail) filename)
1385 (setq found t))
1386 (setq tail (cdr tail)))
1387 found))
1388 (with-current-buffer buf
1389 (message "Reverting file %s..." filename)
1390 (revert-buffer t t)
1391 (message "Reverting file %s...done" filename)))
1392 ((yes-or-no-p
1393 (if (string= (file-name-nondirectory filename)
1394 (buffer-name buf))
1395 (format
1396 (if (buffer-modified-p buf)
1397 "File %s changed on disk. Discard your edits? "
1398 "File %s changed on disk. Reread from disk? ")
1399 (file-name-nondirectory filename))
ddd64da9
RS
1400 (format
1401 (if (buffer-modified-p buf)
5de148a2
RS
1402 "File %s changed on disk. Discard your edits in %s? "
1403 "File %s changed on disk. Reread from disk into %s? ")
1404 (file-name-nondirectory filename)
1405 (buffer-name buf))))
1406 (with-current-buffer buf
1407 (revert-buffer t t)))))
1408 (with-current-buffer buf
a8d002d2
GM
1409
1410 ;; Check if a formerly read-only file has become
e554eeb7
RS
1411 ;; writable and vice versa, but if the buffer agrees
1412 ;; with the new state of the file, that is ok too.
a8d002d2 1413 (let ((read-only (not (file-writable-p buffer-file-name))))
e554eeb7
RS
1414 (unless (or (eq read-only buffer-file-read-only)
1415 (eq read-only buffer-read-only))
a8d002d2 1416 (when (or nowarn
36236b72 1417 (let ((question
a8d002d2
GM
1418 (format "File %s is %s on disk. Change buffer mode? "
1419 buffer-file-name
1420 (if read-only "read-only" "writable"))))
1421 (y-or-n-p question)))
e554eeb7
RS
1422 (setq buffer-read-only read-only)))
1423 (setq buffer-file-read-only read-only))
a8d002d2 1424
ef59dd3b
EZ
1425 (when (and (not (eq (not (null rawfile))
1426 (not (null find-file-literally))))
1427 ;; It is confusing to ask whether to visit
1428 ;; non-literally if they have the file in
1429 ;; hexl-mode.
1430 (not (eq major-mode 'hexl-mode)))
5de148a2 1431 (if (buffer-modified-p)
ddd64da9 1432 (if (y-or-n-p (if rawfile
5de148a2
RS
1433 "Save file and revisit literally? "
1434 "Save file and revisit non-literally? "))
1435 (progn
1436 (save-buffer)
1437 (find-file-noselect-1 buf filename nowarn
1438 rawfile truename number))
1439 (if (y-or-n-p (if rawfile
1440 "Discard your edits and revisit file literally? "
1441 "Discard your edits and revisit file non-literally? "))
1442 (find-file-noselect-1 buf filename nowarn
1443 rawfile truename number)
1444 (error (if rawfile "File already visited non-literally"
1445 "File already visited literally"))))
1446 (if (y-or-n-p (if rawfile
1447 "Revisit file literally? "
1448 "Revisit file non-literally? "))
1449 (find-file-noselect-1 buf filename nowarn
1450 rawfile truename number)
1451 (error (if rawfile "File already visited non-literally"
1452 "File already visited literally"))))))
1453 ;; Return the buffer we are using.
1454 buf)
1455 ;; Create a new buffer.
1456 (setq buf (create-file-buffer filename))
1457 (set-buffer-major-mode buf)
1458 ;; find-file-noselect-1 may use a different buffer.
1459 (find-file-noselect-1 buf filename nowarn
1460 rawfile truename number))))))
ddd64da9
RS
1461
1462(defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
4edcfd17 1463 (let (error)
ddd64da9
RS
1464 (with-current-buffer buf
1465 (kill-local-variable 'find-file-literally)
b296cbd4
RS
1466 ;; Needed in case we are re-visiting the file with a different
1467 ;; text representation.
e73ec04b 1468 (kill-local-variable 'buffer-file-coding-system)
4ad1689f 1469 (kill-local-variable 'cursor-type)
4edcfd17 1470 (let ((inhibit-read-only t))
0a11c70b
LT
1471 (erase-buffer))
1472 (and (default-value 'enable-multibyte-characters)
1473 (not rawfile)
1474 (set-buffer-multibyte t))
1475 (if rawfile
74dca654 1476 (condition-case ()
0a11c70b
LT
1477 (let ((inhibit-read-only t))
1478 (insert-file-contents-literally filename t))
74dca654
LT
1479 (file-error
1480 (when (and (file-exists-p filename)
1481 (not (file-readable-p filename)))
1482 (kill-buffer buf)
1483 (signal 'file-error (list "File is not readable"
1484 filename)))
0a11c70b
LT
1485 ;; Unconditionally set error
1486 (setq error t)))
1487 (condition-case ()
1488 (let ((inhibit-read-only t))
1489 (insert-file-contents filename t))
1490 (file-error
1491 (when (and (file-exists-p filename)
1492 (not (file-readable-p filename)))
1493 (kill-buffer buf)
1494 (signal 'file-error (list "File is not readable"
1495 filename)))
1496 ;; Run find-file-not-found-hooks until one returns non-nil.
1497 (or (run-hook-with-args-until-success 'find-file-not-found-functions)
1498 ;; If they fail too, set error.
1499 (setq error t)))))
b120e713
KH
1500 ;; Record the file's truename, and maybe use that as visited name.
1501 (if (equal filename buffer-file-name)
1502 (setq buffer-file-truename truename)
9ab19105
DL
1503 (setq buffer-file-truename
1504 (abbreviate-file-name (file-truename buffer-file-name))))
ddd64da9
RS
1505 (setq buffer-file-number number)
1506 ;; On VMS, we may want to remember which directory in a search list
1507 ;; the file was found in.
1508 (and (eq system-type 'vax-vms)
1509 (let (logical)
1510 (if (string-match ":" (file-name-directory filename))
1511 (setq logical (substring (file-name-directory filename)
1512 0 (match-beginning 0))))
1513 (not (member logical find-file-not-true-dirname-list)))
1514 (setq buffer-file-name buffer-file-truename))
1515 (if find-file-visit-truename
1516 (setq buffer-file-name
1517 (setq filename
1518 (expand-file-name buffer-file-truename))))
1519 ;; Set buffer's default directory to that of the file.
b120e713 1520 (setq default-directory (file-name-directory buffer-file-name))
ddd64da9
RS
1521 ;; Turn off backup files for certain file names. Since
1522 ;; this is a permanent local, the major mode won't eliminate it.
1523 (and (not (funcall backup-enable-predicate buffer-file-name))
1524 (progn
1525 (make-local-variable 'backup-inhibited)
1526 (setq backup-inhibited t)))
f402ba38
RS
1527 (if rawfile
1528 (progn
1529 (set-buffer-multibyte nil)
1530 (setq buffer-file-coding-system 'no-conversion)
1531 (make-local-variable 'find-file-literally)
1532 (setq find-file-literally t))
1533 (after-find-file error (not nowarn)))
1534 (current-buffer))))
9b8ef27d
RS
1535\f
1536(defun insert-file-contents-literally (filename &optional visit beg end replace)
1537 "Like `insert-file-contents', but only reads in the file literally.
1538A buffer may be modified in several ways after reading into the buffer,
1539to Emacs features such as format decoding, character code
0370fe77 1540conversion, `find-file-hook', automatic uncompression, etc.
9b8ef27d
RS
1541
1542This function ensures that none of these modifications will take place."
1543 (let ((format-alist nil)
1544 (after-insert-file-functions nil)
1545 (coding-system-for-read 'no-conversion)
1546 (coding-system-for-write 'no-conversion)
9b8ef27d 1547 (find-buffer-file-type-function
cdec2ad7
JB
1548 (if (fboundp 'find-buffer-file-type)
1549 (symbol-function 'find-buffer-file-type)
1550 nil))
1551 (inhibit-file-name-handlers
1552 (append '(jka-compr-handler image-file-handler)
1553 inhibit-file-name-handlers))
1554 (inhibit-file-name-operation 'insert-file-contents))
9b8ef27d 1555 (unwind-protect
cdec2ad7
JB
1556 (progn
1557 (fset 'find-buffer-file-type (lambda (filename) t))
1558 (insert-file-contents filename visit beg end replace))
9b8ef27d
RS
1559 (if find-buffer-file-type-function
1560 (fset 'find-buffer-file-type find-buffer-file-type-function)
1561 (fmakunbound 'find-buffer-file-type)))))
1562
3a64a3cf
JB
1563(defun insert-file-1 (filename insert-func)
1564 (if (file-directory-p filename)
1565 (signal 'file-error (list "Opening input file" "file is a directory"
1566 filename)))
1567 (let* ((buffer (find-buffer-visiting (abbreviate-file-name (file-truename filename))
1568 #'buffer-modified-p))
1569 (tem (funcall insert-func filename)))
1570 (push-mark (+ (point) (car (cdr tem))))
1571 (when buffer
1572 (message "File %s already visited and modified in buffer %s"
1573 filename (buffer-name buffer)))))
1574
9b8ef27d
RS
1575(defun insert-file-literally (filename)
1576 "Insert contents of file FILENAME into buffer after point with no conversion.
1577
1578This function is meant for the user to run interactively.
1579Don't call it from programs! Use `insert-file-contents-literally' instead.
1580\(Its calling sequence is different; see its documentation)."
1581 (interactive "*fInsert file literally: ")
3a64a3cf 1582 (insert-file-1 filename #'insert-file-contents-literally))
9b8ef27d
RS
1583
1584(defvar find-file-literally nil
1585 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1586This is a permanent local.")
1587(put 'find-file-literally 'permanent-local t)
5fc196af 1588
ffc0e1ca 1589(defun find-file-literally (filename)
5fc196af
RS
1590 "Visit file FILENAME with no conversion of any kind.
1591Format conversion and character code conversion are both disabled,
1592and multibyte characters are disabled in the resulting buffer.
e65db7b8
RS
1593The major mode used is Fundamental mode regardless of the file name,
1594and local variable specifications in the file are ignored.
407b4328
GM
1595Automatic uncompression and adding a newline at the end of the
1596file due to `require-final-newline' is also disabled.
9b8ef27d
RS
1597
1598You cannot absolutely rely on this function to result in
b9aa9537 1599visiting the file literally. If Emacs already has a buffer
9b8ef27d
RS
1600which is visiting the file, you get the existing buffer,
1601regardless of whether it was created literally or not.
1602
1603In a Lisp program, if you want to be sure of accessing a file's
1604contents literally, you should create a temporary buffer and then read
1605the file contents into it using `insert-file-contents-literally'."
5fc196af 1606 (interactive "FFind file literally: ")
9b8ef27d 1607 (switch-to-buffer (find-file-noselect filename nil t)))
b4da00e9 1608\f
f7d786d0
RS
1609(defvar after-find-file-from-revert-buffer nil)
1610
e0ab8879 1611(defun after-find-file (&optional error warn noauto
9a30563f
RS
1612 after-find-file-from-revert-buffer
1613 nomodes)
b4da00e9
RM
1614 "Called after finding a file and by the default revert function.
1615Sets buffer mode, parses local variables.
8cfb9d46 1616Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
b4da00e9
RM
1617error in reading the file. WARN non-nil means warn if there
1618exists an auto-save file more recent than the visited file.
8cfb9d46 1619NOAUTO means don't mess with auto-save mode.
e0ab8879
RS
1620Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1621 means this call was from `revert-buffer'.
9a30563f 1622Fifth arg NOMODES non-nil means don't alter the file's modes.
0370fe77 1623Finishes by calling the functions in `find-file-hook'
9a30563f 1624unless NOMODES is non-nil."
b4da00e9
RM
1625 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1626 (if noninteractive
1627 nil
1628 (let* (not-serious
1629 (msg
fe50b6ab
GM
1630 (cond
1631 ((not warn) nil)
1632 ((and error (file-attributes buffer-file-name))
1633 (setq buffer-read-only t)
1634 "File exists, but cannot be read")
1635 ((not buffer-read-only)
1636 (if (and warn
1637 ;; No need to warn if buffer is auto-saved
1638 ;; under the name of the visited file.
1639 (not (and buffer-file-name
1640 auto-save-visited-file-name))
1641 (file-newer-than-file-p (or buffer-auto-save-file-name
1642 (make-auto-save-file-name))
1643 buffer-file-name))
64d18e8f 1644 (format "%s has auto save data; consider M-x recover-this-file"
fe50b6ab
GM
1645 (file-name-nondirectory buffer-file-name))
1646 (setq not-serious t)
1647 (if error "(New file)" nil)))
1648 ((not error)
1649 (setq not-serious t)
1650 "Note: file is write protected")
1651 ((file-attributes (directory-file-name default-directory))
1652 "File not found and directory write-protected")
1653 ((file-exists-p (file-name-directory buffer-file-name))
1654 (setq buffer-read-only nil))
1655 (t
1656 (setq buffer-read-only nil)
07703430 1657 "Use M-x make-directory RET RET to create the directory and its parents"))))
fe50b6ab 1658 (when msg
a74357d4 1659 (message "%s" msg)
e09f3bff 1660 (or not-serious (sit-for 1 t))))
fe50b6ab
GM
1661 (when (and auto-save-default (not noauto))
1662 (auto-save-mode t)))
ffc0e1ca
AS
1663 ;; Make people do a little extra work (C-x C-q)
1664 ;; before altering a backup file.
fe50b6ab
GM
1665 (when (backup-file-name-p buffer-file-name)
1666 (setq buffer-read-only t))
8fd9c174
RS
1667 ;; When a file is marked read-only,
1668 ;; make the buffer read-only even if root is looking at it.
879365c6
KS
1669 (when (and (file-modes (buffer-file-name))
1670 (zerop (logand (file-modes (buffer-file-name)) #o222)))
8fd9c174 1671 (setq buffer-read-only t))
fe50b6ab
GM
1672 (unless nomodes
1673 (when (and view-read-only view-mode)
1674 (view-mode-disable))
9a30563f 1675 (normal-mode t)
f4206092
RS
1676 ;; If requested, add a newline at the end of the file.
1677 (and (memq require-final-newline '(visit visit-save))
1678 (> (point-max) (point-min))
1679 (/= (char-after (1- (point-max))) ?\n)
1680 (not (and (eq selective-display t)
1681 (= (char-after (1- (point-max))) ?\r)))
1682 (save-excursion
1683 (goto-char (point-max))
1684 (insert "\n")))
fe50b6ab
GM
1685 (when (and buffer-read-only
1686 view-read-only
1687 (not (eq (get major-mode 'mode-class) 'special)))
1688 (view-mode-enter))
0370fe77 1689 (run-hooks 'find-file-hook)))
b4da00e9 1690
818286f4
SM
1691(defmacro report-errors (format &rest body)
1692 "Eval BODY and turn any error into a FORMAT message.
1693FORMAT can have a %s escape which will be replaced with the actual error.
1694If `debug-on-error' is set, errors are not caught, so that you can
1695debug them.
1696Avoid using a large BODY since it is duplicated."
1697 (declare (debug t) (indent 1))
1698 `(if debug-on-error
1699 (progn . ,body)
1700 (condition-case err
1701 (progn . ,body)
1702 (error (message ,format (prin1-to-string err))))))
1703
b4da00e9
RM
1704(defun normal-mode (&optional find-file)
1705 "Choose the major mode for this buffer automatically.
1706Also sets up any specified local variables of the file.
1707Uses the visited file name, the -*- line, and the local variables spec.
1708
1709This function is called automatically from `find-file'. In that case,
aa5fcebf
KH
1710we may set up the file-specified mode and local variables,
1711depending on the value of `enable-local-variables': if it is t, we do;
1712if it is nil, we don't; otherwise, we query.
1713In addition, if `local-enable-local-variables' is nil, we do
1714not set local variables (though we do notice a mode specified with -*-.)
1715
1716`enable-local-variables' is ignored if you run `normal-mode' interactively,
1717or from Lisp without specifying the optional argument FIND-FILE;
1718in that case, this function acts as if `enable-local-variables' were t."
b4da00e9
RM
1719 (interactive)
1720 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
818286f4
SM
1721 (report-errors "File mode specification error: %s"
1722 (set-auto-mode))
1723 (report-errors "File local-variables error: %s"
1724 (let ((enable-local-variables (or (not find-file) enable-local-variables)))
1725 (hack-local-variables)))
24c9eeeb
DL
1726 (if (fboundp 'ucs-set-table-for-input) ; don't lose when building
1727 (ucs-set-table-for-input)))
b4da00e9 1728
f76e0cd0 1729(defvar auto-mode-alist
f209c999
MS
1730 ;; Note: The entries for the modes defined in cc-mode.el (c-mode,
1731 ;; c++-mode, java-mode and more) are added through autoload
1732 ;; directives in that file. That way is discouraged since it
1733 ;; spreads out the definition of the initial value.
ffc0e1ca
AS
1734 (mapc
1735 (lambda (elt)
1736 (cons (purecopy (car elt)) (cdr elt)))
9e6f5419
DP
1737 '(;; do this first, so that .html.pl is Polish html, not Perl
1738 ("\\.s?html?\\(\\.[a-zA-Z_]+\\)?\\'" . html-mode)
1739 ("\\.te?xt\\'" . text-mode)
bbc67516 1740 ("\\.[tT]e[xX]\\'" . tex-mode)
4e163715 1741 ("\\.ins\\'" . tex-mode) ;Installation files for TeX packages.
ffc0e1ca 1742 ("\\.ltx\\'" . latex-mode)
4e163715 1743 ("\\.dtx\\'" . doctex-mode)
ffc0e1ca 1744 ("\\.el\\'" . emacs-lisp-mode)
21575d92 1745 ("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . scheme-mode)
ffc0e1ca 1746 ("\\.l\\'" . lisp-mode)
bbc67516
DP
1747 ("\\.li?sp\\'" . lisp-mode)
1748 ("\\.[fF]\\'" . fortran-mode)
ffc0e1ca
AS
1749 ("\\.for\\'" . fortran-mode)
1750 ("\\.p\\'" . pascal-mode)
1751 ("\\.pas\\'" . pascal-mode)
1752 ("\\.ad[abs]\\'" . ada-mode)
7defe888 1753 ("\\.ad[bs].dg\\'" . ada-mode)
bbc67516 1754 ("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . perl-mode)
ffc0e1ca 1755 ("\\.mk\\'" . makefile-mode)
bbc67516 1756 ("\\([Mm]\\|GNUm\\)akep*file\\'" . makefile-mode)
ffc0e1ca 1757 ("\\.am\\'" . makefile-mode) ;For Automake.
5c6d31a4
SM
1758 ;; Less common extensions come here
1759 ;; so more common ones above are found faster.
ffc0e1ca
AS
1760 ("\\.texinfo\\'" . texinfo-mode)
1761 ("\\.te?xi\\'" . texinfo-mode)
bbc67516 1762 ("\\.[sS]\\'" . asm-mode)
ffc0e1ca 1763 ("\\.asm\\'" . asm-mode)
bbc67516
DP
1764 ("[cC]hange\\.?[lL]og?\\'" . change-log-mode)
1765 ("[cC]hange[lL]og\\.[0-9]+\\'" . change-log-mode)
ffc0e1ca
AS
1766 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1767 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
1768 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
b921b596 1769 ("\\.bash\\'" . sh-mode)
ffc0e1ca
AS
1770 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1771 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1772 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
d5798fa7 1773 ("\\.m?spec\\'" . sh-mode)
bbc67516 1774 ("\\.m[mes]\\'" . nroff-mode)
ffc0e1ca 1775 ("\\.man\\'" . nroff-mode)
ffc0e1ca 1776 ("\\.sty\\'" . latex-mode)
bbc67516 1777 ("\\.cl[so]\\'" . latex-mode) ;LaTeX 2e class option
ffc0e1ca
AS
1778 ("\\.bbl\\'" . latex-mode)
1779 ("\\.bib\\'" . bibtex-mode)
1780 ("\\.sql\\'" . sql-mode)
bbc67516 1781 ("\\.m[4c]\\'" . m4-mode)
9e6f5419
DP
1782 ("\\.mf\\'" . metafont-mode)
1783 ("\\.mp\\'" . metapost-mode)
ffc0e1ca
AS
1784 ("\\.vhdl?\\'" . vhdl-mode)
1785 ("\\.article\\'" . text-mode)
1786 ("\\.letter\\'" . text-mode)
bbc67516 1787 ("\\.i?tcl\\'" . tcl-mode)
ffc0e1ca 1788 ("\\.exp\\'" . tcl-mode)
ffc0e1ca
AS
1789 ("\\.itk\\'" . tcl-mode)
1790 ("\\.icn\\'" . icon-mode)
1791 ("\\.sim\\'" . simula-mode)
1792 ("\\.mss\\'" . scribe-mode)
bbc67516 1793 ("\\.f9[05]\\'" . f90-mode)
8f9495e7 1794 ("\\.indent\\.pro\\'" . fundamental-mode) ; to avoid idlwave-mode
ffc0e1ca 1795 ("\\.pro\\'" . idlwave-mode)
ffc0e1ca
AS
1796 ("\\.prolog\\'" . prolog-mode)
1797 ("\\.tar\\'" . tar-mode)
0ee6e7b7
JL
1798 ;; The list of archive file extensions should be in sync with
1799 ;; `auto-coding-alist' with `no-conversion' coding system.
e084f8c3
EZ
1800 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|[jew]ar\\|xpi\\)\\'" . archive-mode)
1801 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|[JEW]AR\\|XPI\\)\\'" . archive-mode)
c25773c4 1802 ("\\.sx[dmicw]\\'" . archive-mode) ; OpenOffice.org
ffc0e1ca
AS
1803 ;; Mailer puts message to be edited in
1804 ;; /tmp/Re.... or Message
1805 ("\\`/tmp/Re" . text-mode)
1806 ("/Message[0-9]*\\'" . text-mode)
1807 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1808 ("\\.zone\\'" . zone-mode)
1809 ;; some news reader is reported to use this
1810 ("\\`/tmp/fol/" . text-mode)
ffc0e1ca
AS
1811 ("\\.oak\\'" . scheme-mode)
1812 ("\\.sgml?\\'" . sgml-mode)
bbc67516 1813 ("\\.x[ms]l\\'" . xml-mode)
ffc0e1ca
AS
1814 ("\\.dtd\\'" . sgml-mode)
1815 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
bbc67516
DP
1816 ("\\.js\\'" . java-mode) ; javascript-mode would be better
1817 ("\\.x[bp]m\\'" . c-mode)
709d45e1
KG
1818 ;; .emacs or .gnus or .viper following a directory delimiter in
1819 ;; Unix, MSDOG or VMS syntax.
1820 ("[]>:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode)
ffc0e1ca
AS
1821 ("\\`\\..*emacs\\'" . emacs-lisp-mode)
1822 ;; _emacs following a directory delimiter
1823 ;; in MsDos syntax
1824 ("[:/]_emacs\\'" . emacs-lisp-mode)
1825 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode)
1826 ("\\.ml\\'" . lisp-mode)
d5798fa7
SM
1827 ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode)
1828 ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode)
ffc0e1ca 1829 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode)
e854cc22 1830 ("\\.\\(dif\\|pat\\)\\'" . diff-mode) ; for MSDOG
d5798fa7 1831 ("\\.[eE]?[pP][sS]\\'" . ps-mode)
e55c4863 1832 ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode)
ffc0e1ca
AS
1833 ("BROWSE\\'" . ebrowse-tree-mode)
1834 ("\\.ebrowse\\'" . ebrowse-tree-mode)
9ee45b2c 1835 ("#\\*mail\\*" . mail-mode)
80174d35
DP
1836 ("\\.g\\'" . antlr-mode)
1837 ("\\.ses\\'" . ses-mode)
1838 ("\\.\\(soa\\|zone\\)\\'" . dns-mode)
1839 ("\\.docbook\\'" . sgml-mode)
00daa381 1840 ("\\.com\\'" . dcl-mode)
80174d35
DP
1841 ("/config\\.\\(?:bat\\|log\\)\\'" . fundamental-mode)
1842 ;; Windows candidates may be opened case sensitively on Unix
1843 ("\\.\\(?:[iI][nN][iI]\\|[lL][sS][tT]\\|[rR][eE][gG]\\|[sS][yY][sS]\\)\\'" . conf-mode)
1844 ("\\.\\(?:desktop\\|la\\)\\'" . conf-unix-mode)
08adf84e 1845 ("\\.ppd\\'" . conf-ppd-mode)
80174d35
DP
1846 ("java.+\\.conf\\'" . conf-javaprop-mode)
1847 ("\\.properties\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-javaprop-mode)
1848 ;; *.cf, *.cfg, *.conf, *.config[.local|.de_DE.UTF8|...], */config
1849 ("[/.]c\\(?:on\\)?f\\(?:i?g\\)?\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-mode)
a35d9075
AS
1850 ("\\`/etc/\\(?:DIR_COLORS\\|ethers\\|.?fstab\\|.*hosts\\|lesskey\\|login\\.?de\\(?:fs\\|vperm\\)\\|magic\\|mtab\\|pam\\.d/.*\\|permissions\\(?:\\.d/.+\\)?\\|protocols\\|rpc\\|services\\)\\'" . conf-space-mode)
1851 ("\\`/etc/\\(?:acpid?/.+\\|aliases\\(?:\\.d/.+\\)?\\|default/.+\\|group-?\\|hosts\\..+\\|inittab\\|ksysguarddrc\\|opera6rc\\|passwd-?\\|shadow-?\\|sysconfig/.+\\)\\'" . conf-mode)
80174d35
DP
1852 ;; either user's dot-files or under /etc or some such
1853 ("/\\.?\\(?:gnokiirc\\|kde.*rc\\|mime\\.types\\|wgetrc\\)\\'" . conf-mode)
1854 ;; alas not all ~/.*rc files are like this
b14f1885 1855 ("/\\.\\(?:enigma\\|gltron\\|gtk\\|hxplayer\\|net\\|neverball\\|qt/.+\\|realplayer\\|scummvm\\|sversion\\|sylpheed/.+\\|xmp\\)rc\\'" . conf-mode)
80174d35
DP
1856 ("/\\.\\(?:gdbtkinit\\|grip\\|orbital/.+txt\\|rhosts\\|tuxracer/options\\)\\'" . conf-mode)
1857 ("/\\.?X\\(?:default\\|resource\\|re\\)s\\>" . conf-xdefaults-mode)
1858 ("/X11.+app-defaults/" . conf-xdefaults-mode)
1859 ("/X11.+locale/.+/Compose\\'" . conf-colon-mode)
1860 ;; this contains everything twice, with space and with colon :-(
1861 ("/X11.+locale/compose\\.dir\\'" . conf-javaprop-mode)
9ee45b2c
SM
1862 ;; Get rid of any trailing .n.m and try again.
1863 ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
5c6d31a4
SM
1864 ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
1865 ;; Using mode nil rather than `ignore' would let the search continue
1866 ;; through this list (with the shortened name) rather than start over.
bbc67516 1867 ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" nil t)
5c6d31a4
SM
1868 ;; The following should come after the ChangeLog pattern
1869 ;; for the sake of ChangeLog.1, etc.
1870 ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
e043664a 1871 ("\\.[1-9]\\'" . nroff-mode)
80174d35 1872 ("\\.\\(?:orig\\|in\\|[bB][aA][kK]\\)\\'" nil t)))
ffc0e1ca 1873 "Alist of filename patterns vs corresponding major mode functions.
116987ba
RS
1874Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1875\(NON-NIL stands for anything that is not nil; the value does not matter.)
1876Visiting a file whose name matches REGEXP specifies FUNCTION as the
1877mode function to use. FUNCTION will be called, unless it is nil.
1878
1879If the element has the form (REGEXP FUNCTION NON-NIL), then after
1880calling FUNCTION (if it's not nil), we delete the suffix that matched
969be033 1881REGEXP and search the list again for another match.
7b3f3dc2 1882
969be033
RS
1883If the file name matches `inhibit-first-line-modes-regexps',
1884then `auto-mode-alist' is not processed.
1885
1886See also `interpreter-mode-alist', which detects executable script modes
1887based on the interpreters they specify to run,
1888and `magic-mode-alist', which determines modes based on file contents.")
e13322a0 1889
d7fa5aa2 1890(defvar interpreter-mode-alist
f209c999
MS
1891 ;; Note: The entries for the modes defined in cc-mode.el (awk-mode
1892 ;; and pike-mode) are added through autoload directives in that
1893 ;; file. That way is discouraged since it spreads out the
1894 ;; definition of the initial value.
ffc0e1ca
AS
1895 (mapc
1896 (lambda (l)
1897 (cons (purecopy (car l)) (cdr l)))
1898 '(("perl" . perl-mode)
1899 ("perl5" . perl-mode)
1900 ("miniperl" . perl-mode)
1901 ("wish" . tcl-mode)
1902 ("wishx" . tcl-mode)
1903 ("tcl" . tcl-mode)
1904 ("tclsh" . tcl-mode)
ffc0e1ca
AS
1905 ("scm" . scheme-mode)
1906 ("ash" . sh-mode)
1907 ("bash" . sh-mode)
1908 ("bash2" . sh-mode)
1909 ("csh" . sh-mode)
1910 ("dtksh" . sh-mode)
1911 ("es" . sh-mode)
1912 ("itcsh" . sh-mode)
1913 ("jsh" . sh-mode)
1914 ("ksh" . sh-mode)
1915 ("oash" . sh-mode)
1916 ("pdksh" . sh-mode)
1917 ("rc" . sh-mode)
1918 ("rpm" . sh-mode)
1919 ("sh" . sh-mode)
1920 ("sh5" . sh-mode)
1921 ("tcsh" . sh-mode)
1922 ("wksh" . sh-mode)
1923 ("wsh" . sh-mode)
1924 ("zsh" . sh-mode)
1925 ("tail" . text-mode)
1926 ("more" . text-mode)
1927 ("less" . text-mode)
1928 ("pg" . text-mode)
1929 ("make" . makefile-mode) ; Debian uses this
1930 ("guile" . scheme-mode)
1931 ("clisp" . lisp-mode)))
c907d156 1932 "Alist mapping interpreter names to major modes.
969be033 1933This is used for files whose first lines match `auto-mode-interpreter-regexp'.
c907d156
RS
1934Each element looks like (INTERPRETER . MODE).
1935The car of each element is compared with
1936the name of the interpreter specified in the first line.
969be033
RS
1937If it matches, mode MODE is selected.
1938
1939See also `auto-mode-alist'.")
c907d156 1940
d7fa5aa2 1941(defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
45fb3bb8 1942 "List of regexps; if one matches a file name, don't look for `-*-'.")
a0c9f21b 1943
d7fa5aa2 1944(defvar inhibit-first-line-modes-suffixes nil
b20ff6d0
RS
1945 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1946When checking `inhibit-first-line-modes-regexps', we first discard
1947from the end of the file name anything that matches one of these regexps.")
1948
ffc0e1ca
AS
1949(defvar auto-mode-interpreter-regexp
1950 "#![ \t]?\\([^ \t\n]*\
1951/bin/env[ \t]\\)?\\([^ \t\n]+\\)"
1952 "Regular expression matching interpreters, for file mode determination.
1953This regular expression is matched against the first line of a file
1954to determine the file's mode in `set-auto-mode' when Emacs can't deduce
1955a mode from the file's name. If it matches, the file is assumed to
1956be interpreted by the interpreter matched by the second group of the
1957regular expression. The mode is then determined as the mode associated
1958with that interpreter in `interpreter-mode-alist'.")
0720b68b 1959
4ac1d37a 1960(defvar magic-mode-alist
32a0479a 1961 `(;; The < comes before the groups (but the first) to reduce backtracking.
4ac1d37a 1962 ;; TODO: UTF-16 <?xml may be preceded by a BOM 0xff 0xfe or 0xfe 0xff.
32a0479a
SM
1963 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
1964 (comment-re (concat "\\(?:!--" incomment-re "*-->\\s *<\\)")))
1965 (concat "\\(?:<\\?xml\\s +[^>]*>\\)?\\s *<"
1966 comment-re "*"
1967 "\\(?:!DOCTYPE\\s +[^>]*>\\s *<\\s *" comment-re "*\\)?"
969be033
RS
1968 "[Hh][Tt][Mm][Ll]"))
1969 . html-mode)
4ac1d37a
DP
1970 ;; These two must come after html, because they are more general:
1971 ("<\\?xml " . xml-mode)
811cab86
JL
1972 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
1973 (comment-re (concat "\\(?:!--" incomment-re "*-->\\s *<\\)")))
969be033
RS
1974 (concat "\\s *<" comment-re "*!DOCTYPE "))
1975 . sgml-mode)
80174d35
DP
1976 ("%![^V]" . ps-mode)
1977 ("# xmcd " . conf-unix-mode))
1978 "Alist of buffer beginnings vs. corresponding major mode functions.
44dce0fb
RS
1979Each element looks like (REGEXP . FUNCTION). After visiting a file,
1980if REGEXP matches the text at the beginning of the buffer,
1981`normal-mode' will call FUNCTION rather than allowing `auto-mode-alist'
1982to decide the buffer's major mode.
1983
1984If FUNCTION is nil, then it is not called. (That is a way of saying
1985\"allow `auto-mode-alist' to decide for these files.")
bbc67516 1986
9e6f5419 1987(defun set-auto-mode (&optional keep-mode-if-same)
b4da00e9 1988 "Select major mode appropriate for current buffer.
4ac1d37a 1989
bbc67516
DP
1990This checks for a -*- mode tag in the buffer's text, checks the
1991interpreter that runs this file against `interpreter-mode-alist',
811cab86
JL
1992compares the buffer beginning against `magic-mode-alist', or
1993compares the filename against the entries in `auto-mode-alist'.
e3998da1
RS
1994
1995It does not check for the `mode:' local variable in the
1996Local Variables section of the file; for that, use `hack-local-variables'.
7b3f3dc2 1997
f3e23606 1998If `enable-local-variables' is nil, this function does not check for a
9de9b6a2
RS
1999-*- mode tag.
2000
521cf174
DP
2001If the optional argument KEEP-MODE-IF-SAME is non-nil, then we
2002only set the major mode, if that would change it."
b4da00e9 2003 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
811cab86 2004 (let (end done mode modes)
9e6f5419
DP
2005 ;; Find a -*- mode tag
2006 (save-excursion
2007 (goto-char (point-min))
2008 (skip-chars-forward " \t\n")
9e6f5419
DP
2009 (and enable-local-variables
2010 (setq end (set-auto-mode-1))
2011 (if (save-excursion (search-forward ":" end t))
2012 ;; Find all specifications for the `mode:' variable
2013 ;; and execute them left to right.
2014 (while (let ((case-fold-search t))
2015 (or (and (looking-at "mode:")
2016 (goto-char (match-end 0)))
2017 (re-search-forward "[ \t;]mode:" end t)))
2018 (skip-chars-forward " \t")
2019 (let ((beg (point)))
2020 (if (search-forward ";" end t)
2021 (forward-char -1)
2022 (goto-char end))
2023 (skip-chars-backward " \t")
2024 (push (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
2025 modes)))
2026 ;; Simple -*-MODE-*- case.
2027 (push (intern (concat (downcase (buffer-substring (point) end))
2028 "-mode"))
2029 modes))))
2030 ;; If we found modes to use, invoke them now, outside the save-excursion.
2031 (if modes
521cf174
DP
2032 (catch 'nop
2033 (dolist (mode (nreverse modes))
2034 (if (not (functionp mode))
2035 (message "Ignoring unknown mode `%s'" mode)
2036 (setq done t)
3467488e 2037 (or (set-auto-mode-0 mode keep-mode-if-same)
df4d0613 2038 ;; continuing would call minor modes again, toggling them off
8a9cdb8d 2039 (throw 'nop nil)))))
9e6f5419
DP
2040 ;; If we didn't, look for an interpreter specified in the first line.
2041 ;; As a special case, allow for things like "#!/bin/env perl", which
2042 ;; finds the interpreter anywhere in $PATH.
2043 (setq mode (save-excursion
2044 (goto-char (point-min))
2045 (if (looking-at auto-mode-interpreter-regexp)
2046 (match-string 2)
2047 ""))
2048 ;; Map interpreter name to a mode, signalling we're done at the
2049 ;; same time.
2050 done (assoc (file-name-nondirectory mode)
df4d0613 2051 interpreter-mode-alist))
811cab86 2052 ;; If we found an interpreter mode to use, invoke it now.
df4d0613
DP
2053 (if done
2054 (set-auto-mode-0 (cdr done) keep-mode-if-same)))
811cab86 2055 ;; If we didn't, match the buffer beginning against magic-mode-alist.
df4d0613 2056 (unless done
4ac1d37a
DP
2057 (if (setq done (save-excursion
2058 (goto-char (point-min))
2059 (assoc-default nil magic-mode-alist
2060 (lambda (re dummy)
2061 (looking-at re)))))
2062 (set-auto-mode-0 done keep-mode-if-same)
811cab86 2063 ;; Compare the filename against the entries in auto-mode-alist.
4ac1d37a
DP
2064 (if buffer-file-name
2065 (let ((name buffer-file-name))
2066 ;; Remove backup-suffixes from file name.
2067 (setq name (file-name-sans-versions name))
2068 (while name
2069 ;; Find first matching alist entry.
2070 (let ((case-fold-search
2071 (memq system-type '(vax-vms windows-nt cygwin))))
2072 (if (and (setq mode (assoc-default name auto-mode-alist
811cab86 2073 'string-match))
4ac1d37a
DP
2074 (consp mode)
2075 (cadr mode))
2076 (setq mode (car mode)
2077 name (substring name 0 (match-beginning 0)))
2078 (setq name)))
2079 (when mode
2080 (set-auto-mode-0 mode keep-mode-if-same)))))))))
521cf174 2081
521cf174
DP
2082;; When `keep-mode-if-same' is set, we are working on behalf of
2083;; set-visited-file-name. In that case, if the major mode specified is the
2084;; same one we already have, don't actually reset it. We don't want to lose
2085;; minor modes such as Font Lock.
3467488e 2086(defun set-auto-mode-0 (mode &optional keep-mode-if-same)
521cf174 2087 "Apply MODE and return it.
3467488e
KS
2088If optional arg KEEP-MODE-IF-SAME is non-nil, MODE is chased of
2089any aliases and compared to current major mode. If they are the
2090same, do nothing and return nil."
521cf174
DP
2091 (when keep-mode-if-same
2092 (while (symbolp (symbol-function mode))
2093 (setq mode (symbol-function mode)))
2094 (if (eq mode major-mode)
3467488e 2095 (setq mode nil)))
521cf174
DP
2096 (when mode
2097 (funcall mode)
2098 mode))
b4da00e9 2099
e3f9b9c0
RS
2100(defun set-auto-mode-1 ()
2101 "Find the -*- spec in the buffer.
2102Call with point at the place to start searching from.
2103If one is found, set point to the beginning
2104and return the position of the end.
2105Otherwise, return nil; point may be changed."
2106 (let (beg end)
2107 (and
2108 ;; Don't look for -*- if this file name matches any
2109 ;; of the regexps in inhibit-first-line-modes-regexps.
2110 (let ((temp inhibit-first-line-modes-regexps)
2111 (name (if buffer-file-name
2112 (file-name-sans-versions buffer-file-name)
2113 (buffer-name))))
2114 (while (let ((sufs inhibit-first-line-modes-suffixes))
2115 (while (and sufs (not (string-match (car sufs) name)))
2116 (setq sufs (cdr sufs)))
2117 sufs)
2118 (setq name (substring name 0 (match-beginning 0))))
2119 (while (and temp
2120 (not (string-match (car temp) name)))
2121 (setq temp (cdr temp)))
2122 (not temp))
2123
f587e30b
SM
2124 (search-forward "-*-" (line-end-position
2125 ;; If the file begins with "#!"
2126 ;; (exec interpreter magic), look
2127 ;; for mode frobs in the first two
2128 ;; lines. You cannot necessarily
2129 ;; put them in the first line of
2130 ;; such a file without screwing up
2131 ;; the interpreter invocation.
2132 (and (looking-at "^#!") 2)) t)
e3f9b9c0
RS
2133 (progn
2134 (skip-chars-forward " \t")
2135 (setq beg (point))
f587e30b 2136 (search-forward "-*-" (line-end-position) t))
e3f9b9c0
RS
2137 (progn
2138 (forward-char -3)
2139 (skip-chars-backward " \t")
2140 (setq end (point))
2141 (goto-char beg)
2142 end))))
2143
a0e74e72 2144(defun hack-local-variables-prop-line (&optional mode-only)
ffc0e1ca
AS
2145 "Set local variables specified in the -*- line.
2146Ignore any specification for `mode:' and `coding:';
2147`set-auto-mode' should already have handled `mode:',
a0e74e72
RS
2148`set-auto-coding' should already have handled `coding:'.
2149If MODE-ONLY is non-nil, all we do is check whether the major mode
2150is specified, returning t if it is specified."
f3e23606
RS
2151 (save-excursion
2152 (goto-char (point-min))
13a66180 2153 (let ((result nil)
e3f9b9c0 2154 (end (set-auto-mode-1))
a0e74e72 2155 mode-specified
aa5fcebf
KH
2156 (enable-local-variables
2157 (and local-enable-local-variables enable-local-variables)))
a0e74e72
RS
2158 ;; Parse the -*- line into the RESULT alist.
2159 ;; Also set MODE-SPECIFIED if we see a spec or `mode'.
e3f9b9c0 2160 (cond ((not end)
f3e23606
RS
2161 nil)
2162 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
13a66180 2163 ;; Simple form: "-*- MODENAME -*-". Already handled.
a0e74e72 2164 (setq mode-specified t)
13a66180 2165 nil)
f3e23606
RS
2166 (t
2167 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
2168 ;; (last ";" is optional).
f3e23606
RS
2169 (while (< (point) end)
2170 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
ffc0e1ca 2171 (error "Malformed -*- line"))
f3e23606 2172 (goto-char (match-end 0))
1c26a6f3
KH
2173 ;; There used to be a downcase here,
2174 ;; but the manual didn't say so,
2175 ;; and people want to set var names that aren't all lc.
2176 (let ((key (intern (buffer-substring
2177 (match-beginning 1)
2178 (match-end 1))))
f3e23606
RS
2179 (val (save-restriction
2180 (narrow-to-region (point) end)
2181 (read (current-buffer)))))
93a2702d
RS
2182 ;; It is traditional to ignore
2183 ;; case when checking for `mode' in set-auto-mode,
2184 ;; so we must do that here as well.
2185 ;; That is inconsistent, but we're stuck with it.
3fa0a9aa 2186 ;; The same can be said for `coding' in set-auto-coding.
93a2702d 2187 (or (equal (downcase (symbol-name key)) "mode")
3fa0a9aa 2188 (equal (downcase (symbol-name key)) "coding")
13a66180 2189 (setq result (cons (cons key val) result)))
a0e74e72
RS
2190 (if (equal (downcase (symbol-name key)) "mode")
2191 (setq mode-specified t))
f3e23606
RS
2192 (skip-chars-forward " \t;")))
2193 (setq result (nreverse result))))
76d5492b 2194
a0e74e72
RS
2195 (if mode-only mode-specified
2196 (if (and result
2197 (or mode-only
2198 (eq enable-local-variables t)
2199 (and enable-local-variables
2200 (save-window-excursion
2201 (condition-case nil
2202 (switch-to-buffer (current-buffer))
2203 (error
2204 ;; If we fail to switch in the selected window,
2205 ;; it is probably a minibuffer.
2206 ;; So try another window.
2207 (condition-case nil
2208 (switch-to-buffer-other-window (current-buffer))
2209 (error
2210 (switch-to-buffer-other-frame (current-buffer))))))
2211 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
2212 (file-name-nondirectory buffer-file-name)))))))
2213 (let ((enable-local-eval enable-local-eval))
2214 (while result
2215 (hack-one-local-variable (car (car result)) (cdr (car result)))
2216 (setq result (cdr result)))))
2217 nil))))
f3e23606 2218
1d517019
RS
2219(defvar hack-local-variables-hook nil
2220 "Normal hook run after processing a file's local variables specs.
2221Major modes can use this to examine user-specified local variables
2222in order to initialize other data structure based on them.")
2223
9de9b6a2
RS
2224(defun hack-local-variables (&optional mode-only)
2225 "Parse and put into effect this buffer's local variables spec.
2226If MODE-ONLY is non-nil, all we do is check whether the major mode
2227is specified, returning t if it is specified."
a0e74e72
RS
2228 (let ((mode-specified
2229 ;; If MODE-ONLY is t, we check here for specifying the mode
2230 ;; in the -*- line. If MODE-ONLY is nil, we process
2231 ;; the -*- line here.
2232 (hack-local-variables-prop-line mode-only))
aa5fcebf
KH
2233 (enable-local-variables
2234 (and local-enable-local-variables enable-local-variables)))
a0e74e72 2235 ;; Look for "Local variables:" line in last page.
9de9b6a2
RS
2236 (save-excursion
2237 (goto-char (point-max))
2238 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
50292b6e
SM
2239 (when (let ((case-fold-search t))
2240 (and (search-forward "Local Variables:" nil t)
2241 (or (eq enable-local-variables t)
2242 mode-only
2243 (and enable-local-variables
2244 (save-window-excursion
2245 (switch-to-buffer (current-buffer))
2246 (save-excursion
2247 (beginning-of-line)
2248 (set-window-start (selected-window) (point)))
2249 (y-or-n-p (format "Set local variables as specified at end of %s? "
2250 (if buffer-file-name
2251 (file-name-nondirectory
2252 buffer-file-name)
2253 (concat "buffer "
2254 (buffer-name))))))))))
2255 (skip-chars-forward " \t")
2256 (let ((enable-local-eval enable-local-eval)
2257 ;; suffix is what comes after "local variables:" in its line.
2258 (suffix
2259 (concat
2260 (regexp-quote (buffer-substring (point) (line-end-position)))
2261 "$"))
2262 ;; prefix is what comes before "local variables:" in its line.
2263 (prefix
2264 (concat "^" (regexp-quote
2265 (buffer-substring (line-beginning-position)
2266 (match-beginning 0)))))
2267 beg)
2268
2269 (forward-line 1)
2270 (let ((startpos (point))
2271 endpos
2272 (thisbuf (current-buffer)))
2273 (save-excursion
5a146628
DP
2274 (unless (let ((case-fold-search t))
2275 (re-search-forward
2276 (concat prefix "[ \t]*End:[ \t]*" suffix)
2277 nil t))
2278 (error "Local variables list is not properly terminated"))
50292b6e
SM
2279 (beginning-of-line)
2280 (setq endpos (point)))
2281
2282 (with-temp-buffer
2283 (insert-buffer-substring thisbuf startpos endpos)
2284 (goto-char (point-min))
2285 (subst-char-in-region (point) (point-max) ?\^m ?\n)
2286 (while (not (eobp))
2287 ;; Discard the prefix.
2288 (if (looking-at prefix)
2289 (delete-region (point) (match-end 0))
2290 (error "Local variables entry is missing the prefix"))
2291 (end-of-line)
2292 ;; Discard the suffix.
2293 (if (looking-back suffix)
2294 (delete-region (match-beginning 0) (point))
2295 (error "Local variables entry is missing the suffix"))
2296 (forward-line 1))
2297 (goto-char (point-min))
2298
2299 (while (not (eobp))
2300 ;; Find the variable name; strip whitespace.
2301 (skip-chars-forward " \t")
2302 (setq beg (point))
2303 (skip-chars-forward "^:\n")
2304 (if (eolp) (error "Missing colon in local variables entry"))
2305 (skip-chars-backward " \t")
2306 (let* ((str (buffer-substring beg (point)))
2307 (var (read str))
2308 val)
2309 ;; Read the variable value.
2310 (skip-chars-forward "^:")
2311 (forward-char 1)
2312 (setq val (read (current-buffer)))
2313 (if mode-only
2314 (if (eq var 'mode)
2315 (setq mode-specified t))
2316 ;; Set the variable. "Variables" mode and eval are funny.
2317 (with-current-buffer thisbuf
2318 (hack-one-local-variable var val))))
2319 (forward-line 1)))))))
9de9b6a2
RS
2320 (unless mode-only
2321 (run-hooks 'hack-local-variables-hook))
2322 mode-specified))
f3e23606 2323
e0b2a2d9 2324(defvar ignored-local-variables ()
f3e23606
RS
2325 "Variables to be ignored in a file's local variable spec.")
2326
be0218a8 2327;; Get confirmation before setting these variables as locals in a file.
05ef1cda 2328(put 'debugger 'risky-local-variable t)
f6fa3ee3 2329(put 'enable-local-eval 'risky-local-variable t)
fce47eea 2330(put 'ignored-local-variables 'risky-local-variable t)
be0218a8
RS
2331(put 'eval 'risky-local-variable t)
2332(put 'file-name-handler-alist 'risky-local-variable t)
7ed9159a 2333(put 'inhibit-quit 'risky-local-variable t)
7078d9d2 2334(put 'minor-mode-alist 'risky-local-variable t)
be0218a8 2335(put 'minor-mode-map-alist 'risky-local-variable t)
7078d9d2
RS
2336(put 'minor-mode-overriding-map-alist 'risky-local-variable t)
2337(put 'overriding-local-map 'risky-local-variable t)
2338(put 'overriding-terminal-local-map 'risky-local-variable t)
2339(put 'auto-mode-alist 'risky-local-variable t)
be0218a8 2340(put 'after-load-alist 'risky-local-variable t)
f6fa3ee3 2341(put 'buffer-file-name 'risky-local-variable t)
7078d9d2 2342(put 'buffer-undo-list 'risky-local-variable t)
f6fa3ee3
RS
2343(put 'buffer-auto-save-file-name 'risky-local-variable t)
2344(put 'buffer-file-truename 'risky-local-variable t)
7078d9d2 2345(put 'default-text-properties 'risky-local-variable t)
b0ffcc0d
RS
2346(put 'exec-path 'risky-local-variable t)
2347(put 'load-path 'risky-local-variable t)
2348(put 'exec-directory 'risky-local-variable t)
2349(put 'process-environment 'risky-local-variable t)
eba1c87a
RS
2350(put 'dabbrev-case-fold-search 'risky-local-variable t)
2351(put 'dabbrev-case-replace 'risky-local-variable t)
9afa8bf7
RS
2352;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
2353(put 'outline-level 'risky-local-variable t)
d98b741d 2354(put 'rmail-output-file-alist 'risky-local-variable t)
f4d04672 2355(put 'font-lock-defaults 'risky-local-variable t)
7078d9d2
RS
2356(put 'special-display-buffer-names 'risky-local-variable t)
2357(put 'frame-title-format 'risky-local-variable t)
2358(put 'global-mode-string 'risky-local-variable t)
2359(put 'header-line-format 'risky-local-variable t)
2360(put 'icon-title-format 'risky-local-variable t)
2361(put 'input-method-alist 'risky-local-variable t)
032388f3 2362(put 'format-alist 'risky-local-variable t)
7078d9d2
RS
2363(put 'vc-mode 'risky-local-variable t)
2364(put 'imenu-generic-expression 'risky-local-variable t)
cfdd394e 2365(put 'imenu--index-alist 'risky-local-variable t)
7078d9d2
RS
2366(put 'standard-input 'risky-local-variable t)
2367(put 'standard-output 'risky-local-variable t)
2368(put 'unread-command-events 'risky-local-variable t)
2369(put 'max-lisp-eval-depth 'risky-local-variable t)
2370(put 'max-specpdl-size 'risky-local-variable t)
ec4ba9e3
RS
2371(put 'mode-line-format 'risky-local-variable t)
2372(put 'mode-line-modified 'risky-local-variable t)
2373(put 'mode-line-mule-info 'risky-local-variable t)
2374(put 'mode-line-buffer-identification 'risky-local-variable t)
2375(put 'mode-line-modes 'risky-local-variable t)
2376(put 'mode-line-position 'risky-local-variable t)
b459083c 2377(put 'mode-line-process 'risky-local-variable t)
fbafc3bd 2378(put 'mode-name 'risky-local-variable t)
2bbbe4f6 2379(put 'display-time-string 'risky-local-variable t)
fecddd0d 2380(put 'parse-time-rules 'risky-local-variable t)
f6fa3ee3 2381
472514b7
RS
2382;; This case is safe because the user gets to check it before it is used.
2383(put 'compile-command 'safe-local-variable 'stringp)
2384
40ebe9bd 2385(defun risky-local-variable-p (sym &optional val)
0d8781d8 2386 "Non-nil if SYM could be dangerous as a file-local variable with value VAL.
40ebe9bd
LT
2387If VAL is nil or omitted, the question is whether any value might be
2388dangerous."
472514b7 2389 (let ((safep (get sym 'safe-local-variable)))
e0b2a2d9 2390 (or (get sym 'risky-local-variable)
472514b7
RS
2391 (and (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$\\|-predicate$\\|font-lock-keywords$\\|font-lock-keywords-[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|-map$\\|-map-alist$"
2392 (symbol-name sym))
2393 (not safep))
2394 ;; If the safe-local-variable property isn't t or nil,
2395 ;; then it must return non-nil on the proposed value to be safe.
2396 (and (not (memq safep '(t nil)))
0d8781d8
RS
2397 (or (null val)
2398 (not (funcall safep val)))))))
7ed9159a 2399
8fd9c174
RS
2400(defcustom safe-local-eval-forms nil
2401 "*Expressions that are considered \"safe\" in an `eval:' local variable.
2402Add expressions to this list if you want Emacs to evaluate them, when
2403they appear in an `eval' local variable specification, without first
2404asking you for confirmation."
2405 :group 'find-file
bf247b6e 2406 :version "22.1"
8fd9c174
RS
2407 :type '(repeat sexp))
2408
ff7affeb
RS
2409(put 'c-set-style 'safe-local-eval-function t)
2410
d0bd3513
RS
2411(defun hack-one-local-variable-quotep (exp)
2412 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
2413
ff7affeb
RS
2414(defun hack-one-local-variable-constantp (exp)
2415 (or (and (not (symbolp exp)) (not (consp exp)))
2416 (memq exp '(t nil))
2417 (keywordp exp)
2418 (hack-one-local-variable-quotep exp)))
2419
2420(defun hack-one-local-variable-eval-safep (exp)
2421 "Return t if it is safe to eval EXP when it is found in a file."
8fd9c174
RS
2422 (or (not (consp exp))
2423 ;; Detect certain `put' expressions.
2424 (and (eq (car exp) 'put)
2425 (hack-one-local-variable-quotep (nth 1 exp))
2426 (hack-one-local-variable-quotep (nth 2 exp))
2427 (memq (nth 1 (nth 2 exp))
2428 '(lisp-indent-hook))
2429 ;; Only allow safe values of lisp-indent-hook;
2430 ;; not functions.
2431 (or (numberp (nth 3 exp))
2432 (equal (nth 3 exp) ''defun)))
2433 ;; Allow expressions that the user requested.
2434 (member exp safe-local-eval-forms)
2435 ;; Certain functions can be allowed with safe arguments
2436 ;; or can specify verification functions to try.
2437 (and (symbolp (car exp))
2438 (let ((prop (get (car exp) 'safe-local-eval-function)))
2439 (cond ((eq prop t)
2440 (let ((ok t))
2441 (dolist (arg (cdr exp))
2442 (unless (hack-one-local-variable-constantp arg)
2443 (setq ok nil)))
2444 ok))
2445 ((functionp prop)
2446 (funcall prop exp))
2447 ((listp prop)
2448 (let ((ok nil))
2449 (dolist (function prop)
2450 (if (funcall function exp)
2451 (setq ok t)))
2452 ok)))))))
ff7affeb 2453
f3e23606 2454(defun hack-one-local-variable (var val)
ffc0e1ca 2455 "\"Set\" one variable in a local variables spec.
7078d9d2
RS
2456A few patterns are specified so that any name which matches one
2457is considered risky."
f3e23606
RS
2458 (cond ((eq var 'mode)
2459 (funcall (intern (concat (downcase (symbol-name val))
2460 "-mode"))))
3fa0a9aa
KH
2461 ((eq var 'coding)
2462 ;; We have already handled coding: tag in set-auto-coding.
2463 nil)
e0b2a2d9
RS
2464 ((memq var ignored-local-variables)
2465 nil)
f3e23606 2466 ;; "Setting" eval means either eval it or do nothing.
7d3221d7 2467 ;; Likewise for setting hook variables.
472514b7 2468 ((risky-local-variable-p var val)
0225ae5e 2469 ;; Permit evalling a put of a harmless property.
d0bd3513
RS
2470 ;; if the args do nothing tricky.
2471 (if (or (and (eq var 'eval)
ff7affeb 2472 (hack-one-local-variable-eval-safep val))
d0bd3513 2473 ;; Permit eval if not root and user says ok.
c7e62660 2474 (and (not (zerop (user-uid)))
d0bd3513
RS
2475 (or (eq enable-local-eval t)
2476 (and enable-local-eval
2477 (save-window-excursion
2478 (switch-to-buffer (current-buffer))
2479 (save-excursion
2480 (beginning-of-line)
2481 (set-window-start (selected-window) (point)))
2482 (setq enable-local-eval
abf16d5e
RS
2483 (y-or-n-p (format "Process `eval' or hook local variables in %s? "
2484 (if buffer-file-name
2485 (concat "file " (file-name-nondirectory buffer-file-name))
2486 (concat "buffer " (buffer-name)))))))))))
7d3221d7
RS
2487 (if (eq var 'eval)
2488 (save-excursion (eval val))
2489 (make-local-variable var)
2490 (set var val))
472514b7 2491 (message "Ignoring risky spec in the local variables list")))
f3e23606
RS
2492 ;; Ordinary variable, really set it.
2493 (t (make-local-variable var)
87a6a5d8
RS
2494 ;; Make sure the string has no text properties.
2495 ;; Some text properties can get evaluated in various ways,
2496 ;; so it is risky to put them on with a local variable list.
2497 (if (stringp val)
2498 (set-text-properties 0 (length val) nil val))
f3e23606
RS
2499 (set var val))))
2500
b4da00e9 2501\f
21540597 2502(defcustom change-major-mode-with-file-name t
9de9b6a2
RS
2503 "*Non-nil means \\[write-file] should set the major mode from the file name.
2504However, the mode will not be changed if
2505\(1) a local variables list or the `-*-' line specifies a major mode, or
2506\(2) the current major mode is a \"special\" mode,
8609911b 2507\ not suitable for ordinary files, or
21540597
RS
2508\(3) the new file name does not particularly specify any mode."
2509 :type 'boolean
2510 :group 'editing-basics)
9de9b6a2 2511
f36012a6 2512(defun set-visited-file-name (filename &optional no-query along-with-file)
b4da00e9
RM
2513 "Change name of file visited in current buffer to FILENAME.
2514The next time the buffer is saved it will go in the newly specified file.
814af837 2515FILENAME nil or an empty string means make buffer not be visiting any file.
b4da00e9 2516Remember to delete the initial contents of the minibuffer
6a6b62f8
RS
2517if you wish to pass an empty string as the argument.
2518
2519The optional second argument NO-QUERY, if non-nil, inhibits asking for
f36012a6
RS
2520confirmation in the case where another buffer is already visiting FILENAME.
2521
2522The optional third argument ALONG-WITH-FILE, if non-nil, means that
2523the old visited file has been renamed to the new name FILENAME."
b4da00e9 2524 (interactive "FSet visited file name: ")
c11a94fe
RS
2525 (if (buffer-base-buffer)
2526 (error "An indirect buffer cannot visit a file"))
a522e5bf
RS
2527 (let (truename)
2528 (if filename
2529 (setq filename
2530 (if (string-equal filename "")
2531 nil
2532 (expand-file-name filename))))
2533 (if filename
2534 (progn
2535 (setq truename (file-truename filename))
2536 (if find-file-visit-truename
a522e5bf 2537 (setq filename truename))))
11e314fa 2538 (let ((buffer (and filename (find-buffer-visiting filename))))
7b89d38e 2539 (and buffer (not (eq buffer (current-buffer)))
6a6b62f8 2540 (not no-query)
7b89d38e
RS
2541 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
2542 filename)))
2543 (error "Aborted")))
a522e5bf
RS
2544 (or (equal filename buffer-file-name)
2545 (progn
2546 (and filename (lock-buffer filename))
2547 (unlock-buffer)))
2548 (setq buffer-file-name filename)
2549 (if filename ; make buffer name reflect filename.
2550 (let ((new-name (file-name-nondirectory buffer-file-name)))
2551 (if (string= new-name "")
2552 (error "Empty file name"))
2553 (if (eq system-type 'vax-vms)
2554 (setq new-name (downcase new-name)))
2555 (setq default-directory (file-name-directory buffer-file-name))
67b6fd1c
SM
2556 ;; If new-name == old-name, renaming would add a spurious <2>
2557 ;; and it's considered as a feature in rename-buffer.
a522e5bf
RS
2558 (or (string= new-name (buffer-name))
2559 (rename-buffer new-name t))))
2560 (setq buffer-backed-up nil)
f36012a6
RS
2561 (or along-with-file
2562 (clear-visited-file-modtime))
8ccdc29e 2563 ;; Abbreviate the file names of the buffer.
4826e97f 2564 (if truename
8ccdc29e
RS
2565 (progn
2566 (setq buffer-file-truename (abbreviate-file-name truename))
2567 (if find-file-visit-truename
b1f1ceb8 2568 (setq buffer-file-name truename))))
a522e5bf
RS
2569 (setq buffer-file-number
2570 (if filename
2a47b4f5 2571 (nthcdr 10 (file-attributes buffer-file-name))
a522e5bf 2572 nil)))
0370fe77 2573 ;; write-file-functions is normally used for things like ftp-find-file
b4da00e9
RM
2574 ;; that visit things that are not local files as if they were files.
2575 ;; Changing to visit an ordinary local file instead should flush the hook.
0370fe77 2576 (kill-local-variable 'write-file-functions)
c9dca4e0 2577 (kill-local-variable 'local-write-file-hooks)
b4da00e9
RM
2578 (kill-local-variable 'revert-buffer-function)
2579 (kill-local-variable 'backup-inhibited)
ee81c959
RS
2580 ;; If buffer was read-only because of version control,
2581 ;; that reason is gone now, so make it writable.
2582 (if vc-mode
2583 (setq buffer-read-only nil))
2584 (kill-local-variable 'vc-mode)
b4da00e9
RM
2585 ;; Turn off backup files for certain file names.
2586 ;; Since this is a permanent local, the major mode won't eliminate it.
4d49551a
KH
2587 (and buffer-file-name
2588 (not (funcall backup-enable-predicate buffer-file-name))
b4da00e9
RM
2589 (progn
2590 (make-local-variable 'backup-inhibited)
2591 (setq backup-inhibited t)))
c77a81cf
RS
2592 (let ((oauto buffer-auto-save-file-name))
2593 ;; If auto-save was not already on, turn it on if appropriate.
2594 (if (not buffer-auto-save-file-name)
2595 (and buffer-file-name auto-save-default
2596 (auto-save-mode t))
2597 ;; If auto save is on, start using a new name.
2598 ;; We deliberately don't rename or delete the old auto save
2599 ;; for the old visited file name. This is because perhaps
2600 ;; the user wants to save the new state and then compare with the
2601 ;; previous state from the auto save file.
2602 (setq buffer-auto-save-file-name
2603 (make-auto-save-file-name)))
2604 ;; Rename the old auto save file if any.
2605 (and oauto buffer-auto-save-file-name
e6f0e76c 2606 (file-exists-p oauto)
c77a81cf 2607 (rename-file oauto buffer-auto-save-file-name t)))
f36012a6
RS
2608 (and buffer-file-name
2609 (not along-with-file)
9de9b6a2
RS
2610 (set-buffer-modified-p t))
2611 ;; Update the major mode, if the file name determines it.
2612 (condition-case nil
2613 ;; Don't change the mode if it is special.
2614 (or (not change-major-mode-with-file-name)
2615 (get major-mode 'mode-class)
2616 ;; Don't change the mode if the local variable list specifies it.
2617 (hack-local-variables t)
2618 (set-auto-mode t))
2619 (error nil)))
b4da00e9 2620
912192d1 2621(defun write-file (filename &optional confirm)
b4da00e9 2622 "Write current buffer into file FILENAME.
7f99999a 2623This makes the buffer visit that file, and marks it as not modified.
7458cc35 2624
7f99999a
KH
2625If you specify just a directory name as FILENAME, that means to use
2626the default file name but in that directory. You can also yank
074eb6ac 2627the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
7f99999a
KH
2628
2629If the buffer is not already visiting a file, the default file name
2630for the output file is the buffer name.
2631
2632If optional second arg CONFIRM is non-nil, this function
2633asks for confirmation before overwriting an existing file.
912192d1 2634Interactively, confirmation is required unless you supply a prefix argument."
b4da00e9
RM
2635;; (interactive "FWrite file: ")
2636 (interactive
2637 (list (if buffer-file-name
2638 (read-file-name "Write file: "
2639 nil nil nil nil)
7f99999a
KH
2640 (read-file-name "Write file: " default-directory
2641 (expand-file-name
2642 (file-name-nondirectory (buffer-name))
2643 default-directory)
2644 nil nil))
912192d1 2645 (not current-prefix-arg)))
b4da00e9 2646 (or (null filename) (string-equal filename "")
41f48cb1
RS
2647 (progn
2648 ;; If arg is just a directory,
7f99999a
KH
2649 ;; use the default file name, but in that directory.
2650 (if (file-directory-p filename)
41f48cb1 2651 (setq filename (concat (file-name-as-directory filename)
7f99999a
KH
2652 (file-name-nondirectory
2653 (or buffer-file-name (buffer-name))))))
c2fb8488
RS
2654 (and confirm
2655 (file-exists-p filename)
2656 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
2657 (error "Canceled")))
5f65549e 2658 (set-visited-file-name filename (not confirm))))
b4da00e9 2659 (set-buffer-modified-p t)
6492b55d
KH
2660 ;; Make buffer writable if file is writable.
2661 (and buffer-file-name
2662 (file-writable-p buffer-file-name)
2663 (setq buffer-read-only nil))
912192d1 2664 (save-buffer))
b4da00e9
RM
2665\f
2666(defun backup-buffer ()
2667 "Make a backup of the disk file visited by the current buffer, if appropriate.
2668This is normally done before saving the buffer the first time.
27ab6944
KH
2669
2670A backup may be done by renaming or by copying; see documentation of
2671variable `make-backup-files'. If it's done by renaming, then the file is
f3f9e207
RS
2672no longer accessible under its old name.
2673
2674The value is non-nil after a backup was made by renaming.
2675It has the form (MODES . BACKUPNAME).
2676MODES is the result of `file-modes' on the original
2677file; this means that the caller, after saving the buffer, should change
2678the modes of the new file to agree with the old modes.
2679BACKUPNAME is the backup file name, which is the old file renamed."
b4da00e9
RM
2680 (if (and make-backup-files (not backup-inhibited)
2681 (not buffer-backed-up)
2682 (file-exists-p buffer-file-name)
2683 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
2684 '(?- ?l)))
2685 (let ((real-file-name buffer-file-name)
2686 backup-info backupname targets setmodes)
2687 ;; If specified name is a symbolic link, chase it to the target.
2688 ;; Thus we make the backups in the directory where the real file is.
5dadeb29 2689 (setq real-file-name (file-chase-links real-file-name))
b4da00e9
RM
2690 (setq backup-info (find-backup-file-name real-file-name)
2691 backupname (car backup-info)
2692 targets (cdr backup-info))
5c6d31a4
SM
2693 ;; (if (file-directory-p buffer-file-name)
2694 ;; (error "Cannot save buffer in directory %s" buffer-file-name))
eb650569
RS
2695 (if backup-info
2696 (condition-case ()
2697 (let ((delete-old-versions
2698 ;; If have old versions to maybe delete,
2699 ;; ask the user to confirm now, before doing anything.
2700 ;; But don't actually delete til later.
2701 (and targets
2702 (or (eq delete-old-versions t) (eq delete-old-versions nil))
2703 (or delete-old-versions
2704 (y-or-n-p (format "Delete excess backup versions of %s? "
446c63b0
RS
2705 real-file-name)))))
2706 (modes (file-modes buffer-file-name)))
eb650569
RS
2707 ;; Actually write the back up file.
2708 (condition-case ()
2709 (if (or file-precious-flag
ffc0e1ca 2710 ; (file-symlink-p buffer-file-name)
eb650569 2711 backup-by-copying
446c63b0 2712 ;; Don't rename a suid or sgid file.
7da6bf00 2713 (and modes (< 0 (logand modes #o6000)))
79d2d279 2714 (not (file-writable-p (file-name-directory real-file-name)))
eb650569
RS
2715 (and backup-by-copying-when-linked
2716 (> (file-nlinks real-file-name) 1))
ffc0e1ca
AS
2717 (and (or backup-by-copying-when-mismatch
2718 (integerp backup-by-copying-when-privileged-mismatch))
eb650569 2719 (let ((attr (file-attributes real-file-name)))
ffc0e1ca
AS
2720 (and (or backup-by-copying-when-mismatch
2721 (and (integerp (nth 2 attr))
2722 (integerp backup-by-copying-when-privileged-mismatch)
2723 (<= (nth 2 attr) backup-by-copying-when-privileged-mismatch)))
2724 (or (nth 9 attr)
2725 (not (file-ownership-preserved-p real-file-name)))))))
446c63b0 2726 (backup-buffer-copy real-file-name backupname modes)
eb650569
RS
2727 ;; rename-file should delete old backup.
2728 (rename-file real-file-name backupname t)
446c63b0 2729 (setq setmodes (cons modes backupname)))
eb650569
RS
2730 (file-error
2731 ;; If trouble writing the backup, write it in ~.
567c1ca9
RS
2732 (setq backupname (expand-file-name
2733 (convert-standard-filename
2734 "~/%backup%~")))
2735 (message "Cannot write backup file; backing up in %s"
2736 (file-name-nondirectory backupname))
eb650569 2737 (sleep-for 1)
446c63b0 2738 (backup-buffer-copy real-file-name backupname modes)))
eb650569
RS
2739 (setq buffer-backed-up t)
2740 ;; Now delete the old versions, if desired.
2741 (if delete-old-versions
2742 (while targets
2743 (condition-case ()
2744 (delete-file (car targets))
2745 (file-error nil))
2746 (setq targets (cdr targets))))
2747 setmodes)
2748 (file-error nil))))))
b4da00e9 2749
446c63b0 2750(defun backup-buffer-copy (from-name to-name modes)
44dce0fb
RS
2751 (let ((umask (default-file-modes)))
2752 (unwind-protect
2753 (progn
2754 ;; Create temp files with strict access rights. It's easy to
2755 ;; loosen them later, whereas it's impossible to close the
2756 ;; time-window of loose permissions otherwise.
2757 (set-default-file-modes ?\700)
2758 (while (condition-case ()
2759 (progn
2760 (condition-case nil
2761 (delete-file to-name)
2762 (file-error nil))
2763 (write-region "" nil to-name nil 'silent nil 'excl)
2764 nil)
2765 (file-already-exists t))
2766 ;; the file was somehow created by someone else between
2767 ;; `make-temp-name' and `write-region', let's try again.
2768 nil)
1441edfe
EZ
2769; (copy-file from-name to-name t t 'excl))
2770 (copy-file from-name to-name t t))
44dce0fb
RS
2771 ;; Reset the umask.
2772 (set-default-file-modes umask)))
147fbf70
RS
2773 (and modes
2774 (set-file-modes to-name (logand modes #o1777))))
446c63b0 2775
c3554e95 2776(defun file-name-sans-versions (name &optional keep-backup-version)
ffc0e1ca 2777 "Return file NAME sans backup versions or strings.
b4da00e9 2778This is a separate procedure so your site-init or startup file can
c3554e95
RS
2779redefine it.
2780If the optional argument KEEP-BACKUP-VERSION is non-nil,
2781we do not remove backup version numbers, only true file version numbers."
6eaebaa2 2782 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
c3554e95
RS
2783 (if handler
2784 (funcall handler 'file-name-sans-versions name keep-backup-version)
2785 (substring name 0
2786 (if (eq system-type 'vax-vms)
2787 ;; VMS version number is (a) semicolon, optional
2788 ;; sign, zero or more digits or (b) period, option
2789 ;; sign, zero or more digits, provided this is the
2790 ;; second period encountered outside of the
2791 ;; device/directory part of the file name.
26add1bf
KH
2792 (or (string-match ";[-+]?[0-9]*\\'" name)
2793 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
c3554e95
RS
2794 name)
2795 (match-beginning 1))
2796 (length name))
2797 (if keep-backup-version
2798 (length name)
dbb12f2c 2799 (or (string-match "\\.~[0-9.]+~\\'" name)
c3554e95
RS
2800 (string-match "~\\'" name)
2801 (length name))))))))
b4da00e9 2802
cb0cd911 2803(defun file-ownership-preserved-p (file)
ffc0e1ca 2804 "Return t if deleting FILE and rewriting it would preserve the owner."
cb0cd911
RS
2805 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
2806 (if handler
2807 (funcall handler 'file-ownership-preserved-p file)
ec5533be 2808 (let ((attributes (file-attributes file)))
306faa42
RS
2809 ;; Return t if the file doesn't exist, since it's true that no
2810 ;; information would be lost by an (attempted) delete and create.
2811 (or (null attributes)
2812 (= (nth 2 attributes) (user-uid)))))))
cb0cd911 2813
20b5d24c
RS
2814(defun file-name-sans-extension (filename)
2815 "Return FILENAME sans final \"extension\".
2531b0c3
EZ
2816The extension, in a file name, is the part that follows the last `.',
2817except that a leading `.', if any, doesn't count."
20b5d24c
RS
2818 (save-match-data
2819 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
2820 directory)
2531b0c3
EZ
2821 (if (and (string-match "\\.[^.]*\\'" file)
2822 (not (eq 0 (match-beginning 0))))
20b5d24c 2823 (if (setq directory (file-name-directory filename))
6ee24f1e
RS
2824 ;; Don't use expand-file-name here; if DIRECTORY is relative,
2825 ;; we don't want to expand it.
2826 (concat directory (substring file 0 (match-beginning 0)))
20b5d24c
RS
2827 (substring file 0 (match-beginning 0)))
2828 filename))))
2829
93a2702d
RS
2830(defun file-name-extension (filename &optional period)
2831 "Return FILENAME's final \"extension\".
2531b0c3
EZ
2832The extension, in a file name, is the part that follows the last `.',
2833except that a leading `.', if any, doesn't count.
93a2702d
RS
2834Return nil for extensionless file names such as `foo'.
2835Return the empty string for file names such as `foo.'.
2836
2837If PERIOD is non-nil, then the returned value includes the period
2838that delimits the extension, and if FILENAME has no extension,
2839the value is \"\"."
2840 (save-match-data
2841 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
2531b0c3
EZ
2842 (if (and (string-match "\\.[^.]*\\'" file)
2843 (not (eq 0 (match-beginning 0))))
93a2702d
RS
2844 (substring file (+ (match-beginning 0) (if period 0 1)))
2845 (if period
2846 "")))))
2847
ffc0e1ca
AS
2848(defcustom make-backup-file-name-function nil
2849 "A function to use instead of the default `make-backup-file-name'.
2850A value of nil gives the default `make-backup-file-name' behaviour.
2851
d5798fa7 2852This could be buffer-local to do something special for specific
ffc0e1ca
AS
2853files. If you define it, you may need to change `backup-file-name-p'
2854and `file-name-sans-versions' too.
2855
2856See also `backup-directory-alist'."
2857 :group 'backup
2858 :type '(choice (const :tag "Default" nil)
2859 (function :tag "Your function")))
2860
2861(defcustom backup-directory-alist nil
2862 "Alist of filename patterns and backup directory names.
2863Each element looks like (REGEXP . DIRECTORY). Backups of files with
2864names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
2865relative or absolute. If it is absolute, so that all matching files
2866are backed up into the same directory, the file names in this
2867directory will be the full name of the file backed up with all
2868directory separators changed to `!' to prevent clashes. This will not
2869work correctly if your filesystem truncates the resulting name.
2870
2871For the common case of all backups going into one directory, the alist
2872should contain a single element pairing \".\" with the appropriate
2873directory name.
2874
2875If this variable is nil, or it fails to match a filename, the backup
2876is made in the original file's directory.
2877
2878On MS-DOS filesystems without long names this variable is always
2879ignored."
2880 :group 'backup
dca5e71d 2881 :type '(repeat (cons (regexp :tag "Regexp matching filename")
ffc0e1ca
AS
2882 (directory :tag "Backup directory name"))))
2883
388d6ab5
RS
2884(defun normal-backup-enable-predicate (name)
2885 "Default `backup-enable-predicate' function.
0c2f6dda
RS
2886Checks for files in `temporary-file-directory',
2887`small-temporary-file-directory', and /tmp."
388d6ab5
RS
2888 (not (or (let ((comp (compare-strings temporary-file-directory 0 nil
2889 name 0 nil)))
2890 ;; Directory is under temporary-file-directory.
2891 (and (not (eq comp t))
2892 (< comp (- (length temporary-file-directory)))))
0c2f6dda
RS
2893 (let ((comp (compare-strings "/tmp" 0 nil
2894 name 0 nil)))
2895 ;; Directory is under /tmp.
2896 (and (not (eq comp t))
2897 (< comp (- (length "/tmp")))))
388d6ab5
RS
2898 (if small-temporary-file-directory
2899 (let ((comp (compare-strings small-temporary-file-directory
2900 0 nil
2901 name 0 nil)))
2902 ;; Directory is under small-temporary-file-directory.
2903 (and (not (eq comp t))
2904 (< comp (- (length small-temporary-file-directory)))))))))
2905
b4da00e9
RM
2906(defun make-backup-file-name (file)
2907 "Create the non-numeric backup file name for FILE.
ffc0e1ca
AS
2908Normally this will just be the file's name with `~' appended.
2909Customization hooks are provided as follows.
2910
2911If the variable `make-backup-file-name-function' is non-nil, its value
2912should be a function which will be called with FILE as its argument;
2913the resulting name is used.
2914
2915Otherwise a match for FILE is sought in `backup-directory-alist'; see
2916the documentation of that variable. If the directory for the backup
2917doesn't exist, it is created."
2918 (if make-backup-file-name-function
2919 (funcall make-backup-file-name-function file)
2920 (if (and (eq system-type 'ms-dos)
2921 (not (msdos-long-file-names)))
2922 (let ((fn (file-name-nondirectory file)))
2923 (concat (file-name-directory file)
2924 (or (and (string-match "\\`[^.]+\\'" fn)
2925 (concat (match-string 0 fn) ".~"))
2926 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
2927 (concat (match-string 0 fn) "~")))))
2928 (concat (make-backup-file-name-1 file) "~"))))
2929
2930(defun make-backup-file-name-1 (file)
2931 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
2932 (let ((alist backup-directory-alist)
818286f4 2933 elt backup-directory)
ffc0e1ca
AS
2934 (while alist
2935 (setq elt (pop alist))
2936 (if (string-match (car elt) file)
2937 (setq backup-directory (cdr elt)
2938 alist nil)))
ee291b46 2939 (if (and backup-directory (not (file-exists-p backup-directory)))
ffc0e1ca
AS
2940 (condition-case nil
2941 (make-directory backup-directory 'parents)
ee291b46
RS
2942 (file-error (setq backup-directory nil))))
2943 (if (null backup-directory)
2944 file
ffc0e1ca
AS
2945 (if (file-name-absolute-p backup-directory)
2946 (progn
c60ee5e7 2947 (when (memq system-type '(windows-nt ms-dos cygwin))
d7b6ca4a
RS
2948 ;; Normalize DOSish file names: downcase the drive
2949 ;; letter, if any, and replace the leading "x:" with
2950 ;; "/drive_x".
ffc0e1ca
AS
2951 (or (file-name-absolute-p file)
2952 (setq file (expand-file-name file))) ; make defaults explicit
2953 ;; Replace any invalid file-name characters (for the
2954 ;; case of backing up remote files).
446c097e 2955 (setq file (expand-file-name (convert-standard-filename file)))
ffc0e1ca 2956 (if (eq (aref file 1) ?:)
d7b6ca4a 2957 (setq file (concat "/"
ffc0e1ca
AS
2958 "drive_"
2959 (char-to-string (downcase (aref file 0)))
d7b6ca4a 2960 (if (eq (aref file 2) ?/)
ffc0e1ca 2961 ""
d7b6ca4a 2962 "/")
ffc0e1ca
AS
2963 (substring file 2)))))
2964 ;; Make the name unique by substituting directory
2965 ;; separators. It may not really be worth bothering about
2966 ;; doubling `!'s in the original name...
2967 (expand-file-name
2968 (subst-char-in-string
d7b6ca4a 2969 ?/ ?!
ffc0e1ca
AS
2970 (replace-regexp-in-string "!" "!!" file))
2971 backup-directory))
2972 (expand-file-name (file-name-nondirectory file)
2973 (file-name-as-directory
2974 (expand-file-name backup-directory
2975 (file-name-directory file))))))))
b4da00e9
RM
2976
2977(defun backup-file-name-p (file)
2978 "Return non-nil if FILE is a backup file name (numeric or not).
2979This is a separate function so you can redefine it for customization.
2980You may need to redefine `file-name-sans-versions' as well."
066327ae 2981 (string-match "~\\'" file))
b4da00e9 2982
e2b30772
RS
2983(defvar backup-extract-version-start)
2984
2d051399 2985;; This is used in various files.
a7aa942a
KH
2986;; The usage of backup-extract-version-start is not very clean,
2987;; but I can't see a good alternative, so as of now I am leaving it alone.
2d051399 2988(defun backup-extract-version (fn)
ffc0e1ca 2989 "Given the name of a numeric backup file, FN, return the backup number.
e2b30772 2990Uses the free variable `backup-extract-version-start', whose value should be
2d051399 2991the index in the name where the version number begins."
e2b30772
RS
2992 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
2993 (= (match-beginning 0) backup-extract-version-start))
2994 (string-to-int (substring fn backup-extract-version-start -1))
2d051399
RS
2995 0))
2996
b4da00e9
RM
2997;; I believe there is no need to alter this behavior for VMS;
2998;; since backup files are not made on VMS, it should not get called.
2999(defun find-backup-file-name (fn)
ffc0e1ca 3000 "Find a file name for a backup file FN, and suggestions for deletions.
b4da00e9 3001Value is a list whose car is the name for the backup file
ffc0e1ca
AS
3002and whose cdr is a list of old versions to consider deleting now.
3003If the value is nil, don't make a backup.
3004Uses `backup-directory-alist' in the same way as does
3005`make-backup-file-name'."
eb650569
RS
3006 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
3007 ;; Run a handler for this function so that ange-ftp can refuse to do it.
3008 (if handler
3009 (funcall handler 'find-backup-file-name fn)
f26d858e
EZ
3010 (if (or (eq version-control 'never)
3011 ;; We don't support numbered backups on plain MS-DOS
3012 ;; when long file names are unavailable.
3013 (and (eq system-type 'ms-dos)
3014 (not (msdos-long-file-names))))
b4da00e9 3015 (list (make-backup-file-name fn))
ffc0e1ca
AS
3016 (let* ((basic-name (make-backup-file-name-1 fn))
3017 (base-versions (concat (file-name-nondirectory basic-name)
3018 ".~"))
e2b30772 3019 (backup-extract-version-start (length base-versions))
eb650569 3020 (high-water-mark 0)
ffc0e1ca
AS
3021 (number-to-delete 0)
3022 possibilities deserve-versions-p versions)
eb650569
RS
3023 (condition-case ()
3024 (setq possibilities (file-name-all-completions
3025 base-versions
ffc0e1ca
AS
3026 (file-name-directory basic-name))
3027 versions (sort (mapcar #'backup-extract-version
3028 possibilities)
3029 #'<)
eb650569
RS
3030 high-water-mark (apply 'max 0 versions)
3031 deserve-versions-p (or version-control
3032 (> high-water-mark 0))
3033 number-to-delete (- (length versions)
ffc0e1ca
AS
3034 kept-old-versions
3035 kept-new-versions
3036 -1))
3037 (file-error (setq possibilities nil)))
eb650569 3038 (if (not deserve-versions-p)
8767d866 3039 (list (make-backup-file-name fn))
ffc0e1ca 3040 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
eb650569
RS
3041 (if (and (> number-to-delete 0)
3042 ;; Delete nothing if there is overflow
3043 ;; in the number of versions to keep.
3044 (>= (+ kept-new-versions kept-old-versions -1) 0))
ffc0e1ca
AS
3045 (mapcar (lambda (n)
3046 (format "%s.~%d~" basic-name n))
eb650569
RS
3047 (let ((v (nthcdr kept-old-versions versions)))
3048 (rplacd (nthcdr (1- number-to-delete) v) ())
3049 v))))))))))
b4da00e9 3050
b4da00e9
RM
3051(defun file-nlinks (filename)
3052 "Return number of names file FILENAME has."
3053 (car (cdr (file-attributes filename))))
6c636af9 3054
753ad988
KG
3055;; (defun file-relative-name (filename &optional directory)
3056;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
3057;; This function returns a relative file name which is equivalent to FILENAME
3058;; when used with that default directory as the default.
3059;; If this is impossible (which can happen on MSDOS and Windows
3060;; when the file name and directory use different drive names)
3061;; then it returns FILENAME."
3062;; (save-match-data
3063;; (let ((fname (expand-file-name filename)))
3064;; (setq directory (file-name-as-directory
3065;; (expand-file-name (or directory default-directory))))
3066;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
3067;; ;; drive names, they can't be relative, so return the absolute name.
3068;; (if (and (or (eq system-type 'ms-dos)
3069;; (eq system-type 'cygwin)
3070;; (eq system-type 'windows-nt))
3071;; (not (string-equal (substring fname 0 2)
3072;; (substring directory 0 2))))
3073;; filename
3074;; (let ((ancestor ".")
3075;; (fname-dir (file-name-as-directory fname)))
3076;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
3077;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
3078;; (setq directory (file-name-directory (substring directory 0 -1))
3079;; ancestor (if (equal ancestor ".")
3080;; ".."
3081;; (concat "../" ancestor))))
3082;; ;; Now ancestor is empty, or .., or ../.., etc.
3083;; (if (string-match (concat "^" (regexp-quote directory)) fname)
3084;; ;; We matched within FNAME's directory part.
3085;; ;; Add the rest of FNAME onto ANCESTOR.
3086;; (let ((rest (substring fname (match-end 0))))
3087;; (if (and (equal ancestor ".")
3088;; (not (equal rest "")))
3089;; ;; But don't bother with ANCESTOR if it would give us `./'.
3090;; rest
3091;; (concat (file-name-as-directory ancestor) rest)))
3092;; ;; We matched FNAME's directory equivalent.
3093;; ancestor))))))
3094
6c636af9 3095(defun file-relative-name (filename &optional directory)
ffc0e1ca 3096 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
2d6562a5
RS
3097This function returns a relative file name which is equivalent to FILENAME
3098when used with that default directory as the default.
753ad988 3099If FILENAME and DIRECTORY lie on different machines or on different drives
493c98af 3100on a DOS/Windows machine, it returns FILENAME on expanded form."
96c188b0 3101 (save-match-data
753ad988
KG
3102 (setq directory
3103 (file-name-as-directory (expand-file-name (or directory
3104 default-directory))))
3105 (setq filename (expand-file-name filename))
3f788773
KG
3106 (let ((fremote (file-remote-p filename))
3107 (dremote (file-remote-p directory)))
493c98af
KG
3108 (if ;; Conditions for separate trees
3109 (or
3110 ;; Test for different drives on DOS/Windows
3111 (and
7c64272b 3112 ;; Should `cygwin' really be included here? --stef
493c98af 3113 (memq system-type '(ms-dos cygwin windows-nt))
7c64272b 3114 (not (eq t (compare-strings filename 0 2 directory 0 2))))
493c98af 3115 ;; Test for different remote file system identification
3f788773 3116 (not (equal fremote dremote)))
e2b30772 3117 filename
753ad988
KG
3118 (let ((ancestor ".")
3119 (filename-dir (file-name-as-directory filename)))
7c64272b
SM
3120 (while (not
3121 (or
3122 (eq t (compare-strings filename-dir nil (length directory)
3123 directory nil nil case-fold-search))
3124 (eq t (compare-strings filename nil (length directory)
3125 directory nil nil case-fold-search))))
753ad988 3126 (setq directory (file-name-directory (substring directory 0 -1))
9695aac6
RS
3127 ancestor (if (equal ancestor ".")
3128 ".."
3129 (concat "../" ancestor))))
753ad988 3130 ;; Now ancestor is empty, or .., or ../.., etc.
7c64272b
SM
3131 (if (eq t (compare-strings filename nil (length directory)
3132 directory nil nil case-fold-search))
753ad988
KG
3133 ;; We matched within FILENAME's directory part.
3134 ;; Add the rest of FILENAME onto ANCESTOR.
3f7d6528 3135 (let ((rest (substring filename (length directory))))
753ad988 3136 (if (and (equal ancestor ".") (not (equal rest "")))
9695aac6
RS
3137 ;; But don't bother with ANCESTOR if it would give us `./'.
3138 rest
3139 (concat (file-name-as-directory ancestor) rest)))
753ad988
KG
3140 ;; We matched FILENAME's directory equivalent.
3141 ancestor))))))
b4da00e9
RM
3142\f
3143(defun save-buffer (&optional args)
9dce96b5 3144 "Save current buffer in visited file if modified. Variations are described below.
b4da00e9
RM
3145By default, makes the previous version into a backup file
3146 if previously requested or if this is the first save.
dc2ab26e 3147Prefixed with one \\[universal-argument], marks this version
b4da00e9 3148 to become a backup when the next save is done.
dc2ab26e 3149Prefixed with two \\[universal-argument]'s,
b4da00e9 3150 unconditionally makes the previous version into a backup file.
dc2ab26e 3151Prefixed with three \\[universal-argument]'s, marks this version
ac9650be
RS
3152 to become a backup when the next save is done,
3153 and unconditionally makes the previous version into a backup file.
3154
dc2ab26e
EZ
3155With a numeric argument of 0, never make the previous version
3156into a backup file.
b4da00e9
RM
3157
3158If a file's name is FOO, the names of its numbered backup versions are
3159 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
3160Numeric backups (rather than FOO~) will be made if value of
3161 `version-control' is not the atom `never' and either there are already
3162 numeric versions of the file being backed up, or `version-control' is
3163 non-nil.
3164We don't want excessive versions piling up, so there are variables
3165 `kept-old-versions', which tells Emacs how many oldest versions to keep,
3166 and `kept-new-versions', which tells how many newest versions to keep.
3167 Defaults are 2 old versions and 2 new.
3168`dired-kept-versions' controls dired's clean-directory (.) command.
de7d5e1b 3169If `delete-old-versions' is nil, system will query user
e73ec04b
RS
3170 before trimming versions. Otherwise it does it silently.
3171
749d2ee6
RS
3172If `vc-make-backup-files' is nil, which is the default,
3173 no backup files are made for files managed by version control.
3174 (This is because the version control system itself records previous versions.)
3175
e73ec04b 3176See the subroutine `basic-save-buffer' for more information."
b4da00e9
RM
3177 (interactive "p")
3178 (let ((modp (buffer-modified-p))
3179 (large (> (buffer-size) 50000))
b5a8e0fc
RS
3180 (make-backup-files (or (and make-backup-files (not (eq args 0)))
3181 (memq args '(16 64)))))
b4da00e9 3182 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
b4990dde
GM
3183 (if (and modp large (buffer-file-name))
3184 (message "Saving file %s..." (buffer-file-name)))
b4da00e9
RM
3185 (basic-save-buffer)
3186 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
3187
3188(defun delete-auto-save-file-if-necessary (&optional force)
3189 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
3190Normally delete only if the file was written by this Emacs since
3191the last real save, but optional arg FORCE non-nil means delete anyway."
3192 (and buffer-auto-save-file-name delete-auto-save-files
3193 (not (string= buffer-file-name buffer-auto-save-file-name))
3194 (or force (recent-auto-save-p))
3195 (progn
3196 (condition-case ()
3197 (delete-file buffer-auto-save-file-name)
3198 (file-error nil))
3199 (set-buffer-auto-saved))))
3200
481f215b
KH
3201(defvar auto-save-hook nil
3202 "Normal hook run just before auto-saving.")
3203
3c3b81d1
SJ
3204(defcustom before-save-hook nil
3205 "Normal hook that is run before a buffer is saved to its file."
25f6295e 3206 :options '(copyright-update time-stamp)
3c3b81d1
SJ
3207 :type 'hook
3208 :group 'files)
3209
ffc0e1ca
AS
3210(defcustom after-save-hook nil
3211 "Normal hook that is run after a buffer is saved to its file."
3212 :options '(executable-make-buffer-file-executable-if-script-p)
3213 :type 'hook
3214 :group 'files)
1cc852cc 3215
0516edee
RS
3216(defvar save-buffer-coding-system nil
3217 "If non-nil, use this coding system for saving the buffer.
3218More precisely, use this coding system in place of the
3219value of `buffer-file-coding-system', when saving the buffer.
3220Calling `write-region' for any purpose other than saving the buffer
3221will still use `buffer-file-coding-system'; this variable has no effect
3222in such cases.")
3223
d5fe94cc
RS
3224(make-variable-buffer-local 'save-buffer-coding-system)
3225(put 'save-buffer-coding-system 'permanent-local t)
3226
b4da00e9 3227(defun basic-save-buffer ()
1cc852cc 3228 "Save the current buffer in its visited file, if it has been modified.
0370fe77
SM
3229The hooks `write-contents-functions' and `write-file-functions' get a chance
3230to do the job of saving; if they do not, then the buffer is saved in
3231the visited file file in the usual way.
3c3b81d1
SJ
3232Before and after saving the buffer, this function runs
3233`before-save-hook' and `after-save-hook', respectively."
b4da00e9 3234 (interactive)
19618231 3235 (save-current-buffer
c11a94fe
RS
3236 ;; In an indirect buffer, save its base buffer instead.
3237 (if (buffer-base-buffer)
3238 (set-buffer (buffer-base-buffer)))
3239 (if (buffer-modified-p)
3240 (let ((recent-save (recent-auto-save-p))
818286f4 3241 setmodes)
c11a94fe
RS
3242 ;; On VMS, rename file and buffer to get rid of version number.
3243 (if (and (eq system-type 'vax-vms)
3244 (not (string= buffer-file-name
3245 (file-name-sans-versions buffer-file-name))))
3246 (let (buffer-new-name)
3247 ;; Strip VMS version number before save.
3248 (setq buffer-file-name
3249 (file-name-sans-versions buffer-file-name))
3250 ;; Construct a (unique) buffer name to correspond.
3251 (let ((buf (create-file-buffer (downcase buffer-file-name))))
3252 (setq buffer-new-name (buffer-name buf))
3253 (kill-buffer buf))
3254 (rename-buffer buffer-new-name)))
3255 ;; If buffer has no file name, ask user for one.
3256 (or buffer-file-name
182891ef
RS
3257 (let ((filename
3258 (expand-file-name
3259 (read-file-name "File to save in: ") nil)))
3260 (and (file-exists-p filename)
3261 (or (y-or-n-p (format "File `%s' exists; overwrite? "
3262 filename))
3263 (error "Canceled")))
3264 (set-visited-file-name filename)))
c11a94fe
RS
3265 (or (verify-visited-file-modtime (current-buffer))
3266 (not (file-exists-p buffer-file-name))
3267 (yes-or-no-p
3268 (format "%s has changed since visited or saved. Save anyway? "
3269 (file-name-nondirectory buffer-file-name)))
3270 (error "Save not confirmed"))
3271 (save-restriction
3272 (widen)
19618231 3273 (save-excursion
0370fe77 3274 (and (> (point-max) (point-min))
407b4328 3275 (not find-file-literally)
19618231
RS
3276 (/= (char-after (1- (point-max))) ?\n)
3277 (not (and (eq selective-display t)
3278 (= (char-after (1- (point-max))) ?\r)))
3279 (or (eq require-final-newline t)
f4206092 3280 (eq require-final-newline 'visit-save)
19618231
RS
3281 (and require-final-newline
3282 (y-or-n-p
3283 (format "Buffer %s does not end in newline. Add one? "
3284 (buffer-name)))))
3285 (save-excursion
3286 (goto-char (point-max))
3287 (insert ?\n))))
fa5867f6
AS
3288 ;; Support VC version backups.
3289 (vc-before-save)
3c3b81d1 3290 (run-hooks 'before-save-hook)
0370fe77 3291 (or (run-hook-with-args-until-success 'write-contents-functions)
c11a94fe 3292 (run-hook-with-args-until-success 'local-write-file-hooks)
0370fe77 3293 (run-hook-with-args-until-success 'write-file-functions)
0ba5894b
RS
3294 ;; If a hook returned t, file is already "written".
3295 ;; Otherwise, write it the usual way now.
3296 (setq setmodes (basic-save-buffer-1)))
d6e8ea6f
KH
3297 ;; Now we have saved the current buffer. Let's make sure
3298 ;; that buffer-file-coding-system is fixed to what
3299 ;; actually used for saving by binding it locally.
0516edee
RS
3300 (if save-buffer-coding-system
3301 (setq save-buffer-coding-system last-coding-system-used)
3302 (setq buffer-file-coding-system last-coding-system-used))
2a47b4f5
RS
3303 (setq buffer-file-number
3304 (nthcdr 10 (file-attributes buffer-file-name)))
c11a94fe
RS
3305 (if setmodes
3306 (condition-case ()
f3f9e207 3307 (set-file-modes buffer-file-name (car setmodes))
c11a94fe
RS
3308 (error nil))))
3309 ;; If the auto-save file was recent before this command,
3310 ;; delete it now.
3311 (delete-auto-save-file-if-necessary recent-save)
49530862
RS
3312 ;; Support VC `implicit' locking.
3313 (vc-after-save)
c11a94fe
RS
3314 (run-hooks 'after-save-hook))
3315 (message "(No changes need to be saved)"))))
b4da00e9 3316
87d26afc
RS
3317;; This does the "real job" of writing a buffer into its visited file
3318;; and making a backup file. This is what is normally done
0370fe77 3319;; but inhibited if one of write-file-functions returns non-nil.
f3f9e207 3320;; It returns a value (MODES . BACKUPNAME), like backup-buffer.
87d26afc 3321(defun basic-save-buffer-1 ()
969be033
RS
3322 (prog1
3323 (if save-buffer-coding-system
3324 (let ((coding-system-for-write save-buffer-coding-system))
3325 (basic-save-buffer-2))
d5fe94cc 3326 (basic-save-buffer-2))
969be033 3327 (setq buffer-file-coding-system-explicit last-coding-system-used)))
d5fe94cc 3328
f3f9e207 3329;; This returns a value (MODES . BACKUPNAME), like backup-buffer.
d5fe94cc
RS
3330(defun basic-save-buffer-2 ()
3331 (let (tempsetmodes setmodes)
87d26afc
RS
3332 (if (not (file-writable-p buffer-file-name))
3333 (let ((dir (file-name-directory buffer-file-name)))
3334 (if (not (file-directory-p dir))
83c6f446
RS
3335 (if (file-exists-p dir)
3336 (error "%s is not a directory" dir)
cb2fdcfa 3337 (error "%s: no such directory" buffer-file-name))
87d26afc
RS
3338 (if (not (file-exists-p buffer-file-name))
3339 (error "Directory %s write-protected" dir)
3340 (if (yes-or-no-p
3341 (format "File %s is write-protected; try to save anyway? "
3342 (file-name-nondirectory
3343 buffer-file-name)))
3344 (setq tempsetmodes t)
3345 (error "Attempt to save to a file which you aren't allowed to write"))))))
3346 (or buffer-backed-up
3347 (setq setmodes (backup-buffer)))
76d5492b 3348 (let ((dir (file-name-directory buffer-file-name)))
f4a0f59b
RS
3349 (if (and file-precious-flag
3350 (file-writable-p dir))
3351 ;; If file is precious, write temp name, then rename it.
3352 ;; This requires write access to the containing dir,
3353 ;; which is why we don't try it if we don't have that access.
3354 (let ((realname buffer-file-name)
44dce0fb
RS
3355 tempname succeed
3356 (umask (default-file-modes))
6782610c 3357 (old-modtime (visited-file-modtime)))
44dce0fb
RS
3358 ;; Create temp files with strict access rights. It's easy to
3359 ;; loosen them later, whereas it's impossible to close the
3360 ;; time-window of loose permissions otherwise.
f4a0f59b 3361 (unwind-protect
44dce0fb
RS
3362 (progn
3363 (clear-visited-file-modtime)
3364 (set-default-file-modes ?\700)
3365 ;; Try various temporary names.
3366 ;; This code follows the example of make-temp-file,
3367 ;; but it calls write-region in the appropriate way
3368 ;; for saving the buffer.
3369 (while (condition-case ()
3370 (progn
3371 (setq tempname
3372 (make-temp-name
3373 (expand-file-name "tmp" dir)))
3374 (write-region (point-min) (point-max)
3375 tempname nil realname
3376 buffer-file-truename 'excl)
3377 nil)
3378 (file-already-exists t))
3379 ;; The file was somehow created by someone else between
3380 ;; `make-temp-name' and `write-region', let's try again.
3381 nil)
3382 (setq succeed t))
3383 ;; Reset the umask.
3384 (set-default-file-modes umask)
3385 ;; If we failed, restore the buffer's modtime.
3386 (unless succeed
3387 (set-visited-file-modtime old-modtime)))
3388 ;; Since we have created an entirely new file,
3389 ;; make sure it gets the right permission bits set.
f3f9e207
RS
3390 (setq setmodes (or setmodes (cons (file-modes buffer-file-name)
3391 buffer-file-name)))
f4a0f59b
RS
3392 ;; We succeeded in writing the temp file,
3393 ;; so rename it.
3394 (rename-file tempname buffer-file-name t))
3395 ;; If file not writable, see if we can make it writable
3396 ;; temporarily while we write it.
3397 ;; But no need to do so if we have just backed it up
3398 ;; (setmodes is set) because that says we're superseding.
3399 (cond ((and tempsetmodes (not setmodes))
3400 ;; Change the mode back, after writing.
f3f9e207
RS
3401 (setq setmodes (cons (file-modes buffer-file-name) buffer-file-name))
3402 (set-file-modes buffer-file-name (logior (car setmodes) 128))))
3403 (let (success)
3404 (unwind-protect
3405 (progn
3406 (write-region (point-min) (point-max)
3407 buffer-file-name nil t buffer-file-truename)
3408 (setq success t))
3409 ;; If we get an error writing the new file, and we made
3410 ;; the backup by renaming, undo the backing-up.
3411 (and setmodes (not success)
3412 (rename-file (cdr setmodes) buffer-file-name))))))
87d26afc
RS
3413 setmodes))
3414
1eeae2a1
RS
3415(defun diff-buffer-with-file (&optional buffer)
3416 "View the differences between BUFFER and its associated file.
0b9e4749 3417This requires the external program `diff' to be in your `exec-path'."
1eeae2a1 3418 (interactive "bBuffer: ")
0b9e4749 3419 (with-current-buffer (get-buffer (or buffer (current-buffer)))
4e4e9519
MR
3420 (if (and buffer-file-name
3421 (file-exists-p buffer-file-name))
3422 (let ((tempfile (make-temp-file "buffer-content-")))
3423 (unwind-protect
3424 (save-restriction
3425 (widen)
3426 (write-region (point-min) (point-max) tempfile nil 'nomessage)
3427 (diff buffer-file-name tempfile nil t)
3428 (sit-for 0))
3429 (when (file-exists-p tempfile)
3430 (delete-file tempfile))))
3431 (message "Buffer %s has no associated file on disc" (buffer-name))
3432 ;; Display that message for 1 second so that user can read it
3433 ;; in the minibuffer.
3434 (sit-for 1)))
3435 ;; return always nil, so that save-buffers-kill-emacs will not move
3436 ;; over to the next unsaved buffer when calling `d'.
3437 nil)
1eeae2a1
RS
3438
3439(defvar save-some-buffers-action-alist
3440 '((?\C-r
3441 (lambda (buf)
3442 (view-buffer buf
3443 (lambda (ignore)
3444 (exit-recursive-edit)))
3445 (recursive-edit)
3446 ;; Return nil to ask about BUF again.
3447 nil)
3448 "display the current buffer")
3449 (?d diff-buffer-with-file
d97182ab 3450 "show difference to last saved version"))
1eeae2a1
RS
3451 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
3452(put 'save-some-buffers-action-alist 'risky-local-variable t)
3453
a1b0c2a7
RS
3454(defvar buffer-save-without-query nil
3455 "Non-nil means `save-some-buffers' should save this buffer without asking.")
3456(make-variable-buffer-local 'buffer-save-without-query)
3457
ffc0e1ca 3458(defun save-some-buffers (&optional arg pred)
b4da00e9 3459 "Save some modified file-visiting buffers. Asks user about each one.
1eeae2a1
RS
3460You can answer `y' to save, `n' not to save, `C-r' to look at the
3461buffer in question with `view-buffer' before deciding or `d' to
126c9dda 3462view the differences using `diff-buffer-with-file'.
8fd9c174 3463
5bbbceb1 3464Optional argument (the prefix) non-nil means save all with no questions.
ffc0e1ca
AS
3465Optional second argument PRED determines which buffers are considered:
3466If PRED is nil, all the file-visiting buffers are considered.
3467If PRED is t, then certain non-file buffers will also be considered.
3468If PRED is a zero-argument function, it indicates for each buffer whether
1eeae2a1
RS
3469to consider it or not when called with that buffer current.
3470
3471See `save-some-buffers-action-alist' if you want to
3472change the additional actions you can take on files."
b4da00e9 3473 (interactive "P")
907482b9 3474 (save-window-excursion
a1b0c2a7
RS
3475 (let* (queried some-automatic
3476 files-done abbrevs-done)
3477 (dolist (buffer (buffer-list))
3478 ;; First save any buffers that we're supposed to save unconditionally.
3479 ;; That way the following code won't ask about them.
3480 (with-current-buffer buffer
3481 (when (and buffer-save-without-query (buffer-modified-p))
3482 (setq some-automatic t)
3483 (save-buffer))))
3484 ;; Ask about those buffers that merit it,
3485 ;; and record the number thus saved.
3486 (setq files-done
76d5492b
RM
3487 (map-y-or-n-p
3488 (function
3489 (lambda (buffer)
3490 (and (buffer-modified-p buffer)
3491 (not (buffer-base-buffer buffer))
3492 (or
3493 (buffer-file-name buffer)
ffc0e1ca 3494 (and pred
76d5492b
RM
3495 (progn
3496 (set-buffer buffer)
3497 (and buffer-offer-save (> (buffer-size) 0)))))
ffc0e1ca
AS
3498 (or (not (functionp pred))
3499 (with-current-buffer buffer (funcall pred)))
76d5492b
RM
3500 (if arg
3501 t
3502 (setq queried t)
3503 (if (buffer-file-name buffer)
3504 (format "Save file %s? "
3505 (buffer-file-name buffer))
3506 (format "Save buffer %s? "
3507 (buffer-name buffer)))))))
3508 (function
3509 (lambda (buffer)
3510 (set-buffer buffer)
3511 (save-buffer)))
3512 (buffer-list)
3513 '("buffer" "buffers" "save")
1eeae2a1 3514 save-some-buffers-action-alist))
bf247b6e 3515 ;; Maybe to save abbrevs, and record whether
a1b0c2a7
RS
3516 ;; we either saved them or asked to.
3517 (and save-abbrevs abbrevs-changed
3518 (progn
3519 (if (or arg
3520 (eq save-abbrevs 'silently)
3521 (y-or-n-p (format "Save abbrevs in %s? "
3522 abbrev-file-name)))
3523 (write-abbrev-file nil))
3524 ;; Don't keep bothering user if he says no.
3525 (setq abbrevs-changed nil)
3526 (setq abbrevs-done t)))
76d5492b 3527 (or queried (> files-done 0) abbrevs-done
a1b0c2a7
RS
3528 (message (if some-automatic
3529 "(Some special files were saved without asking)"
3530 "(No files need saving)"))))))
b4da00e9
RM
3531\f
3532(defun not-modified (&optional arg)
3533 "Mark current buffer as unmodified, not needing to be saved.
a641f9a1
RM
3534With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
3535
3536It is not a good idea to use this function in Lisp programs, because it
3537prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
b4da00e9
RM
3538 (interactive "P")
3539 (message (if arg "Modification-flag set"
3540 "Modification-flag cleared"))
3541 (set-buffer-modified-p arg))
3542
3543(defun toggle-read-only (&optional arg)
3544 "Change whether this buffer is visiting its file read-only.
2a9fe1e2
RS
3545With arg, set read-only iff arg is positive.
3546If visiting file read-only and `view-read-only' is non-nil, enter view mode."
b4da00e9 3547 (interactive "P")
c60ee5e7 3548 (if (and arg
d758359d
AS
3549 (if (> (prefix-numeric-value arg) 0) buffer-read-only
3550 (not buffer-read-only))) ; If buffer-read-only is set correctly,
3551 nil ; do nothing.
3552 ;; Toggle.
3553 (cond
3554 ((and buffer-read-only view-mode)
3555 (View-exit-and-edit)
3556 (make-local-variable 'view-read-only)
3557 (setq view-read-only t)) ; Must leave view mode.
3558 ((and (not buffer-read-only) view-read-only
818286f4
SM
3559 ;; If view-mode is already active, `view-mode-enter' is a nop.
3560 (not view-mode)
d758359d
AS
3561 (not (eq (get major-mode 'mode-class) 'special)))
3562 (view-mode-enter))
3563 (t (setq buffer-read-only (not buffer-read-only))
3564 (force-mode-line-update)))
3565 (if (vc-backend buffer-file-name)
3566 (message (substitute-command-keys
a5dd5f60
RS
3567 (concat "File is under version-control; "
3568 "use \\[vc-next-action] to check in/out"))))))
b4da00e9 3569
912192d1 3570(defun insert-file (filename)
b4da00e9
RM
3571 "Insert contents of file FILENAME into buffer after point.
3572Set mark after the inserted text.
3573
3574This function is meant for the user to run interactively.
3575Don't call it from programs! Use `insert-file-contents' instead.
3576\(Its calling sequence is different; see its documentation)."
912192d1 3577 (interactive "*fInsert file: ")
3a64a3cf 3578 (insert-file-1 filename #'insert-file-contents))
b4da00e9 3579
912192d1 3580(defun append-to-file (start end filename)
b4da00e9
RM
3581 "Append the contents of the region to the end of file FILENAME.
3582When called from a function, expects three arguments,
3583START, END and FILENAME. START and END are buffer positions
da30bf98 3584saying what text to write."
912192d1
KH
3585 (interactive "r\nFAppend to file: ")
3586 (write-region start end filename t))
b4da00e9
RM
3587
3588(defun file-newest-backup (filename)
3589 "Return most recent backup file for FILENAME or nil if no backups exist."
ffc0e1ca
AS
3590 ;; `make-backup-file-name' will get us the right directory for
3591 ;; ordinary or numeric backups. It might create a directory for
3592 ;; backups as a side-effect, according to `backup-directory-alist'.
e31cfca5 3593 (let* ((filename (file-name-sans-versions
783bf210 3594 (make-backup-file-name (expand-file-name filename))))
b4da00e9
RM
3595 (file (file-name-nondirectory filename))
3596 (dir (file-name-directory filename))
3597 (comp (file-name-all-completions file dir))
cf7e94a0
RS
3598 (newest nil)
3599 tem)
b4da00e9 3600 (while comp
ffc0e1ca 3601 (setq tem (pop comp))
cf7e94a0
RS
3602 (cond ((and (backup-file-name-p tem)
3603 (string= (file-name-sans-versions tem) file))
3604 (setq tem (concat dir tem))
3605 (if (or (null newest)
3606 (file-newer-than-file-p tem newest))
3607 (setq newest tem)))))
b4da00e9
RM
3608 newest))
3609
3610(defun rename-uniquely ()
3611 "Rename current buffer to a similar name not already taken.
3612This function is useful for creating multiple shell process buffers
3613or multiple mail buffers, etc."
3614 (interactive)
40eb8038 3615 (save-match-data
e0df3aef
KH
3616 (let ((base-name (buffer-name)))
3617 (and (string-match "<[0-9]+>\\'" base-name)
3618 (not (and buffer-file-name
3619 (string= base-name
3620 (file-name-nondirectory buffer-file-name))))
3621 ;; If the existing buffer name has a <NNN>,
3622 ;; which isn't part of the file name (if any),
3623 ;; then get rid of that.
3624 (setq base-name (substring base-name 0 (match-beginning 0))))
3625 (rename-buffer (generate-new-buffer-name base-name))
3941fe2c 3626 (force-mode-line-update))))
5bbbceb1 3627
4e43240a 3628(defun make-directory (dir &optional parents)
5ce8bb89
RS
3629 "Create the directory DIR and any nonexistent parent dirs.
3630Interactively, the default choice of directory to create
3631is the current default directory for file names.
0225ae5e 3632That is useful when you have visited a file in a nonexistent directory.
5ce8bb89
RS
3633
3634Noninteractively, the second (optional) argument PARENTS says whether
07703430
RS
3635to create parent directories if they don't exist. Interactively,
3636this happens by default."
5ce8bb89
RS
3637 (interactive
3638 (list (read-file-name "Make directory: " default-directory default-directory
3639 nil nil)
3640 t))
ee291b46
RS
3641 ;; If default-directory is a remote directory,
3642 ;; make sure we find its make-directory handler.
3643 (setq dir (expand-file-name dir))
6eaebaa2 3644 (let ((handler (find-file-name-handler dir 'make-directory)))
4e43240a
RS
3645 (if handler
3646 (funcall handler 'make-directory dir parents)
3647 (if (not parents)
3648 (make-directory-internal dir)
3649 (let ((dir (directory-file-name (expand-file-name dir)))
3650 create-list)
3651 (while (not (file-exists-p dir))
76d5492b 3652 (setq create-list (cons dir create-list)
4e43240a
RS
3653 dir (directory-file-name (file-name-directory dir))))
3654 (while create-list
3655 (make-directory-internal (car create-list))
3656 (setq create-list (cdr create-list))))))))
b4da00e9
RM
3657\f
3658(put 'revert-buffer-function 'permanent-local t)
3659(defvar revert-buffer-function nil
0973d78b
RS
3660 "Function to use to revert this buffer, or nil to do the default.
3661The function receives two arguments IGNORE-AUTO and NOCONFIRM,
3662which are the arguments that `revert-buffer' received.")
b4da00e9
RM
3663
3664(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
3665(defvar revert-buffer-insert-file-contents-function nil
3666 "Function to use to insert contents when reverting this buffer.
3667Gets two args, first the nominal file name to use,
2df32500
RS
3668and second, t if reading the auto-save file.
3669
3670The function you specify is responsible for updating (or preserving) point.")
b4da00e9 3671
b0dc9757
LT
3672(defvar buffer-stale-function nil
3673 "Function to check whether a non-file buffer needs reverting.
3674This should be a function with one optional argument NOCONFIRM.
44dce0fb 3675Auto Revert Mode passes t for NOCONFIRM. The function should return
8b0b6932
LT
3676non-nil if the buffer should be reverted. A return value of
3677`fast' means that the need for reverting was not checked, but
3678that reverting the buffer is fast. The buffer is current when
3679this function is called.
b0dc9757 3680
4f8453ae
LT
3681The idea behind the NOCONFIRM argument is that it should be
3682non-nil if the buffer is going to be reverted without asking the
3683user. In such situations, one has to be careful with potentially
c90dcdd5
LT
3684time consuming operations.
3685
3686For more information on how this variable is used by Auto Revert mode,
3687see Info node `(emacs-xtra)Supporting additional buffers'.")
b0dc9757 3688
5f76e7d4
KH
3689(defvar before-revert-hook nil
3690 "Normal hook for `revert-buffer' to run before reverting.
3691If `revert-buffer-function' is used to override the normal revert
3692mechanism, this hook is not used.")
3693
3694(defvar after-revert-hook nil
3695 "Normal hook for `revert-buffer' to run after reverting.
3696Note that the hook value that it runs is the value that was in effect
3697before reverting; that makes a difference if you have buffer-local
3698hook functions.
3699
3700If `revert-buffer-function' is used to override the normal revert
3701mechanism, this hook is not used.")
3702
1554c03b
RS
3703(defvar revert-buffer-internal-hook)
3704
9a30563f 3705(defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
7e7c9c4e 3706 "Replace current buffer text with the text of the visited file on disk.
b4da00e9 3707This undoes all changes since the file was visited or saved.
8c0e7b73
JB
3708With a prefix argument, offer to revert from latest auto-save file, if
3709that is more recent than the visited file.
1ab31687 3710
7e7c9c4e
RS
3711This command also works for special buffers that contain text which
3712doesn't come from a file, but reflects some other data base instead:
4e163715 3713for example, Dired buffers and `buffer-list' buffers. In these cases,
7e7c9c4e
RS
3714it reconstructs the buffer contents from the appropriate data base.
3715
65ee6096 3716When called from Lisp, the first argument is IGNORE-AUTO; only offer
1ab31687
JB
3717to revert from the auto-save file when this is nil. Note that the
3718sense of this argument is the reverse of the prefix argument, for the
3719sake of backward compatibility. IGNORE-AUTO is optional, defaulting
3720to nil.
3721
3722Optional second argument NOCONFIRM means don't ask for confirmation at
ffc0e1ca 3723all. (The local variable `revert-without-query', if non-nil, prevents
d1f04130 3724confirmation.)
b4da00e9 3725
5b2b26d5
RS
3726Optional third argument PRESERVE-MODES non-nil means don't alter
3727the files modes. Normally we reinitialize them using `normal-mode'.
3728
8c0e7b73 3729If the value of `revert-buffer-function' is non-nil, it is called to
7e7c9c4e
RS
3730do all the work for this command. Otherwise, the hooks
3731`before-revert-hook' and `after-revert-hook' are run at the beginning
3732and the end, and if `revert-buffer-insert-file-contents-function' is
3733non-nil, it is called instead of rereading visited file contents."
fb6208a6 3734
1ab31687
JB
3735 ;; I admit it's odd to reverse the sense of the prefix argument, but
3736 ;; there is a lot of code out there which assumes that the first
3737 ;; argument should be t to avoid consulting the auto-save file, and
3738 ;; there's no straightforward way to encourage authors to notice a
3739 ;; reversal of the argument sense. So I'm just changing the user
3740 ;; interface, but leaving the programmatic interface the same.
e0867e99 3741 (interactive (list (not current-prefix-arg)))
b4da00e9 3742 (if revert-buffer-function
1ab31687 3743 (funcall revert-buffer-function ignore-auto noconfirm)
44dce0fb
RS
3744 (with-current-buffer (or (buffer-base-buffer (current-buffer))
3745 (current-buffer))
3746 (let* ((auto-save-p (and (not ignore-auto)
3747 (recent-auto-save-p)
3748 buffer-auto-save-file-name
3749 (file-readable-p buffer-auto-save-file-name)
3750 (y-or-n-p
3751 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
3752 (file-name (if auto-save-p
3753 buffer-auto-save-file-name
3754 buffer-file-name)))
3755 (cond ((null file-name)
3756 (error "Buffer does not seem to be associated with any file"))
3757 ((or noconfirm
3758 (and (not (buffer-modified-p))
3759 (let ((tail revert-without-query)
3760 (found nil))
3761 (while tail
3762 (if (string-match (car tail) file-name)
3763 (setq found t))
3764 (setq tail (cdr tail)))
3765 found))
3766 (yes-or-no-p (format "Revert buffer from file %s? "
3767 file-name)))
3768 (run-hooks 'before-revert-hook)
3769 ;; If file was backed up but has changed since,
3770 ;; we shd make another backup.
3771 (and (not auto-save-p)
3772 (not (verify-visited-file-modtime (current-buffer)))
3773 (setq buffer-backed-up nil))
3774 ;; Get rid of all undo records for this buffer.
3775 (or (eq buffer-undo-list t)
3776 (setq buffer-undo-list nil))
3777 ;; Effectively copy the after-revert-hook status,
3778 ;; since after-find-file will clobber it.
3779 (let ((global-hook (default-value 'after-revert-hook))
3780 (local-hook-p (local-variable-p 'after-revert-hook))
3781 (local-hook (and (local-variable-p 'after-revert-hook)
3782 after-revert-hook)))
3783 (let (buffer-read-only
3784 ;; Don't make undo records for the reversion.
3785 (buffer-undo-list t))
3786 (if revert-buffer-insert-file-contents-function
3787 (funcall revert-buffer-insert-file-contents-function
3788 file-name auto-save-p)
3789 (if (not (file-exists-p file-name))
3790 (error (if buffer-file-number
3791 "File %s no longer exists!"
3792 "Cannot revert nonexistent file %s")
3793 file-name))
3794 ;; Bind buffer-file-name to nil
3795 ;; so that we don't try to lock the file.
3796 (let ((buffer-file-name nil))
3797 (or auto-save-p
3798 (unlock-buffer)))
3799 (widen)
3800 (let ((coding-system-for-read
3801 ;; Auto-saved file shoule be read by Emacs'
3802 ;; internal coding.
3803 (if auto-save-p 'auto-save-coding
3804 (or coding-system-for-read
3805 buffer-file-coding-system-explicit))))
3806 ;; This force after-insert-file-set-coding
3807 ;; (called from insert-file-contents) to set
3808 ;; buffer-file-coding-system to a proper value.
3809 (kill-local-variable 'buffer-file-coding-system)
3810
3811 ;; Note that this preserves point in an intelligent way.
3812 (if preserve-modes
3813 (let ((buffer-file-format buffer-file-format))
3814 (insert-file-contents file-name (not auto-save-p)
3815 nil nil t))
3816 (insert-file-contents file-name (not auto-save-p)
3817 nil nil t)))))
3818 ;; Recompute the truename in case changes in symlinks
3819 ;; have changed the truename.
3820 (setq buffer-file-truename
3821 (abbreviate-file-name (file-truename buffer-file-name)))
3822 (after-find-file nil nil t t preserve-modes)
3823 ;; Run after-revert-hook as it was before we reverted.
3824 (setq-default revert-buffer-internal-hook global-hook)
3825 (if local-hook-p
3826 (set (make-local-variable 'revert-buffer-internal-hook)
3827 local-hook)
3828 (kill-local-variable 'revert-buffer-internal-hook))
3829 (run-hooks 'revert-buffer-internal-hook))
3830 t))))))
b4da00e9 3831
64d18e8f
RS
3832(defun recover-this-file ()
3833 "Recover the visited file--get contents from its last auto-save file."
3834 (interactive)
3835 (recover-file buffer-file-name))
3836
b4da00e9
RM
3837(defun recover-file (file)
3838 "Visit file FILE, but get contents from its last auto-save file."
10f7c7fc
RS
3839 ;; Actually putting the file name in the minibuffer should be used
3840 ;; only rarely.
3841 ;; Not just because users often use the default.
e1dadc17 3842 (interactive "FRecover file: ")
b4da00e9 3843 (setq file (expand-file-name file))
f7da6740 3844 (if (auto-save-file-name-p (file-name-nondirectory file))
4e163715 3845 (error "%s is an auto-save file" (abbreviate-file-name file)))
b4da00e9
RM
3846 (let ((file-name (let ((buffer-file-name file))
3847 (make-auto-save-file-name))))
945e1965
RS
3848 (cond ((if (file-exists-p file)
3849 (not (file-newer-than-file-p file-name file))
3850 (not (file-exists-p file-name)))
4e163715
SM
3851 (error "Auto-save file %s not current"
3852 (abbreviate-file-name file-name)))
b4da00e9 3853 ((save-window-excursion
ffc0e1ca
AS
3854 (with-output-to-temp-buffer "*Directory*"
3855 (buffer-disable-undo standard-output)
3856 (save-excursion
3857 (let ((switches dired-listing-switches))
3858 (if (file-symlink-p file)
3859 (setq switches (concat switches "L")))
3860 (set-buffer standard-output)
bc22fd18
EZ
3861 ;; Use insert-directory-safely, not insert-directory,
3862 ;; because these files might not exist. In particular,
3863 ;; FILE might not exist if the auto-save file was for
3864 ;; a buffer that didn't visit a file, such as "*mail*".
3865 ;; The code in v20.x called `ls' directly, so we need
3866 ;; to emulate what `ls' did in that case.
3867 (insert-directory-safely file switches)
3868 (insert-directory-safely file-name switches))))
b4da00e9
RM
3869 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3870 (switch-to-buffer (find-file-noselect file t))
82d0954a 3871 (let ((buffer-read-only nil)
1e87edf5
KH
3872 ;; Keep the current buffer-file-coding-system.
3873 (coding-system buffer-file-coding-system)
77619f8e
KH
3874 ;; Auto-saved file shoule be read with special coding.
3875 (coding-system-for-read 'auto-save-coding))
b4da00e9 3876 (erase-buffer)
1e87edf5
KH
3877 (insert-file-contents file-name nil)
3878 (set-buffer-file-coding-system coding-system))
8cfb9d46 3879 (after-find-file nil nil t))
ffa7ab70 3880 (t (error "Recover-file cancelled")))))
b4da00e9 3881
6598027d 3882(defun recover-session ()
9aee5392
RS
3883 "Recover auto save files from a previous Emacs session.
3884This command first displays a Dired buffer showing you the
3885previous sessions that you could recover from.
3886To choose one, move point to the proper line and then type C-c C-c.
3887Then you'll be asked about a number of files to recover."
3888 (interactive)
363a5030
RS
3889 (if (null auto-save-list-file-prefix)
3890 (error "You set `auto-save-list-file-prefix' to disable making session files"))
ffc0e1ca
AS
3891 (let ((dir (file-name-directory auto-save-list-file-prefix)))
3892 (unless (file-directory-p dir)
194600a8
JPW
3893 (make-directory dir t))
3894 (unless (directory-files dir nil
3895 (concat "\\`" (regexp-quote
3896 (file-name-nondirectory
3897 auto-save-list-file-prefix)))
3898 t)
3899 (error "No previous sessions to recover")))
6f4983e6 3900 (let ((ls-lisp-support-shell-wildcards t))
7b3478a5
RS
3901 (dired (concat auto-save-list-file-prefix "*")
3902 (concat dired-listing-switches "t")))
05e076c7
AS
3903 (save-excursion
3904 (goto-char (point-min))
3905 (or (looking-at " Move to the session you want to recover,")
3906 (let ((inhibit-read-only t))
3907 ;; Each line starts with a space
3908 ;; so that Font Lock mode won't highlight the first character.
3909 (insert " Move to the session you want to recover,\n"
3910 " then type C-c C-c to select it.\n\n"
3911 " You can also delete some of these files;\n"
3912 " type d on a line to mark that file for deletion.\n\n"))))
9aee5392 3913 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
80280bb7 3914 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
9aee5392 3915
80280bb7 3916(defun recover-session-finish ()
9aee5392
RS
3917 "Choose one saved session to recover auto-save files from.
3918This command is used in the special Dired buffer created by
80280bb7 3919\\[recover-session]."
9aee5392
RS
3920 (interactive)
3921 ;; Get the name of the session file to recover from.
3922 (let ((file (dired-get-filename))
953a03b2 3923 files
9aee5392 3924 (buffer (get-buffer-create " *recover*")))
c11032b9 3925 (dired-unmark 1)
033ef863 3926 (dired-do-flagged-delete t)
9aee5392
RS
3927 (unwind-protect
3928 (save-excursion
3929 ;; Read in the auto-save-list file.
3930 (set-buffer buffer)
3931 (erase-buffer)
3932 (insert-file-contents file)
953a03b2
RS
3933 ;; Loop thru the text of that file
3934 ;; and get out the names of the files to recover.
3935 (while (not (eobp))
3936 (let (thisfile autofile)
3937 (if (eolp)
3938 ;; This is a pair of lines for a non-file-visiting buffer.
3939 ;; Get the auto-save file name and manufacture
3940 ;; a "visited file name" from that.
3941 (progn
3942 (forward-line 1)
259be4e6
JB
3943 ;; If there is no auto-save file name, the
3944 ;; auto-save-list file is probably corrupted.
3945 (unless (eolp)
3946 (setq autofile
3947 (buffer-substring-no-properties
3948 (point)
3949 (save-excursion
3950 (end-of-line)
3951 (point))))
3952 (setq thisfile
3953 (expand-file-name
3954 (substring
3955 (file-name-nondirectory autofile)
3956 1 -1)
3957 (file-name-directory autofile))))
953a03b2
RS
3958 (forward-line 1))
3959 ;; This pair of lines is a file-visiting
3960 ;; buffer. Use the visited file name.
3961 (progn
3962 (setq thisfile
3963 (buffer-substring-no-properties
3964 (point) (progn (end-of-line) (point))))
3965 (forward-line 1)
3966 (setq autofile
3967 (buffer-substring-no-properties
3968 (point) (progn (end-of-line) (point))))
3969 (forward-line 1)))
3970 ;; Ignore a file if its auto-save file does not exist now.
259be4e6 3971 (if (and autofile (file-exists-p autofile))
953a03b2
RS
3972 (setq files (cons thisfile files)))))
3973 (setq files (nreverse files))
945e1965
RS
3974 ;; The file contains a pair of line for each auto-saved buffer.
3975 ;; The first line of the pair contains the visited file name
3976 ;; or is empty if the buffer was not visiting a file.
3977 ;; The second line is the auto-save file name.
953a03b2
RS
3978 (if files
3979 (map-y-or-n-p "Recover %s? "
3980 (lambda (file)
3981 (condition-case nil
3982 (save-excursion (recover-file file))
76d5492b 3983 (error
953a03b2
RS
3984 "Failed to recover `%s'" file)))
3985 files
3986 '("file" "files" "recover"))
3987 (message "No files can be recovered from this session now")))
9aee5392
RS
3988 (kill-buffer buffer))))
3989
73ba610a 3990(defun kill-some-buffers (&optional list)
243a3ae0 3991 "Kill some buffers. Asks the user whether to kill each one of them.
bb8eaf67 3992Non-interactively, if optional argument LIST is non-nil, it
243a3ae0 3993specifies the list of buffers to kill, asking for approval for each one."
b4da00e9 3994 (interactive)
73ba610a
RS
3995 (if (null list)
3996 (setq list (buffer-list)))
3997 (while list
3998 (let* ((buffer (car list))
3999 (name (buffer-name buffer)))
4000 (and (not (string-equal name ""))
4001 (/= (aref name 0) ? )
4002 (yes-or-no-p
4003 (format "Buffer %s %s. Kill? "
4004 name
4005 (if (buffer-modified-p buffer)
4006 "HAS BEEN EDITED" "is unmodified")))
4007 (kill-buffer buffer)))
4008 (setq list (cdr list))))
b4da00e9
RM
4009\f
4010(defun auto-save-mode (arg)
4011 "Toggle auto-saving of contents of current buffer.
f3e23606 4012With prefix argument ARG, turn auto-saving on if positive, else off."
b4da00e9
RM
4013 (interactive "P")
4014 (setq buffer-auto-save-file-name
4015 (and (if (null arg)
74b9c2af 4016 (or (not buffer-auto-save-file-name)
4e0c8650 4017 ;; If auto-save is off because buffer has shrunk,
74b9c2af
RS
4018 ;; then toggling should turn it on.
4019 (< buffer-saved-size 0))
b4da00e9
RM
4020 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
4021 (if (and buffer-file-name auto-save-visited-file-name
4022 (not buffer-read-only))
4023 buffer-file-name
4024 (make-auto-save-file-name))))
0b7f1ef2
RS
4025 ;; If -1 was stored here, to temporarily turn off saving,
4026 ;; turn it back on.
4027 (and (< buffer-saved-size 0)
4028 (setq buffer-saved-size 0))
b4da00e9
RM
4029 (if (interactive-p)
4030 (message "Auto-save %s (in this buffer)"
4031 (if buffer-auto-save-file-name "on" "off")))
4032 buffer-auto-save-file-name)
4033
4034(defun rename-auto-save-file ()
4035 "Adjust current buffer's auto save file name for current conditions.
4036Also rename any existing auto save file, if it was made in this session."
4037 (let ((osave buffer-auto-save-file-name))
4038 (setq buffer-auto-save-file-name
4039 (make-auto-save-file-name))
4040 (if (and osave buffer-auto-save-file-name
4041 (not (string= buffer-auto-save-file-name buffer-file-name))
4042 (not (string= buffer-auto-save-file-name osave))
4043 (file-exists-p osave)
4044 (recent-auto-save-p))
4045 (rename-file osave buffer-auto-save-file-name t))))
4046
4047(defun make-auto-save-file-name ()
4048 "Return file name to use for auto-saves of current buffer.
4049Does not consider `auto-save-visited-file-name' as that variable is checked
4050before calling this function. You can redefine this for customization.
4051See also `auto-save-file-name-p'."
4052 (if buffer-file-name
ffc0e1ca
AS
4053 (let ((list auto-save-file-name-transforms)
4054 (filename buffer-file-name)
a0b60c33 4055 result uniq)
ffc0e1ca
AS
4056 ;; Apply user-specified translations
4057 ;; to the file name.
4058 (while (and list (not result))
4059 (if (string-match (car (car list)) filename)
4060 (setq result (replace-match (cadr (car list)) t nil
a0b60c33 4061 filename)
38eea7c7 4062 uniq (car (cddr (car list)))))
ffc0e1ca 4063 (setq list (cdr list)))
a0b60c33 4064 (if result
3c4a7cf3
RS
4065 (if uniq
4066 (setq filename (concat
4067 (file-name-directory result)
4068 (subst-char-in-string
d7b6ca4a 4069 ?/ ?!
3c4a7cf3
RS
4070 (replace-regexp-in-string "!" "!!"
4071 filename))))
4072 (setq filename result)))
1e57a696
EZ
4073 (setq result
4074 (if (and (eq system-type 'ms-dos)
4075 (not (msdos-long-file-names)))
4076 ;; We truncate the file name to DOS 8+3 limits
4077 ;; before doing anything else, because the regexp
4078 ;; passed to string-match below cannot handle
4079 ;; extensions longer than 3 characters, multiple
4080 ;; dots, and other atrocities.
4081 (let ((fn (dos-8+3-filename
4082 (file-name-nondirectory buffer-file-name))))
4083 (string-match
4084 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
4085 fn)
4086 (concat (file-name-directory buffer-file-name)
4087 "#" (match-string 1 fn)
4088 "." (match-string 3 fn) "#"))
4089 (concat (file-name-directory filename)
4090 "#"
4091 (file-name-nondirectory filename)
4092 "#")))
4093 ;; Make sure auto-save file names don't contain characters
4094 ;; invalid for the underlying filesystem.
4095 (if (and (memq system-type '(ms-dos windows-nt))
4096 ;; Don't modify remote (ange-ftp) filenames
4097 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result)))
4098 (convert-standard-filename result)
4099 result))
0a1763b4
RS
4100
4101 ;; Deal with buffers that don't have any associated files. (Mail
4102 ;; mode tends to create a good number of these.)
4103
7d483e8c 4104 (let ((buffer-name (buffer-name))
ff5c7181 4105 (limit 0)
77d18896 4106 file-name)
c3348e10
RS
4107 ;; Eliminate all slashes and backslashes by
4108 ;; replacing them with sequences that start with %.
4109 ;; Quote % also, to keep distinct names distinct.
4110 (while (string-match "[/\\%]" buffer-name limit)
4111 (let* ((character (aref buffer-name (match-beginning 0)))
4112 (replacement
4113 (cond ((eq character ?%) "%%")
4114 ((eq character ?/) "%+")
4115 ((eq character ?\\) "%-"))))
4116 (setq buffer-name (replace-match replacement t t buffer-name))
4117 (setq limit (1+ (match-end 0)))))
a8abaf83 4118 ;; Generate the file name.
ff5c7181
RS
4119 (setq file-name
4120 (make-temp-file
4121 (let ((fname
4122 (expand-file-name
4123 (format "#%s#" buffer-name)
4124 ;; Try a few alternative directories, to get one we can
4125 ;; write it.
4126 (cond
4127 ((file-writable-p default-directory) default-directory)
4128 ((file-writable-p "/var/tmp/") "/var/tmp/")
4129 ("~/")))))
4130 (if (and (memq system-type '(ms-dos windows-nt))
4131 ;; Don't modify remote (ange-ftp) filenames
4132 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname)))
4133 ;; The call to convert-standard-filename is in case
4134 ;; buffer-name includes characters not allowed by the
4135 ;; DOS/Windows filesystems. make-temp-file writes to the
4136 ;; file it creates, so we must fix the file name _before_
4137 ;; make-temp-file is called.
4138 (convert-standard-filename fname)
4139 fname))
4140 nil "#"))
4141 ;; make-temp-file creates the file,
4142 ;; but we don't want it to exist until we do an auto-save.
4143 (condition-case ()
4144 (delete-file file-name)
4145 (file-error nil))
4146 file-name)))
b4da00e9
RM
4147
4148(defun auto-save-file-name-p (filename)
4149 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
4150FILENAME should lack slashes. You can redefine this for customization."
4151 (string-match "^#.*#$" filename))
4152\f
6f4983e6
RS
4153(defun wildcard-to-regexp (wildcard)
4154 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
4155The generated regexp will match a filename iff the filename
4156matches that wildcard according to shell rules. Only wildcards known
4157by `sh' are supported."
4158 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
4159 ;; Copy the initial run of non-special characters.
4160 (result (substring wildcard 0 i))
4161 (len (length wildcard)))
4162 ;; If no special characters, we're almost done.
4163 (if i
4164 (while (< i len)
4165 (let ((ch (aref wildcard i))
4166 j)
4167 (setq
4168 result
4169 (concat result
4170 (cond
7e7c9c4e
RS
4171 ((and (eq ch ?\[)
4172 (< (1+ i) len)
4173 (eq (aref wildcard (1+ i)) ?\]))
4174 "\\[")
6f4983e6
RS
4175 ((eq ch ?\[) ; [...] maps to regexp char class
4176 (progn
4177 (setq i (1+ i))
4178 (concat
4179 (cond
4180 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
4181 (progn
4182 (setq i (1+ i))
4183 (if (eq (aref wildcard i) ?\])
4184 (progn
4185 (setq i (1+ i))
4186 "[^]")
4187 "[^")))
4188 ((eq (aref wildcard i) ?^)
4189 ;; Found "[^". Insert a `\0' character
4190 ;; (which cannot happen in a filename)
4191 ;; into the character class, so that `^'
4192 ;; is not the first character after `[',
4193 ;; and thus non-special in a regexp.
4194 (progn
4195 (setq i (1+ i))
4196 "[\000^"))
4197 ((eq (aref wildcard i) ?\])
4198 ;; I don't think `]' can appear in a
4199 ;; character class in a wildcard, but
4200 ;; let's be general here.
4201 (progn
4202 (setq i (1+ i))
4203 "[]"))
4204 (t "["))
4205 (prog1 ; copy everything upto next `]'.
4206 (substring wildcard
4207 i
4208 (setq j (string-match
4209 "]" wildcard i)))
4210 (setq i (if j (1- j) (1- len)))))))
4211 ((eq ch ?.) "\\.")
4212 ((eq ch ?*) "[^\000]*")
4213 ((eq ch ?+) "\\+")
4214 ((eq ch ?^) "\\^")
4215 ((eq ch ?$) "\\$")
4216 ((eq ch ?\\) "\\\\") ; probably cannot happen...
4217 ((eq ch ??) "[^\000]")
4218 (t (char-to-string ch)))))
4219 (setq i (1+ i)))))
4220 ;; Shell wildcards should match the entire filename,
4221 ;; not its part. Make the regexp say so.
4222 (concat "\\`" result "\\'")))
4223\f
21540597 4224(defcustom list-directory-brief-switches
b4da00e9 4225 (if (eq system-type 'vax-vms) "" "-CF")
ffc0e1ca 4226 "*Switches for `list-directory' to pass to `ls' for brief listing."
21540597
RS
4227 :type 'string
4228 :group 'dired)
b4da00e9 4229
21540597 4230(defcustom list-directory-verbose-switches
b4da00e9
RM
4231 (if (eq system-type 'vax-vms)
4232 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
4233 "-l")
ffc0e1ca 4234 "*Switches for `list-directory' to pass to `ls' for verbose listing."
21540597
RS
4235 :type 'string
4236 :group 'dired)
b4da00e9 4237
5de148a2
RS
4238(defun file-expand-wildcards (pattern &optional full)
4239 "Expand wildcard pattern PATTERN.
4db2a7de
RS
4240This returns a list of file names which match the pattern.
4241
814af837 4242If PATTERN is written as an absolute file name,
4db2a7de
RS
4243the values are absolute also.
4244
4245If PATTERN is written as a relative file name, it is interpreted
4246relative to the current default directory, `default-directory'.
4247The file names returned are normally also relative to the current
4248default directory. However, if FULL is non-nil, they are absolute."
032388f3
RS
4249 (save-match-data
4250 (let* ((nondir (file-name-nondirectory pattern))
4251 (dirpart (file-name-directory pattern))
4252 ;; A list of all dirs that DIRPART specifies.
4253 ;; This can be more than one dir
4254 ;; if DIRPART contains wildcards.
4255 (dirs (if (and dirpart (string-match "[[*?]" dirpart))
4256 (mapcar 'file-name-as-directory
4257 (file-expand-wildcards (directory-file-name dirpart)))
4258 (list dirpart)))
4259 contents)
4260 (while dirs
4261 (when (or (null (car dirs)) ; Possible if DIRPART is not wild.
4262 (file-directory-p (directory-file-name (car dirs))))
4263 (let ((this-dir-contents
4264 ;; Filter out "." and ".."
4265 (delq nil
4266 (mapcar #'(lambda (name)
4267 (unless (string-match "\\`\\.\\.?\\'"
4268 (file-name-nondirectory name))
4269 name))
4270 (directory-files (or (car dirs) ".") full
4271 (wildcard-to-regexp nondir))))))
4272 (setq contents
4273 (nconc
4274 (if (and (car dirs) (not full))
4275 (mapcar (function (lambda (name) (concat (car dirs) name)))
4276 this-dir-contents)
4277 this-dir-contents)
4278 contents))))
4279 (setq dirs (cdr dirs)))
4280 contents)))
5de148a2 4281
b4da00e9
RM
4282(defun list-directory (dirname &optional verbose)
4283 "Display a list of files in or matching DIRNAME, a la `ls'.
4284DIRNAME is globbed by the shell if necessary.
4285Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
4286Actions controlled by variables `list-directory-brief-switches'
4287and `list-directory-verbose-switches'."
4288 (interactive (let ((pfx current-prefix-arg))
4289 (list (read-file-name (if pfx "List directory (verbose): "
4290 "List directory (brief): ")
4291 nil default-directory nil)
4292 pfx)))
4293 (let ((switches (if verbose list-directory-verbose-switches
84905190
RS
4294 list-directory-brief-switches))
4295 buffer)
b4da00e9
RM
4296 (or dirname (setq dirname default-directory))
4297 (setq dirname (expand-file-name dirname))
4298 (with-output-to-temp-buffer "*Directory*"
84905190 4299 (setq buffer standard-output)
b4da00e9
RM
4300 (buffer-disable-undo standard-output)
4301 (princ "Directory ")
4302 (princ dirname)
4303 (terpri)
c3554e95
RS
4304 (save-excursion
4305 (set-buffer "*Directory*")
4306 (let ((wildcard (not (file-directory-p dirname))))
84905190
RS
4307 (insert-directory dirname switches wildcard (not wildcard)))))
4308 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
4309 (with-current-buffer buffer
4310 (setq default-directory
4311 (if (file-directory-p dirname)
4312 (file-name-as-directory dirname)
4313 (file-name-directory dirname))))))
c3554e95 4314
ffc0e1ca
AS
4315(defun shell-quote-wildcard-pattern (pattern)
4316 "Quote characters special to the shell in PATTERN, leave wildcards alone.
4317
4318PATTERN is assumed to represent a file-name wildcard suitable for the
4319underlying filesystem. For Unix and GNU/Linux, the characters from the
4320set [ \\t\\n;<>&|()#$] are quoted with a backslash; for DOS/Windows, all
4321the parts of the pattern which don't include wildcard characters are
4322quoted with double quotes.
4323Existing quote characters in PATTERN are left alone, so you can pass
4324PATTERN that already quotes some of the special characters."
4325 (save-match-data
4326 (cond
c60ee5e7 4327 ((memq system-type '(ms-dos windows-nt cygwin))
ffc0e1ca
AS
4328 ;; DOS/Windows don't allow `"' in file names. So if the
4329 ;; argument has quotes, we can safely assume it is already
4330 ;; quoted by the caller.
4331 (if (or (string-match "[\"]" pattern)
4332 ;; We quote [&()#$'] in case their shell is a port of a
4333 ;; Unixy shell. We quote [,=+] because stock DOS and
4334 ;; Windows shells require that in some cases, such as
4335 ;; passing arguments to batch files that use positional
4336 ;; arguments like %1.
4337 (not (string-match "[ \t;&()#$',=+]" pattern)))
4338 pattern
4339 (let ((result "\"")
4340 (beg 0)
4341 end)
4342 (while (string-match "[*?]+" pattern beg)
4343 (setq end (match-beginning 0)
4344 result (concat result (substring pattern beg end)
4345 "\""
4346 (substring pattern end (match-end 0))
4347 "\"")
4348 beg (match-end 0)))
4349 (concat result (substring pattern beg) "\""))))
4350 (t
4351 (let ((beg 0))
4352 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
4353 (setq pattern
4354 (concat (substring pattern 0 (match-beginning 0))
4355 "\\"
4356 (substring pattern (match-beginning 0)))
4357 beg (1+ (match-end 0)))))
4358 pattern))))
4359
4360
c3554e95
RS
4361(defvar insert-directory-program "ls"
4362 "Absolute or relative name of the `ls' program used by `insert-directory'.")
4363
f4d04672
RS
4364(defcustom directory-free-space-program "df"
4365 "*Program to get the amount of free space on a file system.
4366We assume the output has the format of `df'.
4367The value of this variable must be just a command name or file name;
4368if you want to specify options, use `directory-free-space-args'.
4369
01b26b90
EZ
4370A value of nil disables this feature.
4371
4372If the function `file-system-info' is defined, it is always used in
4373preference to the program given by this variable."
f4d04672
RS
4374 :type '(choice (string :tag "Program") (const :tag "None" nil))
4375 :group 'dired)
4376
525fdbc9
AS
4377(defcustom directory-free-space-args
4378 (if (eq system-type 'darwin) "-k" "-Pk")
f4d04672
RS
4379 "*Options to use when running `directory-free-space-program'."
4380 :type 'string
4381 :group 'dired)
4382
01b26b90
EZ
4383(defun get-free-disk-space (dir)
4384 "Return the mount of free space on directory DIR's file system.
4385The result is a string that gives the number of free 1KB blocks,
4386or nil if the system call or the program which retrieve the infornmation
4387fail.
4388
4389This function calls `file-system-info' if it is available, or invokes the
4390program specified by `directory-free-space-program' if that is non-nil."
4391 ;; Try to find the number of free blocks. Non-Posix systems don't
4392 ;; always have df, but might have an equivalent system call.
4393 (if (fboundp 'file-system-info)
4394 (let ((fsinfo (file-system-info dir)))
4395 (if fsinfo
4396 (format "%.0f" (/ (nth 2 fsinfo) 1024))))
4397 (save-match-data
4398 (with-temp-buffer
4399 (when (and directory-free-space-program
15502042
EZ
4400 (eq 0 (call-process directory-free-space-program
4401 nil t nil
4402 directory-free-space-args
4403 dir)))
01b26b90
EZ
4404 ;; Usual format is a header line followed by a line of
4405 ;; numbers.
4406 (goto-char (point-min))
4407 (forward-line 1)
4408 (if (not (eobp))
4409 (progn
4410 ;; Move to the end of the "available blocks" number.
4411 (skip-chars-forward "^ \t")
4412 (forward-word 3)
4413 ;; Copy it into AVAILABLE.
4414 (let ((end (point)))
4415 (forward-word -1)
4416 (buffer-substring (point) end)))))))))
4417
4418
a1b0c2a7
RS
4419(defvar insert-directory-ls-version 'unknown)
4420
c3554e95
RS
4421;; insert-directory
4422;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
4423;; FULL-DIRECTORY-P is nil.
4424;; The single line of output must display FILE's name as it was
4425;; given, namely, an absolute path name.
4426;; - must insert exactly one line for each file if WILDCARD or
4427;; FULL-DIRECTORY-P is t, plus one optional "total" line
4428;; before the file lines, plus optional text after the file lines.
4429;; Lines are delimited by "\n", so filenames containing "\n" are not
4430;; allowed.
4431;; File lines should display the basename.
4432;; - must be consistent with
4433;; - functions dired-move-to-filename, (these two define what a file line is)
4434;; dired-move-to-end-of-filename,
4435;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
4436;; dired-insert-headerline
4437;; dired-after-subdir-garbage (defines what a "total" line is)
4438;; - variable dired-subdir-regexp
1fc85dae
KG
4439;; - may be passed "--dired" as the first argument in SWITCHES.
4440;; Filename handlers might have to remove this switch if their
4441;; "ls" command does not support it.
c3554e95 4442(defun insert-directory (file switches &optional wildcard full-directory-p)
a18b7c81 4443 "Insert directory listing for FILE, formatted according to SWITCHES.
c3554e95 4444Leaves point after the inserted text.
8f8607be
LT
4445SWITCHES may be a string of options, or a list of strings
4446representing individual options.
c3554e95
RS
4447Optional third arg WILDCARD means treat FILE as shell wildcard.
4448Optional fourth arg FULL-DIRECTORY-P means file is a directory and
4449switches do not contain `d', so that a full listing is expected.
4450
4451This works by running a directory listing program
406e12d9 4452whose name is in the variable `insert-directory-program'.
8f8607be
LT
4453If WILDCARD, it also runs the shell specified by `shell-file-name'.
4454
60ce7e3e 4455When SWITCHES contains the long `--dired' option, this function
8f8607be
LT
4456treats it specially, for the sake of dired. However, the
4457normally equivalent short `-D' option is just passed on to
4458`insert-directory-program', as any other option."
c870ab8e 4459 ;; We need the directory in order to find the right handler.
d2473540
AS
4460 (let ((handler (find-file-name-handler (expand-file-name file)
4461 'insert-directory)))
ebad92dc 4462 (if handler
c3554e95
RS
4463 (funcall handler 'insert-directory file switches
4464 wildcard full-directory-p)
b4da00e9 4465 (if (eq system-type 'vax-vms)
c3554e95 4466 (vms-read-directory file switches (current-buffer))
818286f4 4467 (let (result (beg (point)))
ebad92dc
RS
4468
4469 ;; Read the actual directory using `insert-directory-program'.
4470 ;; RESULT gets the status code.
99f01c91
KH
4471 (let* (;; We at first read by no-conversion, then after
4472 ;; putting text property `dired-filename, decode one
4473 ;; bunch by one to preserve that property.
4474 (coding-system-for-read 'no-conversion)
4475 ;; This is to control encoding the arguments in call-process.
c60ee5e7 4476 (coding-system-for-write
82e22b57
KH
4477 (and enable-multibyte-characters
4478 (or file-name-coding-system
99f01c91 4479 default-file-name-coding-system))))
ebad92dc
RS
4480 (setq result
4481 (if wildcard
4482 ;; Run ls in the directory part of the file pattern
4483 ;; using the last component as argument.
4484 (let ((default-directory
4485 (if (file-name-absolute-p file)
4486 (file-name-directory file)
4487 (file-name-directory (expand-file-name file))))
4488 (pattern (file-name-nondirectory file)))
4489 (call-process
4490 shell-file-name nil t nil
4491 "-c"
4492 (concat (if (memq system-type '(ms-dos windows-nt))
4493 ""
4494 "\\") ; Disregard Unix shell aliases!
4495 insert-directory-program
4496 " -d "
4497 (if (stringp switches)
4498 switches
4499 (mapconcat 'identity switches " "))
4500 " -- "
4501 ;; Quote some characters that have
4502 ;; special meanings in shells; but
4503 ;; don't quote the wildcards--we want
4504 ;; them to be special. We also
4505 ;; currently don't quote the quoting
4506 ;; characters in case people want to
4507 ;; use them explicitly to quote
4508 ;; wildcard characters.
4509 (shell-quote-wildcard-pattern pattern))))
4510 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
4511 ;; directory if FILE is a symbolic link.
4512 (apply 'call-process
4513 insert-directory-program nil t nil
4514 (append
4515 (if (listp switches) switches
4516 (unless (equal switches "")
4517 ;; Split the switches at any spaces so we can
4518 ;; pass separate options as separate args.
4519 (split-string switches)))
4520 ;; Avoid lossage if FILE starts with `-'.
4521 '("--")
4522 (progn
4523 (if (string-match "\\`~" file)
4524 (setq file (expand-file-name file)))
4525 (list
4526 (if full-directory-p
4527 (concat (file-name-as-directory file) ".")
4528 file))))))))
4529
a1b0c2a7
RS
4530 ;; If we got "//DIRED//" in the output, it means we got a real
4531 ;; directory listing, even if `ls' returned nonzero.
4532 ;; So ignore any errors.
4533 (when (if (stringp switches)
4534 (string-match "--dired\\>" switches)
4535 (member "--dired" switches))
4536 (save-excursion
4537 (forward-line -2)
4538 (when (looking-at "//SUBDIRED//")
4539 (forward-line -1))
4540 (if (looking-at "//DIRED//")
4541 (setq result 0))))
4542
4543 (when (and (not (eq 0 result))
4544 (eq insert-directory-ls-version 'unknown))
4545 ;; The first time ls returns an error,
4546 ;; find the version numbers of ls,
4547 ;; and set insert-directory-ls-version
4548 ;; to > if it is more than 5.2.1, < if it is less, nil if it
4549 ;; is equal or if the info cannot be obtained.
4550 ;; (That can mean it isn't GNU ls.)
4551 (let ((version-out
4552 (with-temp-buffer
4553 (call-process "ls" nil t nil "--version")
4554 (buffer-string))))
4555 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out)
4556 (let* ((version (match-string 1 version-out))
4557 (split (split-string version "[.]"))
4558 (numbers (mapcar 'string-to-int split))
4559 (min '(5 2 1))
4560 comparison)
4561 (while (and (not comparison) (or numbers min))
4562 (cond ((null min)
4563 (setq comparison '>))
4564 ((null numbers)
4565 (setq comparison '<))
4566 ((> (car numbers) (car min))
4567 (setq comparison '>))
4568 ((< (car numbers) (car min))
4569 (setq comparison '<))
4570 (t
4571 (setq numbers (cdr numbers)
4572 min (cdr min)))))
4573 (setq insert-directory-ls-version (or comparison '=)))
4574 (setq insert-directory-ls-version nil))))
4575
4576 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
4577 (when (and (eq 1 result) (eq insert-directory-ls-version '>))
4578 (setq result 0))
4579
ebad92dc 4580 ;; If `insert-directory-program' failed, signal an error.
15502042 4581 (unless (eq 0 result)
f2440e42
RS
4582 ;; Delete the error message it may have output.
4583 (delete-region beg (point))
15502042
EZ
4584 ;; On non-Posix systems, we cannot open a directory, so
4585 ;; don't even try, because that will always result in
4586 ;; the ubiquitous "Access denied". Instead, show the
4587 ;; command line so the user can try to guess what went wrong.
4588 (if (and (file-directory-p file)
4589 (memq system-type '(ms-dos windows-nt)))
4590 (error
4591 "Reading directory: \"%s %s -- %s\" exited with status %s"
4592 insert-directory-program
4593 (if (listp switches) (concat switches) switches)
4594 file result)
4595 ;; Unix. Access the file to get a suitable error.
4596 (access-file file "Reading directory")
4597 (error "Listing directory failed but `access-file' worked")))
ebad92dc 4598
8f8607be
LT
4599 (when (if (stringp switches)
4600 (string-match "--dired\\>" switches)
4601 (member "--dired" switches))
9bb99df6
LT
4602 ;; The following overshoots by one line for an empty
4603 ;; directory listed with "--dired", but without "-a"
4604 ;; switch, where the ls output contains a
4605 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
4606 ;; We take care of that case later.
ff7affeb 4607 (forward-line -2)
9423860f
AS
4608 (when (looking-at "//SUBDIRED//")
4609 (delete-region (point) (progn (forward-line 1) (point)))
4610 (forward-line -1))
9bb99df6
LT
4611 (if (looking-at "//DIRED//")
4612 (let ((end (line-end-position))
4613 (linebeg (point))
4614 error-lines)
4615 ;; Find all the lines that are error messages,
4616 ;; and record the bounds of each one.
4617 (goto-char beg)
4618 (while (< (point) linebeg)
4619 (or (eql (following-char) ?\s)
4620 (push (list (point) (line-end-position)) error-lines))
4621 (forward-line 1))
4622 (setq error-lines (nreverse error-lines))
4623 ;; Now read the numeric positions of file names.
4624 (goto-char linebeg)
4625 (forward-word 1)
4626 (forward-char 3)
4627 (while (< (point) end)
4628 (let ((start (insert-directory-adj-pos
4629 (+ beg (read (current-buffer)))
4630 error-lines))
4631 (end (insert-directory-adj-pos
a1b0c2a7 4632 (+ beg (read (current-buffer)))
9bb99df6
LT
4633 error-lines)))
4634 (if (memq (char-after end) '(?\n ?\ ))
4635 ;; End is followed by \n or by " -> ".
4636 (put-text-property start end 'dired-filename t)
4637 ;; It seems that we can't trust ls's output as to
4638 ;; byte positions of filenames.
4639 (put-text-property beg (point) 'dired-filename nil)
4640 (end-of-line))))
4641 (goto-char end)
4642 (beginning-of-line)
4643 (delete-region (point) (progn (forward-line 1) (point))))
4644 ;; Take care of the case where the ls output contains a
4645 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
4646 ;; and we went one line too far back (see above).
4647 (forward-line 1))
4648 (if (looking-at "//DIRED-OPTIONS//")
4649 (delete-region (point) (progn (forward-line 1) (point)))))
ff7affeb 4650
99f01c91 4651 ;; Now decode what read if necessary.
b6647390
KH
4652 (let ((coding (or coding-system-for-read
4653 file-name-coding-system
4654 default-file-name-coding-system
4655 'undecided))
0bded065 4656 coding-no-eol
99f01c91 4657 val pos)
b6647390
KH
4658 (when (and enable-multibyte-characters
4659 (not (memq (coding-system-base coding)
4660 '(raw-text no-conversion))))
4661 ;; If no coding system is specified or detection is
4662 ;; requested, detect the coding.
4663 (if (eq (coding-system-base coding) 'undecided)
4664 (setq coding (detect-coding-region beg (point) t)))
4665 (if (not (eq (coding-system-base coding) 'undecided))
4666 (save-restriction
0bded065
AS
4667 (setq coding-no-eol
4668 (coding-system-change-eol-conversion coding 'unix))
b6647390
KH
4669 (narrow-to-region beg (point))
4670 (goto-char (point-min))
4671 (while (not (eobp))
4672 (setq pos (point)
4673 val (get-text-property (point) 'dired-filename))
4674 (goto-char (next-single-property-change
4675 (point) 'dired-filename nil (point-max)))
0bded065
AS
4676 ;; Force no eol conversion on a file name, so
4677 ;; that CR is preserved.
4678 (decode-coding-region pos (point)
4679 (if val coding-no-eol coding))
b6647390
KH
4680 (if val
4681 (put-text-property pos (point)
4682 'dired-filename t)))))))
99f01c91 4683
75bb5ca4
AS
4684 (if full-directory-p
4685 ;; Try to insert the amount of free space.
4686 (save-excursion
4687 (goto-char beg)
4688 ;; First find the line to put it on.
4689 (when (re-search-forward "^ *\\(total\\)" nil t)
4690 (let ((available (get-free-disk-space ".")))
4691 (when available
4692 ;; Replace "total" with "used", to avoid confusion.
4693 (replace-match "total used in directory" nil nil nil 1)
4694 (end-of-line)
4695 (insert " available " available)))))))))))
34342a07 4696
a1b0c2a7 4697(defun insert-directory-adj-pos (pos error-lines)
fead94d6 4698 "Convert `ls --dired' file name position value POS to a buffer position.
a1b0c2a7
RS
4699File name position values returned in ls --dired output
4700count only stdout; they don't count the error messages sent to stderr.
4701So this function converts to them to real buffer positions.
4702ERROR-LINES is a list of buffer positions of error message lines,
4703of the form (START END)."
4704 (while (and error-lines (< (caar error-lines) pos))
4705 (setq pos (+ pos (- (nth 1 (car error-lines)) (nth 0 (car error-lines)))))
4706 (pop error-lines))
4707 pos)
4708
bc22fd18
EZ
4709(defun insert-directory-safely (file switches
4710 &optional wildcard full-directory-p)
4711 "Insert directory listing for FILE, formatted according to SWITCHES.
4712
4713Like `insert-directory', but if FILE does not exist, it inserts a
4714message to that effect instead of signaling an error."
4715 (if (file-exists-p file)
4716 (insert-directory file switches wildcard full-directory-p)
4717 ;; Simulate the message printed by `ls'.
4718 (insert (format "%s: No such file or directory\n" file))))
4719
88902b35 4720(defvar kill-emacs-query-functions nil
65d5c6de 4721 "Functions to call with no arguments to query about killing Emacs.
78c793d1
RS
4722If any of these functions returns nil, killing Emacs is cancelled.
4723`save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
4724but `kill-emacs', the low level primitive, does not.
4725See also `kill-emacs-hook'.")
88902b35 4726
11f15305 4727(defcustom confirm-kill-emacs nil
9c2ba08f
EZ
4728 "How to ask for confirmation when leaving Emacs.
4729If nil, the default, don't ask at all. If the value is non-nil, it should
4730be a predicate function such as `yes-or-no-p'."
11f15305
GM
4731 :type '(choice (const :tag "Ask with yes-or-no-p" yes-or-no-p)
4732 (const :tag "Ask with y-or-n-p" y-or-n-p)
4733 (const :tag "Don't confirm" nil))
bdd9ab6e 4734 :group 'convenience
11f15305
GM
4735 :version "21.1")
4736
b4da00e9
RM
4737(defun save-buffers-kill-emacs (&optional arg)
4738 "Offer to save each buffer, then kill this Emacs process.
4739With prefix arg, silently save all file-visiting buffers, then kill."
4740 (interactive "P")
4741 (save-some-buffers arg t)
4742 (and (or (not (memq t (mapcar (function
4743 (lambda (buf) (and (buffer-file-name buf)
4744 (buffer-modified-p buf))))
4745 (buffer-list))))
4746 (yes-or-no-p "Modified buffers exist; exit anyway? "))
4747 (or (not (fboundp 'process-list))
4748 ;; process-list is not defined on VMS.
4749 (let ((processes (process-list))
4750 active)
4751 (while processes
48a4a1fb
KS
4752 (and (memq (process-status (car processes)) '(run stop open listen))
4753 (process-query-on-exit-flag (car processes))
b4da00e9
RM
4754 (setq active t))
4755 (setq processes (cdr processes)))
4756 (or (not active)
48a4a1fb 4757 (list-processes t)
b4da00e9 4758 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
88902b35 4759 ;; Query the user for other things, perhaps.
fb15c113 4760 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
11f15305
GM
4761 (or (null confirm-kill-emacs)
4762 (funcall confirm-kill-emacs "Really exit Emacs? "))
b4da00e9
RM
4763 (kill-emacs)))
4764\f
ffc0e1ca 4765;; We use /: as a prefix to "quote" a file name
47afc068
RS
4766;; so that magic file name handlers will not apply to it.
4767
4768(setq file-name-handler-alist
4769 (cons '("\\`/:" . file-name-non-special)
4770 file-name-handler-alist))
4771
4772;; We depend on being the last handler on the list,
4773;; so that anything else which does need handling
4774;; has been handled already.
4775;; So it is safe for us to inhibit *all* magic file name handlers.
4776
4777(defun file-name-non-special (operation &rest arguments)
4778 (let ((file-name-handler-alist nil)
5cb1f728
KH
4779 (default-directory
4780 (if (eq operation 'insert-directory)
4781 (directory-file-name
ffc0e1ca 4782 (expand-file-name
5cb1f728
KH
4783 (unhandled-file-name-directory default-directory)))
4784 default-directory))
47afc068
RS
4785 ;; Get a list of the indices of the args which are file names.
4786 (file-arg-indices
4787 (cdr (or (assq operation
ae3b2983 4788 ;; The first six are special because they
47afc068
RS
4789 ;; return a file name. We want to include the /:
4790 ;; in the return value.
4791 ;; So just avoid stripping it in the first place.
4792 '((expand-file-name . nil)
4793 (file-name-directory . nil)
4794 (file-name-as-directory . nil)
4795 (directory-file-name . nil)
c736f678 4796 (file-name-sans-versions . nil)
ae3b2983 4797 (find-backup-file-name . nil)
c736f678 4798 ;; `identity' means just return the first arg
6750c852
RS
4799 ;; not stripped of its quoting.
4800 (substitute-in-file-name identity)
ae3b2983
MA
4801 ;; `add' means add "/:" to the result.
4802 (file-truename add 0)
4803 ;; `quote' means add "/:" to buffer-file-name.
4804 (insert-file-contents quote 0)
4805 ;; `unquote-then-quote' means set buffer-file-name
4806 ;; temporarily to unquoted filename.
4807 (verify-visited-file-modtime unquote-then-quote)
4808 ;; List the arguments which are filenames.
c37adaa5
SM
4809 (file-name-completion 1)
4810 (file-name-all-completions 1)
ae3b2983 4811 (write-region 2 5)
47afc068
RS
4812 (rename-file 0 1)
4813 (copy-file 0 1)
4814 (make-symbolic-link 0 1)
4815 (add-name-to-file 0 1)))
4816 ;; For all other operations, treat the first argument only
4817 ;; as the file name.
4818 '(nil 0))))
6750c852 4819 method
47afc068
RS
4820 ;; Copy ARGUMENTS so we can replace elements in it.
4821 (arguments (copy-sequence arguments)))
6750c852
RS
4822 (if (symbolp (car file-arg-indices))
4823 (setq method (pop file-arg-indices)))
4824 ;; Strip off the /: from the file names that have it.
47afc068 4825 (save-match-data
18b9dced 4826 (while (consp file-arg-indices)
fe4d9852
KH
4827 (let ((pair (nthcdr (car file-arg-indices) arguments)))
4828 (and (car pair)
4829 (string-match "\\`/:" (car pair))
4830 (setcar pair
4831 (if (= (length (car pair)) 2)
4832 "/"
4833 (substring (car pair) 2)))))
47afc068 4834 (setq file-arg-indices (cdr file-arg-indices))))
6750c852
RS
4835 (cond ((eq method 'identity)
4836 (car arguments))
ae3b2983 4837 ((eq method 'add)
6750c852 4838 (concat "/:" (apply operation arguments)))
ae3b2983
MA
4839 ((eq method 'quote)
4840 (prog1 (apply operation arguments)
4841 (setq buffer-file-name (concat "/:" buffer-file-name))))
4842 ((eq method 'unquote-then-quote)
4843 (let (res)
4844 (setq buffer-file-name (substring buffer-file-name 2))
4845 (setq res (apply operation arguments))
4846 (setq buffer-file-name (concat "/:" buffer-file-name))
4847 res))
6750c852
RS
4848 (t
4849 (apply operation arguments)))))
47afc068 4850\f
b4da00e9 4851(define-key ctl-x-map "\C-f" 'find-file)
b4da00e9
RM
4852(define-key ctl-x-map "\C-r" 'find-file-read-only)
4853(define-key ctl-x-map "\C-v" 'find-alternate-file)
4854(define-key ctl-x-map "\C-s" 'save-buffer)
4855(define-key ctl-x-map "s" 'save-some-buffers)
4856(define-key ctl-x-map "\C-w" 'write-file)
4857(define-key ctl-x-map "i" 'insert-file)
4858(define-key esc-map "~" 'not-modified)
4859(define-key ctl-x-map "\C-d" 'list-directory)
4860(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
d758359d 4861(define-key ctl-x-map "\C-q" 'toggle-read-only)
b4da00e9
RM
4862
4863(define-key ctl-x-4-map "f" 'find-file-other-window)
4864(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
4865(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
4866(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
924f0a24 4867(define-key ctl-x-4-map "\C-o" 'display-buffer)
5bbbceb1 4868
f98955ea
JB
4869(define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
4870(define-key ctl-x-5-map "f" 'find-file-other-frame)
4871(define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
4872(define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
c0274f38 4873
ab5796a9 4874;;; arch-tag: bc68d3ea-19ca-468b-aac6-3a4a7766101f
c0274f38 4875;;; files.el ends here