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