(Faset): Calculate nbytes earlier, to satisfy the now pickier
[bpt/emacs.git] / lisp / files.el
CommitLineData
c0274f38
ER
1;;; files.el --- file input and output commands for Emacs
2
48a4a1fb 3;; Copyright (C) 1985, 86, 87, 92, 93, 94, 95, 96, 97, 98, 99, 2000, 2001, 2002
b4990dde 4;;; Free Software Foundation, Inc.
b4da00e9 5
3a801d0c
ER
6;; Maintainer: FSF
7
b4da00e9
RM
8;; This file is part of GNU Emacs.
9
10;; GNU Emacs is free software; you can redistribute it and/or modify
11;; it under the terms of the GNU General Public License as published by
e5167999 12;; the Free Software Foundation; either version 2, or (at your option)
b4da00e9
RM
13;; any later version.
14
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
693f800d
RS
21;; along with GNU Emacs; see the file COPYING. If not, write to the
22;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23;; Boston, MA 02111-1307, USA.
b4da00e9 24
e41b2db1
ER
25;;; Commentary:
26
27;; Defines most of Emacs's file- and directory-handling functions,
28;; including basic file visiting, backup generation, link handling,
29;; ITS-id version control, load- and write-hook handling, and the like.
30
e5167999
ER
31;;; Code:
32
21540597
RS
33(defgroup backup nil
34 "Backups of edited data files."
2a9fe1e2 35 :group 'files)
b4da00e9 36
21540597 37(defgroup find-file nil
2a9fe1e2
RS
38 "Finding files."
39 :group 'files)
21540597
RS
40
41
42(defcustom delete-auto-save-files t
92631216
EZ
43 "*Non-nil means delete auto-save file when a buffer is saved or killed.
44
45Note that auto-save file will not be deleted if the buffer is killed
46when it has unsaved changes."
21540597
RS
47 :type 'boolean
48 :group 'auto-save)
49
50(defcustom directory-abbrev-alist
b4da00e9
RM
51 nil
52 "*Alist of abbreviations for file directories.
53A list of elements of the form (FROM . TO), each meaning to replace
54FROM with TO when it appears in a directory name. This replacement is
55done when setting up the default directory of a newly visited file.
56*Every* FROM string should start with `^'.
57
65151a1b
RS
58Do not use `~' in the TO strings.
59They should be ordinary absolute directory names.
60
b4da00e9
RM
61Use this feature when you have directories which you normally refer to
62via absolute symbolic links. Make TO the name of the link, and FROM
21540597
RS
63the name it is linked to."
64 :type '(repeat (cons :format "%v"
65 :value ("" . "")
66 (regexp :tag "From")
67 (regexp :tag "To")))
68 :group 'abbrev
69 :group 'find-file)
b4da00e9 70
5c6d31a4 71;; Turn off backup files on VMS since it has version numbers.
21540597 72(defcustom make-backup-files (not (eq system-type 'vax-vms))
4ea836c1 73 "*Non-nil means make a backup of a file the first time it is saved.
b4da00e9
RM
74This can be done by renaming the file or by copying.
75
76Renaming means that Emacs renames the existing file so that it is a
77backup file, then writes the buffer into a new file. Any other names
78that the old file had will now refer to the backup file. The new file
79is owned by you and its group is defaulted.
80
81Copying means that Emacs copies the existing file into the backup
82file, then writes the buffer on top of the existing file. Any other
83names that the old file had will now refer to the new (edited) file.
84The file's owner and group are unchanged.
85
86The choice of renaming or copying is controlled by the variables
ffc0e1ca
AS
87`backup-by-copying', `backup-by-copying-when-linked',
88`backup-by-copying-when-mismatch' and
89`backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
21540597
RS
90 :type 'boolean
91 :group 'backup)
b4da00e9
RM
92
93;; Do this so that local variables based on the file name
94;; are not overridden by the major mode.
95(defvar backup-inhibited nil
f862241d
RS
96 "Non-nil means don't make a backup, regardless of the other parameters.
97This variable is intended for use by making it local to a buffer.
98But it is local only if you make it local.")
b4da00e9
RM
99(put 'backup-inhibited 'permanent-local t)
100
21540597 101(defcustom backup-by-copying nil
b4da00e9 102 "*Non-nil means always use copying to create backup files.
21540597
RS
103See documentation of variable `make-backup-files'."
104 :type 'boolean
105 :group 'backup)
b4da00e9 106
21540597 107(defcustom backup-by-copying-when-linked nil
b4da00e9
RM
108 "*Non-nil means use copying to create backups for files with multiple names.
109This causes the alternate names to refer to the latest version as edited.
21540597
RS
110This variable is relevant only if `backup-by-copying' is nil."
111 :type 'boolean
112 :group 'backup)
b4da00e9 113
21540597 114(defcustom backup-by-copying-when-mismatch nil
b4da00e9
RM
115 "*Non-nil means create backups by copying if this preserves owner or group.
116Renaming may still be used (subject to control of other variables)
117when it would not result in changing the owner or group of the file;
118that is, for files which are owned by you and whose group matches
119the default for a new file created there by you.
21540597
RS
120This variable is relevant only if `backup-by-copying' is nil."
121 :type 'boolean
122 :group 'backup)
b4da00e9 123
ffc0e1ca
AS
124(defcustom backup-by-copying-when-privileged-mismatch 200
125 "*Non-nil means create backups by copying to preserve a privileged owner.
126Renaming may still be used (subject to control of other variables)
127when it would not result in changing the owner of the file or if the owner
128has a user id greater than the value of this variable. This is useful
129when low-numbered uid's are used for special system users (such as root)
130that must maintain ownership of certain files.
131This variable is relevant only if `backup-by-copying' and
132`backup-by-copying-when-mismatch' are nil."
133 :type '(choice (const nil) integer)
134 :group 'backup)
135
ffc0e1ca 136(defvar backup-enable-predicate 'normal-backup-enable-predicate
b4da00e9 137 "Predicate that looks at a file name and decides whether to make backups.
37193ee6 138Called with an absolute file name as argument, it returns t to enable backup.")
b4da00e9 139
21540597 140(defcustom buffer-offer-save nil
ffc0e1ca
AS
141 "*Non-nil in a buffer means always offer to save buffer on exit.
142Do so even if the buffer is not visiting a file.
21540597
RS
143Automatically local in all buffers."
144 :type 'boolean
145 :group 'backup)
b4da00e9
RM
146(make-variable-buffer-local 'buffer-offer-save)
147
21540597 148(defcustom find-file-existing-other-name t
f3e23606
RS
149 "*Non-nil means find a file under alternative names, in existing buffers.
150This means if any existing buffer is visiting the file you want
21540597
RS
151under another name, you get the existing buffer instead of a new buffer."
152 :type 'boolean
153 :group 'find-file)
f3e23606 154
21540597 155(defcustom find-file-visit-truename nil
f3e23606
RS
156 "*Non-nil means visit a file under its truename.
157The truename of a file is found by chasing all links
21540597
RS
158both at the file level and at the levels of the containing directories."
159 :type 'boolean
160 :group 'find-file)
f3e23606 161
db8c4866 162(defcustom revert-without-query
d7fa5aa2 163 nil
ebeb898f
RS
164 "*Specify which files should be reverted without query.
165The value is a list of regular expressions.
166If the file name matches one of these regular expressions,
db8c4866 167then `revert-buffer' reverts the file without querying
21540597 168if the file has changed on disk and you have not edited the buffer."
a0d809f2 169 :type '(repeat regexp)
21540597 170 :group 'find-file)
ebeb898f 171
f3e23606
RS
172(defvar buffer-file-number nil
173 "The device number and file number of the file visited in the current buffer.
174The value is a list of the form (FILENUM DEVNUM).
175This pair of numbers uniquely identifies the file.
176If the buffer is visiting a new file, the value is nil.")
177(make-variable-buffer-local 'buffer-file-number)
178(put 'buffer-file-number 'permanent-local t)
179
de88363f
RS
180(defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
181 "Non-nil means that buffer-file-number uniquely identifies files.")
182
e554eeb7
RS
183(defvar buffer-file-read-only nil
184 "Non-nil if visited file was read-only when visited.")
185(make-variable-buffer-local 'buffer-file-read-only)
186
388d6ab5 187(defcustom temporary-file-directory
eb61b61b
RS
188 (file-name-as-directory
189 (cond ((memq system-type '(ms-dos windows-nt))
190 (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
191 ((memq system-type '(vax-vms axp-vms))
192 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
193 (t
194 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
388d6ab5
RS
195 "The directory for writing temporary files."
196 :group 'files
197 :type 'directory)
eb61b61b 198
388d6ab5 199(defcustom small-temporary-file-directory
eb61b61b
RS
200 (if (eq system-type 'ms-dos) (getenv "TMPDIR"))
201 "The directory for writing small temporary files.
202If non-nil, this directory is used instead of `temporary-file-directory'
203by programs that create small temporary files. This is for systems that
388d6ab5
RS
204have fast storage with limited space, such as a RAM disk."
205 :group 'files
bab6eadb 206 :type '(choice (const nil) directory))
eb61b61b
RS
207
208;; The system null device. (Should reference NULL_DEVICE from C.)
209(defvar null-device "/dev/null" "The system null device.")
210
30966847
EZ
211(defvar file-name-invalid-regexp
212 (cond ((and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
9959c16e 213 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
30966847 214 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
edfc7f25 215 "[\000-\031]\\|" ; control characters
30966847
EZ
216 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
217 "\\(/[^/.]+\\.[^/.]*\\.\\)")) ; more than a single dot
c60ee5e7 218 ((memq system-type '(ms-dos windows-nt cygwin))
9959c16e 219 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
106a57a4 220 "[|<>\"?*\000-\031]")) ; invalid characters
30966847
EZ
221 (t "[\000]"))
222 "Regexp recognizing file names which aren't allowed by the filesystem.")
223
21540597 224(defcustom file-precious-flag nil
b4da00e9 225 "*Non-nil means protect against I/O errors while saving files.
560f4415 226Some modes set this non-nil in particular buffers.
4b7271c1
KH
227
228This feature works by writing the new contents into a temporary file
229and then renaming the temporary file to replace the original.
230In this way, any I/O error in writing leaves the original untouched,
231and there is never any instant where the file is nonexistent.
232
233Note that this feature forces backups to be made by copying.
560f4415 234Yet, at the same time, saving a precious file
21540597
RS
235breaks any hard links between it and other files."
236 :type 'boolean
237 :group 'backup)
b4da00e9 238
21540597 239(defcustom version-control nil
b4da00e9
RM
240 "*Control use of version numbers for backup files.
241t means make numeric backup versions unconditionally.
242nil means make them for files that have some already.
21540597 243`never' means do not make them."
e48807d1
AS
244 :type '(choice (const :tag "Never" never)
245 (const :tag "If existing" nil)
246 (other :tag "Always" t))
21540597
RS
247 :group 'backup
248 :group 'vc)
249
250(defcustom dired-kept-versions 2
251 "*When cleaning directory, number of versions to keep."
252 :type 'integer
253 :group 'backup
254 :group 'dired)
255
256(defcustom delete-old-versions nil
de7d5e1b 257 "*If t, delete excess backup versions silently.
21540597
RS
258If nil, ask confirmation. Any other value prevents any trimming."
259 :type '(choice (const :tag "Delete" t)
260 (const :tag "Ask" nil)
e48807d1 261 (other :tag "Leave" other))
21540597
RS
262 :group 'backup)
263
264(defcustom kept-old-versions 2
265 "*Number of oldest versions to keep when a new numbered backup is made."
266 :type 'integer
267 :group 'backup)
268
269(defcustom kept-new-versions 2
b4da00e9 270 "*Number of newest versions to keep when a new numbered backup is made.
21540597
RS
271Includes the new backup. Must be > 0"
272 :type 'integer
273 :group 'backup)
b4da00e9 274
21540597 275(defcustom require-final-newline nil
b4da00e9
RM
276 "*Value of t says silently ensure a file ends in a newline when it is saved.
277Non-nil but not t says ask user whether to add a newline when there isn't one.
21540597 278nil means don't add newlines."
ad375092
RS
279 :type '(choice (const :tag "Off" nil)
280 (const :tag "Add" t)
e48807d1 281 (other :tag "Ask" ask))
21540597 282 :group 'editing-basics)
b4da00e9 283
21540597
RS
284(defcustom auto-save-default t
285 "*Non-nil says by default do auto-saving of every file-visiting buffer."
286 :type 'boolean
287 :group 'auto-save)
b4da00e9 288
21540597 289(defcustom auto-save-visited-file-name nil
b4da00e9 290 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
21540597
RS
291Normally auto-save files are written under other names."
292 :type 'boolean
293 :group 'auto-save)
b4da00e9 294
ffc0e1ca 295(defcustom auto-save-file-name-transforms
a2899d6c 296 `(("\\`/[^/]*:\\(.+/\\)*\\(.*\\)"
747981b0
EZ
297 ;; Don't put "\\2" inside expand-file-name, since it will be
298 ;; transformed to "/2" on DOS/Windows.
a0b60c33 299 ,(concat temporary-file-directory "\\2") t))
ffc0e1ca 300 "*Transforms to apply to buffer file name before making auto-save file name.
a0b60c33 301Each transform is a list (REGEXP REPLACEMENT UNIQUIFY):
ffc0e1ca
AS
302REGEXP is a regular expression to match against the file name.
303If it matches, `replace-match' is used to replace the
304matching part with REPLACEMENT.
a0b60c33 305If the optional element UNIQUIFY is non-nil, the auto-save file name is
36236b72 306constructed by taking the directory part of the replaced file-name,
a0b60c33
GM
307concatenated with the buffer file name with all directory separators
308changed to `!' to prevent clashes. This will not work
309correctly if your filesystem truncates the resulting name.
310
ffc0e1ca
AS
311All the transforms in the list are tried, in the order they are listed.
312When one transform applies, its result is final;
313no further transforms are tried.
314
a2899d6c
KG
315The default value is set up to put the auto-save file into the
316temporary directory (see the variable `temporary-file-directory') for
a0b60c33
GM
317editing a remote file.
318
319On MS-DOS filesystems without long names this variable is always
320ignored."
ffc0e1ca 321 :group 'auto-save
a0b60c33
GM
322 :type '(repeat (list (string :tag "Regexp") (string :tag "Replacement")
323 (boolean :tag "Uniquify")))
ffc0e1ca
AS
324 :version "21.1")
325
88b36776 326(defcustom save-abbrevs t
02c6a1cc
EZ
327 "*Non-nil means save word abbrevs too when files are saved.
328If `silently', don't ask the user before saving."
329 :type '(choice (const t) (const nil) (const silently))
21540597 330 :group 'abbrev)
b4da00e9 331
21540597 332(defcustom find-file-run-dired t
ffc0e1ca
AS
333 "*Non-nil means allow `find-file' to visit directories.
334To visit the directory, `find-file' runs `find-directory-functions'."
21540597
RS
335 :type 'boolean
336 :group 'find-file)
b4da00e9 337
ffc0e1ca
AS
338(defcustom find-directory-functions '(cvs-dired-noselect dired-noselect)
339 "*List of functions to try in sequence to visit a directory.
340Each function is called with the directory name as the sole argument
341and should return either a buffer or nil."
342 :type '(hook :options (cvs-dired-noselect dired-noselect))
343 :group 'find-file)
344
92966e6f
RS
345;;;It is not useful to make this a local variable.
346;;;(put 'find-file-not-found-hooks 'permanent-local t)
0370fe77 347(defvar find-file-not-found-functions nil
b4da00e9
RM
348 "List of functions to be called for `find-file' on nonexistent file.
349These functions are called as soon as the error is detected.
ffc0e1ca 350Variable `buffer-file-name' is already set up.
b4da00e9 351The functions are called in the order given until one of them returns non-nil.")
0370fe77
SM
352(defvaralias 'find-file-not-found-hooks 'find-file-not-found-functions)
353(make-obsolete-variable
354 'find-file-not-found-hooks 'find-file-not-found-functions "21.4")
b4da00e9 355
92966e6f
RS
356;;;It is not useful to make this a local variable.
357;;;(put 'find-file-hooks 'permanent-local t)
0370fe77 358(defvar find-file-hook nil
b4da00e9
RM
359 "List of functions to be called after a buffer is loaded from a file.
360The buffer's local variables (if any) will have been processed before the
361functions are called.")
0370fe77
SM
362(defvaralias 'find-file-hooks 'find-file-hook)
363(make-obsolete-variable 'find-file-hooks 'find-file-hook "21.4")
b4da00e9 364
0370fe77 365(defvar write-file-functions nil
b4da00e9
RM
366 "List of functions to be called before writing out a buffer to a file.
367If one of them returns non-nil, the file is considered already written
8c0e7b73
JB
368and the rest are not called.
369These hooks are considered to pertain to the visited file.
0370fe77
SM
370So any buffer-local binding of this variable is discarded if you change
371the visited file name with \\[set-visited-file-name], but not when you
372change the major mode.
373
374See also `write-contents-functions'.")
375(put 'write-file-functions 'permanent-local t)
376(defvaralias 'write-file-hooks 'write-file-functions)
377(make-obsolete-variable 'write-file-hooks 'write-file-functions "21.4")
378
379(defvar local-write-file-hooks nil)
b19f1da4
BF
380(make-variable-buffer-local 'local-write-file-hooks)
381(put 'local-write-file-hooks 'permanent-local t)
0370fe77 382(make-obsolete-variable 'local-write-file-hooks 'write-file-functions "21.4")
8c0e7b73 383
0370fe77 384(defvar write-contents-functions nil
8c0e7b73
JB
385 "List of functions to be called before writing out a buffer to a file.
386If one of them returns non-nil, the file is considered already written
387and the rest are not called.
f82966e4
KH
388
389This variable is meant to be used for hooks that pertain to the
390buffer's contents, not to the particular visited file; thus,
391`set-visited-file-name' does not clear this variable; but changing the
693f800d
RS
392major mode does clear it.
393
0370fe77
SM
394See also `write-file-functions'.")
395(make-variable-buffer-local 'write-contents-functions)
396(defvaralias 'write-contents-hooks 'write-contents-functions)
397(make-obsolete-variable 'write-contents-hooks 'write-contents-functions "21.4")
b4da00e9 398
21540597 399(defcustom enable-local-variables t
93a2702d 400 "*Control use of local variables in files you visit.
b4da00e9 401The value can be t, nil or something else.
93a2702d 402A value of t means file local variables specifications are obeyed;
b4da00e9 403nil means they are ignored; anything else means query.
aa5fcebf
KH
404This variable also controls use of major modes specified in
405a -*- line.
b4da00e9 406
aa5fcebf
KH
407The command \\[normal-mode], when used interactively,
408always obeys file local variable specifications and the -*- line,
409and ignores this variable."
21540597
RS
410 :type '(choice (const :tag "Obey" t)
411 (const :tag "Ignore" nil)
e48807d1 412 (other :tag "Query" other))
21540597 413 :group 'find-file)
b4da00e9 414
da09b92b
RS
415(defvar local-enable-local-variables t
416 "Like `enable-local-variables' but meant for buffer-local bindings.
aa5fcebf 417The meaningful values are nil and non-nil. The default is non-nil.
da09b92b 418If a major mode sets this to nil, buffer-locally, then any local
aa5fcebf
KH
419variables list in the file will be ignored.
420
421This variable does not affect the use of major modes
422specified in a -*- line.")
da09b92b 423
21540597 424(defcustom enable-local-eval 'maybe
d207b766
RS
425 "*Control processing of the \"variable\" `eval' in a file's local variables.
426The value can be t, nil or something else.
427A value of t means obey `eval' variables;
428nil means ignore them; anything else means query.
429
430The command \\[normal-mode] always obeys local-variables lists
21540597
RS
431and ignores this variable."
432 :type '(choice (const :tag "Obey" t)
433 (const :tag "Ignore" nil)
e48807d1 434 (other :tag "Query" other))
21540597 435 :group 'find-file)
b4da00e9
RM
436
437;; Avoid losing in versions where CLASH_DETECTION is disabled.
438(or (fboundp 'lock-buffer)
231c4e10 439 (defalias 'lock-buffer 'ignore))
b4da00e9 440(or (fboundp 'unlock-buffer)
231c4e10 441 (defalias 'unlock-buffer 'ignore))
a7305f6e
RS
442(or (fboundp 'file-locked-p)
443 (defalias 'file-locked-p 'ignore))
93fe0a35 444
818286f4 445(defvar view-read-only) ;Declared in view.el.
2a9fe1e2 446
1aa8fe46 447(put 'ange-ftp-completion-hook-function 'safe-magic t)
93fe0a35 448(defun ange-ftp-completion-hook-function (op &rest args)
ffc0e1ca
AS
449 "Provides support for ange-ftp host name completion.
450Runs the usual ange-ftp hook, but only for completion operations."
451 ;; Having this here avoids the need to load ange-ftp when it's not
452 ;; really in use.
93fe0a35
RS
453 (if (memq op '(file-name-completion file-name-all-completions))
454 (apply 'ange-ftp-hook-function op args)
57e81f57
RS
455 (let ((inhibit-file-name-handlers
456 (cons 'ange-ftp-completion-hook-function
457 (and (eq inhibit-file-name-operation op)
458 inhibit-file-name-handlers)))
459 (inhibit-file-name-operation op))
93fe0a35 460 (apply op args))))
567c1ca9
RS
461
462(defun convert-standard-filename (filename)
463 "Convert a standard file's name to something suitable for the current OS.
464This function's standard definition is trivial; it just returns the argument.
ffc0e1ca
AS
465However, on some systems, the function is redefined with a definition
466that really does change some file names to canonicalize certain
467patterns and to guarantee valid names."
567c1ca9 468 filename)
5d4d17b8
KS
469
470(defun read-directory-name (prompt &optional dir default-dirname mustmatch initial)
471 "Read directory name, prompting with PROMPT and completing in directory DIR.
472Value is not expanded---you must call `expand-file-name' yourself.
473Default name to DEFAULT-DIRNAME if user enters a null string.
474 (If DEFAULT-DIRNAME is omitted, the current buffer's directory is used,
475 except that if INITIAL is specified, that combined with DIR is used.)
476Fourth arg MUSTMATCH non-nil means require existing directory's name.
477 Non-nil and non-t means also require confirmation after completion.
478Fifth arg INITIAL specifies text to start with.
479DIR defaults to current buffer's directory default."
480 (unless dir
481 (setq dir default-directory))
482 (unless default-dirname
36236b72 483 (setq default-dirname
5d4d17b8
KS
484 (if initial (concat dir initial) default-directory)))
485 (read-file-name prompt dir default-dirname mustmatch initial
486 'file-directory-p))
487
b4da00e9
RM
488\f
489(defun pwd ()
490 "Show the current default directory."
491 (interactive nil)
492 (message "Directory %s" default-directory))
493
231c4e10
ER
494(defvar cd-path nil
495 "Value of the CDPATH environment variable, as a list.
9ee45b2c 496Not actually set up until the first time you use it.")
231c4e10
ER
497
498(defun parse-colon-path (cd-path)
ffc0e1ca
AS
499 "Explode a colon-separated search path into a list of directory names.
500\(For values of `colon' equal to `path-separator'.)"
501 ;; We could use split-string here.
231c4e10 502 (and cd-path
818286f4 503 (let (cd-list (cd-start 0) cd-colon)
306faa42
RS
504 (setq cd-path (concat cd-path path-separator))
505 (while (setq cd-colon (string-match path-separator cd-path cd-start))
231c4e10 506 (setq cd-list
9daefb36 507 (nconc cd-list
c52e4104
RS
508 (list (if (= cd-start cd-colon)
509 nil
510 (substitute-in-file-name
e33e80e4
RS
511 (file-name-as-directory
512 (substring cd-path cd-start cd-colon)))))))
231c4e10
ER
513 (setq cd-start (+ cd-colon 1)))
514 cd-list)))
515
516(defun cd-absolute (dir)
30c5ce9c 517 "Change current directory to given absolute file name DIR."
f4a0f59b
RS
518 ;; Put the name into directory syntax now,
519 ;; because otherwise expand-file-name may give some bad results.
b4da00e9
RM
520 (if (not (eq system-type 'vax-vms))
521 (setq dir (file-name-as-directory dir)))
f4a0f59b 522 (setq dir (abbreviate-file-name (expand-file-name dir)))
b4da00e9 523 (if (not (file-directory-p dir))
83c6f446
RS
524 (if (file-exists-p dir)
525 (error "%s is not a directory" dir)
31c691c1 526 (error "%s: no such directory" dir))
b4da00e9
RM
527 (if (file-executable-p dir)
528 (setq default-directory dir)
9daefb36 529 (error "Cannot cd to %s: Permission denied" dir))))
b4da00e9 530
231c4e10
ER
531(defun cd (dir)
532 "Make DIR become the current buffer's default directory.
30c5ce9c
RS
533If your environment includes a `CDPATH' variable, try each one of that
534colon-separated list of directories when resolving a relative directory name."
dac4ea74 535 (interactive
5d4d17b8 536 (list (read-directory-name "Change default directory: "
2121cd9c
RM
537 default-directory default-directory
538 (and (member cd-path '(nil ("./")))
539 (null (getenv "CDPATH"))))))
30c5ce9c
RS
540 (if (file-name-absolute-p dir)
541 (cd-absolute (expand-file-name dir))
542 (if (null cd-path)
543 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
544 (setq cd-path (or trypath (list "./")))))
545 (if (not (catch 'found
546 (mapcar
547 (function (lambda (x)
548 (let ((f (expand-file-name (concat x dir))))
549 (if (file-directory-p f)
550 (progn
551 (cd-absolute f)
552 (throw 'found t))))))
553 cd-path)
554 nil))
555 (error "No such directory found via CDPATH environment variable"))))
231c4e10 556
b4da00e9
RM
557(defun load-file (file)
558 "Load the Lisp file named FILE."
58195faa
DL
559 ;; This is a case where .elc makes a lot of sense.
560 (interactive (list (let ((completion-ignored-extensions
9ab80679 561 (remove ".elc" completion-ignored-extensions)))
58195faa
DL
562 (read-file-name "Load file: "))))
563 (load (expand-file-name file) nil nil t))
b4da00e9 564
38eea7c7
SM
565(defun locate-file (filename path &optional suffixes predicate)
566 "Search for FILENAME through PATH.
567If SUFFIXES is non-nil, it should be a list of suffixes to append to
568file name when searching. If SUFFIXES is nil, it is equivalent to '(\"\").
569If non-nil, PREDICATE is used instead of `file-readable-p'.
e6f0ff92
RS
570PREDICATE can also be an integer to pass to the `access' system call,
571in which case file-name handlers are ignored. This usage is deprecated.
572
573For compatibility, PREDICATE can also be one of the symbols
574`executable', `readable', `writable', or `exists', or a list of
575one or more of those symbols."
38eea7c7
SM
576 (if (and predicate (symbolp predicate) (not (functionp predicate)))
577 (setq predicate (list predicate)))
578 (when (and (consp predicate) (not (functionp predicate)))
579 (setq predicate
580 (logior (if (memq 'executable predicate) 1 0)
581 (if (memq 'writable predicate) 2 0)
582 (if (memq 'readable predicate) 4 0))))
583 (locate-file-internal filename path suffixes predicate))
584
585(defun locate-file-completion (string path-and-suffixes action)
586 "Do completion for file names passed to `locate-file'.
587PATH-AND-SUFFIXES is a pair of lists (DIRECTORIES . SUFFIXES)."
2c3d8820 588 (if (file-name-absolute-p string)
38eea7c7 589 (read-file-name-internal string nil action)
2c3d8820 590 (let ((names nil)
38eea7c7 591 (suffix (concat (regexp-opt (cdr path-and-suffixes) t) "\\'"))
2c3d8820 592 (string-dir (file-name-directory string)))
38eea7c7 593 (dolist (dir (car path-and-suffixes))
2c3d8820
SM
594 (if string-dir (setq dir (expand-file-name string-dir dir)))
595 (when (file-directory-p dir)
596 (dolist (file (file-name-all-completions
597 (file-name-nondirectory string) dir))
598 (push (if string-dir (concat string-dir file) file) names)
599 (when (string-match suffix file)
600 (setq file (substring file 0 (match-beginning 0)))
601 (push (if string-dir (concat string-dir file) file) names)))))
0370fe77
SM
602 (cond
603 ((eq action t) (all-completions string names))
604 ((null action) (try-completion string names))
605 (t (test-completion string names))))))
2c3d8820 606
b4da00e9
RM
607(defun load-library (library)
608 "Load the library named LIBRARY.
609This is an interface to the function `load'."
38eea7c7
SM
610 (interactive
611 (list (completing-read "Load library: "
612 'locate-file-completion
613 (cons load-path load-suffixes))))
b4da00e9 614 (load library))
5d68c2c2 615
ff7affeb
RS
616(defun file-remote-p (file)
617 "Test whether FILE specifies a location on a remote system."
618 (let ((handler (find-file-name-handler file 'file-local-copy)))
619 (if handler
620 (get handler 'file-remote-p))))
621
ffc0e1ca 622(defun file-local-copy (file)
5d68c2c2
RS
623 "Copy the file FILE into a temporary file on this machine.
624Returns the name of the local copy, or nil, if FILE is directly
625accessible."
ffc0e1ca
AS
626 ;; This formerly had an optional BUFFER argument that wasn't used by
627 ;; anything.
6eaebaa2 628 (let ((handler (find-file-name-handler file 'file-local-copy)))
5d68c2c2
RS
629 (if handler
630 (funcall handler 'file-local-copy file)
631 nil)))
f3e23606 632
05ef1cda 633(defun file-truename (filename &optional counter prev-dirs)
f3e23606
RS
634 "Return the truename of FILENAME, which should be absolute.
635The truename of a file name is found by chasing symbolic links
636both at the level of the file and at the level of the directories
05ef1cda
RS
637containing it, until no links are left at any level.
638
639The arguments COUNTER and PREV-DIRS are used only in recursive calls.
640Do not specify them in other calls."
641 ;; COUNTER can be a cons cell whose car is the count of how many more links
642 ;; to chase before getting an error.
643 ;; PREV-DIRS can be a cons cell whose car is an alist
644 ;; of truenames we've just recently computed.
cc37a58c 645
cc37a58c
SM
646 ;; The last test looks dubious, maybe `+' is meant here? --simon.
647 (if (or (string= filename "") (string= filename "~")
7a5a26a6
RS
648 (and (string= (substring filename 0 1) "~")
649 (string-match "~[^/]*" filename)))
1cc2fbeb
RS
650 (progn
651 (setq filename (expand-file-name filename))
652 (if (string= filename "")
653 (setq filename "/"))))
05ef1cda 654 (or counter (setq counter (list 100)))
b505828b
RS
655 (let (done
656 ;; For speed, remove the ange-ftp completion handler from the list.
657 ;; We know it's not needed here.
658 ;; For even more speed, do this only on the outermost call.
659 (file-name-handler-alist
660 (if prev-dirs file-name-handler-alist
661 (let ((tem (copy-sequence file-name-handler-alist)))
662 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
663 (or prev-dirs (setq prev-dirs (list nil)))
b1667e6c
GV
664
665 ;; andrewi@harlequin.co.uk - none of the following code (except for
666 ;; invoking the file-name handler) currently applies on Windows
667 ;; (ie. there are no native symlinks), but there is an issue with
668 ;; case differences being ignored by the OS, and short "8.3 DOS"
669 ;; name aliases existing for all files. (The short names are not
670 ;; reported by directory-files, but can be used to refer to files.)
671 ;; It seems appropriate for file-truename to resolve these issues in
672 ;; the most natural way, which on Windows is to call the function
673 ;; `w32-long-file-name' - this returns the exact name of a file as
674 ;; it is stored on disk (expanding short name aliases with the full
675 ;; name in the process).
676 (if (eq system-type 'windows-nt)
06dd5ef7 677 (let ((handler (find-file-name-handler filename 'file-truename)))
b1667e6c
GV
678 ;; For file name that has a special handler, call handler.
679 ;; This is so that ange-ftp can save time by doing a no-op.
680 (if handler
681 (setq filename (funcall handler 'file-truename filename))
682 ;; If filename contains a wildcard, newname will be the old name.
06dd5ef7 683 (unless (string-match "[[*?]" filename)
5b373bd3
JB
684 ;; If filename exists, use the long name
685 (setq filename (or (w32-long-file-name filename) filename))))
b1667e6c
GV
686 (setq done t)))
687
05ef1cda
RS
688 ;; If this file directly leads to a link, process that iteratively
689 ;; so that we don't use lots of stack.
690 (while (not done)
691 (setcar counter (1- (car counter)))
692 (if (< (car counter) 0)
693 (error "Apparent cycle of symbolic links for %s" filename))
694 (let ((handler (find-file-name-handler filename 'file-truename)))
695 ;; For file name that has a special handler, call handler.
696 ;; This is so that ange-ftp can save time by doing a no-op.
697 (if handler
698 (setq filename (funcall handler 'file-truename filename)
699 done t)
fb145562 700 (let ((dir (or (file-name-directory filename) default-directory))
05ef1cda
RS
701 target dirfile)
702 ;; Get the truename of the directory.
703 (setq dirfile (directory-file-name dir))
704 ;; If these are equal, we have the (or a) root directory.
705 (or (string= dir dirfile)
706 ;; If this is the same dir we last got the truename for,
707 ;; save time--don't recalculate.
708 (if (assoc dir (car prev-dirs))
709 (setq dir (cdr (assoc dir (car prev-dirs))))
710 (let ((old dir)
711 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
712 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
713 (setq dir new))))
714 (if (equal ".." (file-name-nondirectory filename))
715 (setq filename
716 (directory-file-name (file-name-directory (directory-file-name dir)))
717 done t)
718 (if (equal "." (file-name-nondirectory filename))
719 (setq filename (directory-file-name dir)
720 done t)
721 ;; Put it back on the file name.
722 (setq filename (concat dir (file-name-nondirectory filename)))
723 ;; Is the file name the name of a link?
724 (setq target (file-symlink-p filename))
725 (if target
726 ;; Yes => chase that link, then start all over
727 ;; since the link may point to a directory name that uses links.
728 ;; We can't safely use expand-file-name here
729 ;; since target might look like foo/../bar where foo
730 ;; is itself a link. Instead, we handle . and .. above.
731 (setq filename
732 (if (file-name-absolute-p target)
733 target
734 (concat dir target))
735 done nil)
736 ;; No, we are done!
737 (setq done t))))))))
738 filename))
5dbfdacd 739
302fcc98 740(defun file-chase-links (filename &optional limit)
5dadeb29 741 "Chase links in FILENAME until a name that is not a link.
302fcc98
RS
742Unlike `file-truename', this does not check whether a parent
743directory name is a symbolic link.
744If the optional argument LIMIT is a number,
745it means chase no more than that many links and then stop."
746 (let (tem (newname filename)
92464ae6 747 (count 0))
302fcc98
RS
748 (while (and (or (null limit) (< count limit))
749 (setq tem (file-symlink-p newname)))
9695aac6 750 (save-match-data
92464ae6 751 (if (and (null limit) (= count 100))
9695aac6
RS
752 (error "Apparent cycle of symbolic links for %s" filename))
753 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
754 (while (string-match "//+" tem)
755 (setq tem (replace-match "/" nil nil tem)))
756 ;; Handle `..' by hand, since it needs to work in the
757 ;; target of any directory symlink.
758 ;; This code is not quite complete; it does not handle
759 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
760 (while (string-match "\\`\\.\\./" tem)
761 (setq tem (substring tem 3))
762 (setq newname (expand-file-name newname))
763 ;; Chase links in the default dir of the symlink.
764 (setq newname
765 (file-chase-links
766 (directory-file-name (file-name-directory newname))))
767 ;; Now find the parent of that dir.
768 (setq newname (file-name-directory newname)))
769 (setq newname (expand-file-name tem (file-name-directory newname)))
92464ae6 770 (setq count (1+ count))))
5dadeb29 771 newname))
9bdbd98e
KH
772
773(defun recode-file-name (file coding new-coding &optional ok-if-already-exists)
774 "Change the encoding of FILE's name from CODING to NEW-CODING.
775The value is a new name of FILE.
776Signals a `file-already-exists' error if a file of the new name
777already exists unless optional third argument OK-IF-ALREADY-EXISTS
778is non-nil. A number as third arg means request confirmation if
779the new name already exists. This is what happens in interactive
780use with M-x."
781 (interactive
782 (let ((default-coding (or file-name-coding-system
783 default-file-name-coding-system))
784 (filename (read-file-name "Recode filename: " nil nil t))
785 from-coding to-coding)
786 (if (and default-coding
787 ;; We provide the default coding only when it seems that
788 ;; the filename is correctly decoded by the default
789 ;; coding.
790 (let ((charsets (find-charset-string filename)))
791 (and (not (memq 'eight-bit-control charsets))
792 (not (memq 'eight-bit-graphic charsets)))))
793 (setq from-coding (read-coding-system
794 (format "Recode filename %s from (default %s): "
795 filename default-coding)
796 default-coding))
797 (setq from-coding (read-coding-system
798 (format "Recode filename %s from: " filename))))
799
800 ;; We provide the default coding only when a user is going to
801 ;; change the encoding not from the default coding.
802 (if (eq from-coding default-coding)
803 (setq to-coding (read-coding-system
804 (format "Recode filename %s from %s to: "
805 filename from-coding)))
806 (setq to-coding (read-coding-system
807 (format "Recode filename %s from %s to (default %s): "
808 filename from-coding default-coding)
809 default-coding)))
810 (list filename from-coding to-coding)))
811
812 (let* ((default-coding (or file-name-coding-system
813 default-file-name-coding-system))
814 ;; FILE should have been decoded by DEFAULT-CODING.
815 (encoded (encode-coding-string file default-coding))
816 (newname (decode-coding-string encoded coding))
817 (new-encoded (encode-coding-string newname new-coding))
818 ;; Suppress further encoding.
819 (file-name-coding-system nil)
820 (default-file-name-coding-system nil)
821 (locale-coding-system nil))
822 (rename-file encoded new-encoded ok-if-already-exists)
823 newname))
b4da00e9 824\f
467ff692
RS
825(defun switch-to-buffer-other-window (buffer &optional norecord)
826 "Select buffer BUFFER in another window.
827Optional second arg NORECORD non-nil means
4c6a4739
EZ
828do not put this buffer at the front of the list of recently selected ones.
829
830This uses the function `display-buffer' as a subroutine; see its
831documentation for additional customization information."
b4da00e9
RM
832 (interactive "BSwitch to buffer in other window: ")
833 (let ((pop-up-windows t))
467ff692 834 (pop-to-buffer buffer t norecord)))
b4da00e9 835
467ff692
RS
836(defun switch-to-buffer-other-frame (buffer &optional norecord)
837 "Switch to buffer BUFFER in another frame.
838Optional second arg NORECORD non-nil means
4c6a4739
EZ
839do not put this buffer at the front of the list of recently selected ones.
840
841This uses the function `display-buffer' as a subroutine; see its
842documentation for additional customization information."
f98955ea
JB
843 (interactive "BSwitch to buffer in other frame: ")
844 (let ((pop-up-frames t))
467ff692 845 (pop-to-buffer buffer t norecord)
336b7f41 846 (raise-frame (window-frame (selected-window)))))
5bbbceb1 847
a49a58f9
RS
848(defvar find-file-default nil
849 "Used within `find-file-read-args'.")
850
05a7cb3d 851(defun find-file-read-args (prompt mustmatch)
e6f0ff92
RS
852 (list (let ((find-file-default
853 (and buffer-file-name
854 (abbreviate-file-name buffer-file-name)))
257ae3a6
MB
855 (munge-default-fun
856 (lambda ()
857 (setq minibuffer-default find-file-default)
858 ;; Clear out this hook so it does not interfere
859 ;; with any recursive minibuffer usage.
860 (pop minibuffer-setup-hook)))
e6f0ff92 861 (minibuffer-setup-hook
257ae3a6
MB
862 minibuffer-setup-hook))
863 (add-hook 'minibuffer-setup-hook munge-default-fun)
05a7cb3d 864 (read-file-name prompt nil default-directory mustmatch))
b2a26f4e 865 t))
e6f0ff92 866
243ce842 867(defun find-file (filename &optional wildcards)
b4da00e9
RM
868 "Edit file FILENAME.
869Switch to a buffer visiting file FILENAME,
243ce842 870creating one if none already exists.
e6f0ff92
RS
871Interactively, the default if you just type RET is the current directory,
872but the visited file name is available through the minibuffer history:
873type M-n to pull it into the minibuffer.
874
243ce842 875Interactively, or if WILDCARDS is non-nil in a call from Lisp,
ffc0e1ca
AS
876expand wildcards (if any) and visit multiple files. Wildcard expansion
877can be suppressed by setting `find-file-wildcards'."
e6f0ff92 878 (interactive
05a7cb3d 879 (find-file-read-args "Find file: " nil))
5b8ed07b
RS
880 (let ((value (find-file-noselect filename nil nil wildcards)))
881 (if (listp value)
882 (mapcar 'switch-to-buffer (nreverse value))
883 (switch-to-buffer value))))
82d0954a 884
243ce842 885(defun find-file-other-window (filename &optional wildcards)
b4da00e9
RM
886 "Edit file FILENAME, in another window.
887May create a new window, or reuse an existing one.
243ce842 888See the function `display-buffer'.
e6f0ff92
RS
889
890Interactively, the default if you just type RET is the current directory,
891but the visited file name is available through the minibuffer history:
892type M-n to pull it into the minibuffer.
893
243ce842
RS
894Interactively, or if WILDCARDS is non-nil in a call from Lisp,
895expand wildcards (if any) and visit multiple files."
05a7cb3d 896 (interactive (find-file-read-args "Find file in other window: " nil))
5b8ed07b
RS
897 (let ((value (find-file-noselect filename nil nil wildcards)))
898 (if (listp value)
899 (progn
900 (setq value (nreverse value))
901 (switch-to-buffer-other-window (car value))
902 (mapcar 'switch-to-buffer (cdr value)))
903 (switch-to-buffer-other-window value))))
243ce842
RS
904
905(defun find-file-other-frame (filename &optional wildcards)
f98955ea
JB
906 "Edit file FILENAME, in another frame.
907May create a new frame, or reuse an existing one.
243ce842 908See the function `display-buffer'.
e6f0ff92
RS
909
910Interactively, the default if you just type RET is the current directory,
911but the visited file name is available through the minibuffer history:
912type M-n to pull it into the minibuffer.
913
243ce842
RS
914Interactively, or if WILDCARDS is non-nil in a call from Lisp,
915expand wildcards (if any) and visit multiple files."
05a7cb3d 916 (interactive (find-file-read-args "Find file in other frame: " nil))
5b8ed07b
RS
917 (let ((value (find-file-noselect filename nil nil wildcards)))
918 (if (listp value)
919 (progn
920 (setq value (nreverse value))
921 (switch-to-buffer-other-frame (car value))
922 (mapcar 'switch-to-buffer (cdr value)))
923 (switch-to-buffer-other-frame value))))
243ce842
RS
924
925(defun find-file-read-only (filename &optional wildcards)
b4da00e9 926 "Edit file FILENAME but don't allow changes.
e6f0ff92 927Like \\[find-file] but marks buffer as read-only.
b4da00e9 928Use \\[toggle-read-only] to permit editing."
05a7cb3d 929 (interactive (find-file-read-args "Find file read-only: " t))
818286f4 930 (unless (file-exists-p filename) (error "%s does not exist" filename))
243ce842 931 (find-file filename wildcards)
2a9fe1e2 932 (toggle-read-only 1)
320b4233 933 (current-buffer))
b4da00e9 934
243ce842 935(defun find-file-read-only-other-window (filename &optional wildcards)
b4da00e9
RM
936 "Edit file FILENAME in another window but don't allow changes.
937Like \\[find-file-other-window] but marks buffer as read-only.
938Use \\[toggle-read-only] to permit editing."
05a7cb3d 939 (interactive (find-file-read-args "Find file read-only other window: " t))
818286f4 940 (unless (file-exists-p filename) (error "%s does not exist" filename))
243ce842 941 (find-file-other-window filename wildcards)
2a9fe1e2 942 (toggle-read-only 1)
320b4233 943 (current-buffer))
b4da00e9 944
243ce842 945(defun find-file-read-only-other-frame (filename &optional wildcards)
f98955ea
JB
946 "Edit file FILENAME in another frame but don't allow changes.
947Like \\[find-file-other-frame] but marks buffer as read-only.
5bbbceb1 948Use \\[toggle-read-only] to permit editing."
05a7cb3d 949 (interactive (find-file-read-args "Find file read-only other frame: " t))
818286f4 950 (unless (file-exists-p filename) (error "%s does not exist" filename))
243ce842 951 (find-file-other-frame filename wildcards)
2a9fe1e2 952 (toggle-read-only 1)
320b4233 953 (current-buffer))
5bbbceb1 954
912192d1 955(defun find-alternate-file-other-window (filename)
60eaf370 956 "Find file FILENAME as a replacement for the file in the next window.
912192d1 957This command does not select that window."
60eaf370
RS
958 (interactive
959 (save-selected-window
960 (other-window 1)
961 (let ((file buffer-file-name)
962 (file-name nil)
963 (file-dir nil))
964 (and file
965 (setq file-name (file-name-nondirectory file)
966 file-dir (file-name-directory file)))
967 (list (read-file-name
912192d1 968 "Find alternate file: " file-dir nil nil file-name)))))
60eaf370 969 (if (one-window-p)
912192d1 970 (find-file-other-window filename)
60eaf370
RS
971 (save-selected-window
972 (other-window 1)
912192d1 973 (find-alternate-file filename))))
60eaf370 974
912192d1 975(defun find-alternate-file (filename)
b4da00e9
RM
976 "Find file FILENAME, select its buffer, kill previous buffer.
977If the current buffer now contains an empty file that you just visited
912192d1 978\(presumably by mistake), use this command to visit the file you really want."
b4da00e9
RM
979 (interactive
980 (let ((file buffer-file-name)
981 (file-name nil)
982 (file-dir nil))
983 (and file
984 (setq file-name (file-name-nondirectory file)
985 file-dir (file-name-directory file)))
a61f59b4 986 (list (read-file-name
912192d1 987 "Find alternate file: " file-dir nil nil file-name))))
63fabbb4
RS
988 (unless (run-hook-with-args-until-failure 'kill-buffer-query-functions)
989 (error "Aborted"))
990 (when (and (buffer-modified-p) (buffer-file-name))
991 (if (yes-or-no-p (format "Buffer %s is modified; save it first? "
992 (buffer-name)))
993 (save-buffer)
994 (unless (yes-or-no-p "Kill and replace the buffer without saving it? ")
995 (error "Aborted"))))
b4da00e9
RM
996 (let ((obuf (current-buffer))
997 (ofile buffer-file-name)
8bb27285 998 (onum buffer-file-number)
37c58ca6 999 (odir dired-directory)
8bb27285 1000 (otrue buffer-file-truename)
b4da00e9 1001 (oname (buffer-name)))
baf9b8c4
RS
1002 (if (get-buffer " **lose**")
1003 (kill-buffer " **lose**"))
b4da00e9 1004 (rename-buffer " **lose**")
b4da00e9
RM
1005 (unwind-protect
1006 (progn
1007 (unlock-buffer)
7906c044
RS
1008 ;; This prevents us from finding the same buffer
1009 ;; if we specified the same file again.
a4ad4d96
RS
1010 (setq buffer-file-name nil)
1011 (setq buffer-file-number nil)
1012 (setq buffer-file-truename nil)
7906c044
RS
1013 ;; Likewise for dired buffers.
1014 (setq dired-directory nil)
912192d1 1015 (find-file filename))
63fabbb4
RS
1016 (when (eq obuf (current-buffer))
1017 ;; This executes if find-file gets an error
1018 ;; and does not really find anything.
1019 ;; We put things back as they were.
1020 ;; If find-file actually finds something, we kill obuf below.
1021 (setq buffer-file-name ofile)
1022 (setq buffer-file-number onum)
1023 (setq buffer-file-truename otrue)
7906c044 1024 (setq dired-directory odir)
63fabbb4
RS
1025 (lock-buffer)
1026 (rename-buffer oname)))
1027 (unless (eq (current-buffer) obuf)
d97a9ff3
RS
1028 (with-current-buffer obuf
1029 ;; We already asked; don't ask again.
1030 (let ((kill-buffer-query-functions))
1031 (kill-buffer obuf))))))
9b8ef27d 1032\f
b4da00e9
RM
1033(defun create-file-buffer (filename)
1034 "Create a suitably named buffer for visiting FILENAME, and return it.
1035FILENAME (sans directory) is used unchanged if that name is free;
1036otherwise a string <2> or <3> or ... is appended to get an unused name."
1037 (let ((lastname (file-name-nondirectory filename)))
1038 (if (string= lastname "")
1039 (setq lastname filename))
1040 (generate-new-buffer lastname)))
1041
5bbbceb1
JB
1042(defun generate-new-buffer (name)
1043 "Create and return a buffer with a name based on NAME.
29165787 1044Choose the buffer's name using `generate-new-buffer-name'."
5bbbceb1
JB
1045 (get-buffer-create (generate-new-buffer-name name)))
1046
ffc0e1ca
AS
1047(defcustom automount-dir-prefix "^/tmp_mnt/"
1048 "Regexp to match the automounter prefix in a directory name."
1049 :group 'files
1050 :type 'regexp)
e373f201 1051
ffb3a4db 1052(defvar abbreviated-home-dir nil
ffc0e1ca 1053 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
ffb3a4db 1054
5bbbceb1 1055(defun abbreviate-file-name (filename)
29165787 1056 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
b69a0de9 1057This also substitutes \"~\" for the user's home directory and
5baabf7b 1058removes automounter prefixes (see the variable `automount-dir-prefix')."
e373f201 1059 ;; Get rid of the prefixes added by the automounter.
a8f34fc0
RS
1060 (if (and automount-dir-prefix
1061 (string-match automount-dir-prefix filename)
e373f201
JB
1062 (file-exists-p (file-name-directory
1063 (substring filename (1- (match-end 0))))))
1064 (setq filename (substring filename (1- (match-end 0)))))
5bbbceb1 1065 (let ((tail directory-abbrev-alist))
ffb3a4db
RS
1066 ;; If any elt of directory-abbrev-alist matches this name,
1067 ;; abbreviate accordingly.
5bbbceb1
JB
1068 (while tail
1069 (if (string-match (car (car tail)) filename)
1070 (setq filename
1071 (concat (cdr (car tail)) (substring filename (match-end 0)))))
1072 (setq tail (cdr tail)))
ffb3a4db
RS
1073 ;; Compute and save the abbreviated homedir name.
1074 ;; We defer computing this until the first time it's needed, to
1075 ;; give time for directory-abbrev-alist to be set properly.
e98dda89
RS
1076 ;; We include a slash at the end, to avoid spurious matches
1077 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
ffb3a4db
RS
1078 (or abbreviated-home-dir
1079 (setq abbreviated-home-dir
1080 (let ((abbreviated-home-dir "$foo"))
3a8a836d
RS
1081 (concat "^" (abbreviate-file-name (expand-file-name "~"))
1082 "\\(/\\|$\\)"))))
76d5492b 1083
ffb3a4db
RS
1084 ;; If FILENAME starts with the abbreviated homedir,
1085 ;; make it start with `~' instead.
ca33ccb5
RS
1086 (if (and (string-match abbreviated-home-dir filename)
1087 ;; If the home dir is just /, don't change it.
1088 (not (and (= (match-end 0) 1)
288201bd 1089 (= (aref filename 0) ?/)))
567c1ca9
RS
1090 ;; MS-DOS root directories can come with a drive letter;
1091 ;; Novell Netware allows drive letters beyond `Z:'.
76d5492b 1092 (not (and (or (eq system-type 'ms-dos)
c60ee5e7 1093 (eq system-type 'cygwin)
c32d49e8 1094 (eq system-type 'windows-nt))
288201bd 1095 (save-match-data
567c1ca9 1096 (string-match "^[a-zA-`]:/$" filename)))))
5bbbceb1 1097 (setq filename
28dbf501 1098 (concat "~"
3a8a836d 1099 (substring filename (match-beginning 1) (match-end 1))
28dbf501 1100 (substring filename (match-end 0)))))
5bbbceb1
JB
1101 filename))
1102
21540597 1103(defcustom find-file-not-true-dirname-list nil
1770543d
RS
1104 "*List of logical names for which visiting shouldn't save the true dirname.
1105On VMS, when you visit a file using a logical name that searches a path,
1106you may or may not want the visited file name to record the specific
1107directory where the file was found. If you *do not* want that, add the logical
21540597
RS
1108name to this list as a string."
1109 :type '(repeat (string :tag "Name"))
1110 :group 'find-file)
1770543d 1111
3a64a3cf 1112(defun find-buffer-visiting (filename &optional predicate)
138c44f6
KH
1113 "Return the buffer visiting file FILENAME (a string).
1114This is like `get-file-buffer', except that it checks for any buffer
1115visiting the same file, possibly under a different name.
3a64a3cf 1116If PREDICATE is non-nil, only a buffer satisfying it can be returned.
138c44f6 1117If there is no such live buffer, return nil."
3a64a3cf
JB
1118 (let ((predicate (or predicate #'identity))
1119 (truename (abbreviate-file-name (file-truename filename))))
1120 (or (let ((buf (get-file-buffer filename)))
1121 (when (and buf (funcall predicate buf)) buf))
1122 (let ((list (buffer-list)) found)
1123 (while (and (not found) list)
1124 (save-excursion
1125 (set-buffer (car list))
1126 (if (and buffer-file-name
1127 (string= buffer-file-truename truename)
1128 (funcall predicate (current-buffer)))
1129 (setq found (car list))))
1130 (setq list (cdr list)))
1131 found)
1132 (let* ((attributes (file-attributes truename))
1133 (number (nthcdr 10 attributes))
1134 (list (buffer-list)) found)
1135 (and buffer-file-numbers-unique
1136 number
1137 (while (and (not found) list)
1138 (with-current-buffer (car list)
1139 (if (and buffer-file-name
1140 (equal buffer-file-number number)
1141 ;; Verify this buffer's file number
1142 ;; still belongs to its file.
1143 (file-exists-p buffer-file-name)
1144 (equal (file-attributes buffer-file-truename)
1145 attributes)
1146 (funcall predicate (current-buffer)))
1147 (setq found (car list))))
1148 (setq list (cdr list))))
1149 found))))
9b8ef27d 1150\f
5de148a2
RS
1151(defcustom find-file-wildcards t
1152 "*Non-nil means file-visiting commands should handle wildcards.
1153For example, if you specify `*.c', that would visit all the files
1154whose names match the pattern."
1155 :group 'files
3957c982 1156 :version "20.4"
5de148a2
RS
1157 :type 'boolean)
1158
ffc0e1ca
AS
1159(defcustom find-file-suppress-same-file-warnings nil
1160 "*Non-nil means suppress warning messages for symlinked files.
1161When nil, Emacs prints a warning when visiting a file that is already
1162visited, but with a different name. Setting this option to t
1163suppresses this warning."
1164 :group 'files
1165 :version "21.1"
1166 :type 'boolean)
1167
818286f4
SM
1168(defcustom large-file-warning-threshold 10000000
1169 "Maximum size of file above which a confirmation is requested."
1170 :type 'integer)
1171
243ce842 1172(defun find-file-noselect (filename &optional nowarn rawfile wildcards)
b4da00e9
RM
1173 "Read file FILENAME into a buffer and return the buffer.
1174If a buffer exists visiting FILENAME, return that one, but
1175verify that the file has not changed since visited or saved.
82d0954a
KH
1176The buffer is not selected, just returned to the caller.
1177Optional first arg NOWARN non-nil means suppress any warning messages.
243ce842
RS
1178Optional second arg RAWFILE non-nil means the file is read literally.
1179Optional third arg WILDCARDS non-nil means do wildcard processing
5b8ed07b
RS
1180and visit all the matching files. When wildcards are actually
1181used and expanded, the value is a list of buffers
1182that are visiting the various files."
e373f201
JB
1183 (setq filename
1184 (abbreviate-file-name
1185 (expand-file-name filename)))
b4da00e9 1186 (if (file-directory-p filename)
ffc0e1ca
AS
1187 (or (and find-file-run-dired
1188 (run-hook-with-args-until-success
1189 'find-directory-functions
1190 (if find-file-visit-truename
1191 (abbreviate-file-name (file-truename filename))
1192 filename)))
1193 (error "%s is a directory" filename))
243ce842
RS
1194 (if (and wildcards
1195 find-file-wildcards
f91fe604 1196 (not (string-match "\\`/:" filename))
5de148a2 1197 (string-match "[[*?]" filename))
ffc0e1ca
AS
1198 (let ((files (condition-case nil
1199 (file-expand-wildcards filename t)
1200 (error (list filename))))
5de148a2 1201 (find-file-wildcards nil))
f91fe604 1202 (if (null files)
ffc0e1ca 1203 (find-file-noselect filename)
648ec2ff 1204 (mapcar #'find-file-noselect files)))
5de148a2
RS
1205 (let* ((buf (get-file-buffer filename))
1206 (truename (abbreviate-file-name (file-truename filename)))
818286f4
SM
1207 (attributes (file-attributes truename))
1208 (number (nthcdr 10 attributes))
5de148a2
RS
1209 ;; Find any buffer for a file which has same truename.
1210 (other (and (not buf) (find-buffer-visiting filename))))
1211 ;; Let user know if there is a buffer with the same truename.
1212 (if other
1213 (progn
1214 (or nowarn
ffc0e1ca 1215 find-file-suppress-same-file-warnings
5de148a2
RS
1216 (string-equal filename (buffer-file-name other))
1217 (message "%s and %s are the same file"
1218 filename (buffer-file-name other)))
1219 ;; Optionally also find that buffer.
1220 (if (or find-file-existing-other-name find-file-visit-truename)
1221 (setq buf other))))
818286f4
SM
1222 ;; Check to see if the file looks uncommonly large.
1223 (when (and large-file-warning-threshold (nth 7 attributes)
1224 ;; Don't ask again if we already have the file or
1225 ;; if we're asked to be quiet.
1226 (not (or buf nowarn))
1227 (> (nth 7 attributes) large-file-warning-threshold)
1228 (not (y-or-n-p
1229 (format "File %s is large (%sMB), really open? "
1230 (file-name-nondirectory filename)
1231 (/ (nth 7 attributes) 1048576)))))
1232 (error "Aborted"))
5de148a2
RS
1233 (if buf
1234 ;; We are using an existing buffer.
1235 (progn
1236 (or nowarn
1237 (verify-visited-file-modtime buf)
1238 (cond ((not (file-exists-p filename))
1239 (error "File %s no longer exists!" filename))
1240 ;; Certain files should be reverted automatically
1241 ;; if they have changed on disk and not in the buffer.
1242 ((and (not (buffer-modified-p buf))
1243 (let ((tail revert-without-query)
1244 (found nil))
1245 (while tail
1246 (if (string-match (car tail) filename)
1247 (setq found t))
1248 (setq tail (cdr tail)))
1249 found))
1250 (with-current-buffer buf
1251 (message "Reverting file %s..." filename)
1252 (revert-buffer t t)
1253 (message "Reverting file %s...done" filename)))
1254 ((yes-or-no-p
1255 (if (string= (file-name-nondirectory filename)
1256 (buffer-name buf))
1257 (format
1258 (if (buffer-modified-p buf)
1259 "File %s changed on disk. Discard your edits? "
1260 "File %s changed on disk. Reread from disk? ")
1261 (file-name-nondirectory filename))
ddd64da9
RS
1262 (format
1263 (if (buffer-modified-p buf)
5de148a2
RS
1264 "File %s changed on disk. Discard your edits in %s? "
1265 "File %s changed on disk. Reread from disk into %s? ")
1266 (file-name-nondirectory filename)
1267 (buffer-name buf))))
1268 (with-current-buffer buf
1269 (revert-buffer t t)))))
1270 (with-current-buffer buf
a8d002d2
GM
1271
1272 ;; Check if a formerly read-only file has become
e554eeb7
RS
1273 ;; writable and vice versa, but if the buffer agrees
1274 ;; with the new state of the file, that is ok too.
a8d002d2 1275 (let ((read-only (not (file-writable-p buffer-file-name))))
e554eeb7
RS
1276 (unless (or (eq read-only buffer-file-read-only)
1277 (eq read-only buffer-read-only))
a8d002d2 1278 (when (or nowarn
36236b72 1279 (let ((question
a8d002d2
GM
1280 (format "File %s is %s on disk. Change buffer mode? "
1281 buffer-file-name
1282 (if read-only "read-only" "writable"))))
1283 (y-or-n-p question)))
e554eeb7
RS
1284 (setq buffer-read-only read-only)))
1285 (setq buffer-file-read-only read-only))
a8d002d2 1286
ef59dd3b
EZ
1287 (when (and (not (eq (not (null rawfile))
1288 (not (null find-file-literally))))
1289 ;; It is confusing to ask whether to visit
1290 ;; non-literally if they have the file in
1291 ;; hexl-mode.
1292 (not (eq major-mode 'hexl-mode)))
5de148a2 1293 (if (buffer-modified-p)
ddd64da9 1294 (if (y-or-n-p (if rawfile
5de148a2
RS
1295 "Save file and revisit literally? "
1296 "Save file and revisit non-literally? "))
1297 (progn
1298 (save-buffer)
1299 (find-file-noselect-1 buf filename nowarn
1300 rawfile truename number))
1301 (if (y-or-n-p (if rawfile
1302 "Discard your edits and revisit file literally? "
1303 "Discard your edits and revisit file non-literally? "))
1304 (find-file-noselect-1 buf filename nowarn
1305 rawfile truename number)
1306 (error (if rawfile "File already visited non-literally"
1307 "File already visited literally"))))
1308 (if (y-or-n-p (if rawfile
1309 "Revisit file literally? "
1310 "Revisit file non-literally? "))
1311 (find-file-noselect-1 buf filename nowarn
1312 rawfile truename number)
1313 (error (if rawfile "File already visited non-literally"
1314 "File already visited literally"))))))
1315 ;; Return the buffer we are using.
1316 buf)
1317 ;; Create a new buffer.
1318 (setq buf (create-file-buffer filename))
1319 (set-buffer-major-mode buf)
1320 ;; find-file-noselect-1 may use a different buffer.
1321 (find-file-noselect-1 buf filename nowarn
1322 rawfile truename number))))))
ddd64da9
RS
1323
1324(defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
666c1d8b
RS
1325 (let ((inhibit-read-only t)
1326 error)
ddd64da9
RS
1327 (with-current-buffer buf
1328 (kill-local-variable 'find-file-literally)
b296cbd4
RS
1329 ;; Needed in case we are re-visiting the file with a different
1330 ;; text representation.
e73ec04b 1331 (kill-local-variable 'buffer-file-coding-system)
4ad1689f 1332 (kill-local-variable 'cursor-type)
ddd64da9
RS
1333 (erase-buffer)
1334 (and (default-value 'enable-multibyte-characters)
1335 (not rawfile)
1336 (set-buffer-multibyte t))
1337 (if rawfile
1338 (condition-case ()
1339 (insert-file-contents-literally filename t)
1340 (file-error
1341 (when (and (file-exists-p filename)
1342 (not (file-readable-p filename)))
1343 (kill-buffer buf)
1344 (signal 'file-error (list "File is not readable"
1345 filename)))
1346 ;; Unconditionally set error
1347 (setq error t)))
1348 (condition-case ()
1349 (insert-file-contents filename t)
1350 (file-error
1351 (when (and (file-exists-p filename)
1352 (not (file-readable-p filename)))
1353 (kill-buffer buf)
1354 (signal 'file-error (list "File is not readable"
1355 filename)))
1356 ;; Run find-file-not-found-hooks until one returns non-nil.
0370fe77 1357 (or (run-hook-with-args-until-success 'find-file-not-found-functions)
ddd64da9
RS
1358 ;; If they fail too, set error.
1359 (setq error t)))))
b120e713
KH
1360 ;; Record the file's truename, and maybe use that as visited name.
1361 (if (equal filename buffer-file-name)
1362 (setq buffer-file-truename truename)
9ab19105
DL
1363 (setq buffer-file-truename
1364 (abbreviate-file-name (file-truename buffer-file-name))))
ddd64da9
RS
1365 (setq buffer-file-number number)
1366 ;; On VMS, we may want to remember which directory in a search list
1367 ;; the file was found in.
1368 (and (eq system-type 'vax-vms)
1369 (let (logical)
1370 (if (string-match ":" (file-name-directory filename))
1371 (setq logical (substring (file-name-directory filename)
1372 0 (match-beginning 0))))
1373 (not (member logical find-file-not-true-dirname-list)))
1374 (setq buffer-file-name buffer-file-truename))
1375 (if find-file-visit-truename
1376 (setq buffer-file-name
1377 (setq filename
1378 (expand-file-name buffer-file-truename))))
1379 ;; Set buffer's default directory to that of the file.
b120e713 1380 (setq default-directory (file-name-directory buffer-file-name))
ddd64da9
RS
1381 ;; Turn off backup files for certain file names. Since
1382 ;; this is a permanent local, the major mode won't eliminate it.
1383 (and (not (funcall backup-enable-predicate buffer-file-name))
1384 (progn
1385 (make-local-variable 'backup-inhibited)
1386 (setq backup-inhibited t)))
f402ba38
RS
1387 (if rawfile
1388 (progn
1389 (set-buffer-multibyte nil)
1390 (setq buffer-file-coding-system 'no-conversion)
1391 (make-local-variable 'find-file-literally)
1392 (setq find-file-literally t))
1393 (after-find-file error (not nowarn)))
1394 (current-buffer))))
9b8ef27d
RS
1395\f
1396(defun insert-file-contents-literally (filename &optional visit beg end replace)
1397 "Like `insert-file-contents', but only reads in the file literally.
1398A buffer may be modified in several ways after reading into the buffer,
1399to Emacs features such as format decoding, character code
0370fe77 1400conversion, `find-file-hook', automatic uncompression, etc.
9b8ef27d
RS
1401
1402This function ensures that none of these modifications will take place."
1403 (let ((format-alist nil)
1404 (after-insert-file-functions nil)
1405 (coding-system-for-read 'no-conversion)
1406 (coding-system-for-write 'no-conversion)
9b8ef27d
RS
1407 (find-buffer-file-type-function
1408 (if (fboundp 'find-buffer-file-type)
1409 (symbol-function 'find-buffer-file-type)
7e365285
DL
1410 nil))
1411 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
1412 (inhibit-file-name-operation 'insert-file-contents))
9b8ef27d
RS
1413 (unwind-protect
1414 (progn
1415 (fset 'find-buffer-file-type (lambda (filename) t))
1416 (insert-file-contents filename visit beg end replace))
1417 (if find-buffer-file-type-function
1418 (fset 'find-buffer-file-type find-buffer-file-type-function)
1419 (fmakunbound 'find-buffer-file-type)))))
1420
3a64a3cf
JB
1421(defun insert-file-1 (filename insert-func)
1422 (if (file-directory-p filename)
1423 (signal 'file-error (list "Opening input file" "file is a directory"
1424 filename)))
1425 (let* ((buffer (find-buffer-visiting (abbreviate-file-name (file-truename filename))
1426 #'buffer-modified-p))
1427 (tem (funcall insert-func filename)))
1428 (push-mark (+ (point) (car (cdr tem))))
1429 (when buffer
1430 (message "File %s already visited and modified in buffer %s"
1431 filename (buffer-name buffer)))))
1432
9b8ef27d
RS
1433(defun insert-file-literally (filename)
1434 "Insert contents of file FILENAME into buffer after point with no conversion.
1435
1436This function is meant for the user to run interactively.
1437Don't call it from programs! Use `insert-file-contents-literally' instead.
1438\(Its calling sequence is different; see its documentation)."
1439 (interactive "*fInsert file literally: ")
3a64a3cf 1440 (insert-file-1 filename #'insert-file-contents-literally))
9b8ef27d
RS
1441
1442(defvar find-file-literally nil
1443 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1444This is a permanent local.")
1445(put 'find-file-literally 'permanent-local t)
5fc196af 1446
ffc0e1ca 1447(defun find-file-literally (filename)
5fc196af
RS
1448 "Visit file FILENAME with no conversion of any kind.
1449Format conversion and character code conversion are both disabled,
1450and multibyte characters are disabled in the resulting buffer.
e65db7b8
RS
1451The major mode used is Fundamental mode regardless of the file name,
1452and local variable specifications in the file are ignored.
407b4328
GM
1453Automatic uncompression and adding a newline at the end of the
1454file due to `require-final-newline' is also disabled.
9b8ef27d
RS
1455
1456You cannot absolutely rely on this function to result in
b9aa9537 1457visiting the file literally. If Emacs already has a buffer
9b8ef27d
RS
1458which is visiting the file, you get the existing buffer,
1459regardless of whether it was created literally or not.
1460
1461In a Lisp program, if you want to be sure of accessing a file's
1462contents literally, you should create a temporary buffer and then read
1463the file contents into it using `insert-file-contents-literally'."
5fc196af 1464 (interactive "FFind file literally: ")
9b8ef27d 1465 (switch-to-buffer (find-file-noselect filename nil t)))
b4da00e9 1466\f
f7d786d0
RS
1467(defvar after-find-file-from-revert-buffer nil)
1468
e0ab8879 1469(defun after-find-file (&optional error warn noauto
9a30563f
RS
1470 after-find-file-from-revert-buffer
1471 nomodes)
b4da00e9
RM
1472 "Called after finding a file and by the default revert function.
1473Sets buffer mode, parses local variables.
8cfb9d46 1474Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
b4da00e9
RM
1475error in reading the file. WARN non-nil means warn if there
1476exists an auto-save file more recent than the visited file.
8cfb9d46 1477NOAUTO means don't mess with auto-save mode.
e0ab8879
RS
1478Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1479 means this call was from `revert-buffer'.
9a30563f 1480Fifth arg NOMODES non-nil means don't alter the file's modes.
0370fe77 1481Finishes by calling the functions in `find-file-hook'
9a30563f 1482unless NOMODES is non-nil."
b4da00e9
RM
1483 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1484 (if noninteractive
1485 nil
1486 (let* (not-serious
1487 (msg
fe50b6ab
GM
1488 (cond
1489 ((not warn) nil)
1490 ((and error (file-attributes buffer-file-name))
1491 (setq buffer-read-only t)
1492 "File exists, but cannot be read")
1493 ((not buffer-read-only)
1494 (if (and warn
1495 ;; No need to warn if buffer is auto-saved
1496 ;; under the name of the visited file.
1497 (not (and buffer-file-name
1498 auto-save-visited-file-name))
1499 (file-newer-than-file-p (or buffer-auto-save-file-name
1500 (make-auto-save-file-name))
1501 buffer-file-name))
64d18e8f 1502 (format "%s has auto save data; consider M-x recover-this-file"
fe50b6ab
GM
1503 (file-name-nondirectory buffer-file-name))
1504 (setq not-serious t)
1505 (if error "(New file)" nil)))
1506 ((not error)
1507 (setq not-serious t)
1508 "Note: file is write protected")
1509 ((file-attributes (directory-file-name default-directory))
1510 "File not found and directory write-protected")
1511 ((file-exists-p (file-name-directory buffer-file-name))
1512 (setq buffer-read-only nil))
1513 (t
1514 (setq buffer-read-only nil)
1515 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1516 "Use M-x make-directory RET RET to create the directory"
1517 "Use C-u M-x make-directory RET RET to create directory and its parents")))))
1518 (when msg
a74357d4 1519 (message "%s" msg)
fe50b6ab
GM
1520 (or not-serious (sit-for 1 nil t))))
1521 (when (and auto-save-default (not noauto))
1522 (auto-save-mode t)))
ffc0e1ca
AS
1523 ;; Make people do a little extra work (C-x C-q)
1524 ;; before altering a backup file.
fe50b6ab
GM
1525 (when (backup-file-name-p buffer-file-name)
1526 (setq buffer-read-only t))
8fd9c174
RS
1527 ;; When a file is marked read-only,
1528 ;; make the buffer read-only even if root is looking at it.
879365c6
KS
1529 (when (and (file-modes (buffer-file-name))
1530 (zerop (logand (file-modes (buffer-file-name)) #o222)))
8fd9c174 1531 (setq buffer-read-only t))
fe50b6ab
GM
1532 (unless nomodes
1533 (when (and view-read-only view-mode)
1534 (view-mode-disable))
9a30563f 1535 (normal-mode t)
fe50b6ab
GM
1536 (when (and buffer-read-only
1537 view-read-only
1538 (not (eq (get major-mode 'mode-class) 'special)))
1539 (view-mode-enter))
0370fe77 1540 (run-hooks 'find-file-hook)))
b4da00e9 1541
818286f4
SM
1542(defmacro report-errors (format &rest body)
1543 "Eval BODY and turn any error into a FORMAT message.
1544FORMAT can have a %s escape which will be replaced with the actual error.
1545If `debug-on-error' is set, errors are not caught, so that you can
1546debug them.
1547Avoid using a large BODY since it is duplicated."
1548 (declare (debug t) (indent 1))
1549 `(if debug-on-error
1550 (progn . ,body)
1551 (condition-case err
1552 (progn . ,body)
1553 (error (message ,format (prin1-to-string err))))))
1554
b4da00e9
RM
1555(defun normal-mode (&optional find-file)
1556 "Choose the major mode for this buffer automatically.
1557Also sets up any specified local variables of the file.
1558Uses the visited file name, the -*- line, and the local variables spec.
1559
1560This function is called automatically from `find-file'. In that case,
aa5fcebf
KH
1561we may set up the file-specified mode and local variables,
1562depending on the value of `enable-local-variables': if it is t, we do;
1563if it is nil, we don't; otherwise, we query.
1564In addition, if `local-enable-local-variables' is nil, we do
1565not set local variables (though we do notice a mode specified with -*-.)
1566
1567`enable-local-variables' is ignored if you run `normal-mode' interactively,
1568or from Lisp without specifying the optional argument FIND-FILE;
1569in that case, this function acts as if `enable-local-variables' were t."
b4da00e9
RM
1570 (interactive)
1571 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
818286f4
SM
1572 (report-errors "File mode specification error: %s"
1573 (set-auto-mode))
1574 (report-errors "File local-variables error: %s"
1575 (let ((enable-local-variables (or (not find-file) enable-local-variables)))
1576 (hack-local-variables)))
24c9eeeb
DL
1577 (if (fboundp 'ucs-set-table-for-input) ; don't lose when building
1578 (ucs-set-table-for-input)))
b4da00e9 1579
f76e0cd0 1580(defvar auto-mode-alist
ffc0e1ca
AS
1581 (mapc
1582 (lambda (elt)
1583 (cons (purecopy (car elt)) (cdr elt)))
dfd8bf47 1584 '(("\\.te?xt\\'" . text-mode)
ffc0e1ca
AS
1585 ("\\.c\\'" . c-mode)
1586 ("\\.h\\'" . c-mode)
1587 ("\\.tex\\'" . tex-mode)
4e163715 1588 ("\\.ins\\'" . tex-mode) ;Installation files for TeX packages.
ffc0e1ca 1589 ("\\.ltx\\'" . latex-mode)
4e163715 1590 ("\\.dtx\\'" . doctex-mode)
ffc0e1ca
AS
1591 ("\\.el\\'" . emacs-lisp-mode)
1592 ("\\.scm\\'" . scheme-mode)
1593 ("\\.l\\'" . lisp-mode)
1594 ("\\.lisp\\'" . lisp-mode)
1595 ("\\.f\\'" . fortran-mode)
1596 ("\\.F\\'" . fortran-mode)
1597 ("\\.for\\'" . fortran-mode)
1598 ("\\.p\\'" . pascal-mode)
1599 ("\\.pas\\'" . pascal-mode)
1600 ("\\.ad[abs]\\'" . ada-mode)
7defe888 1601 ("\\.ad[bs].dg\\'" . ada-mode)
5c6d31a4 1602 ("\\.\\([pP]\\([Llm]\\|erl\\)\\|al\\)\\'" . perl-mode)
ffc0e1ca
AS
1603 ("\\.s?html?\\'" . html-mode)
1604 ("\\.cc\\'" . c++-mode)
1605 ("\\.hh\\'" . c++-mode)
1606 ("\\.hpp\\'" . c++-mode)
1607 ("\\.C\\'" . c++-mode)
1608 ("\\.H\\'" . c++-mode)
1609 ("\\.cpp\\'" . c++-mode)
1610 ("\\.cxx\\'" . c++-mode)
1611 ("\\.hxx\\'" . c++-mode)
1612 ("\\.c\\+\\+\\'" . c++-mode)
1613 ("\\.h\\+\\+\\'" . c++-mode)
1614 ("\\.m\\'" . objc-mode)
1615 ("\\.java\\'" . java-mode)
1616 ("\\.mk\\'" . makefile-mode)
36236b72 1617 ("\\(M\\|m\\|GNUm\\)akefile\\'" . makefile-mode)
ffc0e1ca 1618 ("\\.am\\'" . makefile-mode) ;For Automake.
5c6d31a4
SM
1619 ;; Less common extensions come here
1620 ;; so more common ones above are found faster.
ffc0e1ca
AS
1621 ("\\.texinfo\\'" . texinfo-mode)
1622 ("\\.te?xi\\'" . texinfo-mode)
1623 ("\\.s\\'" . asm-mode)
1624 ("\\.S\\'" . asm-mode)
1625 ("\\.asm\\'" . asm-mode)
1626 ("ChangeLog\\'" . change-log-mode)
1627 ("change\\.log\\'" . change-log-mode)
1628 ("changelo\\'" . change-log-mode)
1629 ("ChangeLog\\.[0-9]+\\'" . change-log-mode)
1630 ;; for MSDOS and MS-Windows (which are case-insensitive)
1631 ("changelog\\'" . change-log-mode)
1632 ("changelog\\.[0-9]+\\'" . change-log-mode)
1633 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1634 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
1635 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
b921b596 1636 ("\\.bash\\'" . sh-mode)
ffc0e1ca
AS
1637 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1638 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1639 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
d5798fa7 1640 ("\\.m?spec\\'" . sh-mode)
ffc0e1ca
AS
1641 ("\\.mm\\'" . nroff-mode)
1642 ("\\.me\\'" . nroff-mode)
1643 ("\\.ms\\'" . nroff-mode)
1644 ("\\.man\\'" . nroff-mode)
1645 ("\\.\\(u?lpc\\|pike\\|pmod\\)\\'" . pike-mode)
ffc0e1ca
AS
1646 ("\\.TeX\\'" . tex-mode)
1647 ("\\.sty\\'" . latex-mode)
1648 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
1649 ("\\.clo\\'" . latex-mode) ;LaTeX 2e class option
1650 ("\\.bbl\\'" . latex-mode)
1651 ("\\.bib\\'" . bibtex-mode)
1652 ("\\.sql\\'" . sql-mode)
1653 ("\\.m4\\'" . m4-mode)
1654 ("\\.mc\\'" . m4-mode)
1655 ("\\.mf\\'" . metafont-mode)
1656 ("\\.mp\\'" . metapost-mode)
1657 ("\\.vhdl?\\'" . vhdl-mode)
1658 ("\\.article\\'" . text-mode)
1659 ("\\.letter\\'" . text-mode)
1660 ("\\.tcl\\'" . tcl-mode)
1661 ("\\.exp\\'" . tcl-mode)
1662 ("\\.itcl\\'" . tcl-mode)
1663 ("\\.itk\\'" . tcl-mode)
1664 ("\\.icn\\'" . icon-mode)
1665 ("\\.sim\\'" . simula-mode)
1666 ("\\.mss\\'" . scribe-mode)
1667 ("\\.f90\\'" . f90-mode)
9211d053 1668 ("\\.f95\\'" . f90-mode)
8f9495e7 1669 ("\\.indent\\.pro\\'" . fundamental-mode) ; to avoid idlwave-mode
ffc0e1ca
AS
1670 ("\\.pro\\'" . idlwave-mode)
1671 ("\\.lsp\\'" . lisp-mode)
1672 ("\\.awk\\'" . awk-mode)
1673 ("\\.prolog\\'" . prolog-mode)
1674 ("\\.tar\\'" . tar-mode)
eb551704
PR
1675 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|ear\\|jar\\|war\\)\\'" . archive-mode)
1676 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|EAR\\|JAR\\|WAR\\)\\'" . archive-mode)
c25773c4 1677 ("\\.sx[dmicw]\\'" . archive-mode) ; OpenOffice.org
ffc0e1ca
AS
1678 ;; Mailer puts message to be edited in
1679 ;; /tmp/Re.... or Message
1680 ("\\`/tmp/Re" . text-mode)
1681 ("/Message[0-9]*\\'" . text-mode)
1682 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1683 ("\\.zone\\'" . zone-mode)
1684 ;; some news reader is reported to use this
1685 ("\\`/tmp/fol/" . text-mode)
1686 ("\\.y\\'" . c-mode)
1687 ("\\.lex\\'" . c-mode)
1688 ("\\.oak\\'" . scheme-mode)
1689 ("\\.sgml?\\'" . sgml-mode)
1690 ("\\.xml\\'" . sgml-mode)
3f5c8d98 1691 ("\\.xsl\\'" . sgml-mode)
ffc0e1ca
AS
1692 ("\\.dtd\\'" . sgml-mode)
1693 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
1694 ("\\.idl\\'" . idl-mode)
709d45e1
KG
1695 ;; .emacs or .gnus or .viper following a directory delimiter in
1696 ;; Unix, MSDOG or VMS syntax.
1697 ("[]>:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode)
ffc0e1ca
AS
1698 ("\\`\\..*emacs\\'" . emacs-lisp-mode)
1699 ;; _emacs following a directory delimiter
1700 ;; in MsDos syntax
1701 ("[:/]_emacs\\'" . emacs-lisp-mode)
1702 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode)
1703 ("\\.ml\\'" . lisp-mode)
d5798fa7
SM
1704 ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode)
1705 ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode)
ffc0e1ca 1706 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode)
e854cc22 1707 ("\\.\\(dif\\|pat\\)\\'" . diff-mode) ; for MSDOG
d5798fa7 1708 ("\\.[eE]?[pP][sS]\\'" . ps-mode)
e55c4863 1709 ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode)
ffc0e1ca
AS
1710 ("BROWSE\\'" . ebrowse-tree-mode)
1711 ("\\.ebrowse\\'" . ebrowse-tree-mode)
9ee45b2c
SM
1712 ("#\\*mail\\*" . mail-mode)
1713 ;; Get rid of any trailing .n.m and try again.
1714 ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
5c6d31a4
SM
1715 ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
1716 ;; Using mode nil rather than `ignore' would let the search continue
1717 ;; through this list (with the shortened name) rather than start over.
1718 ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" ignore t)
1719 ;; The following should come after the ChangeLog pattern
1720 ;; for the sake of ChangeLog.1, etc.
1721 ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
e043664a 1722 ("\\.[1-9]\\'" . nroff-mode)
dfd8bf47 1723 ("\\.g\\'" . antlr-mode)
7ed9159a 1724 ("\\.ses\\'" . ses-mode)
dfd8bf47 1725 ("\\.in\\'" nil t)))
ffc0e1ca 1726 "Alist of filename patterns vs corresponding major mode functions.
116987ba
RS
1727Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1728\(NON-NIL stands for anything that is not nil; the value does not matter.)
1729Visiting a file whose name matches REGEXP specifies FUNCTION as the
1730mode function to use. FUNCTION will be called, unless it is nil.
1731
1732If the element has the form (REGEXP FUNCTION NON-NIL), then after
1733calling FUNCTION (if it's not nil), we delete the suffix that matched
1734REGEXP and search the list again for another match.")
7b3f3dc2 1735
e13322a0 1736
d7fa5aa2 1737(defvar interpreter-mode-alist
ffc0e1ca
AS
1738 (mapc
1739 (lambda (l)
1740 (cons (purecopy (car l)) (cdr l)))
1741 '(("perl" . perl-mode)
1742 ("perl5" . perl-mode)
1743 ("miniperl" . perl-mode)
1744 ("wish" . tcl-mode)
1745 ("wishx" . tcl-mode)
1746 ("tcl" . tcl-mode)
1747 ("tclsh" . tcl-mode)
1748 ("awk" . awk-mode)
1749 ("mawk" . awk-mode)
1750 ("nawk" . awk-mode)
1751 ("gawk" . awk-mode)
1752 ("scm" . scheme-mode)
1753 ("ash" . sh-mode)
1754 ("bash" . sh-mode)
1755 ("bash2" . sh-mode)
1756 ("csh" . sh-mode)
1757 ("dtksh" . sh-mode)
1758 ("es" . sh-mode)
1759 ("itcsh" . sh-mode)
1760 ("jsh" . sh-mode)
1761 ("ksh" . sh-mode)
1762 ("oash" . sh-mode)
1763 ("pdksh" . sh-mode)
1764 ("rc" . sh-mode)
1765 ("rpm" . sh-mode)
1766 ("sh" . sh-mode)
1767 ("sh5" . sh-mode)
1768 ("tcsh" . sh-mode)
1769 ("wksh" . sh-mode)
1770 ("wsh" . sh-mode)
1771 ("zsh" . sh-mode)
1772 ("tail" . text-mode)
1773 ("more" . text-mode)
1774 ("less" . text-mode)
1775 ("pg" . text-mode)
1776 ("make" . makefile-mode) ; Debian uses this
1777 ("guile" . scheme-mode)
1778 ("clisp" . lisp-mode)))
c907d156
RS
1779 "Alist mapping interpreter names to major modes.
1780This alist applies to files whose first line starts with `#!'.
1781Each element looks like (INTERPRETER . MODE).
1782The car of each element is compared with
1783the name of the interpreter specified in the first line.
1784If it matches, mode MODE is selected.")
1785
d7fa5aa2 1786(defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
45fb3bb8 1787 "List of regexps; if one matches a file name, don't look for `-*-'.")
a0c9f21b 1788
d7fa5aa2 1789(defvar inhibit-first-line-modes-suffixes nil
b20ff6d0
RS
1790 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1791When checking `inhibit-first-line-modes-regexps', we first discard
1792from the end of the file name anything that matches one of these regexps.")
1793
ffc0e1ca
AS
1794(defvar auto-mode-interpreter-regexp
1795 "#![ \t]?\\([^ \t\n]*\
1796/bin/env[ \t]\\)?\\([^ \t\n]+\\)"
1797 "Regular expression matching interpreters, for file mode determination.
1798This regular expression is matched against the first line of a file
1799to determine the file's mode in `set-auto-mode' when Emacs can't deduce
1800a mode from the file's name. If it matches, the file is assumed to
1801be interpreted by the interpreter matched by the second group of the
1802regular expression. The mode is then determined as the mode associated
1803with that interpreter in `interpreter-mode-alist'.")
0720b68b 1804
9de9b6a2 1805(defun set-auto-mode (&optional just-from-file-name)
b4da00e9 1806 "Select major mode appropriate for current buffer.
e3998da1
RS
1807This checks for a -*- mode tag in the buffer's text,
1808compares the filename against the entries in `auto-mode-alist',
1809or checks the interpreter that runs this file against
1810`interpreter-mode-alist'.
1811
1812It does not check for the `mode:' local variable in the
1813Local Variables section of the file; for that, use `hack-local-variables'.
7b3f3dc2 1814
f3e23606 1815If `enable-local-variables' is nil, this function does not check for a
9de9b6a2
RS
1816-*- mode tag.
1817
1818If the optional argument JUST-FROM-FILE-NAME is non-nil,
1819then we do not set anything but the major mode,
1820and we don't even do that unless it would come from the file name."
b4da00e9 1821 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
2d2ab9da 1822 (let (end done modes)
b4da00e9
RM
1823 (save-excursion
1824 (goto-char (point-min))
1825 (skip-chars-forward " \t\n")
9fa7bfe5 1826 (and enable-local-variables
e3f9b9c0 1827 (setq end (set-auto-mode-1))
2d2ab9da
RS
1828 (if (save-excursion (search-forward ":" end t))
1829 ;; Find all specifications for the `mode:' variable
1830 ;; and execute them left to right.
1831 (while (let ((case-fold-search t))
1832 (or (and (looking-at "mode:")
1833 (goto-char (match-end 0)))
1834 (re-search-forward "[ \t;]mode:" end t)))
1835 (skip-chars-forward " \t")
1836 (let ((beg (point)))
9fa7bfe5
RS
1837 (if (search-forward ";" end t)
1838 (forward-char -1)
1839 (goto-char end))
1840 (skip-chars-backward " \t")
9ee45b2c 1841 (push (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
2d2ab9da
RS
1842 modes)))
1843 ;; Simple -*-MODE-*- case.
1844 (push (intern (concat (downcase (buffer-substring (point) end))
1845 "-mode"))
1846 modes))))
d0fc03ef
RS
1847 ;; If we found modes to use, invoke them now,
1848 ;; outside the save-excursion.
9ee45b2c
SM
1849 (unless just-from-file-name
1850 (dolist (mode (nreverse modes))
1851 (if (not (functionp mode))
1852 (message "Ignoring unknown mode `%s'" mode)
1853 (setq done t)
1854 (funcall mode))))
d0fc03ef
RS
1855 ;; If we didn't find a mode from a -*- line, try using the file name.
1856 (if (and (not done) buffer-file-name)
1857 (let ((name buffer-file-name)
1858 (keep-going t))
1859 ;; Remove backup-suffixes from file name.
1860 (setq name (file-name-sans-versions name))
1861 (while keep-going
1862 (setq keep-going nil)
1863 (let ((alist auto-mode-alist)
1864 (mode nil))
1865 ;; Find first matching alist entry.
76d5492b 1866 (let ((case-fold-search
c60ee5e7 1867 (memq system-type '(vax-vms windows-nt cygwin))))
d0fc03ef
RS
1868 (while (and (not mode) alist)
1869 (if (string-match (car (car alist)) name)
1870 (if (and (consp (cdr (car alist)))
1871 (nth 2 (car alist)))
ffc0e1ca
AS
1872 (setq mode (car (cdr (car alist)))
1873 name (substring name 0 (match-beginning 0))
1874 keep-going t)
d0fc03ef
RS
1875 (setq mode (cdr (car alist))
1876 keep-going nil)))
1877 (setq alist (cdr alist))))
1878 (if mode
3b9ffb77
RS
1879 ;; When JUST-FROM-FILE-NAME is set,
1880 ;; we are working on behalf of set-visited-file-name.
1881 ;; In that case, if the major mode specified is the
1882 ;; same one we already have, don't actually reset it.
1883 ;; We don't want to lose minor modes such as Font Lock.
1884 (unless (and just-from-file-name (eq mode major-mode))
1885 (funcall mode))
d0fc03ef
RS
1886 ;; If we can't deduce a mode from the file name,
1887 ;; look for an interpreter specified in the first line.
1540e4e9
KH
1888 ;; As a special case, allow for things like "#!/bin/env perl",
1889 ;; which finds the interpreter anywhere in $PATH.
d0fc03ef
RS
1890 (let ((interpreter
1891 (save-excursion
1892 (goto-char (point-min))
ffc0e1ca
AS
1893 (if (looking-at auto-mode-interpreter-regexp)
1894 (match-string 2)
d0fc03ef
RS
1895 "")))
1896 elt)
1897 ;; Map interpreter name to a mode.
1898 (setq elt (assoc (file-name-nondirectory interpreter)
1899 interpreter-mode-alist))
9de9b6a2
RS
1900 (unless just-from-file-name
1901 (if elt
1902 (funcall (cdr elt))))))))))))
b4da00e9 1903
e3f9b9c0
RS
1904
1905(defun set-auto-mode-1 ()
1906 "Find the -*- spec in the buffer.
1907Call with point at the place to start searching from.
1908If one is found, set point to the beginning
1909and return the position of the end.
1910Otherwise, return nil; point may be changed."
1911 (let (beg end)
1912 (and
1913 ;; Don't look for -*- if this file name matches any
1914 ;; of the regexps in inhibit-first-line-modes-regexps.
1915 (let ((temp inhibit-first-line-modes-regexps)
1916 (name (if buffer-file-name
1917 (file-name-sans-versions buffer-file-name)
1918 (buffer-name))))
1919 (while (let ((sufs inhibit-first-line-modes-suffixes))
1920 (while (and sufs (not (string-match (car sufs) name)))
1921 (setq sufs (cdr sufs)))
1922 sufs)
1923 (setq name (substring name 0 (match-beginning 0))))
1924 (while (and temp
1925 (not (string-match (car temp) name)))
1926 (setq temp (cdr temp)))
1927 (not temp))
1928
1929 (search-forward "-*-" (save-excursion
1930 ;; If the file begins with "#!"
1931 ;; (exec interpreter magic), look
1932 ;; for mode frobs in the first two
1933 ;; lines. You cannot necessarily
1934 ;; put them in the first line of
1935 ;; such a file without screwing up
1936 ;; the interpreter invocation.
1937 (end-of-line (and (looking-at "^#!") 2))
1938 (point)) t)
1939 (progn
1940 (skip-chars-forward " \t")
1941 (setq beg (point))
1942 (search-forward "-*-"
1943 (save-excursion (end-of-line) (point))
1944 t))
1945 (progn
1946 (forward-char -3)
1947 (skip-chars-backward " \t")
1948 (setq end (point))
1949 (goto-char beg)
1950 end))))
1951
a0e74e72 1952(defun hack-local-variables-prop-line (&optional mode-only)
ffc0e1ca
AS
1953 "Set local variables specified in the -*- line.
1954Ignore any specification for `mode:' and `coding:';
1955`set-auto-mode' should already have handled `mode:',
a0e74e72
RS
1956`set-auto-coding' should already have handled `coding:'.
1957If MODE-ONLY is non-nil, all we do is check whether the major mode
1958is specified, returning t if it is specified."
f3e23606
RS
1959 (save-excursion
1960 (goto-char (point-min))
13a66180 1961 (let ((result nil)
e3f9b9c0 1962 (end (set-auto-mode-1))
a0e74e72 1963 mode-specified
aa5fcebf
KH
1964 (enable-local-variables
1965 (and local-enable-local-variables enable-local-variables)))
a0e74e72
RS
1966 ;; Parse the -*- line into the RESULT alist.
1967 ;; Also set MODE-SPECIFIED if we see a spec or `mode'.
e3f9b9c0 1968 (cond ((not end)
f3e23606
RS
1969 nil)
1970 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
13a66180 1971 ;; Simple form: "-*- MODENAME -*-". Already handled.
a0e74e72 1972 (setq mode-specified t)
13a66180 1973 nil)
f3e23606
RS
1974 (t
1975 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1976 ;; (last ";" is optional).
f3e23606
RS
1977 (while (< (point) end)
1978 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
ffc0e1ca 1979 (error "Malformed -*- line"))
f3e23606 1980 (goto-char (match-end 0))
1c26a6f3
KH
1981 ;; There used to be a downcase here,
1982 ;; but the manual didn't say so,
1983 ;; and people want to set var names that aren't all lc.
1984 (let ((key (intern (buffer-substring
1985 (match-beginning 1)
1986 (match-end 1))))
f3e23606
RS
1987 (val (save-restriction
1988 (narrow-to-region (point) end)
1989 (read (current-buffer)))))
93a2702d
RS
1990 ;; It is traditional to ignore
1991 ;; case when checking for `mode' in set-auto-mode,
1992 ;; so we must do that here as well.
1993 ;; That is inconsistent, but we're stuck with it.
3fa0a9aa 1994 ;; The same can be said for `coding' in set-auto-coding.
93a2702d 1995 (or (equal (downcase (symbol-name key)) "mode")
3fa0a9aa 1996 (equal (downcase (symbol-name key)) "coding")
13a66180 1997 (setq result (cons (cons key val) result)))
a0e74e72
RS
1998 (if (equal (downcase (symbol-name key)) "mode")
1999 (setq mode-specified t))
f3e23606
RS
2000 (skip-chars-forward " \t;")))
2001 (setq result (nreverse result))))
76d5492b 2002
a0e74e72
RS
2003 (if mode-only mode-specified
2004 (if (and result
2005 (or mode-only
2006 (eq enable-local-variables t)
2007 (and enable-local-variables
2008 (save-window-excursion
2009 (condition-case nil
2010 (switch-to-buffer (current-buffer))
2011 (error
2012 ;; If we fail to switch in the selected window,
2013 ;; it is probably a minibuffer.
2014 ;; So try another window.
2015 (condition-case nil
2016 (switch-to-buffer-other-window (current-buffer))
2017 (error
2018 (switch-to-buffer-other-frame (current-buffer))))))
2019 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
2020 (file-name-nondirectory buffer-file-name)))))))
2021 (let ((enable-local-eval enable-local-eval))
2022 (while result
2023 (hack-one-local-variable (car (car result)) (cdr (car result)))
2024 (setq result (cdr result)))))
2025 nil))))
f3e23606 2026
1d517019
RS
2027(defvar hack-local-variables-hook nil
2028 "Normal hook run after processing a file's local variables specs.
2029Major modes can use this to examine user-specified local variables
2030in order to initialize other data structure based on them.")
2031
9de9b6a2
RS
2032(defun hack-local-variables (&optional mode-only)
2033 "Parse and put into effect this buffer's local variables spec.
2034If MODE-ONLY is non-nil, all we do is check whether the major mode
2035is specified, returning t if it is specified."
a0e74e72
RS
2036 (let ((mode-specified
2037 ;; If MODE-ONLY is t, we check here for specifying the mode
2038 ;; in the -*- line. If MODE-ONLY is nil, we process
2039 ;; the -*- line here.
2040 (hack-local-variables-prop-line mode-only))
aa5fcebf
KH
2041 (enable-local-variables
2042 (and local-enable-local-variables enable-local-variables)))
a0e74e72 2043 ;; Look for "Local variables:" line in last page.
9de9b6a2
RS
2044 (save-excursion
2045 (goto-char (point-max))
2046 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
2047 (if (let ((case-fold-search t))
2048 (and (search-forward "Local Variables:" nil t)
2049 (or (eq enable-local-variables t)
2050 mode-only
2051 (and enable-local-variables
2052 (save-window-excursion
2053 (switch-to-buffer (current-buffer))
2054 (save-excursion
2055 (beginning-of-line)
2056 (set-window-start (selected-window) (point)))
2057 (y-or-n-p (format "Set local variables as specified at end of %s? "
2058 (if buffer-file-name
2059 (file-name-nondirectory
2060 buffer-file-name)
2061 (concat "buffer "
2062 (buffer-name))))))))))
2063 (let ((continue t)
2064 prefix prefixlen suffix beg
2065 mode-specified
2066 (enable-local-eval enable-local-eval))
2067 ;; The prefix is what comes before "local variables:" in its line.
2068 ;; The suffix is what comes after "local variables:" in its line.
b4da00e9 2069 (skip-chars-forward " \t")
9de9b6a2
RS
2070 (or (eolp)
2071 (setq suffix (buffer-substring (point)
2072 (progn (end-of-line) (point)))))
2073 (goto-char (match-beginning 0))
2074 (or (bolp)
2075 (setq prefix
2076 (buffer-substring (point)
2077 (progn (beginning-of-line) (point)))))
2078
2079 (if prefix (setq prefixlen (length prefix)
2080 prefix (regexp-quote prefix)))
2081 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
2082 (while continue
2083 ;; Look at next local variable spec.
2084 (if selective-display (re-search-forward "[\n\C-m]")
2085 (forward-line 1))
2086 ;; Skip the prefix, if any.
2087 (if prefix
2088 (if (looking-at prefix)
2089 (forward-char prefixlen)
2090 (error "Local variables entry is missing the prefix")))
2091 ;; Find the variable name; strip whitespace.
2092 (skip-chars-forward " \t")
2093 (setq beg (point))
2094 (skip-chars-forward "^:\n")
2095 (if (eolp) (error "Missing colon in local variables entry"))
2096 (skip-chars-backward " \t")
2097 (let* ((str (buffer-substring beg (point)))
2098 (var (read str))
2099 val)
2100 ;; Setting variable named "end" means end of list.
2101 (if (string-equal (downcase str) "end")
2102 (setq continue nil)
2103 ;; Otherwise read the variable value.
2104 (skip-chars-forward "^:")
2105 (forward-char 1)
2106 (setq val (read (current-buffer)))
2107 (skip-chars-backward "\n")
2108 (skip-chars-forward " \t")
2109 (or (if suffix (looking-at suffix) (eolp))
2110 (error "Local variables entry is terminated incorrectly"))
2111 (if mode-only
2112 (if (eq var 'mode)
2113 (setq mode-specified t))
2114 ;; Set the variable. "Variables" mode and eval are funny.
2115 (hack-one-local-variable var val))))))))
2116 (unless mode-only
2117 (run-hooks 'hack-local-variables-hook))
2118 mode-specified))
f3e23606 2119
d7fa5aa2 2120(defvar ignored-local-variables
f3e23606
RS
2121 '(enable-local-eval)
2122 "Variables to be ignored in a file's local variable spec.")
2123
be0218a8 2124;; Get confirmation before setting these variables as locals in a file.
05ef1cda 2125(put 'debugger 'risky-local-variable t)
f6fa3ee3 2126(put 'enable-local-eval 'risky-local-variable t)
fce47eea 2127(put 'ignored-local-variables 'risky-local-variable t)
be0218a8
RS
2128(put 'eval 'risky-local-variable t)
2129(put 'file-name-handler-alist 'risky-local-variable t)
7ed9159a 2130(put 'inhibit-quit 'risky-local-variable t)
7078d9d2 2131(put 'minor-mode-alist 'risky-local-variable t)
be0218a8 2132(put 'minor-mode-map-alist 'risky-local-variable t)
7078d9d2
RS
2133(put 'minor-mode-overriding-map-alist 'risky-local-variable t)
2134(put 'overriding-local-map 'risky-local-variable t)
2135(put 'overriding-terminal-local-map 'risky-local-variable t)
2136(put 'auto-mode-alist 'risky-local-variable t)
be0218a8 2137(put 'after-load-alist 'risky-local-variable t)
f6fa3ee3 2138(put 'buffer-file-name 'risky-local-variable t)
7078d9d2 2139(put 'buffer-undo-list 'risky-local-variable t)
f6fa3ee3
RS
2140(put 'buffer-auto-save-file-name 'risky-local-variable t)
2141(put 'buffer-file-truename 'risky-local-variable t)
7078d9d2 2142(put 'default-text-properties 'risky-local-variable t)
b0ffcc0d
RS
2143(put 'exec-path 'risky-local-variable t)
2144(put 'load-path 'risky-local-variable t)
2145(put 'exec-directory 'risky-local-variable t)
2146(put 'process-environment 'risky-local-variable t)
eba1c87a
RS
2147(put 'dabbrev-case-fold-search 'risky-local-variable t)
2148(put 'dabbrev-case-replace 'risky-local-variable t)
9afa8bf7
RS
2149;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
2150(put 'outline-level 'risky-local-variable t)
d98b741d 2151(put 'rmail-output-file-alist 'risky-local-variable t)
f4d04672 2152(put 'font-lock-defaults 'risky-local-variable t)
7078d9d2
RS
2153(put 'special-display-buffer-names 'risky-local-variable t)
2154(put 'frame-title-format 'risky-local-variable t)
2155(put 'global-mode-string 'risky-local-variable t)
2156(put 'header-line-format 'risky-local-variable t)
2157(put 'icon-title-format 'risky-local-variable t)
2158(put 'input-method-alist 'risky-local-variable t)
032388f3 2159(put 'format-alist 'risky-local-variable t)
7078d9d2
RS
2160(put 'vc-mode 'risky-local-variable t)
2161(put 'imenu-generic-expression 'risky-local-variable t)
2162(put 'imenu-index-alist 'risky-local-variable t)
2163(put 'standard-input 'risky-local-variable t)
2164(put 'standard-output 'risky-local-variable t)
2165(put 'unread-command-events 'risky-local-variable t)
2166(put 'max-lisp-eval-depth 'risky-local-variable t)
2167(put 'max-specpdl-size 'risky-local-variable t)
ec4ba9e3
RS
2168(put 'mode-line-format 'risky-local-variable t)
2169(put 'mode-line-modified 'risky-local-variable t)
2170(put 'mode-line-mule-info 'risky-local-variable t)
2171(put 'mode-line-buffer-identification 'risky-local-variable t)
2172(put 'mode-line-modes 'risky-local-variable t)
2173(put 'mode-line-position 'risky-local-variable t)
b459083c 2174(put 'mode-line-process 'risky-local-variable t)
fbafc3bd 2175(put 'mode-name 'risky-local-variable t)
2bbbe4f6 2176(put 'display-time-string 'risky-local-variable t)
fecddd0d 2177(put 'parse-time-rules 'risky-local-variable t)
f6fa3ee3 2178
472514b7
RS
2179;; This case is safe because the user gets to check it before it is used.
2180(put 'compile-command 'safe-local-variable 'stringp)
2181
2182(defun risky-local-variable-p (sym val)
0d8781d8
RS
2183 "Non-nil if SYM could be dangerous as a file-local variable with value VAL.
2184If VAL is nil, the question is whether any value might be dangerous."
472514b7
RS
2185 (let ((safep (get sym 'safe-local-variable)))
2186 (or (memq sym ignored-local-variables)
2187 (get sym 'risky-local-variable)
2188 (and (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$\\|-predicate$\\|font-lock-keywords$\\|font-lock-keywords-[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|-map$\\|-map-alist$"
2189 (symbol-name sym))
2190 (not safep))
2191 ;; If the safe-local-variable property isn't t or nil,
2192 ;; then it must return non-nil on the proposed value to be safe.
2193 (and (not (memq safep '(t nil)))
0d8781d8
RS
2194 (or (null val)
2195 (not (funcall safep val)))))))
7ed9159a 2196
8fd9c174
RS
2197(defcustom safe-local-eval-forms nil
2198 "*Expressions that are considered \"safe\" in an `eval:' local variable.
2199Add expressions to this list if you want Emacs to evaluate them, when
2200they appear in an `eval' local variable specification, without first
2201asking you for confirmation."
2202 :group 'find-file
2203 :version "21.4"
2204 :type '(repeat sexp))
2205
ff7affeb
RS
2206(put 'c-set-style 'safe-local-eval-function t)
2207
d0bd3513
RS
2208(defun hack-one-local-variable-quotep (exp)
2209 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
2210
ff7affeb
RS
2211(defun hack-one-local-variable-constantp (exp)
2212 (or (and (not (symbolp exp)) (not (consp exp)))
2213 (memq exp '(t nil))
2214 (keywordp exp)
2215 (hack-one-local-variable-quotep exp)))
2216
2217(defun hack-one-local-variable-eval-safep (exp)
2218 "Return t if it is safe to eval EXP when it is found in a file."
8fd9c174
RS
2219 (or (not (consp exp))
2220 ;; Detect certain `put' expressions.
2221 (and (eq (car exp) 'put)
2222 (hack-one-local-variable-quotep (nth 1 exp))
2223 (hack-one-local-variable-quotep (nth 2 exp))
2224 (memq (nth 1 (nth 2 exp))
2225 '(lisp-indent-hook))
2226 ;; Only allow safe values of lisp-indent-hook;
2227 ;; not functions.
2228 (or (numberp (nth 3 exp))
2229 (equal (nth 3 exp) ''defun)))
2230 ;; Allow expressions that the user requested.
2231 (member exp safe-local-eval-forms)
2232 ;; Certain functions can be allowed with safe arguments
2233 ;; or can specify verification functions to try.
2234 (and (symbolp (car exp))
2235 (let ((prop (get (car exp) 'safe-local-eval-function)))
2236 (cond ((eq prop t)
2237 (let ((ok t))
2238 (dolist (arg (cdr exp))
2239 (unless (hack-one-local-variable-constantp arg)
2240 (setq ok nil)))
2241 ok))
2242 ((functionp prop)
2243 (funcall prop exp))
2244 ((listp prop)
2245 (let ((ok nil))
2246 (dolist (function prop)
2247 (if (funcall function exp)
2248 (setq ok t)))
2249 ok)))))))
ff7affeb 2250
f3e23606 2251(defun hack-one-local-variable (var val)
ffc0e1ca 2252 "\"Set\" one variable in a local variables spec.
7078d9d2
RS
2253A few patterns are specified so that any name which matches one
2254is considered risky."
f3e23606
RS
2255 (cond ((eq var 'mode)
2256 (funcall (intern (concat (downcase (symbol-name val))
2257 "-mode"))))
3fa0a9aa
KH
2258 ((eq var 'coding)
2259 ;; We have already handled coding: tag in set-auto-coding.
2260 nil)
f3e23606 2261 ;; "Setting" eval means either eval it or do nothing.
7d3221d7 2262 ;; Likewise for setting hook variables.
472514b7 2263 ((risky-local-variable-p var val)
0225ae5e 2264 ;; Permit evalling a put of a harmless property.
d0bd3513
RS
2265 ;; if the args do nothing tricky.
2266 (if (or (and (eq var 'eval)
ff7affeb 2267 (hack-one-local-variable-eval-safep val))
d0bd3513 2268 ;; Permit eval if not root and user says ok.
c7e62660 2269 (and (not (zerop (user-uid)))
d0bd3513
RS
2270 (or (eq enable-local-eval t)
2271 (and enable-local-eval
2272 (save-window-excursion
2273 (switch-to-buffer (current-buffer))
2274 (save-excursion
2275 (beginning-of-line)
2276 (set-window-start (selected-window) (point)))
2277 (setq enable-local-eval
abf16d5e
RS
2278 (y-or-n-p (format "Process `eval' or hook local variables in %s? "
2279 (if buffer-file-name
2280 (concat "file " (file-name-nondirectory buffer-file-name))
2281 (concat "buffer " (buffer-name)))))))))))
7d3221d7
RS
2282 (if (eq var 'eval)
2283 (save-excursion (eval val))
2284 (make-local-variable var)
2285 (set var val))
472514b7 2286 (message "Ignoring risky spec in the local variables list")))
f3e23606
RS
2287 ;; Ordinary variable, really set it.
2288 (t (make-local-variable var)
87a6a5d8
RS
2289 ;; Make sure the string has no text properties.
2290 ;; Some text properties can get evaluated in various ways,
2291 ;; so it is risky to put them on with a local variable list.
2292 (if (stringp val)
2293 (set-text-properties 0 (length val) nil val))
f3e23606
RS
2294 (set var val))))
2295
b4da00e9 2296\f
21540597 2297(defcustom change-major-mode-with-file-name t
9de9b6a2
RS
2298 "*Non-nil means \\[write-file] should set the major mode from the file name.
2299However, the mode will not be changed if
2300\(1) a local variables list or the `-*-' line specifies a major mode, or
2301\(2) the current major mode is a \"special\" mode,
8609911b 2302\ not suitable for ordinary files, or
21540597
RS
2303\(3) the new file name does not particularly specify any mode."
2304 :type 'boolean
2305 :group 'editing-basics)
9de9b6a2 2306
f36012a6 2307(defun set-visited-file-name (filename &optional no-query along-with-file)
b4da00e9
RM
2308 "Change name of file visited in current buffer to FILENAME.
2309The next time the buffer is saved it will go in the newly specified file.
2310nil or empty string as argument means make buffer not be visiting any file.
2311Remember to delete the initial contents of the minibuffer
6a6b62f8
RS
2312if you wish to pass an empty string as the argument.
2313
2314The optional second argument NO-QUERY, if non-nil, inhibits asking for
f36012a6
RS
2315confirmation in the case where another buffer is already visiting FILENAME.
2316
2317The optional third argument ALONG-WITH-FILE, if non-nil, means that
2318the old visited file has been renamed to the new name FILENAME."
b4da00e9 2319 (interactive "FSet visited file name: ")
c11a94fe
RS
2320 (if (buffer-base-buffer)
2321 (error "An indirect buffer cannot visit a file"))
a522e5bf
RS
2322 (let (truename)
2323 (if filename
2324 (setq filename
2325 (if (string-equal filename "")
2326 nil
2327 (expand-file-name filename))))
2328 (if filename
2329 (progn
2330 (setq truename (file-truename filename))
2331 (if find-file-visit-truename
a522e5bf 2332 (setq filename truename))))
11e314fa 2333 (let ((buffer (and filename (find-buffer-visiting filename))))
7b89d38e 2334 (and buffer (not (eq buffer (current-buffer)))
6a6b62f8 2335 (not no-query)
7b89d38e
RS
2336 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
2337 filename)))
2338 (error "Aborted")))
a522e5bf
RS
2339 (or (equal filename buffer-file-name)
2340 (progn
2341 (and filename (lock-buffer filename))
2342 (unlock-buffer)))
2343 (setq buffer-file-name filename)
2344 (if filename ; make buffer name reflect filename.
2345 (let ((new-name (file-name-nondirectory buffer-file-name)))
2346 (if (string= new-name "")
2347 (error "Empty file name"))
2348 (if (eq system-type 'vax-vms)
2349 (setq new-name (downcase new-name)))
2350 (setq default-directory (file-name-directory buffer-file-name))
2351 (or (string= new-name (buffer-name))
2352 (rename-buffer new-name t))))
2353 (setq buffer-backed-up nil)
f36012a6
RS
2354 (or along-with-file
2355 (clear-visited-file-modtime))
8ccdc29e 2356 ;; Abbreviate the file names of the buffer.
4826e97f 2357 (if truename
8ccdc29e
RS
2358 (progn
2359 (setq buffer-file-truename (abbreviate-file-name truename))
2360 (if find-file-visit-truename
2361 (setq buffer-file-name buffer-file-truename))))
a522e5bf
RS
2362 (setq buffer-file-number
2363 (if filename
2a47b4f5 2364 (nthcdr 10 (file-attributes buffer-file-name))
a522e5bf 2365 nil)))
0370fe77 2366 ;; write-file-functions is normally used for things like ftp-find-file
b4da00e9
RM
2367 ;; that visit things that are not local files as if they were files.
2368 ;; Changing to visit an ordinary local file instead should flush the hook.
0370fe77 2369 (kill-local-variable 'write-file-functions)
c9dca4e0 2370 (kill-local-variable 'local-write-file-hooks)
b4da00e9
RM
2371 (kill-local-variable 'revert-buffer-function)
2372 (kill-local-variable 'backup-inhibited)
ee81c959
RS
2373 ;; If buffer was read-only because of version control,
2374 ;; that reason is gone now, so make it writable.
2375 (if vc-mode
2376 (setq buffer-read-only nil))
2377 (kill-local-variable 'vc-mode)
b4da00e9
RM
2378 ;; Turn off backup files for certain file names.
2379 ;; Since this is a permanent local, the major mode won't eliminate it.
4d49551a
KH
2380 (and buffer-file-name
2381 (not (funcall backup-enable-predicate buffer-file-name))
b4da00e9
RM
2382 (progn
2383 (make-local-variable 'backup-inhibited)
2384 (setq backup-inhibited t)))
c77a81cf
RS
2385 (let ((oauto buffer-auto-save-file-name))
2386 ;; If auto-save was not already on, turn it on if appropriate.
2387 (if (not buffer-auto-save-file-name)
2388 (and buffer-file-name auto-save-default
2389 (auto-save-mode t))
2390 ;; If auto save is on, start using a new name.
2391 ;; We deliberately don't rename or delete the old auto save
2392 ;; for the old visited file name. This is because perhaps
2393 ;; the user wants to save the new state and then compare with the
2394 ;; previous state from the auto save file.
2395 (setq buffer-auto-save-file-name
2396 (make-auto-save-file-name)))
2397 ;; Rename the old auto save file if any.
2398 (and oauto buffer-auto-save-file-name
e6f0e76c 2399 (file-exists-p oauto)
c77a81cf 2400 (rename-file oauto buffer-auto-save-file-name t)))
f36012a6
RS
2401 (and buffer-file-name
2402 (not along-with-file)
9de9b6a2
RS
2403 (set-buffer-modified-p t))
2404 ;; Update the major mode, if the file name determines it.
2405 (condition-case nil
2406 ;; Don't change the mode if it is special.
2407 (or (not change-major-mode-with-file-name)
2408 (get major-mode 'mode-class)
2409 ;; Don't change the mode if the local variable list specifies it.
2410 (hack-local-variables t)
2411 (set-auto-mode t))
2412 (error nil)))
b4da00e9 2413
912192d1 2414(defun write-file (filename &optional confirm)
b4da00e9 2415 "Write current buffer into file FILENAME.
7f99999a 2416This makes the buffer visit that file, and marks it as not modified.
7458cc35 2417
7f99999a
KH
2418If you specify just a directory name as FILENAME, that means to use
2419the default file name but in that directory. You can also yank
2420the default file name into the minibuffer to edit it, using M-n.
2421
2422If the buffer is not already visiting a file, the default file name
2423for the output file is the buffer name.
2424
2425If optional second arg CONFIRM is non-nil, this function
2426asks for confirmation before overwriting an existing file.
912192d1 2427Interactively, confirmation is required unless you supply a prefix argument."
b4da00e9
RM
2428;; (interactive "FWrite file: ")
2429 (interactive
2430 (list (if buffer-file-name
2431 (read-file-name "Write file: "
2432 nil nil nil nil)
7f99999a
KH
2433 (read-file-name "Write file: " default-directory
2434 (expand-file-name
2435 (file-name-nondirectory (buffer-name))
2436 default-directory)
2437 nil nil))
912192d1 2438 (not current-prefix-arg)))
b4da00e9 2439 (or (null filename) (string-equal filename "")
41f48cb1
RS
2440 (progn
2441 ;; If arg is just a directory,
7f99999a
KH
2442 ;; use the default file name, but in that directory.
2443 (if (file-directory-p filename)
41f48cb1 2444 (setq filename (concat (file-name-as-directory filename)
7f99999a
KH
2445 (file-name-nondirectory
2446 (or buffer-file-name (buffer-name))))))
c2fb8488
RS
2447 (and confirm
2448 (file-exists-p filename)
2449 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
2450 (error "Canceled")))
5f65549e 2451 (set-visited-file-name filename (not confirm))))
b4da00e9 2452 (set-buffer-modified-p t)
6492b55d
KH
2453 ;; Make buffer writable if file is writable.
2454 (and buffer-file-name
2455 (file-writable-p buffer-file-name)
2456 (setq buffer-read-only nil))
912192d1 2457 (save-buffer))
b4da00e9
RM
2458\f
2459(defun backup-buffer ()
2460 "Make a backup of the disk file visited by the current buffer, if appropriate.
2461This is normally done before saving the buffer the first time.
27ab6944
KH
2462
2463A backup may be done by renaming or by copying; see documentation of
2464variable `make-backup-files'. If it's done by renaming, then the file is
f3f9e207
RS
2465no longer accessible under its old name.
2466
2467The value is non-nil after a backup was made by renaming.
2468It has the form (MODES . BACKUPNAME).
2469MODES is the result of `file-modes' on the original
2470file; this means that the caller, after saving the buffer, should change
2471the modes of the new file to agree with the old modes.
2472BACKUPNAME is the backup file name, which is the old file renamed."
b4da00e9
RM
2473 (if (and make-backup-files (not backup-inhibited)
2474 (not buffer-backed-up)
2475 (file-exists-p buffer-file-name)
2476 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
2477 '(?- ?l)))
2478 (let ((real-file-name buffer-file-name)
2479 backup-info backupname targets setmodes)
2480 ;; If specified name is a symbolic link, chase it to the target.
2481 ;; Thus we make the backups in the directory where the real file is.
5dadeb29 2482 (setq real-file-name (file-chase-links real-file-name))
b4da00e9
RM
2483 (setq backup-info (find-backup-file-name real-file-name)
2484 backupname (car backup-info)
2485 targets (cdr backup-info))
5c6d31a4
SM
2486 ;; (if (file-directory-p buffer-file-name)
2487 ;; (error "Cannot save buffer in directory %s" buffer-file-name))
eb650569
RS
2488 (if backup-info
2489 (condition-case ()
2490 (let ((delete-old-versions
2491 ;; If have old versions to maybe delete,
2492 ;; ask the user to confirm now, before doing anything.
2493 ;; But don't actually delete til later.
2494 (and targets
2495 (or (eq delete-old-versions t) (eq delete-old-versions nil))
2496 (or delete-old-versions
2497 (y-or-n-p (format "Delete excess backup versions of %s? "
446c63b0
RS
2498 real-file-name)))))
2499 (modes (file-modes buffer-file-name)))
eb650569
RS
2500 ;; Actually write the back up file.
2501 (condition-case ()
2502 (if (or file-precious-flag
ffc0e1ca 2503 ; (file-symlink-p buffer-file-name)
eb650569 2504 backup-by-copying
446c63b0 2505 ;; Don't rename a suid or sgid file.
7da6bf00 2506 (and modes (< 0 (logand modes #o6000)))
eb650569
RS
2507 (and backup-by-copying-when-linked
2508 (> (file-nlinks real-file-name) 1))
ffc0e1ca
AS
2509 (and (or backup-by-copying-when-mismatch
2510 (integerp backup-by-copying-when-privileged-mismatch))
eb650569 2511 (let ((attr (file-attributes real-file-name)))
ffc0e1ca
AS
2512 (and (or backup-by-copying-when-mismatch
2513 (and (integerp (nth 2 attr))
2514 (integerp backup-by-copying-when-privileged-mismatch)
2515 (<= (nth 2 attr) backup-by-copying-when-privileged-mismatch)))
2516 (or (nth 9 attr)
2517 (not (file-ownership-preserved-p real-file-name)))))))
446c63b0 2518 (backup-buffer-copy real-file-name backupname modes)
eb650569
RS
2519 ;; rename-file should delete old backup.
2520 (rename-file real-file-name backupname t)
446c63b0 2521 (setq setmodes (cons modes backupname)))
eb650569
RS
2522 (file-error
2523 ;; If trouble writing the backup, write it in ~.
567c1ca9
RS
2524 (setq backupname (expand-file-name
2525 (convert-standard-filename
2526 "~/%backup%~")))
2527 (message "Cannot write backup file; backing up in %s"
2528 (file-name-nondirectory backupname))
eb650569 2529 (sleep-for 1)
446c63b0 2530 (backup-buffer-copy real-file-name backupname modes)))
eb650569
RS
2531 (setq buffer-backed-up t)
2532 ;; Now delete the old versions, if desired.
2533 (if delete-old-versions
2534 (while targets
2535 (condition-case ()
2536 (delete-file (car targets))
2537 (file-error nil))
2538 (setq targets (cdr targets))))
2539 setmodes)
2540 (file-error nil))))))
b4da00e9 2541
446c63b0
RS
2542(defun backup-buffer-copy (from-name to-name modes)
2543 (condition-case ()
2544 (copy-file from-name to-name t t)
2545 (file-error
2546 ;; If copying fails because file TO-NAME
2547 ;; is not writable, delete that file and try again.
2548 (if (and (file-exists-p to-name)
2549 (not (file-writable-p to-name)))
2550 (delete-file to-name))
2551 (copy-file from-name to-name t t)))
2552 (set-file-modes to-name (logand modes #o1777)))
2553
c3554e95 2554(defun file-name-sans-versions (name &optional keep-backup-version)
ffc0e1ca 2555 "Return file NAME sans backup versions or strings.
b4da00e9 2556This is a separate procedure so your site-init or startup file can
c3554e95
RS
2557redefine it.
2558If the optional argument KEEP-BACKUP-VERSION is non-nil,
2559we do not remove backup version numbers, only true file version numbers."
6eaebaa2 2560 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
c3554e95
RS
2561 (if handler
2562 (funcall handler 'file-name-sans-versions name keep-backup-version)
2563 (substring name 0
2564 (if (eq system-type 'vax-vms)
2565 ;; VMS version number is (a) semicolon, optional
2566 ;; sign, zero or more digits or (b) period, option
2567 ;; sign, zero or more digits, provided this is the
2568 ;; second period encountered outside of the
2569 ;; device/directory part of the file name.
26add1bf
KH
2570 (or (string-match ";[-+]?[0-9]*\\'" name)
2571 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
c3554e95
RS
2572 name)
2573 (match-beginning 1))
2574 (length name))
2575 (if keep-backup-version
2576 (length name)
dbb12f2c 2577 (or (string-match "\\.~[0-9.]+~\\'" name)
c3554e95
RS
2578 (string-match "~\\'" name)
2579 (length name))))))))
b4da00e9 2580
cb0cd911 2581(defun file-ownership-preserved-p (file)
ffc0e1ca 2582 "Return t if deleting FILE and rewriting it would preserve the owner."
cb0cd911
RS
2583 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
2584 (if handler
2585 (funcall handler 'file-ownership-preserved-p file)
ec5533be 2586 (let ((attributes (file-attributes file)))
306faa42
RS
2587 ;; Return t if the file doesn't exist, since it's true that no
2588 ;; information would be lost by an (attempted) delete and create.
2589 (or (null attributes)
2590 (= (nth 2 attributes) (user-uid)))))))
cb0cd911 2591
20b5d24c
RS
2592(defun file-name-sans-extension (filename)
2593 "Return FILENAME sans final \"extension\".
2531b0c3
EZ
2594The extension, in a file name, is the part that follows the last `.',
2595except that a leading `.', if any, doesn't count."
20b5d24c
RS
2596 (save-match-data
2597 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
2598 directory)
2531b0c3
EZ
2599 (if (and (string-match "\\.[^.]*\\'" file)
2600 (not (eq 0 (match-beginning 0))))
20b5d24c 2601 (if (setq directory (file-name-directory filename))
6ee24f1e
RS
2602 ;; Don't use expand-file-name here; if DIRECTORY is relative,
2603 ;; we don't want to expand it.
2604 (concat directory (substring file 0 (match-beginning 0)))
20b5d24c
RS
2605 (substring file 0 (match-beginning 0)))
2606 filename))))
2607
93a2702d
RS
2608(defun file-name-extension (filename &optional period)
2609 "Return FILENAME's final \"extension\".
2531b0c3
EZ
2610The extension, in a file name, is the part that follows the last `.',
2611except that a leading `.', if any, doesn't count.
93a2702d
RS
2612Return nil for extensionless file names such as `foo'.
2613Return the empty string for file names such as `foo.'.
2614
2615If PERIOD is non-nil, then the returned value includes the period
2616that delimits the extension, and if FILENAME has no extension,
2617the value is \"\"."
2618 (save-match-data
2619 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
2531b0c3
EZ
2620 (if (and (string-match "\\.[^.]*\\'" file)
2621 (not (eq 0 (match-beginning 0))))
93a2702d
RS
2622 (substring file (+ (match-beginning 0) (if period 0 1)))
2623 (if period
2624 "")))))
2625
ffc0e1ca
AS
2626(defcustom make-backup-file-name-function nil
2627 "A function to use instead of the default `make-backup-file-name'.
2628A value of nil gives the default `make-backup-file-name' behaviour.
2629
d5798fa7 2630This could be buffer-local to do something special for specific
ffc0e1ca
AS
2631files. If you define it, you may need to change `backup-file-name-p'
2632and `file-name-sans-versions' too.
2633
2634See also `backup-directory-alist'."
2635 :group 'backup
2636 :type '(choice (const :tag "Default" nil)
2637 (function :tag "Your function")))
2638
2639(defcustom backup-directory-alist nil
2640 "Alist of filename patterns and backup directory names.
2641Each element looks like (REGEXP . DIRECTORY). Backups of files with
2642names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
2643relative or absolute. If it is absolute, so that all matching files
2644are backed up into the same directory, the file names in this
2645directory will be the full name of the file backed up with all
2646directory separators changed to `!' to prevent clashes. This will not
2647work correctly if your filesystem truncates the resulting name.
2648
2649For the common case of all backups going into one directory, the alist
2650should contain a single element pairing \".\" with the appropriate
2651directory name.
2652
2653If this variable is nil, or it fails to match a filename, the backup
2654is made in the original file's directory.
2655
2656On MS-DOS filesystems without long names this variable is always
2657ignored."
2658 :group 'backup
dca5e71d 2659 :type '(repeat (cons (regexp :tag "Regexp matching filename")
ffc0e1ca
AS
2660 (directory :tag "Backup directory name"))))
2661
388d6ab5
RS
2662(defun normal-backup-enable-predicate (name)
2663 "Default `backup-enable-predicate' function.
2664Checks for files in `temporary-file-directory' or
2665`small-temporary-file-directory'."
2666 (not (or (let ((comp (compare-strings temporary-file-directory 0 nil
2667 name 0 nil)))
2668 ;; Directory is under temporary-file-directory.
2669 (and (not (eq comp t))
2670 (< comp (- (length temporary-file-directory)))))
2671 (if small-temporary-file-directory
2672 (let ((comp (compare-strings small-temporary-file-directory
2673 0 nil
2674 name 0 nil)))
2675 ;; Directory is under small-temporary-file-directory.
2676 (and (not (eq comp t))
2677 (< comp (- (length small-temporary-file-directory)))))))))
2678
b4da00e9
RM
2679(defun make-backup-file-name (file)
2680 "Create the non-numeric backup file name for FILE.
ffc0e1ca
AS
2681Normally this will just be the file's name with `~' appended.
2682Customization hooks are provided as follows.
2683
2684If the variable `make-backup-file-name-function' is non-nil, its value
2685should be a function which will be called with FILE as its argument;
2686the resulting name is used.
2687
2688Otherwise a match for FILE is sought in `backup-directory-alist'; see
2689the documentation of that variable. If the directory for the backup
2690doesn't exist, it is created."
2691 (if make-backup-file-name-function
2692 (funcall make-backup-file-name-function file)
2693 (if (and (eq system-type 'ms-dos)
2694 (not (msdos-long-file-names)))
2695 (let ((fn (file-name-nondirectory file)))
2696 (concat (file-name-directory file)
2697 (or (and (string-match "\\`[^.]+\\'" fn)
2698 (concat (match-string 0 fn) ".~"))
2699 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
2700 (concat (match-string 0 fn) "~")))))
2701 (concat (make-backup-file-name-1 file) "~"))))
2702
2703(defun make-backup-file-name-1 (file)
2704 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
2705 (let ((alist backup-directory-alist)
818286f4 2706 elt backup-directory)
ffc0e1ca
AS
2707 (while alist
2708 (setq elt (pop alist))
2709 (if (string-match (car elt) file)
2710 (setq backup-directory (cdr elt)
2711 alist nil)))
ee291b46 2712 (if (and backup-directory (not (file-exists-p backup-directory)))
ffc0e1ca
AS
2713 (condition-case nil
2714 (make-directory backup-directory 'parents)
ee291b46
RS
2715 (file-error (setq backup-directory nil))))
2716 (if (null backup-directory)
2717 file
ffc0e1ca
AS
2718 (if (file-name-absolute-p backup-directory)
2719 (progn
c60ee5e7 2720 (when (memq system-type '(windows-nt ms-dos cygwin))
d7b6ca4a
RS
2721 ;; Normalize DOSish file names: downcase the drive
2722 ;; letter, if any, and replace the leading "x:" with
2723 ;; "/drive_x".
ffc0e1ca
AS
2724 (or (file-name-absolute-p file)
2725 (setq file (expand-file-name file))) ; make defaults explicit
2726 ;; Replace any invalid file-name characters (for the
2727 ;; case of backing up remote files).
446c097e 2728 (setq file (expand-file-name (convert-standard-filename file)))
ffc0e1ca 2729 (if (eq (aref file 1) ?:)
d7b6ca4a 2730 (setq file (concat "/"
ffc0e1ca
AS
2731 "drive_"
2732 (char-to-string (downcase (aref file 0)))
d7b6ca4a 2733 (if (eq (aref file 2) ?/)
ffc0e1ca 2734 ""
d7b6ca4a 2735 "/")
ffc0e1ca
AS
2736 (substring file 2)))))
2737 ;; Make the name unique by substituting directory
2738 ;; separators. It may not really be worth bothering about
2739 ;; doubling `!'s in the original name...
2740 (expand-file-name
2741 (subst-char-in-string
d7b6ca4a 2742 ?/ ?!
ffc0e1ca
AS
2743 (replace-regexp-in-string "!" "!!" file))
2744 backup-directory))
2745 (expand-file-name (file-name-nondirectory file)
2746 (file-name-as-directory
2747 (expand-file-name backup-directory
2748 (file-name-directory file))))))))
b4da00e9
RM
2749
2750(defun backup-file-name-p (file)
2751 "Return non-nil if FILE is a backup file name (numeric or not).
2752This is a separate function so you can redefine it for customization.
2753You may need to redefine `file-name-sans-versions' as well."
066327ae 2754 (string-match "~\\'" file))
b4da00e9 2755
e2b30772
RS
2756(defvar backup-extract-version-start)
2757
2d051399 2758;; This is used in various files.
a7aa942a
KH
2759;; The usage of backup-extract-version-start is not very clean,
2760;; but I can't see a good alternative, so as of now I am leaving it alone.
2d051399 2761(defun backup-extract-version (fn)
ffc0e1ca 2762 "Given the name of a numeric backup file, FN, return the backup number.
e2b30772 2763Uses the free variable `backup-extract-version-start', whose value should be
2d051399 2764the index in the name where the version number begins."
e2b30772
RS
2765 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
2766 (= (match-beginning 0) backup-extract-version-start))
2767 (string-to-int (substring fn backup-extract-version-start -1))
2d051399
RS
2768 0))
2769
b4da00e9
RM
2770;; I believe there is no need to alter this behavior for VMS;
2771;; since backup files are not made on VMS, it should not get called.
2772(defun find-backup-file-name (fn)
ffc0e1ca 2773 "Find a file name for a backup file FN, and suggestions for deletions.
b4da00e9 2774Value is a list whose car is the name for the backup file
ffc0e1ca
AS
2775and whose cdr is a list of old versions to consider deleting now.
2776If the value is nil, don't make a backup.
2777Uses `backup-directory-alist' in the same way as does
2778`make-backup-file-name'."
eb650569
RS
2779 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2780 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2781 (if handler
2782 (funcall handler 'find-backup-file-name fn)
f26d858e
EZ
2783 (if (or (eq version-control 'never)
2784 ;; We don't support numbered backups on plain MS-DOS
2785 ;; when long file names are unavailable.
2786 (and (eq system-type 'ms-dos)
2787 (not (msdos-long-file-names))))
b4da00e9 2788 (list (make-backup-file-name fn))
ffc0e1ca
AS
2789 (let* ((basic-name (make-backup-file-name-1 fn))
2790 (base-versions (concat (file-name-nondirectory basic-name)
2791 ".~"))
e2b30772 2792 (backup-extract-version-start (length base-versions))
eb650569 2793 (high-water-mark 0)
ffc0e1ca
AS
2794 (number-to-delete 0)
2795 possibilities deserve-versions-p versions)
eb650569
RS
2796 (condition-case ()
2797 (setq possibilities (file-name-all-completions
2798 base-versions
ffc0e1ca
AS
2799 (file-name-directory basic-name))
2800 versions (sort (mapcar #'backup-extract-version
2801 possibilities)
2802 #'<)
eb650569
RS
2803 high-water-mark (apply 'max 0 versions)
2804 deserve-versions-p (or version-control
2805 (> high-water-mark 0))
2806 number-to-delete (- (length versions)
ffc0e1ca
AS
2807 kept-old-versions
2808 kept-new-versions
2809 -1))
2810 (file-error (setq possibilities nil)))
eb650569 2811 (if (not deserve-versions-p)
8767d866 2812 (list (make-backup-file-name fn))
ffc0e1ca 2813 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
eb650569
RS
2814 (if (and (> number-to-delete 0)
2815 ;; Delete nothing if there is overflow
2816 ;; in the number of versions to keep.
2817 (>= (+ kept-new-versions kept-old-versions -1) 0))
ffc0e1ca
AS
2818 (mapcar (lambda (n)
2819 (format "%s.~%d~" basic-name n))
eb650569
RS
2820 (let ((v (nthcdr kept-old-versions versions)))
2821 (rplacd (nthcdr (1- number-to-delete) v) ())
2822 v))))))))))
b4da00e9 2823
b4da00e9
RM
2824(defun file-nlinks (filename)
2825 "Return number of names file FILENAME has."
2826 (car (cdr (file-attributes filename))))
6c636af9 2827
753ad988
KG
2828;; (defun file-relative-name (filename &optional directory)
2829;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
2830;; This function returns a relative file name which is equivalent to FILENAME
2831;; when used with that default directory as the default.
2832;; If this is impossible (which can happen on MSDOS and Windows
2833;; when the file name and directory use different drive names)
2834;; then it returns FILENAME."
2835;; (save-match-data
2836;; (let ((fname (expand-file-name filename)))
2837;; (setq directory (file-name-as-directory
2838;; (expand-file-name (or directory default-directory))))
2839;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2840;; ;; drive names, they can't be relative, so return the absolute name.
2841;; (if (and (or (eq system-type 'ms-dos)
2842;; (eq system-type 'cygwin)
2843;; (eq system-type 'windows-nt))
2844;; (not (string-equal (substring fname 0 2)
2845;; (substring directory 0 2))))
2846;; filename
2847;; (let ((ancestor ".")
2848;; (fname-dir (file-name-as-directory fname)))
2849;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
2850;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
2851;; (setq directory (file-name-directory (substring directory 0 -1))
2852;; ancestor (if (equal ancestor ".")
2853;; ".."
2854;; (concat "../" ancestor))))
2855;; ;; Now ancestor is empty, or .., or ../.., etc.
2856;; (if (string-match (concat "^" (regexp-quote directory)) fname)
2857;; ;; We matched within FNAME's directory part.
2858;; ;; Add the rest of FNAME onto ANCESTOR.
2859;; (let ((rest (substring fname (match-end 0))))
2860;; (if (and (equal ancestor ".")
2861;; (not (equal rest "")))
2862;; ;; But don't bother with ANCESTOR if it would give us `./'.
2863;; rest
2864;; (concat (file-name-as-directory ancestor) rest)))
2865;; ;; We matched FNAME's directory equivalent.
2866;; ancestor))))))
2867
6c636af9 2868(defun file-relative-name (filename &optional directory)
ffc0e1ca 2869 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
2d6562a5
RS
2870This function returns a relative file name which is equivalent to FILENAME
2871when used with that default directory as the default.
753ad988 2872If FILENAME and DIRECTORY lie on different machines or on different drives
493c98af 2873on a DOS/Windows machine, it returns FILENAME on expanded form."
96c188b0 2874 (save-match-data
753ad988
KG
2875 (setq directory
2876 (file-name-as-directory (expand-file-name (or directory
2877 default-directory))))
2878 (setq filename (expand-file-name filename))
2879 (let ((hf (find-file-name-handler filename 'file-local-copy))
2880 (hd (find-file-name-handler directory 'file-local-copy)))
2881 (when (and hf (not (get hf 'file-remote-p))) (setq hf nil))
2882 (when (and hd (not (get hd 'file-remote-p))) (setq hd nil))
493c98af
KG
2883 (if ;; Conditions for separate trees
2884 (or
2885 ;; Test for different drives on DOS/Windows
2886 (and
2887 (memq system-type '(ms-dos cygwin windows-nt))
2888 (not (string-equal (substring filename 0 2)
2889 (substring directory 0 2))))
2890 ;; Test for different remote file handlers
2891 (not (eq hf hd))
2892 ;; Test for different remote file system identification
2893 (and
2894 hf
2895 (let ((re (car (rassq hf file-name-handler-alist))))
2896 (not
2897 (equal
2898 (and
2899 (string-match re filename)
2900 (substring filename 0 (match-end 0)))
2901 (and
2902 (string-match re directory)
2903 (substring directory 0 (match-end 0))))))))
e2b30772 2904 filename
753ad988
KG
2905 (unless (eq (aref filename 0) ?/)
2906 (setq filename (concat "/" filename)))
2907 (unless (eq (aref directory 0) ?/)
2908 (setq directory (concat "/" directory)))
2909 (let ((ancestor ".")
2910 (filename-dir (file-name-as-directory filename)))
2911 (while
2912 (and
2913 (not (string-match (concat "^" (regexp-quote directory))
2914 filename-dir))
2915 (not (string-match (concat "^" (regexp-quote directory))
2916 filename)))
2917 (setq directory (file-name-directory (substring directory 0 -1))
9695aac6
RS
2918 ancestor (if (equal ancestor ".")
2919 ".."
2920 (concat "../" ancestor))))
753ad988
KG
2921 ;; Now ancestor is empty, or .., or ../.., etc.
2922 (if (string-match (concat "^" (regexp-quote directory)) filename)
2923 ;; We matched within FILENAME's directory part.
2924 ;; Add the rest of FILENAME onto ANCESTOR.
2925 (let ((rest (substring filename (match-end 0))))
2926 (if (and (equal ancestor ".") (not (equal rest "")))
9695aac6
RS
2927 ;; But don't bother with ANCESTOR if it would give us `./'.
2928 rest
2929 (concat (file-name-as-directory ancestor) rest)))
753ad988
KG
2930 ;; We matched FILENAME's directory equivalent.
2931 ancestor))))))
b4da00e9
RM
2932\f
2933(defun save-buffer (&optional args)
2934 "Save current buffer in visited file if modified. Versions described below.
2935By default, makes the previous version into a backup file
2936 if previously requested or if this is the first save.
ac9650be 2937With 1 \\[universal-argument], marks this version
b4da00e9 2938 to become a backup when the next save is done.
ac9650be 2939With 2 \\[universal-argument]'s,
b4da00e9 2940 unconditionally makes the previous version into a backup file.
ac9650be
RS
2941With 3 \\[universal-argument]'s, marks this version
2942 to become a backup when the next save is done,
2943 and unconditionally makes the previous version into a backup file.
2944
749d2ee6 2945With argument of 0, never make the previous version into a backup file.
b4da00e9
RM
2946
2947If a file's name is FOO, the names of its numbered backup versions are
2948 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2949Numeric backups (rather than FOO~) will be made if value of
2950 `version-control' is not the atom `never' and either there are already
2951 numeric versions of the file being backed up, or `version-control' is
2952 non-nil.
2953We don't want excessive versions piling up, so there are variables
2954 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2955 and `kept-new-versions', which tells how many newest versions to keep.
2956 Defaults are 2 old versions and 2 new.
2957`dired-kept-versions' controls dired's clean-directory (.) command.
de7d5e1b 2958If `delete-old-versions' is nil, system will query user
e73ec04b
RS
2959 before trimming versions. Otherwise it does it silently.
2960
749d2ee6
RS
2961If `vc-make-backup-files' is nil, which is the default,
2962 no backup files are made for files managed by version control.
2963 (This is because the version control system itself records previous versions.)
2964
e73ec04b 2965See the subroutine `basic-save-buffer' for more information."
b4da00e9
RM
2966 (interactive "p")
2967 (let ((modp (buffer-modified-p))
2968 (large (> (buffer-size) 50000))
b5a8e0fc
RS
2969 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2970 (memq args '(16 64)))))
b4da00e9 2971 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
b4990dde
GM
2972 (if (and modp large (buffer-file-name))
2973 (message "Saving file %s..." (buffer-file-name)))
b4da00e9
RM
2974 (basic-save-buffer)
2975 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2976
2977(defun delete-auto-save-file-if-necessary (&optional force)
2978 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2979Normally delete only if the file was written by this Emacs since
2980the last real save, but optional arg FORCE non-nil means delete anyway."
2981 (and buffer-auto-save-file-name delete-auto-save-files
2982 (not (string= buffer-file-name buffer-auto-save-file-name))
2983 (or force (recent-auto-save-p))
2984 (progn
2985 (condition-case ()
2986 (delete-file buffer-auto-save-file-name)
2987 (file-error nil))
2988 (set-buffer-auto-saved))))
2989
481f215b
KH
2990(defvar auto-save-hook nil
2991 "Normal hook run just before auto-saving.")
2992
ffc0e1ca
AS
2993(defcustom after-save-hook nil
2994 "Normal hook that is run after a buffer is saved to its file."
2995 :options '(executable-make-buffer-file-executable-if-script-p)
2996 :type 'hook
2997 :group 'files)
1cc852cc 2998
0516edee
RS
2999(defvar save-buffer-coding-system nil
3000 "If non-nil, use this coding system for saving the buffer.
3001More precisely, use this coding system in place of the
3002value of `buffer-file-coding-system', when saving the buffer.
3003Calling `write-region' for any purpose other than saving the buffer
3004will still use `buffer-file-coding-system'; this variable has no effect
3005in such cases.")
3006
d5fe94cc
RS
3007(make-variable-buffer-local 'save-buffer-coding-system)
3008(put 'save-buffer-coding-system 'permanent-local t)
3009
b4da00e9 3010(defun basic-save-buffer ()
1cc852cc 3011 "Save the current buffer in its visited file, if it has been modified.
0370fe77
SM
3012The hooks `write-contents-functions' and `write-file-functions' get a chance
3013to do the job of saving; if they do not, then the buffer is saved in
3014the visited file file in the usual way.
e73ec04b 3015After saving the buffer, this function runs `after-save-hook'."
b4da00e9 3016 (interactive)
19618231 3017 (save-current-buffer
c11a94fe
RS
3018 ;; In an indirect buffer, save its base buffer instead.
3019 (if (buffer-base-buffer)
3020 (set-buffer (buffer-base-buffer)))
3021 (if (buffer-modified-p)
3022 (let ((recent-save (recent-auto-save-p))
818286f4 3023 setmodes)
c11a94fe
RS
3024 ;; On VMS, rename file and buffer to get rid of version number.
3025 (if (and (eq system-type 'vax-vms)
3026 (not (string= buffer-file-name
3027 (file-name-sans-versions buffer-file-name))))
3028 (let (buffer-new-name)
3029 ;; Strip VMS version number before save.
3030 (setq buffer-file-name
3031 (file-name-sans-versions buffer-file-name))
3032 ;; Construct a (unique) buffer name to correspond.
3033 (let ((buf (create-file-buffer (downcase buffer-file-name))))
3034 (setq buffer-new-name (buffer-name buf))
3035 (kill-buffer buf))
3036 (rename-buffer buffer-new-name)))
3037 ;; If buffer has no file name, ask user for one.
3038 (or buffer-file-name
182891ef
RS
3039 (let ((filename
3040 (expand-file-name
3041 (read-file-name "File to save in: ") nil)))
3042 (and (file-exists-p filename)
3043 (or (y-or-n-p (format "File `%s' exists; overwrite? "
3044 filename))
3045 (error "Canceled")))
3046 (set-visited-file-name filename)))
c11a94fe
RS
3047 (or (verify-visited-file-modtime (current-buffer))
3048 (not (file-exists-p buffer-file-name))
3049 (yes-or-no-p
3050 (format "%s has changed since visited or saved. Save anyway? "
3051 (file-name-nondirectory buffer-file-name)))
3052 (error "Save not confirmed"))
3053 (save-restriction
3054 (widen)
19618231 3055 (save-excursion
0370fe77 3056 (and (> (point-max) (point-min))
407b4328 3057 (not find-file-literally)
19618231
RS
3058 (/= (char-after (1- (point-max))) ?\n)
3059 (not (and (eq selective-display t)
3060 (= (char-after (1- (point-max))) ?\r)))
3061 (or (eq require-final-newline t)
3062 (and require-final-newline
3063 (y-or-n-p
3064 (format "Buffer %s does not end in newline. Add one? "
3065 (buffer-name)))))
3066 (save-excursion
3067 (goto-char (point-max))
3068 (insert ?\n))))
fa5867f6
AS
3069 ;; Support VC version backups.
3070 (vc-before-save)
0370fe77 3071 (or (run-hook-with-args-until-success 'write-contents-functions)
c11a94fe 3072 (run-hook-with-args-until-success 'local-write-file-hooks)
0370fe77 3073 (run-hook-with-args-until-success 'write-file-functions)
0ba5894b
RS
3074 ;; If a hook returned t, file is already "written".
3075 ;; Otherwise, write it the usual way now.
3076 (setq setmodes (basic-save-buffer-1)))
d6e8ea6f
KH
3077 ;; Now we have saved the current buffer. Let's make sure
3078 ;; that buffer-file-coding-system is fixed to what
3079 ;; actually used for saving by binding it locally.
0516edee
RS
3080 (if save-buffer-coding-system
3081 (setq save-buffer-coding-system last-coding-system-used)
3082 (setq buffer-file-coding-system last-coding-system-used))
2a47b4f5
RS
3083 (setq buffer-file-number
3084 (nthcdr 10 (file-attributes buffer-file-name)))
c11a94fe
RS
3085 (if setmodes
3086 (condition-case ()
f3f9e207 3087 (set-file-modes buffer-file-name (car setmodes))
c11a94fe
RS
3088 (error nil))))
3089 ;; If the auto-save file was recent before this command,
3090 ;; delete it now.
3091 (delete-auto-save-file-if-necessary recent-save)
49530862
RS
3092 ;; Support VC `implicit' locking.
3093 (vc-after-save)
c11a94fe
RS
3094 (run-hooks 'after-save-hook))
3095 (message "(No changes need to be saved)"))))
b4da00e9 3096
87d26afc
RS
3097;; This does the "real job" of writing a buffer into its visited file
3098;; and making a backup file. This is what is normally done
0370fe77 3099;; but inhibited if one of write-file-functions returns non-nil.
f3f9e207 3100;; It returns a value (MODES . BACKUPNAME), like backup-buffer.
87d26afc 3101(defun basic-save-buffer-1 ()
d5fe94cc
RS
3102 (if save-buffer-coding-system
3103 (let ((coding-system-for-write save-buffer-coding-system))
3104 (basic-save-buffer-2))
3105 (basic-save-buffer-2)))
3106
f3f9e207 3107;; This returns a value (MODES . BACKUPNAME), like backup-buffer.
d5fe94cc
RS
3108(defun basic-save-buffer-2 ()
3109 (let (tempsetmodes setmodes)
87d26afc
RS
3110 (if (not (file-writable-p buffer-file-name))
3111 (let ((dir (file-name-directory buffer-file-name)))
3112 (if (not (file-directory-p dir))
83c6f446
RS
3113 (if (file-exists-p dir)
3114 (error "%s is not a directory" dir)
cb2fdcfa 3115 (error "%s: no such directory" buffer-file-name))
87d26afc
RS
3116 (if (not (file-exists-p buffer-file-name))
3117 (error "Directory %s write-protected" dir)
3118 (if (yes-or-no-p
3119 (format "File %s is write-protected; try to save anyway? "
3120 (file-name-nondirectory
3121 buffer-file-name)))
3122 (setq tempsetmodes t)
3123 (error "Attempt to save to a file which you aren't allowed to write"))))))
3124 (or buffer-backed-up
3125 (setq setmodes (backup-buffer)))
76d5492b 3126 (let ((dir (file-name-directory buffer-file-name)))
f4a0f59b
RS
3127 (if (and file-precious-flag
3128 (file-writable-p dir))
3129 ;; If file is precious, write temp name, then rename it.
3130 ;; This requires write access to the containing dir,
3131 ;; which is why we don't try it if we don't have that access.
3132 (let ((realname buffer-file-name)
818286f4 3133 tempname nogood i succeed
6782610c 3134 (old-modtime (visited-file-modtime)))
f4a0f59b
RS
3135 (setq i 0)
3136 (setq nogood t)
3137 ;; Find the temporary name to write under.
3138 (while nogood
567c1ca9 3139 (setq tempname (format
28ee503c
KH
3140 (if (and (eq system-type 'ms-dos)
3141 (not (msdos-long-file-names)))
567c1ca9 3142 "%s#%d.tm#" ; MSDOS limits files to 8+3
ffc0e1ca
AS
3143 (if (memq system-type '(vax-vms axp-vms))
3144 "%s$tmp$%d"
3145 "%s#tmp#%d"))
567c1ca9 3146 dir i))
f4a0f59b
RS
3147 (setq nogood (file-exists-p tempname))
3148 (setq i (1+ i)))
3149 (unwind-protect
3150 (progn (clear-visited-file-modtime)
3151 (write-region (point-min) (point-max)
89095962
RS
3152 tempname nil realname
3153 buffer-file-truename)
f4a0f59b
RS
3154 (setq succeed t))
3155 ;; If writing the temp file fails,
3156 ;; delete the temp file.
76d5492b 3157 (or succeed
6782610c 3158 (progn
c9783dfe
RS
3159 (condition-case nil
3160 (delete-file tempname)
3161 (file-error nil))
6782610c 3162 (set-visited-file-modtime old-modtime))))
f4a0f59b
RS
3163 ;; Since we have created an entirely new file
3164 ;; and renamed it, make sure it gets the
3165 ;; right permission bits set.
f3f9e207
RS
3166 (setq setmodes (or setmodes (cons (file-modes buffer-file-name)
3167 buffer-file-name)))
f4a0f59b
RS
3168 ;; We succeeded in writing the temp file,
3169 ;; so rename it.
3170 (rename-file tempname buffer-file-name t))
3171 ;; If file not writable, see if we can make it writable
3172 ;; temporarily while we write it.
3173 ;; But no need to do so if we have just backed it up
3174 ;; (setmodes is set) because that says we're superseding.
3175 (cond ((and tempsetmodes (not setmodes))
3176 ;; Change the mode back, after writing.
f3f9e207
RS
3177 (setq setmodes (cons (file-modes buffer-file-name) buffer-file-name))
3178 (set-file-modes buffer-file-name (logior (car setmodes) 128))))
3179 (let (success)
3180 (unwind-protect
3181 (progn
3182 (write-region (point-min) (point-max)
3183 buffer-file-name nil t buffer-file-truename)
3184 (setq success t))
3185 ;; If we get an error writing the new file, and we made
3186 ;; the backup by renaming, undo the backing-up.
3187 (and setmodes (not success)
3188 (rename-file (cdr setmodes) buffer-file-name))))))
87d26afc
RS
3189 setmodes))
3190
1eeae2a1
RS
3191(defun diff-buffer-with-file (&optional buffer)
3192 "View the differences between BUFFER and its associated file.
0b9e4749 3193This requires the external program `diff' to be in your `exec-path'."
1eeae2a1 3194 (interactive "bBuffer: ")
0b9e4749 3195 (with-current-buffer (get-buffer (or buffer (current-buffer)))
4e4e9519
MR
3196 (if (and buffer-file-name
3197 (file-exists-p buffer-file-name))
3198 (let ((tempfile (make-temp-file "buffer-content-")))
3199 (unwind-protect
3200 (save-restriction
3201 (widen)
3202 (write-region (point-min) (point-max) tempfile nil 'nomessage)
3203 (diff buffer-file-name tempfile nil t)
3204 (sit-for 0))
3205 (when (file-exists-p tempfile)
3206 (delete-file tempfile))))
3207 (message "Buffer %s has no associated file on disc" (buffer-name))
3208 ;; Display that message for 1 second so that user can read it
3209 ;; in the minibuffer.
3210 (sit-for 1)))
3211 ;; return always nil, so that save-buffers-kill-emacs will not move
3212 ;; over to the next unsaved buffer when calling `d'.
3213 nil)
1eeae2a1
RS
3214
3215(defvar save-some-buffers-action-alist
3216 '((?\C-r
3217 (lambda (buf)
3218 (view-buffer buf
3219 (lambda (ignore)
3220 (exit-recursive-edit)))
3221 (recursive-edit)
3222 ;; Return nil to ask about BUF again.
3223 nil)
3224 "display the current buffer")
3225 (?d diff-buffer-with-file
d97182ab 3226 "show difference to last saved version"))
1eeae2a1
RS
3227 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
3228(put 'save-some-buffers-action-alist 'risky-local-variable t)
3229
ffc0e1ca 3230(defun save-some-buffers (&optional arg pred)
b4da00e9 3231 "Save some modified file-visiting buffers. Asks user about each one.
1eeae2a1
RS
3232You can answer `y' to save, `n' not to save, `C-r' to look at the
3233buffer in question with `view-buffer' before deciding or `d' to
3234view the differences using `diff-buffer-to-file'.
8fd9c174 3235
5bbbceb1 3236Optional argument (the prefix) non-nil means save all with no questions.
ffc0e1ca
AS
3237Optional second argument PRED determines which buffers are considered:
3238If PRED is nil, all the file-visiting buffers are considered.
3239If PRED is t, then certain non-file buffers will also be considered.
3240If PRED is a zero-argument function, it indicates for each buffer whether
1eeae2a1
RS
3241to consider it or not when called with that buffer current.
3242
3243See `save-some-buffers-action-alist' if you want to
3244change the additional actions you can take on files."
b4da00e9 3245 (interactive "P")
907482b9 3246 (save-window-excursion
76d5492b
RM
3247 (let* ((queried nil)
3248 (files-done
3249 (map-y-or-n-p
3250 (function
3251 (lambda (buffer)
3252 (and (buffer-modified-p buffer)
3253 (not (buffer-base-buffer buffer))
3254 (or
3255 (buffer-file-name buffer)
ffc0e1ca 3256 (and pred
76d5492b
RM
3257 (progn
3258 (set-buffer buffer)
3259 (and buffer-offer-save (> (buffer-size) 0)))))
ffc0e1ca
AS
3260 (or (not (functionp pred))
3261 (with-current-buffer buffer (funcall pred)))
76d5492b
RM
3262 (if arg
3263 t
3264 (setq queried t)
3265 (if (buffer-file-name buffer)
3266 (format "Save file %s? "
3267 (buffer-file-name buffer))
3268 (format "Save buffer %s? "
3269 (buffer-name buffer)))))))
3270 (function
3271 (lambda (buffer)
3272 (set-buffer buffer)
3273 (save-buffer)))
3274 (buffer-list)
3275 '("buffer" "buffers" "save")
1eeae2a1 3276 save-some-buffers-action-alist))
76d5492b
RM
3277 (abbrevs-done
3278 (and save-abbrevs abbrevs-changed
3279 (progn
3280 (if (or arg
02c6a1cc 3281 (eq save-abbrevs 'silently)
76d5492b
RM
3282 (y-or-n-p (format "Save abbrevs in %s? "
3283 abbrev-file-name)))
3284 (write-abbrev-file nil))
3285 ;; Don't keep bothering user if he says no.
3286 (setq abbrevs-changed nil)
3287 t))))
3288 (or queried (> files-done 0) abbrevs-done
5625c2fc 3289 (message "(No files need saving)")))))
b4da00e9
RM
3290\f
3291(defun not-modified (&optional arg)
3292 "Mark current buffer as unmodified, not needing to be saved.
a641f9a1
RM
3293With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
3294
3295It is not a good idea to use this function in Lisp programs, because it
3296prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
b4da00e9
RM
3297 (interactive "P")
3298 (message (if arg "Modification-flag set"
3299 "Modification-flag cleared"))
3300 (set-buffer-modified-p arg))
3301
3302(defun toggle-read-only (&optional arg)
3303 "Change whether this buffer is visiting its file read-only.
2a9fe1e2
RS
3304With arg, set read-only iff arg is positive.
3305If visiting file read-only and `view-read-only' is non-nil, enter view mode."
b4da00e9 3306 (interactive "P")
c60ee5e7 3307 (if (and arg
d758359d
AS
3308 (if (> (prefix-numeric-value arg) 0) buffer-read-only
3309 (not buffer-read-only))) ; If buffer-read-only is set correctly,
3310 nil ; do nothing.
3311 ;; Toggle.
3312 (cond
3313 ((and buffer-read-only view-mode)
3314 (View-exit-and-edit)
3315 (make-local-variable 'view-read-only)
3316 (setq view-read-only t)) ; Must leave view mode.
3317 ((and (not buffer-read-only) view-read-only
818286f4
SM
3318 ;; If view-mode is already active, `view-mode-enter' is a nop.
3319 (not view-mode)
d758359d
AS
3320 (not (eq (get major-mode 'mode-class) 'special)))
3321 (view-mode-enter))
3322 (t (setq buffer-read-only (not buffer-read-only))
3323 (force-mode-line-update)))
3324 (if (vc-backend buffer-file-name)
3325 (message (substitute-command-keys
a5dd5f60
RS
3326 (concat "File is under version-control; "
3327 "use \\[vc-next-action] to check in/out"))))))
b4da00e9 3328
912192d1 3329(defun insert-file (filename)
b4da00e9
RM
3330 "Insert contents of file FILENAME into buffer after point.
3331Set mark after the inserted text.
3332
3333This function is meant for the user to run interactively.
3334Don't call it from programs! Use `insert-file-contents' instead.
3335\(Its calling sequence is different; see its documentation)."
912192d1 3336 (interactive "*fInsert file: ")
3a64a3cf 3337 (insert-file-1 filename #'insert-file-contents))
b4da00e9 3338
912192d1 3339(defun append-to-file (start end filename)
b4da00e9
RM
3340 "Append the contents of the region to the end of file FILENAME.
3341When called from a function, expects three arguments,
3342START, END and FILENAME. START and END are buffer positions
da30bf98 3343saying what text to write."
912192d1
KH
3344 (interactive "r\nFAppend to file: ")
3345 (write-region start end filename t))
b4da00e9
RM
3346
3347(defun file-newest-backup (filename)
3348 "Return most recent backup file for FILENAME or nil if no backups exist."
ffc0e1ca
AS
3349 ;; `make-backup-file-name' will get us the right directory for
3350 ;; ordinary or numeric backups. It might create a directory for
3351 ;; backups as a side-effect, according to `backup-directory-alist'.
e31cfca5
MR
3352 (let* ((filename (file-name-sans-versions
3353 (make-backup-file-name filename)))
b4da00e9
RM
3354 (file (file-name-nondirectory filename))
3355 (dir (file-name-directory filename))
3356 (comp (file-name-all-completions file dir))
cf7e94a0
RS
3357 (newest nil)
3358 tem)
b4da00e9 3359 (while comp
ffc0e1ca 3360 (setq tem (pop comp))
cf7e94a0
RS
3361 (cond ((and (backup-file-name-p tem)
3362 (string= (file-name-sans-versions tem) file))
3363 (setq tem (concat dir tem))
3364 (if (or (null newest)
3365 (file-newer-than-file-p tem newest))
3366 (setq newest tem)))))
b4da00e9
RM
3367 newest))
3368
3369(defun rename-uniquely ()
3370 "Rename current buffer to a similar name not already taken.
3371This function is useful for creating multiple shell process buffers
3372or multiple mail buffers, etc."
3373 (interactive)
40eb8038 3374 (save-match-data
e0df3aef
KH
3375 (let ((base-name (buffer-name)))
3376 (and (string-match "<[0-9]+>\\'" base-name)
3377 (not (and buffer-file-name
3378 (string= base-name
3379 (file-name-nondirectory buffer-file-name))))
3380 ;; If the existing buffer name has a <NNN>,
3381 ;; which isn't part of the file name (if any),
3382 ;; then get rid of that.
3383 (setq base-name (substring base-name 0 (match-beginning 0))))
3384 (rename-buffer (generate-new-buffer-name base-name))
3941fe2c 3385 (force-mode-line-update))))
5bbbceb1 3386
4e43240a 3387(defun make-directory (dir &optional parents)
5ce8bb89
RS
3388 "Create the directory DIR and any nonexistent parent dirs.
3389Interactively, the default choice of directory to create
3390is the current default directory for file names.
0225ae5e 3391That is useful when you have visited a file in a nonexistent directory.
5ce8bb89
RS
3392
3393Noninteractively, the second (optional) argument PARENTS says whether
3394to create parent directories if they don't exist."
3395 (interactive
3396 (list (read-file-name "Make directory: " default-directory default-directory
3397 nil nil)
3398 t))
ee291b46
RS
3399 ;; If default-directory is a remote directory,
3400 ;; make sure we find its make-directory handler.
3401 (setq dir (expand-file-name dir))
6eaebaa2 3402 (let ((handler (find-file-name-handler dir 'make-directory)))
4e43240a
RS
3403 (if handler
3404 (funcall handler 'make-directory dir parents)
3405 (if (not parents)
3406 (make-directory-internal dir)
3407 (let ((dir (directory-file-name (expand-file-name dir)))
3408 create-list)
3409 (while (not (file-exists-p dir))
76d5492b 3410 (setq create-list (cons dir create-list)
4e43240a
RS
3411 dir (directory-file-name (file-name-directory dir))))
3412 (while create-list
3413 (make-directory-internal (car create-list))
3414 (setq create-list (cdr create-list))))))))
b4da00e9
RM
3415\f
3416(put 'revert-buffer-function 'permanent-local t)
3417(defvar revert-buffer-function nil
0973d78b
RS
3418 "Function to use to revert this buffer, or nil to do the default.
3419The function receives two arguments IGNORE-AUTO and NOCONFIRM,
3420which are the arguments that `revert-buffer' received.")
b4da00e9
RM
3421
3422(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
3423(defvar revert-buffer-insert-file-contents-function nil
3424 "Function to use to insert contents when reverting this buffer.
3425Gets two args, first the nominal file name to use,
2df32500
RS
3426and second, t if reading the auto-save file.
3427
3428The function you specify is responsible for updating (or preserving) point.")
b4da00e9 3429
5f76e7d4
KH
3430(defvar before-revert-hook nil
3431 "Normal hook for `revert-buffer' to run before reverting.
3432If `revert-buffer-function' is used to override the normal revert
3433mechanism, this hook is not used.")
3434
3435(defvar after-revert-hook nil
3436 "Normal hook for `revert-buffer' to run after reverting.
3437Note that the hook value that it runs is the value that was in effect
3438before reverting; that makes a difference if you have buffer-local
3439hook functions.
3440
3441If `revert-buffer-function' is used to override the normal revert
3442mechanism, this hook is not used.")
3443
1554c03b
RS
3444(defvar revert-buffer-internal-hook)
3445
9a30563f 3446(defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
7e7c9c4e 3447 "Replace current buffer text with the text of the visited file on disk.
b4da00e9 3448This undoes all changes since the file was visited or saved.
8c0e7b73
JB
3449With a prefix argument, offer to revert from latest auto-save file, if
3450that is more recent than the visited file.
1ab31687 3451
7e7c9c4e
RS
3452This command also works for special buffers that contain text which
3453doesn't come from a file, but reflects some other data base instead:
4e163715 3454for example, Dired buffers and `buffer-list' buffers. In these cases,
7e7c9c4e
RS
3455it reconstructs the buffer contents from the appropriate data base.
3456
65ee6096 3457When called from Lisp, the first argument is IGNORE-AUTO; only offer
1ab31687
JB
3458to revert from the auto-save file when this is nil. Note that the
3459sense of this argument is the reverse of the prefix argument, for the
3460sake of backward compatibility. IGNORE-AUTO is optional, defaulting
3461to nil.
3462
3463Optional second argument NOCONFIRM means don't ask for confirmation at
ffc0e1ca 3464all. (The local variable `revert-without-query', if non-nil, prevents
d1f04130 3465confirmation.)
b4da00e9 3466
5b2b26d5
RS
3467Optional third argument PRESERVE-MODES non-nil means don't alter
3468the files modes. Normally we reinitialize them using `normal-mode'.
3469
8c0e7b73 3470If the value of `revert-buffer-function' is non-nil, it is called to
7e7c9c4e
RS
3471do all the work for this command. Otherwise, the hooks
3472`before-revert-hook' and `after-revert-hook' are run at the beginning
3473and the end, and if `revert-buffer-insert-file-contents-function' is
3474non-nil, it is called instead of rereading visited file contents."
fb6208a6 3475
1ab31687
JB
3476 ;; I admit it's odd to reverse the sense of the prefix argument, but
3477 ;; there is a lot of code out there which assumes that the first
3478 ;; argument should be t to avoid consulting the auto-save file, and
3479 ;; there's no straightforward way to encourage authors to notice a
3480 ;; reversal of the argument sense. So I'm just changing the user
3481 ;; interface, but leaving the programmatic interface the same.
e0867e99 3482 (interactive (list (not current-prefix-arg)))
b4da00e9 3483 (if revert-buffer-function
1ab31687 3484 (funcall revert-buffer-function ignore-auto noconfirm)
2df32500 3485 (let* ((auto-save-p (and (not ignore-auto)
1ab31687 3486 (recent-auto-save-p)
b4da00e9
RM
3487 buffer-auto-save-file-name
3488 (file-readable-p buffer-auto-save-file-name)
3489 (y-or-n-p
3490 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
3491 (file-name (if auto-save-p
3492 buffer-auto-save-file-name
3493 buffer-file-name)))
3494 (cond ((null file-name)
3495 (error "Buffer does not seem to be associated with any file"))
3496 ((or noconfirm
db8c4866
RS
3497 (and (not (buffer-modified-p))
3498 (let ((tail revert-without-query)
3499 (found nil))
3500 (while tail
3501 (if (string-match (car tail) file-name)
3502 (setq found t))
3503 (setq tail (cdr tail)))
3504 found))
b4da00e9
RM
3505 (yes-or-no-p (format "Revert buffer from file %s? "
3506 file-name)))
4fbf62ee 3507 (run-hooks 'before-revert-hook)
b4da00e9
RM
3508 ;; If file was backed up but has changed since,
3509 ;; we shd make another backup.
3510 (and (not auto-save-p)
5bbbceb1 3511 (not (verify-visited-file-modtime (current-buffer)))
b4da00e9
RM
3512 (setq buffer-backed-up nil))
3513 ;; Get rid of all undo records for this buffer.
3514 (or (eq buffer-undo-list t)
3515 (setq buffer-undo-list nil))
ba5c8c93
KH
3516 ;; Effectively copy the after-revert-hook status,
3517 ;; since after-find-file will clobber it.
3518 (let ((global-hook (default-value 'after-revert-hook))
3519 (local-hook-p (local-variable-p 'after-revert-hook))
3520 (local-hook (and (local-variable-p 'after-revert-hook)
3521 after-revert-hook)))
3522 (let (buffer-read-only
3523 ;; Don't make undo records for the reversion.
3524 (buffer-undo-list t))
3525 (if revert-buffer-insert-file-contents-function
3526 (funcall revert-buffer-insert-file-contents-function
3527 file-name auto-save-p)
3528 (if (not (file-exists-p file-name))
e3bfcda9
RS
3529 (error (if buffer-file-number
3530 "File %s no longer exists!"
3531 "Cannot revert nonexistent file %s")
3532 file-name))
ba5c8c93
KH
3533 ;; Bind buffer-file-name to nil
3534 ;; so that we don't try to lock the file.
3535 (let ((buffer-file-name nil))
3536 (or auto-save-p
3537 (unlock-buffer)))
3538 (widen)
b77d8211
KH
3539 (let ((coding-system-for-read
3540 ;; Auto-saved file shoule be read without
3541 ;; any code conversion.
68875f0e 3542 (if auto-save-p 'emacs-mule-unix
01afb4f3
KH
3543 (or coding-system-for-read
3544 buffer-file-coding-system))))
1eb0bebc
KH
3545 ;; This force
3546 ;; after-insert-file-set-buffer-file-coding-system
3547 ;; (called from insert-file-contents) to set
3548 ;; buffer-file-coding-system to a proper value.
3549 (kill-local-variable 'buffer-file-coding-system)
3550
2df32500 3551 ;; Note that this preserves point in an intelligent way.
f402ba38 3552 (if preserve-modes
0415fedc 3553 (let ((buffer-file-format buffer-file-format))
f402ba38
RS
3554 (insert-file-contents file-name (not auto-save-p)
3555 nil nil t))
3556 (insert-file-contents file-name (not auto-save-p)
3557 nil nil t)))))
ba5c8c93
KH
3558 ;; Recompute the truename in case changes in symlinks
3559 ;; have changed the truename.
3560 (setq buffer-file-truename
3561 (abbreviate-file-name (file-truename buffer-file-name)))
9a30563f 3562 (after-find-file nil nil t t preserve-modes)
ba5c8c93
KH
3563 ;; Run after-revert-hook as it was before we reverted.
3564 (setq-default revert-buffer-internal-hook global-hook)
3565 (if local-hook-p
4e163715
SM
3566 (set (make-local-variable 'revert-buffer-internal-hook)
3567 local-hook)
ba5c8c93
KH
3568 (kill-local-variable 'revert-buffer-internal-hook))
3569 (run-hooks 'revert-buffer-internal-hook))
4fbf62ee 3570 t)))))
b4da00e9 3571
64d18e8f
RS
3572(defun recover-this-file ()
3573 "Recover the visited file--get contents from its last auto-save file."
3574 (interactive)
3575 (recover-file buffer-file-name))
3576
b4da00e9
RM
3577(defun recover-file (file)
3578 "Visit file FILE, but get contents from its last auto-save file."
10f7c7fc
RS
3579 ;; Actually putting the file name in the minibuffer should be used
3580 ;; only rarely.
3581 ;; Not just because users often use the default.
e1dadc17 3582 (interactive "FRecover file: ")
b4da00e9 3583 (setq file (expand-file-name file))
f7da6740 3584 (if (auto-save-file-name-p (file-name-nondirectory file))
4e163715 3585 (error "%s is an auto-save file" (abbreviate-file-name file)))
b4da00e9
RM
3586 (let ((file-name (let ((buffer-file-name file))
3587 (make-auto-save-file-name))))
945e1965
RS
3588 (cond ((if (file-exists-p file)
3589 (not (file-newer-than-file-p file-name file))
3590 (not (file-exists-p file-name)))
4e163715
SM
3591 (error "Auto-save file %s not current"
3592 (abbreviate-file-name file-name)))
b4da00e9 3593 ((save-window-excursion
ffc0e1ca
AS
3594 (with-output-to-temp-buffer "*Directory*"
3595 (buffer-disable-undo standard-output)
3596 (save-excursion
3597 (let ((switches dired-listing-switches))
3598 (if (file-symlink-p file)
3599 (setq switches (concat switches "L")))
3600 (set-buffer standard-output)
bc22fd18
EZ
3601 ;; Use insert-directory-safely, not insert-directory,
3602 ;; because these files might not exist. In particular,
3603 ;; FILE might not exist if the auto-save file was for
3604 ;; a buffer that didn't visit a file, such as "*mail*".
3605 ;; The code in v20.x called `ls' directly, so we need
3606 ;; to emulate what `ls' did in that case.
3607 (insert-directory-safely file switches)
3608 (insert-directory-safely file-name switches))))
b4da00e9
RM
3609 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3610 (switch-to-buffer (find-file-noselect file t))
82d0954a 3611 (let ((buffer-read-only nil)
1e87edf5
KH
3612 ;; Keep the current buffer-file-coding-system.
3613 (coding-system buffer-file-coding-system)
82d0954a 3614 ;; Auto-saved file shoule be read without any code conversion.
68875f0e 3615 (coding-system-for-read 'emacs-mule-unix))
b4da00e9 3616 (erase-buffer)
1e87edf5
KH
3617 (insert-file-contents file-name nil)
3618 (set-buffer-file-coding-system coding-system))
8cfb9d46 3619 (after-find-file nil nil t))
ffa7ab70 3620 (t (error "Recover-file cancelled")))))
b4da00e9 3621
6598027d 3622(defun recover-session ()
9aee5392
RS
3623 "Recover auto save files from a previous Emacs session.
3624This command first displays a Dired buffer showing you the
3625previous sessions that you could recover from.
3626To choose one, move point to the proper line and then type C-c C-c.
3627Then you'll be asked about a number of files to recover."
3628 (interactive)
363a5030
RS
3629 (if (null auto-save-list-file-prefix)
3630 (error "You set `auto-save-list-file-prefix' to disable making session files"))
ffc0e1ca
AS
3631 (let ((dir (file-name-directory auto-save-list-file-prefix)))
3632 (unless (file-directory-p dir)
194600a8
JPW
3633 (make-directory dir t))
3634 (unless (directory-files dir nil
3635 (concat "\\`" (regexp-quote
3636 (file-name-nondirectory
3637 auto-save-list-file-prefix)))
3638 t)
3639 (error "No previous sessions to recover")))
6f4983e6 3640 (let ((ls-lisp-support-shell-wildcards t))
7b3478a5
RS
3641 (dired (concat auto-save-list-file-prefix "*")
3642 (concat dired-listing-switches "t")))
05e076c7
AS
3643 (save-excursion
3644 (goto-char (point-min))
3645 (or (looking-at " Move to the session you want to recover,")
3646 (let ((inhibit-read-only t))
3647 ;; Each line starts with a space
3648 ;; so that Font Lock mode won't highlight the first character.
3649 (insert " Move to the session you want to recover,\n"
3650 " then type C-c C-c to select it.\n\n"
3651 " You can also delete some of these files;\n"
3652 " type d on a line to mark that file for deletion.\n\n"))))
9aee5392 3653 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
80280bb7 3654 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
9aee5392 3655
80280bb7 3656(defun recover-session-finish ()
9aee5392
RS
3657 "Choose one saved session to recover auto-save files from.
3658This command is used in the special Dired buffer created by
80280bb7 3659\\[recover-session]."
9aee5392
RS
3660 (interactive)
3661 ;; Get the name of the session file to recover from.
3662 (let ((file (dired-get-filename))
953a03b2 3663 files
9aee5392 3664 (buffer (get-buffer-create " *recover*")))
c11032b9 3665 (dired-unmark 1)
033ef863 3666 (dired-do-flagged-delete t)
9aee5392
RS
3667 (unwind-protect
3668 (save-excursion
3669 ;; Read in the auto-save-list file.
3670 (set-buffer buffer)
3671 (erase-buffer)
3672 (insert-file-contents file)
953a03b2
RS
3673 ;; Loop thru the text of that file
3674 ;; and get out the names of the files to recover.
3675 (while (not (eobp))
3676 (let (thisfile autofile)
3677 (if (eolp)
3678 ;; This is a pair of lines for a non-file-visiting buffer.
3679 ;; Get the auto-save file name and manufacture
3680 ;; a "visited file name" from that.
3681 (progn
3682 (forward-line 1)
3683 (setq autofile
3684 (buffer-substring-no-properties
3685 (point)
3686 (save-excursion
3687 (end-of-line)
3688 (point))))
3689 (setq thisfile
3690 (expand-file-name
3691 (substring
3692 (file-name-nondirectory autofile)
3693 1 -1)
3694 (file-name-directory autofile)))
3695 (forward-line 1))
3696 ;; This pair of lines is a file-visiting
3697 ;; buffer. Use the visited file name.
3698 (progn
3699 (setq thisfile
3700 (buffer-substring-no-properties
3701 (point) (progn (end-of-line) (point))))
3702 (forward-line 1)
3703 (setq autofile
3704 (buffer-substring-no-properties
3705 (point) (progn (end-of-line) (point))))
3706 (forward-line 1)))
3707 ;; Ignore a file if its auto-save file does not exist now.
3708 (if (file-exists-p autofile)
3709 (setq files (cons thisfile files)))))
3710 (setq files (nreverse files))
945e1965
RS
3711 ;; The file contains a pair of line for each auto-saved buffer.
3712 ;; The first line of the pair contains the visited file name
3713 ;; or is empty if the buffer was not visiting a file.
3714 ;; The second line is the auto-save file name.
953a03b2
RS
3715 (if files
3716 (map-y-or-n-p "Recover %s? "
3717 (lambda (file)
3718 (condition-case nil
3719 (save-excursion (recover-file file))
76d5492b 3720 (error
953a03b2
RS
3721 "Failed to recover `%s'" file)))
3722 files
3723 '("file" "files" "recover"))
3724 (message "No files can be recovered from this session now")))
9aee5392
RS
3725 (kill-buffer buffer))))
3726
73ba610a
RS
3727(defun kill-some-buffers (&optional list)
3728 "For each buffer in LIST, ask whether to kill it.
3729LIST defaults to all existing live buffers."
b4da00e9 3730 (interactive)
73ba610a
RS
3731 (if (null list)
3732 (setq list (buffer-list)))
3733 (while list
3734 (let* ((buffer (car list))
3735 (name (buffer-name buffer)))
3736 (and (not (string-equal name ""))
3737 (/= (aref name 0) ? )
3738 (yes-or-no-p
3739 (format "Buffer %s %s. Kill? "
3740 name
3741 (if (buffer-modified-p buffer)
3742 "HAS BEEN EDITED" "is unmodified")))
3743 (kill-buffer buffer)))
3744 (setq list (cdr list))))
b4da00e9
RM
3745\f
3746(defun auto-save-mode (arg)
3747 "Toggle auto-saving of contents of current buffer.
f3e23606 3748With prefix argument ARG, turn auto-saving on if positive, else off."
b4da00e9
RM
3749 (interactive "P")
3750 (setq buffer-auto-save-file-name
3751 (and (if (null arg)
74b9c2af 3752 (or (not buffer-auto-save-file-name)
4e0c8650 3753 ;; If auto-save is off because buffer has shrunk,
74b9c2af
RS
3754 ;; then toggling should turn it on.
3755 (< buffer-saved-size 0))
b4da00e9
RM
3756 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
3757 (if (and buffer-file-name auto-save-visited-file-name
3758 (not buffer-read-only))
3759 buffer-file-name
3760 (make-auto-save-file-name))))
0b7f1ef2
RS
3761 ;; If -1 was stored here, to temporarily turn off saving,
3762 ;; turn it back on.
3763 (and (< buffer-saved-size 0)
3764 (setq buffer-saved-size 0))
b4da00e9
RM
3765 (if (interactive-p)
3766 (message "Auto-save %s (in this buffer)"
3767 (if buffer-auto-save-file-name "on" "off")))
3768 buffer-auto-save-file-name)
3769
3770(defun rename-auto-save-file ()
3771 "Adjust current buffer's auto save file name for current conditions.
3772Also rename any existing auto save file, if it was made in this session."
3773 (let ((osave buffer-auto-save-file-name))
3774 (setq buffer-auto-save-file-name
3775 (make-auto-save-file-name))
3776 (if (and osave buffer-auto-save-file-name
3777 (not (string= buffer-auto-save-file-name buffer-file-name))
3778 (not (string= buffer-auto-save-file-name osave))
3779 (file-exists-p osave)
3780 (recent-auto-save-p))
3781 (rename-file osave buffer-auto-save-file-name t))))
3782
3783(defun make-auto-save-file-name ()
3784 "Return file name to use for auto-saves of current buffer.
3785Does not consider `auto-save-visited-file-name' as that variable is checked
3786before calling this function. You can redefine this for customization.
3787See also `auto-save-file-name-p'."
3788 (if buffer-file-name
ffc0e1ca
AS
3789 (let ((list auto-save-file-name-transforms)
3790 (filename buffer-file-name)
a0b60c33 3791 result uniq)
ffc0e1ca
AS
3792 ;; Apply user-specified translations
3793 ;; to the file name.
3794 (while (and list (not result))
3795 (if (string-match (car (car list)) filename)
3796 (setq result (replace-match (cadr (car list)) t nil
a0b60c33 3797 filename)
38eea7c7 3798 uniq (car (cddr (car list)))))
ffc0e1ca 3799 (setq list (cdr list)))
a0b60c33 3800 (if result
3c4a7cf3
RS
3801 (if uniq
3802 (setq filename (concat
3803 (file-name-directory result)
3804 (subst-char-in-string
d7b6ca4a 3805 ?/ ?!
3c4a7cf3
RS
3806 (replace-regexp-in-string "!" "!!"
3807 filename))))
3808 (setq filename result)))
1e57a696
EZ
3809 (setq result
3810 (if (and (eq system-type 'ms-dos)
3811 (not (msdos-long-file-names)))
3812 ;; We truncate the file name to DOS 8+3 limits
3813 ;; before doing anything else, because the regexp
3814 ;; passed to string-match below cannot handle
3815 ;; extensions longer than 3 characters, multiple
3816 ;; dots, and other atrocities.
3817 (let ((fn (dos-8+3-filename
3818 (file-name-nondirectory buffer-file-name))))
3819 (string-match
3820 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
3821 fn)
3822 (concat (file-name-directory buffer-file-name)
3823 "#" (match-string 1 fn)
3824 "." (match-string 3 fn) "#"))
3825 (concat (file-name-directory filename)
3826 "#"
3827 (file-name-nondirectory filename)
3828 "#")))
3829 ;; Make sure auto-save file names don't contain characters
3830 ;; invalid for the underlying filesystem.
3831 (if (and (memq system-type '(ms-dos windows-nt))
3832 ;; Don't modify remote (ange-ftp) filenames
3833 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result)))
3834 (convert-standard-filename result)
3835 result))
0a1763b4
RS
3836
3837 ;; Deal with buffers that don't have any associated files. (Mail
3838 ;; mode tends to create a good number of these.)
3839
7d483e8c 3840 (let ((buffer-name (buffer-name))
ff5c7181 3841 (limit 0)
77d18896 3842 file-name)
c3348e10
RS
3843 ;; Eliminate all slashes and backslashes by
3844 ;; replacing them with sequences that start with %.
3845 ;; Quote % also, to keep distinct names distinct.
3846 (while (string-match "[/\\%]" buffer-name limit)
3847 (let* ((character (aref buffer-name (match-beginning 0)))
3848 (replacement
3849 (cond ((eq character ?%) "%%")
3850 ((eq character ?/) "%+")
3851 ((eq character ?\\) "%-"))))
3852 (setq buffer-name (replace-match replacement t t buffer-name))
3853 (setq limit (1+ (match-end 0)))))
a8abaf83 3854 ;; Generate the file name.
ff5c7181
RS
3855 (setq file-name
3856 (make-temp-file
3857 (let ((fname
3858 (expand-file-name
3859 (format "#%s#" buffer-name)
3860 ;; Try a few alternative directories, to get one we can
3861 ;; write it.
3862 (cond
3863 ((file-writable-p default-directory) default-directory)
3864 ((file-writable-p "/var/tmp/") "/var/tmp/")
3865 ("~/")))))
3866 (if (and (memq system-type '(ms-dos windows-nt))
3867 ;; Don't modify remote (ange-ftp) filenames
3868 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname)))
3869 ;; The call to convert-standard-filename is in case
3870 ;; buffer-name includes characters not allowed by the
3871 ;; DOS/Windows filesystems. make-temp-file writes to the
3872 ;; file it creates, so we must fix the file name _before_
3873 ;; make-temp-file is called.
3874 (convert-standard-filename fname)
3875 fname))
3876 nil "#"))
3877 ;; make-temp-file creates the file,
3878 ;; but we don't want it to exist until we do an auto-save.
3879 (condition-case ()
3880 (delete-file file-name)
3881 (file-error nil))
3882 file-name)))
b4da00e9
RM
3883
3884(defun auto-save-file-name-p (filename)
3885 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
3886FILENAME should lack slashes. You can redefine this for customization."
3887 (string-match "^#.*#$" filename))
3888\f
6f4983e6
RS
3889(defun wildcard-to-regexp (wildcard)
3890 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
3891The generated regexp will match a filename iff the filename
3892matches that wildcard according to shell rules. Only wildcards known
3893by `sh' are supported."
3894 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
3895 ;; Copy the initial run of non-special characters.
3896 (result (substring wildcard 0 i))
3897 (len (length wildcard)))
3898 ;; If no special characters, we're almost done.
3899 (if i
3900 (while (< i len)
3901 (let ((ch (aref wildcard i))
3902 j)
3903 (setq
3904 result
3905 (concat result
3906 (cond
7e7c9c4e
RS
3907 ((and (eq ch ?\[)
3908 (< (1+ i) len)
3909 (eq (aref wildcard (1+ i)) ?\]))
3910 "\\[")
6f4983e6
RS
3911 ((eq ch ?\[) ; [...] maps to regexp char class
3912 (progn
3913 (setq i (1+ i))
3914 (concat
3915 (cond
3916 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
3917 (progn
3918 (setq i (1+ i))
3919 (if (eq (aref wildcard i) ?\])
3920 (progn
3921 (setq i (1+ i))
3922 "[^]")
3923 "[^")))
3924 ((eq (aref wildcard i) ?^)
3925 ;; Found "[^". Insert a `\0' character
3926 ;; (which cannot happen in a filename)
3927 ;; into the character class, so that `^'
3928 ;; is not the first character after `[',
3929 ;; and thus non-special in a regexp.
3930 (progn
3931 (setq i (1+ i))
3932 "[\000^"))
3933 ((eq (aref wildcard i) ?\])
3934 ;; I don't think `]' can appear in a
3935 ;; character class in a wildcard, but
3936 ;; let's be general here.
3937 (progn
3938 (setq i (1+ i))
3939 "[]"))
3940 (t "["))
3941 (prog1 ; copy everything upto next `]'.
3942 (substring wildcard
3943 i
3944 (setq j (string-match
3945 "]" wildcard i)))
3946 (setq i (if j (1- j) (1- len)))))))
3947 ((eq ch ?.) "\\.")
3948 ((eq ch ?*) "[^\000]*")
3949 ((eq ch ?+) "\\+")
3950 ((eq ch ?^) "\\^")
3951 ((eq ch ?$) "\\$")
3952 ((eq ch ?\\) "\\\\") ; probably cannot happen...
3953 ((eq ch ??) "[^\000]")
3954 (t (char-to-string ch)))))
3955 (setq i (1+ i)))))
3956 ;; Shell wildcards should match the entire filename,
3957 ;; not its part. Make the regexp say so.
3958 (concat "\\`" result "\\'")))
3959\f
21540597 3960(defcustom list-directory-brief-switches
b4da00e9 3961 (if (eq system-type 'vax-vms) "" "-CF")
ffc0e1ca 3962 "*Switches for `list-directory' to pass to `ls' for brief listing."
21540597
RS
3963 :type 'string
3964 :group 'dired)
b4da00e9 3965
21540597 3966(defcustom list-directory-verbose-switches
b4da00e9
RM
3967 (if (eq system-type 'vax-vms)
3968 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
3969 "-l")
ffc0e1ca 3970 "*Switches for `list-directory' to pass to `ls' for verbose listing."
21540597
RS
3971 :type 'string
3972 :group 'dired)
b4da00e9 3973
5de148a2
RS
3974(defun file-expand-wildcards (pattern &optional full)
3975 "Expand wildcard pattern PATTERN.
4db2a7de
RS
3976This returns a list of file names which match the pattern.
3977
3978If PATTERN is written as an absolute relative file name,
3979the values are absolute also.
3980
3981If PATTERN is written as a relative file name, it is interpreted
3982relative to the current default directory, `default-directory'.
3983The file names returned are normally also relative to the current
3984default directory. However, if FULL is non-nil, they are absolute."
032388f3
RS
3985 (save-match-data
3986 (let* ((nondir (file-name-nondirectory pattern))
3987 (dirpart (file-name-directory pattern))
3988 ;; A list of all dirs that DIRPART specifies.
3989 ;; This can be more than one dir
3990 ;; if DIRPART contains wildcards.
3991 (dirs (if (and dirpart (string-match "[[*?]" dirpart))
3992 (mapcar 'file-name-as-directory
3993 (file-expand-wildcards (directory-file-name dirpart)))
3994 (list dirpart)))
3995 contents)
3996 (while dirs
3997 (when (or (null (car dirs)) ; Possible if DIRPART is not wild.
3998 (file-directory-p (directory-file-name (car dirs))))
3999 (let ((this-dir-contents
4000 ;; Filter out "." and ".."
4001 (delq nil
4002 (mapcar #'(lambda (name)
4003 (unless (string-match "\\`\\.\\.?\\'"
4004 (file-name-nondirectory name))
4005 name))
4006 (directory-files (or (car dirs) ".") full
4007 (wildcard-to-regexp nondir))))))
4008 (setq contents
4009 (nconc
4010 (if (and (car dirs) (not full))
4011 (mapcar (function (lambda (name) (concat (car dirs) name)))
4012 this-dir-contents)
4013 this-dir-contents)
4014 contents))))
4015 (setq dirs (cdr dirs)))
4016 contents)))
5de148a2 4017
b4da00e9
RM
4018(defun list-directory (dirname &optional verbose)
4019 "Display a list of files in or matching DIRNAME, a la `ls'.
4020DIRNAME is globbed by the shell if necessary.
4021Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
4022Actions controlled by variables `list-directory-brief-switches'
4023and `list-directory-verbose-switches'."
4024 (interactive (let ((pfx current-prefix-arg))
4025 (list (read-file-name (if pfx "List directory (verbose): "
4026 "List directory (brief): ")
4027 nil default-directory nil)
4028 pfx)))
4029 (let ((switches (if verbose list-directory-verbose-switches
84905190
RS
4030 list-directory-brief-switches))
4031 buffer)
b4da00e9
RM
4032 (or dirname (setq dirname default-directory))
4033 (setq dirname (expand-file-name dirname))
4034 (with-output-to-temp-buffer "*Directory*"
84905190 4035 (setq buffer standard-output)
b4da00e9
RM
4036 (buffer-disable-undo standard-output)
4037 (princ "Directory ")
4038 (princ dirname)
4039 (terpri)
c3554e95
RS
4040 (save-excursion
4041 (set-buffer "*Directory*")
4042 (let ((wildcard (not (file-directory-p dirname))))
84905190
RS
4043 (insert-directory dirname switches wildcard (not wildcard)))))
4044 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
4045 (with-current-buffer buffer
4046 (setq default-directory
4047 (if (file-directory-p dirname)
4048 (file-name-as-directory dirname)
4049 (file-name-directory dirname))))))
c3554e95 4050
ffc0e1ca
AS
4051(defun shell-quote-wildcard-pattern (pattern)
4052 "Quote characters special to the shell in PATTERN, leave wildcards alone.
4053
4054PATTERN is assumed to represent a file-name wildcard suitable for the
4055underlying filesystem. For Unix and GNU/Linux, the characters from the
4056set [ \\t\\n;<>&|()#$] are quoted with a backslash; for DOS/Windows, all
4057the parts of the pattern which don't include wildcard characters are
4058quoted with double quotes.
4059Existing quote characters in PATTERN are left alone, so you can pass
4060PATTERN that already quotes some of the special characters."
4061 (save-match-data
4062 (cond
c60ee5e7 4063 ((memq system-type '(ms-dos windows-nt cygwin))
ffc0e1ca
AS
4064 ;; DOS/Windows don't allow `"' in file names. So if the
4065 ;; argument has quotes, we can safely assume it is already
4066 ;; quoted by the caller.
4067 (if (or (string-match "[\"]" pattern)
4068 ;; We quote [&()#$'] in case their shell is a port of a
4069 ;; Unixy shell. We quote [,=+] because stock DOS and
4070 ;; Windows shells require that in some cases, such as
4071 ;; passing arguments to batch files that use positional
4072 ;; arguments like %1.
4073 (not (string-match "[ \t;&()#$',=+]" pattern)))
4074 pattern
4075 (let ((result "\"")
4076 (beg 0)
4077 end)
4078 (while (string-match "[*?]+" pattern beg)
4079 (setq end (match-beginning 0)
4080 result (concat result (substring pattern beg end)
4081 "\""
4082 (substring pattern end (match-end 0))
4083 "\"")
4084 beg (match-end 0)))
4085 (concat result (substring pattern beg) "\""))))
4086 (t
4087 (let ((beg 0))
4088 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
4089 (setq pattern
4090 (concat (substring pattern 0 (match-beginning 0))
4091 "\\"
4092 (substring pattern (match-beginning 0)))
4093 beg (1+ (match-end 0)))))
4094 pattern))))
4095
4096
c3554e95
RS
4097(defvar insert-directory-program "ls"
4098 "Absolute or relative name of the `ls' program used by `insert-directory'.")
4099
f4d04672
RS
4100(defcustom directory-free-space-program "df"
4101 "*Program to get the amount of free space on a file system.
4102We assume the output has the format of `df'.
4103The value of this variable must be just a command name or file name;
4104if you want to specify options, use `directory-free-space-args'.
4105
01b26b90
EZ
4106A value of nil disables this feature.
4107
4108If the function `file-system-info' is defined, it is always used in
4109preference to the program given by this variable."
f4d04672
RS
4110 :type '(choice (string :tag "Program") (const :tag "None" nil))
4111 :group 'dired)
4112
525fdbc9
AS
4113(defcustom directory-free-space-args
4114 (if (eq system-type 'darwin) "-k" "-Pk")
f4d04672
RS
4115 "*Options to use when running `directory-free-space-program'."
4116 :type 'string
4117 :group 'dired)
4118
01b26b90
EZ
4119(defun get-free-disk-space (dir)
4120 "Return the mount of free space on directory DIR's file system.
4121The result is a string that gives the number of free 1KB blocks,
4122or nil if the system call or the program which retrieve the infornmation
4123fail.
4124
4125This function calls `file-system-info' if it is available, or invokes the
4126program specified by `directory-free-space-program' if that is non-nil."
4127 ;; Try to find the number of free blocks. Non-Posix systems don't
4128 ;; always have df, but might have an equivalent system call.
4129 (if (fboundp 'file-system-info)
4130 (let ((fsinfo (file-system-info dir)))
4131 (if fsinfo
4132 (format "%.0f" (/ (nth 2 fsinfo) 1024))))
4133 (save-match-data
4134 (with-temp-buffer
4135 (when (and directory-free-space-program
4136 (zerop (call-process directory-free-space-program
4137 nil t nil
4138 directory-free-space-args
4139 dir)))
4140 ;; Usual format is a header line followed by a line of
4141 ;; numbers.
4142 (goto-char (point-min))
4143 (forward-line 1)
4144 (if (not (eobp))
4145 (progn
4146 ;; Move to the end of the "available blocks" number.
4147 (skip-chars-forward "^ \t")
4148 (forward-word 3)
4149 ;; Copy it into AVAILABLE.
4150 (let ((end (point)))
4151 (forward-word -1)
4152 (buffer-substring (point) end)))))))))
4153
4154
c3554e95
RS
4155;; insert-directory
4156;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
4157;; FULL-DIRECTORY-P is nil.
4158;; The single line of output must display FILE's name as it was
4159;; given, namely, an absolute path name.
4160;; - must insert exactly one line for each file if WILDCARD or
4161;; FULL-DIRECTORY-P is t, plus one optional "total" line
4162;; before the file lines, plus optional text after the file lines.
4163;; Lines are delimited by "\n", so filenames containing "\n" are not
4164;; allowed.
4165;; File lines should display the basename.
4166;; - must be consistent with
4167;; - functions dired-move-to-filename, (these two define what a file line is)
4168;; dired-move-to-end-of-filename,
4169;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
4170;; dired-insert-headerline
4171;; dired-after-subdir-garbage (defines what a "total" line is)
4172;; - variable dired-subdir-regexp
1fc85dae
KG
4173;; - may be passed "--dired" as the first argument in SWITCHES.
4174;; Filename handlers might have to remove this switch if their
4175;; "ls" command does not support it.
c3554e95 4176(defun insert-directory (file switches &optional wildcard full-directory-p)
a18b7c81 4177 "Insert directory listing for FILE, formatted according to SWITCHES.
c3554e95 4178Leaves point after the inserted text.
727d277d 4179SWITCHES may be a string of options, or a list of strings.
c3554e95
RS
4180Optional third arg WILDCARD means treat FILE as shell wildcard.
4181Optional fourth arg FULL-DIRECTORY-P means file is a directory and
4182switches do not contain `d', so that a full listing is expected.
4183
4184This works by running a directory listing program
406e12d9 4185whose name is in the variable `insert-directory-program'.
c3554e95 4186If WILDCARD, it also runs the shell specified by `shell-file-name'."
c870ab8e 4187 ;; We need the directory in order to find the right handler.
d2473540
AS
4188 (let ((handler (find-file-name-handler (expand-file-name file)
4189 'insert-directory)))
ebad92dc 4190 (if handler
c3554e95
RS
4191 (funcall handler 'insert-directory file switches
4192 wildcard full-directory-p)
b4da00e9 4193 (if (eq system-type 'vax-vms)
c3554e95 4194 (vms-read-directory file switches (current-buffer))
818286f4 4195 (let (result (beg (point)))
ebad92dc
RS
4196
4197 ;; Read the actual directory using `insert-directory-program'.
4198 ;; RESULT gets the status code.
99f01c91
KH
4199 (let* (;; We at first read by no-conversion, then after
4200 ;; putting text property `dired-filename, decode one
4201 ;; bunch by one to preserve that property.
4202 (coding-system-for-read 'no-conversion)
4203 ;; This is to control encoding the arguments in call-process.
c60ee5e7 4204 (coding-system-for-write
82e22b57
KH
4205 (and enable-multibyte-characters
4206 (or file-name-coding-system
99f01c91 4207 default-file-name-coding-system))))
ebad92dc
RS
4208 (setq result
4209 (if wildcard
4210 ;; Run ls in the directory part of the file pattern
4211 ;; using the last component as argument.
4212 (let ((default-directory
4213 (if (file-name-absolute-p file)
4214 (file-name-directory file)
4215 (file-name-directory (expand-file-name file))))
4216 (pattern (file-name-nondirectory file)))
4217 (call-process
4218 shell-file-name nil t nil
4219 "-c"
4220 (concat (if (memq system-type '(ms-dos windows-nt))
4221 ""
4222 "\\") ; Disregard Unix shell aliases!
4223 insert-directory-program
4224 " -d "
4225 (if (stringp switches)
4226 switches
4227 (mapconcat 'identity switches " "))
4228 " -- "
4229 ;; Quote some characters that have
4230 ;; special meanings in shells; but
4231 ;; don't quote the wildcards--we want
4232 ;; them to be special. We also
4233 ;; currently don't quote the quoting
4234 ;; characters in case people want to
4235 ;; use them explicitly to quote
4236 ;; wildcard characters.
4237 (shell-quote-wildcard-pattern pattern))))
4238 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
4239 ;; directory if FILE is a symbolic link.
4240 (apply 'call-process
4241 insert-directory-program nil t nil
4242 (append
4243 (if (listp switches) switches
4244 (unless (equal switches "")
4245 ;; Split the switches at any spaces so we can
4246 ;; pass separate options as separate args.
4247 (split-string switches)))
4248 ;; Avoid lossage if FILE starts with `-'.
4249 '("--")
4250 (progn
4251 (if (string-match "\\`~" file)
4252 (setq file (expand-file-name file)))
4253 (list
4254 (if full-directory-p
4255 (concat (file-name-as-directory file) ".")
4256 file))))))))
4257
4258 ;; If `insert-directory-program' failed, signal an error.
73ba53dc 4259 (if (/= result 0)
ffc0e1ca
AS
4260 ;; On non-Posix systems, we cannot open a directory, so
4261 ;; don't even try, because that will always result in
ebad92dc
RS
4262 ;; the ubiquitous "Access denied". Instead, show the
4263 ;; command line so the user can try to guess what went wrong.
ffc0e1ca
AS
4264 (if (and (file-directory-p file)
4265 (memq system-type '(ms-dos windows-nt)))
4266 (error
4267 "Reading directory: \"%s %s -- %s\" exited with status %s"
4268 insert-directory-program
4269 (if (listp switches) (concat switches) switches)
4270 file result)
4271 ;; Unix. Access the file to get a suitable error.
ebad92dc
RS
4272 (access-file file "Reading directory")
4273 (error "Listing directory failed but `access-file' worked")))
4274
ff7affeb
RS
4275 (when (string-match "--dired\\>" switches)
4276 (forward-line -2)
9423860f
AS
4277 (when (looking-at "//SUBDIRED//")
4278 (delete-region (point) (progn (forward-line 1) (point)))
4279 (forward-line -1))
ff7affeb
RS
4280 (let ((end (line-end-position)))
4281 (forward-word 1)
4282 (forward-char 3)
4283 (while (< (point) end)
4284 (let ((start (+ beg (read (current-buffer))))
4285 (end (+ beg (read (current-buffer)))))
7702ccc5
KH
4286 (if (= (char-after end) ?\n)
4287 (put-text-property start end 'dired-filename t)
4288 ;; It seems that we can't trust ls's output as to
4289 ;; byte positions of filenames.
4290 (put-text-property beg (point) 'dired-filename nil)
4291 (end-of-line))))
ff7affeb
RS
4292 (goto-char end)
4293 (beginning-of-line)
4294 (delete-region (point) (progn (forward-line 2) (point)))))
4295
99f01c91 4296 ;; Now decode what read if necessary.
b6647390
KH
4297 (let ((coding (or coding-system-for-read
4298 file-name-coding-system
4299 default-file-name-coding-system
4300 'undecided))
99f01c91 4301 val pos)
b6647390
KH
4302 (when (and enable-multibyte-characters
4303 (not (memq (coding-system-base coding)
4304 '(raw-text no-conversion))))
4305 ;; If no coding system is specified or detection is
4306 ;; requested, detect the coding.
4307 (if (eq (coding-system-base coding) 'undecided)
4308 (setq coding (detect-coding-region beg (point) t)))
4309 (if (not (eq (coding-system-base coding) 'undecided))
4310 (save-restriction
4311 (narrow-to-region beg (point))
4312 (goto-char (point-min))
4313 (while (not (eobp))
4314 (setq pos (point)
4315 val (get-text-property (point) 'dired-filename))
4316 (goto-char (next-single-property-change
4317 (point) 'dired-filename nil (point-max)))
4318 (decode-coding-region pos (point) coding)
4319 (if val
4320 (put-text-property pos (point)
4321 'dired-filename t)))))))
99f01c91 4322
75bb5ca4
AS
4323 (if full-directory-p
4324 ;; Try to insert the amount of free space.
4325 (save-excursion
4326 (goto-char beg)
4327 ;; First find the line to put it on.
4328 (when (re-search-forward "^ *\\(total\\)" nil t)
4329 (let ((available (get-free-disk-space ".")))
4330 (when available
4331 ;; Replace "total" with "used", to avoid confusion.
4332 (replace-match "total used in directory" nil nil nil 1)
4333 (end-of-line)
4334 (insert " available " available)))))))))))
34342a07 4335
bc22fd18
EZ
4336(defun insert-directory-safely (file switches
4337 &optional wildcard full-directory-p)
4338 "Insert directory listing for FILE, formatted according to SWITCHES.
4339
4340Like `insert-directory', but if FILE does not exist, it inserts a
4341message to that effect instead of signaling an error."
4342 (if (file-exists-p file)
4343 (insert-directory file switches wildcard full-directory-p)
4344 ;; Simulate the message printed by `ls'.
4345 (insert (format "%s: No such file or directory\n" file))))
4346
88902b35 4347(defvar kill-emacs-query-functions nil
65d5c6de 4348 "Functions to call with no arguments to query about killing Emacs.
78c793d1
RS
4349If any of these functions returns nil, killing Emacs is cancelled.
4350`save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
4351but `kill-emacs', the low level primitive, does not.
4352See also `kill-emacs-hook'.")
88902b35 4353
11f15305 4354(defcustom confirm-kill-emacs nil
9c2ba08f
EZ
4355 "How to ask for confirmation when leaving Emacs.
4356If nil, the default, don't ask at all. If the value is non-nil, it should
4357be a predicate function such as `yes-or-no-p'."
11f15305
GM
4358 :type '(choice (const :tag "Ask with yes-or-no-p" yes-or-no-p)
4359 (const :tag "Ask with y-or-n-p" y-or-n-p)
4360 (const :tag "Don't confirm" nil))
4361 :group 'emacs
4362 :version "21.1")
4363
b4da00e9
RM
4364(defun save-buffers-kill-emacs (&optional arg)
4365 "Offer to save each buffer, then kill this Emacs process.
4366With prefix arg, silently save all file-visiting buffers, then kill."
4367 (interactive "P")
4368 (save-some-buffers arg t)
4369 (and (or (not (memq t (mapcar (function
4370 (lambda (buf) (and (buffer-file-name buf)
4371 (buffer-modified-p buf))))
4372 (buffer-list))))
4373 (yes-or-no-p "Modified buffers exist; exit anyway? "))
4374 (or (not (fboundp 'process-list))
4375 ;; process-list is not defined on VMS.
4376 (let ((processes (process-list))
4377 active)
4378 (while processes
48a4a1fb
KS
4379 (and (memq (process-status (car processes)) '(run stop open listen))
4380 (process-query-on-exit-flag (car processes))
b4da00e9
RM
4381 (setq active t))
4382 (setq processes (cdr processes)))
4383 (or (not active)
48a4a1fb 4384 (list-processes t)
b4da00e9 4385 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
88902b35 4386 ;; Query the user for other things, perhaps.
fb15c113 4387 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
11f15305
GM
4388 (or (null confirm-kill-emacs)
4389 (funcall confirm-kill-emacs "Really exit Emacs? "))
b4da00e9
RM
4390 (kill-emacs)))
4391\f
ffc0e1ca 4392;; We use /: as a prefix to "quote" a file name
47afc068
RS
4393;; so that magic file name handlers will not apply to it.
4394
4395(setq file-name-handler-alist
4396 (cons '("\\`/:" . file-name-non-special)
4397 file-name-handler-alist))
4398
4399;; We depend on being the last handler on the list,
4400;; so that anything else which does need handling
4401;; has been handled already.
4402;; So it is safe for us to inhibit *all* magic file name handlers.
4403
4404(defun file-name-non-special (operation &rest arguments)
4405 (let ((file-name-handler-alist nil)
5cb1f728
KH
4406 (default-directory
4407 (if (eq operation 'insert-directory)
4408 (directory-file-name
ffc0e1ca 4409 (expand-file-name
5cb1f728
KH
4410 (unhandled-file-name-directory default-directory)))
4411 default-directory))
47afc068
RS
4412 ;; Get a list of the indices of the args which are file names.
4413 (file-arg-indices
4414 (cdr (or (assq operation
c736f678 4415 ;; The first five are special because they
47afc068
RS
4416 ;; return a file name. We want to include the /:
4417 ;; in the return value.
4418 ;; So just avoid stripping it in the first place.
4419 '((expand-file-name . nil)
4420 (file-name-directory . nil)
4421 (file-name-as-directory . nil)
4422 (directory-file-name . nil)
c736f678
RS
4423 (file-name-sans-versions . nil)
4424 ;; `identity' means just return the first arg
4425 ;; as stripped of its quoting.
4426 (substitute-in-file-name . identity)
c37adaa5
SM
4427 (file-name-completion 1)
4428 (file-name-all-completions 1)
47afc068
RS
4429 (rename-file 0 1)
4430 (copy-file 0 1)
4431 (make-symbolic-link 0 1)
4432 (add-name-to-file 0 1)))
4433 ;; For all other operations, treat the first argument only
4434 ;; as the file name.
4435 '(nil 0))))
4436 ;; Copy ARGUMENTS so we can replace elements in it.
4437 (arguments (copy-sequence arguments)))
4438 ;; Strip off the /: from the file names that have this handler.
4439 (save-match-data
18b9dced 4440 (while (consp file-arg-indices)
fe4d9852
KH
4441 (let ((pair (nthcdr (car file-arg-indices) arguments)))
4442 (and (car pair)
4443 (string-match "\\`/:" (car pair))
4444 (setcar pair
4445 (if (= (length (car pair)) 2)
4446 "/"
4447 (substring (car pair) 2)))))
47afc068 4448 (setq file-arg-indices (cdr file-arg-indices))))
18b9dced
RS
4449 (if (eq file-arg-indices 'identity)
4450 (car arguments)
c37adaa5 4451 (apply operation arguments))))
47afc068 4452\f
b4da00e9 4453(define-key ctl-x-map "\C-f" 'find-file)
b4da00e9
RM
4454(define-key ctl-x-map "\C-r" 'find-file-read-only)
4455(define-key ctl-x-map "\C-v" 'find-alternate-file)
4456(define-key ctl-x-map "\C-s" 'save-buffer)
4457(define-key ctl-x-map "s" 'save-some-buffers)
4458(define-key ctl-x-map "\C-w" 'write-file)
4459(define-key ctl-x-map "i" 'insert-file)
4460(define-key esc-map "~" 'not-modified)
4461(define-key ctl-x-map "\C-d" 'list-directory)
4462(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
d758359d 4463(define-key ctl-x-map "\C-q" 'toggle-read-only)
b4da00e9
RM
4464
4465(define-key ctl-x-4-map "f" 'find-file-other-window)
4466(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
4467(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
4468(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
924f0a24 4469(define-key ctl-x-4-map "\C-o" 'display-buffer)
5bbbceb1 4470
f98955ea
JB
4471(define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
4472(define-key ctl-x-5-map "f" 'find-file-other-frame)
4473(define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
4474(define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
c0274f38
ER
4475
4476;;; files.el ends here