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