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