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