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