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