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