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