(init_charset_once): Fix previous change.
[bpt/emacs.git] / lisp / files.el
CommitLineData
c0274f38
ER
1;;; files.el --- file input and output commands for Emacs
2
9596811a 3;; Copyright (C) 1985, 86, 87, 92, 93,
b0d2a9e7 4;; 94, 95, 96, 97, 1998 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
RM
70
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
87`backup-by-copying', `backup-by-copying-when-linked' and
21540597
RS
88`backup-by-copying-when-mismatch'. See also `backup-inhibited'."
89 :type 'boolean
90 :group 'backup)
b4da00e9
RM
91
92;; Do this so that local variables based on the file name
93;; are not overridden by the major mode.
94(defvar backup-inhibited nil
f862241d
RS
95 "Non-nil means don't make a backup, regardless of the other parameters.
96This variable is intended for use by making it local to a buffer.
97But it is local only if you make it local.")
b4da00e9
RM
98(put 'backup-inhibited 'permanent-local t)
99
21540597 100(defcustom backup-by-copying nil
b4da00e9 101 "*Non-nil means always use copying to create backup files.
21540597
RS
102See documentation of variable `make-backup-files'."
103 :type 'boolean
104 :group 'backup)
b4da00e9 105
21540597 106(defcustom backup-by-copying-when-linked nil
b4da00e9
RM
107 "*Non-nil means use copying to create backups for files with multiple names.
108This causes the alternate names to refer to the latest version as edited.
21540597
RS
109This variable is relevant only if `backup-by-copying' is nil."
110 :type 'boolean
111 :group 'backup)
b4da00e9 112
21540597 113(defcustom backup-by-copying-when-mismatch nil
b4da00e9
RM
114 "*Non-nil means create backups by copying if this preserves owner or group.
115Renaming may still be used (subject to control of other variables)
116when it would not result in changing the owner or group of the file;
117that is, for files which are owned by you and whose group matches
118the default for a new file created there by you.
21540597
RS
119This variable is relevant only if `backup-by-copying' is nil."
120 :type 'boolean
121 :group 'backup)
b4da00e9
RM
122
123(defvar backup-enable-predicate
124 '(lambda (name)
125 (or (< (length name) 5)
126 (not (string-equal "/tmp/" (substring name 0 5)))))
127 "Predicate that looks at a file name and decides whether to make backups.
128Called with an absolute file name as argument, it returns t to enable backup.")
129
21540597 130(defcustom buffer-offer-save nil
b4da00e9
RM
131 "*Non-nil in a buffer means offer to save the buffer on exit
132even if the buffer is not visiting a file.
21540597
RS
133Automatically local in all buffers."
134 :type 'boolean
135 :group 'backup)
b4da00e9
RM
136(make-variable-buffer-local 'buffer-offer-save)
137
21540597 138(defcustom find-file-existing-other-name t
f3e23606
RS
139 "*Non-nil means find a file under alternative names, in existing buffers.
140This means if any existing buffer is visiting the file you want
21540597
RS
141under another name, you get the existing buffer instead of a new buffer."
142 :type 'boolean
143 :group 'find-file)
f3e23606 144
21540597 145(defcustom find-file-visit-truename nil
f3e23606
RS
146 "*Non-nil means visit a file under its truename.
147The truename of a file is found by chasing all links
21540597
RS
148both at the file level and at the levels of the containing directories."
149 :type 'boolean
150 :group 'find-file)
f3e23606 151
db8c4866 152(defcustom revert-without-query
d7fa5aa2 153 nil
ebeb898f
RS
154 "*Specify which files should be reverted without query.
155The value is a list of regular expressions.
156If the file name matches one of these regular expressions,
db8c4866 157then `revert-buffer' reverts the file without querying
21540597 158if the file has changed on disk and you have not edited the buffer."
a0d809f2 159 :type '(repeat regexp)
21540597 160 :group 'find-file)
ebeb898f 161
f3e23606
RS
162(defvar buffer-file-number nil
163 "The device number and file number of the file visited in the current buffer.
164The value is a list of the form (FILENUM DEVNUM).
165This pair of numbers uniquely identifies the file.
166If the buffer is visiting a new file, the value is nil.")
167(make-variable-buffer-local 'buffer-file-number)
168(put 'buffer-file-number 'permanent-local t)
169
de88363f
RS
170(defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
171 "Non-nil means that buffer-file-number uniquely identifies files.")
172
30966847
EZ
173(defvar file-name-invalid-regexp
174 (cond ((and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
9959c16e 175 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
30966847 176 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
edfc7f25 177 "[\000-\031]\\|" ; control characters
30966847
EZ
178 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
179 "\\(/[^/.]+\\.[^/.]*\\.\\)")) ; more than a single dot
180 ((memq system-type '(ms-dos windows-nt))
9959c16e 181 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
106a57a4 182 "[|<>\"?*\000-\031]")) ; invalid characters
30966847
EZ
183 (t "[\000]"))
184 "Regexp recognizing file names which aren't allowed by the filesystem.")
185
21540597 186(defcustom file-precious-flag nil
b4da00e9 187 "*Non-nil means protect against I/O errors while saving files.
560f4415 188Some modes set this non-nil in particular buffers.
4b7271c1
KH
189
190This feature works by writing the new contents into a temporary file
191and then renaming the temporary file to replace the original.
192In this way, any I/O error in writing leaves the original untouched,
193and there is never any instant where the file is nonexistent.
194
195Note that this feature forces backups to be made by copying.
560f4415 196Yet, at the same time, saving a precious file
21540597
RS
197breaks any hard links between it and other files."
198 :type 'boolean
199 :group 'backup)
b4da00e9 200
21540597 201(defcustom version-control nil
b4da00e9
RM
202 "*Control use of version numbers for backup files.
203t means make numeric backup versions unconditionally.
204nil means make them for files that have some already.
21540597 205`never' means do not make them."
e48807d1
AS
206 :type '(choice (const :tag "Never" never)
207 (const :tag "If existing" nil)
208 (other :tag "Always" t))
21540597
RS
209 :group 'backup
210 :group 'vc)
211
212(defcustom dired-kept-versions 2
213 "*When cleaning directory, number of versions to keep."
214 :type 'integer
215 :group 'backup
216 :group 'dired)
217
218(defcustom delete-old-versions nil
de7d5e1b 219 "*If t, delete excess backup versions silently.
21540597
RS
220If nil, ask confirmation. Any other value prevents any trimming."
221 :type '(choice (const :tag "Delete" t)
222 (const :tag "Ask" nil)
e48807d1 223 (other :tag "Leave" other))
21540597
RS
224 :group 'backup)
225
226(defcustom kept-old-versions 2
227 "*Number of oldest versions to keep when a new numbered backup is made."
228 :type 'integer
229 :group 'backup)
230
231(defcustom kept-new-versions 2
b4da00e9 232 "*Number of newest versions to keep when a new numbered backup is made.
21540597
RS
233Includes the new backup. Must be > 0"
234 :type 'integer
235 :group 'backup)
b4da00e9 236
21540597 237(defcustom require-final-newline nil
b4da00e9
RM
238 "*Value of t says silently ensure a file ends in a newline when it is saved.
239Non-nil but not t says ask user whether to add a newline when there isn't one.
21540597 240nil means don't add newlines."
ad375092
RS
241 :type '(choice (const :tag "Off" nil)
242 (const :tag "Add" t)
e48807d1 243 (other :tag "Ask" ask))
21540597 244 :group 'editing-basics)
b4da00e9 245
21540597
RS
246(defcustom auto-save-default t
247 "*Non-nil says by default do auto-saving of every file-visiting buffer."
248 :type 'boolean
249 :group 'auto-save)
b4da00e9 250
21540597 251(defcustom auto-save-visited-file-name nil
b4da00e9 252 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
21540597
RS
253Normally auto-save files are written under other names."
254 :type 'boolean
255 :group 'auto-save)
b4da00e9 256
21540597 257(defcustom save-abbrevs nil
b4da00e9 258 "*Non-nil means save word abbrevs too when files are saved.
21540597
RS
259Loading an abbrev file sets this to t."
260 :type 'boolean
261 :group 'abbrev)
b4da00e9 262
21540597
RS
263(defcustom find-file-run-dired t
264 "*Non-nil says run dired if `find-file' is given the name of a directory."
265 :type 'boolean
266 :group 'find-file)
b4da00e9 267
92966e6f
RS
268;;;It is not useful to make this a local variable.
269;;;(put 'find-file-not-found-hooks 'permanent-local t)
b4da00e9
RM
270(defvar find-file-not-found-hooks nil
271 "List of functions to be called for `find-file' on nonexistent file.
272These functions are called as soon as the error is detected.
273`buffer-file-name' is already set up.
274The functions are called in the order given until one of them returns non-nil.")
275
92966e6f
RS
276;;;It is not useful to make this a local variable.
277;;;(put 'find-file-hooks 'permanent-local t)
b4da00e9
RM
278(defvar find-file-hooks nil
279 "List of functions to be called after a buffer is loaded from a file.
280The buffer's local variables (if any) will have been processed before the
281functions are called.")
282
b4da00e9
RM
283(defvar write-file-hooks nil
284 "List of functions to be called before writing out a buffer to a file.
285If one of them returns non-nil, the file is considered already written
8c0e7b73
JB
286and the rest are not called.
287These hooks are considered to pertain to the visited file.
288So this list is cleared if you change the visited file name.
f82966e4
KH
289
290Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
291See also `write-contents-hooks'.")
b19f1da4
BF
292;;; However, in case someone does make it local...
293(put 'write-file-hooks 'permanent-local t)
c9dca4e0 294
c9dca4e0
RS
295(defvar local-write-file-hooks nil
296 "Just like `write-file-hooks', except intended for per-buffer use.
297The functions in this list are called before the ones in
f82966e4
KH
298`write-file-hooks'.
299
300This variable is meant to be used for hooks that have to do with a
301particular visited file. Therefore, it is a permanent local, so that
302changing the major mode does not clear it. However, calling
303`set-visited-file-name' does clear it.")
b19f1da4
BF
304(make-variable-buffer-local 'local-write-file-hooks)
305(put 'local-write-file-hooks 'permanent-local t)
8c0e7b73
JB
306
307(defvar write-contents-hooks nil
308 "List of functions to be called before writing out a buffer to a file.
309If one of them returns non-nil, the file is considered already written
310and the rest are not called.
f82966e4
KH
311
312This variable is meant to be used for hooks that pertain to the
313buffer's contents, not to the particular visited file; thus,
314`set-visited-file-name' does not clear this variable; but changing the
693f800d
RS
315major mode does clear it.
316
317This variable automatically becomes buffer-local whenever it is set.
659ebcc6 318If you use `add-hook' to add elements to the list, use nil for the
693f800d 319LOCAL argument.
f82966e4 320
8c0e7b73 321See also `write-file-hooks'.")
f82966e4 322(make-variable-buffer-local 'write-contents-hooks)
b4da00e9 323
21540597 324(defcustom enable-local-variables t
93a2702d 325 "*Control use of local variables in files you visit.
b4da00e9 326The value can be t, nil or something else.
93a2702d 327A value of t means file local variables specifications are obeyed;
b4da00e9
RM
328nil means they are ignored; anything else means query.
329
93a2702d 330The command \\[normal-mode] always obeys file local variable
21540597
RS
331specifications and ignores this variable."
332 :type '(choice (const :tag "Obey" t)
333 (const :tag "Ignore" nil)
e48807d1 334 (other :tag "Query" other))
21540597 335 :group 'find-file)
b4da00e9 336
da09b92b
RS
337(defvar local-enable-local-variables t
338 "Like `enable-local-variables' but meant for buffer-local bindings.
339If a major mode sets this to nil, buffer-locally, then any local
340variables list in the file will be ignored.")
341
21540597 342(defcustom enable-local-eval 'maybe
d207b766
RS
343 "*Control processing of the \"variable\" `eval' in a file's local variables.
344The value can be t, nil or something else.
345A value of t means obey `eval' variables;
346nil means ignore them; anything else means query.
347
348The command \\[normal-mode] always obeys local-variables lists
21540597
RS
349and ignores this variable."
350 :type '(choice (const :tag "Obey" t)
351 (const :tag "Ignore" nil)
e48807d1 352 (other :tag "Query" other))
21540597 353 :group 'find-file)
b4da00e9
RM
354
355;; Avoid losing in versions where CLASH_DETECTION is disabled.
356(or (fboundp 'lock-buffer)
231c4e10 357 (defalias 'lock-buffer 'ignore))
b4da00e9 358(or (fboundp 'unlock-buffer)
231c4e10 359 (defalias 'unlock-buffer 'ignore))
a7305f6e
RS
360(or (fboundp 'file-locked-p)
361 (defalias 'file-locked-p 'ignore))
93fe0a35 362
2a9fe1e2
RS
363(defvar view-read-only nil
364 "*Non-nil means buffers visiting files read-only, do it in view mode.")
365
cdda8f47
RS
366(defvar temporary-file-directory
367 (file-name-as-directory
c11032b9
RS
368 (cond ((memq system-type '(ms-dos windows-nt))
369 (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
370 ((memq system-type '(vax-vms axp-vms))
371 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
372 (t
373 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
cdda8f47 374 "The directory for writing temporary files.")
c11032b9 375
03511cfd
RS
376;; The system null device. (Should reference NULL_DEVICE from C.)
377(defvar null-device "/dev/null" "The system null device.")
378
93fe0a35
RS
379;; This hook function provides support for ange-ftp host name
380;; completion. It runs the usual ange-ftp hook, but only for
381;; completion operations. Having this here avoids the need
382;; to load ange-ftp when it's not really in use.
383(defun ange-ftp-completion-hook-function (op &rest args)
384 (if (memq op '(file-name-completion file-name-all-completions))
385 (apply 'ange-ftp-hook-function op args)
57e81f57
RS
386 (let ((inhibit-file-name-handlers
387 (cons 'ange-ftp-completion-hook-function
388 (and (eq inhibit-file-name-operation op)
389 inhibit-file-name-handlers)))
390 (inhibit-file-name-operation op))
93fe0a35 391 (apply op args))))
567c1ca9
RS
392
393(defun convert-standard-filename (filename)
394 "Convert a standard file's name to something suitable for the current OS.
395This function's standard definition is trivial; it just returns the argument.
396However, on some systems, the function is redefined
397with a definition that really does change some file names."
398 filename)
b4da00e9
RM
399\f
400(defun pwd ()
401 "Show the current default directory."
402 (interactive nil)
403 (message "Directory %s" default-directory))
404
231c4e10
ER
405(defvar cd-path nil
406 "Value of the CDPATH environment variable, as a list.
407Not actually set up until the first time you you use it.")
408
409(defun parse-colon-path (cd-path)
db8c4866 410 "Explode a colon-separated search path into a list of directory names."
231c4e10
ER
411 (and cd-path
412 (let (cd-prefix cd-list (cd-start 0) cd-colon)
306faa42
RS
413 (setq cd-path (concat cd-path path-separator))
414 (while (setq cd-colon (string-match path-separator cd-path cd-start))
231c4e10 415 (setq cd-list
9daefb36 416 (nconc cd-list
c52e4104
RS
417 (list (if (= cd-start cd-colon)
418 nil
419 (substitute-in-file-name
e33e80e4
RS
420 (file-name-as-directory
421 (substring cd-path cd-start cd-colon)))))))
231c4e10
ER
422 (setq cd-start (+ cd-colon 1)))
423 cd-list)))
424
425(defun cd-absolute (dir)
30c5ce9c 426 "Change current directory to given absolute file name DIR."
f4a0f59b
RS
427 ;; Put the name into directory syntax now,
428 ;; because otherwise expand-file-name may give some bad results.
b4da00e9
RM
429 (if (not (eq system-type 'vax-vms))
430 (setq dir (file-name-as-directory dir)))
f4a0f59b 431 (setq dir (abbreviate-file-name (expand-file-name dir)))
b4da00e9 432 (if (not (file-directory-p dir))
83c6f446
RS
433 (if (file-exists-p dir)
434 (error "%s is not a directory" dir)
31c691c1 435 (error "%s: no such directory" dir))
b4da00e9
RM
436 (if (file-executable-p dir)
437 (setq default-directory dir)
9daefb36 438 (error "Cannot cd to %s: Permission denied" dir))))
b4da00e9 439
231c4e10
ER
440(defun cd (dir)
441 "Make DIR become the current buffer's default directory.
30c5ce9c
RS
442If your environment includes a `CDPATH' variable, try each one of that
443colon-separated list of directories when resolving a relative directory name."
dac4ea74
RS
444 (interactive
445 (list (read-file-name "Change default directory: "
2121cd9c
RM
446 default-directory default-directory
447 (and (member cd-path '(nil ("./")))
448 (null (getenv "CDPATH"))))))
30c5ce9c
RS
449 (if (file-name-absolute-p dir)
450 (cd-absolute (expand-file-name dir))
451 (if (null cd-path)
452 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
453 (setq cd-path (or trypath (list "./")))))
454 (if (not (catch 'found
455 (mapcar
456 (function (lambda (x)
457 (let ((f (expand-file-name (concat x dir))))
458 (if (file-directory-p f)
459 (progn
460 (cd-absolute f)
461 (throw 'found t))))))
462 cd-path)
463 nil))
464 (error "No such directory found via CDPATH environment variable"))))
231c4e10 465
b4da00e9
RM
466(defun load-file (file)
467 "Load the Lisp file named FILE."
468 (interactive "fLoad file: ")
469 (load (expand-file-name file) nil nil t))
470
471(defun load-library (library)
472 "Load the library named LIBRARY.
473This is an interface to the function `load'."
474 (interactive "sLoad library: ")
475 (load library))
5d68c2c2 476
7c4b8f8c 477(defun file-local-copy (file &optional buffer)
5d68c2c2
RS
478 "Copy the file FILE into a temporary file on this machine.
479Returns the name of the local copy, or nil, if FILE is directly
480accessible."
6eaebaa2 481 (let ((handler (find-file-name-handler file 'file-local-copy)))
5d68c2c2
RS
482 (if handler
483 (funcall handler 'file-local-copy file)
484 nil)))
f3e23606 485
05ef1cda 486(defun file-truename (filename &optional counter prev-dirs)
f3e23606
RS
487 "Return the truename of FILENAME, which should be absolute.
488The truename of a file name is found by chasing symbolic links
489both at the level of the file and at the level of the directories
05ef1cda
RS
490containing it, until no links are left at any level.
491
492The arguments COUNTER and PREV-DIRS are used only in recursive calls.
493Do not specify them in other calls."
494 ;; COUNTER can be a cons cell whose car is the count of how many more links
495 ;; to chase before getting an error.
496 ;; PREV-DIRS can be a cons cell whose car is an alist
497 ;; of truenames we've just recently computed.
cc37a58c 498
cc37a58c
SM
499 ;; The last test looks dubious, maybe `+' is meant here? --simon.
500 (if (or (string= filename "") (string= filename "~")
7a5a26a6
RS
501 (and (string= (substring filename 0 1) "~")
502 (string-match "~[^/]*" filename)))
1cc2fbeb
RS
503 (progn
504 (setq filename (expand-file-name filename))
505 (if (string= filename "")
506 (setq filename "/"))))
05ef1cda 507 (or counter (setq counter (list 100)))
b505828b
RS
508 (let (done
509 ;; For speed, remove the ange-ftp completion handler from the list.
510 ;; We know it's not needed here.
511 ;; For even more speed, do this only on the outermost call.
512 (file-name-handler-alist
513 (if prev-dirs file-name-handler-alist
514 (let ((tem (copy-sequence file-name-handler-alist)))
515 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
516 (or prev-dirs (setq prev-dirs (list nil)))
b1667e6c
GV
517
518 ;; andrewi@harlequin.co.uk - none of the following code (except for
519 ;; invoking the file-name handler) currently applies on Windows
520 ;; (ie. there are no native symlinks), but there is an issue with
521 ;; case differences being ignored by the OS, and short "8.3 DOS"
522 ;; name aliases existing for all files. (The short names are not
523 ;; reported by directory-files, but can be used to refer to files.)
524 ;; It seems appropriate for file-truename to resolve these issues in
525 ;; the most natural way, which on Windows is to call the function
526 ;; `w32-long-file-name' - this returns the exact name of a file as
527 ;; it is stored on disk (expanding short name aliases with the full
528 ;; name in the process).
529 (if (eq system-type 'windows-nt)
530 (let ((handler (find-file-name-handler filename 'file-truename))
531 newname)
532 ;; For file name that has a special handler, call handler.
533 ;; This is so that ange-ftp can save time by doing a no-op.
534 (if handler
535 (setq filename (funcall handler 'file-truename filename))
536 ;; If filename contains a wildcard, newname will be the old name.
537 (if (string-match "[*?]" filename)
538 (setq newname filename)
539 ;; If filename doesn't exist, newname will be nil.
540 (setq newname (w32-long-file-name filename)))
541 (setq filename (or newname filename)))
542 (setq done t)))
543
05ef1cda
RS
544 ;; If this file directly leads to a link, process that iteratively
545 ;; so that we don't use lots of stack.
546 (while (not done)
547 (setcar counter (1- (car counter)))
548 (if (< (car counter) 0)
549 (error "Apparent cycle of symbolic links for %s" filename))
550 (let ((handler (find-file-name-handler filename 'file-truename)))
551 ;; For file name that has a special handler, call handler.
552 ;; This is so that ange-ftp can save time by doing a no-op.
553 (if handler
554 (setq filename (funcall handler 'file-truename filename)
555 done t)
fb145562 556 (let ((dir (or (file-name-directory filename) default-directory))
05ef1cda
RS
557 target dirfile)
558 ;; Get the truename of the directory.
559 (setq dirfile (directory-file-name dir))
560 ;; If these are equal, we have the (or a) root directory.
561 (or (string= dir dirfile)
562 ;; If this is the same dir we last got the truename for,
563 ;; save time--don't recalculate.
564 (if (assoc dir (car prev-dirs))
565 (setq dir (cdr (assoc dir (car prev-dirs))))
566 (let ((old dir)
567 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
568 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
569 (setq dir new))))
570 (if (equal ".." (file-name-nondirectory filename))
571 (setq filename
572 (directory-file-name (file-name-directory (directory-file-name dir)))
573 done t)
574 (if (equal "." (file-name-nondirectory filename))
575 (setq filename (directory-file-name dir)
576 done t)
577 ;; Put it back on the file name.
578 (setq filename (concat dir (file-name-nondirectory filename)))
579 ;; Is the file name the name of a link?
580 (setq target (file-symlink-p filename))
581 (if target
582 ;; Yes => chase that link, then start all over
583 ;; since the link may point to a directory name that uses links.
584 ;; We can't safely use expand-file-name here
585 ;; since target might look like foo/../bar where foo
586 ;; is itself a link. Instead, we handle . and .. above.
587 (setq filename
588 (if (file-name-absolute-p target)
589 target
590 (concat dir target))
591 done nil)
592 ;; No, we are done!
593 (setq done t))))))))
594 filename))
5dbfdacd 595
5dadeb29
RS
596(defun file-chase-links (filename)
597 "Chase links in FILENAME until a name that is not a link.
598Does not examine containing directories for links,
599unlike `file-truename'."
600 (let (tem (count 100) (newname filename))
601 (while (setq tem (file-symlink-p newname))
9695aac6
RS
602 (save-match-data
603 (if (= count 0)
604 (error "Apparent cycle of symbolic links for %s" filename))
605 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
606 (while (string-match "//+" tem)
607 (setq tem (replace-match "/" nil nil tem)))
608 ;; Handle `..' by hand, since it needs to work in the
609 ;; target of any directory symlink.
610 ;; This code is not quite complete; it does not handle
611 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
612 (while (string-match "\\`\\.\\./" tem)
613 (setq tem (substring tem 3))
614 (setq newname (expand-file-name newname))
615 ;; Chase links in the default dir of the symlink.
616 (setq newname
617 (file-chase-links
618 (directory-file-name (file-name-directory newname))))
619 ;; Now find the parent of that dir.
620 (setq newname (file-name-directory newname)))
621 (setq newname (expand-file-name tem (file-name-directory newname)))
622 (setq count (1- count))))
5dadeb29 623 newname))
b4da00e9 624\f
467ff692
RS
625(defun switch-to-buffer-other-window (buffer &optional norecord)
626 "Select buffer BUFFER in another window.
627Optional second arg NORECORD non-nil means
628do not put this buffer at the front of the list of recently selected ones."
b4da00e9
RM
629 (interactive "BSwitch to buffer in other window: ")
630 (let ((pop-up-windows t))
467ff692 631 (pop-to-buffer buffer t norecord)))
b4da00e9 632
467ff692
RS
633(defun switch-to-buffer-other-frame (buffer &optional norecord)
634 "Switch to buffer BUFFER in another frame.
635Optional second arg NORECORD non-nil means
636do not put this buffer at the front of the list of recently selected ones."
f98955ea
JB
637 (interactive "BSwitch to buffer in other frame: ")
638 (let ((pop-up-frames t))
467ff692 639 (pop-to-buffer buffer t norecord)
336b7f41 640 (raise-frame (window-frame (selected-window)))))
5bbbceb1 641
912192d1 642(defun find-file (filename)
b4da00e9
RM
643 "Edit file FILENAME.
644Switch to a buffer visiting file FILENAME,
912192d1
KH
645creating one if none already exists."
646 (interactive "FFind file: ")
647 (switch-to-buffer (find-file-noselect filename)))
82d0954a 648
912192d1 649(defun find-file-other-window (filename)
b4da00e9
RM
650 "Edit file FILENAME, in another window.
651May create a new window, or reuse an existing one.
652See the function `display-buffer'."
912192d1
KH
653 (interactive "FFind file in other window: ")
654 (switch-to-buffer-other-window (find-file-noselect filename)))
b4da00e9 655
912192d1 656(defun find-file-other-frame (filename)
f98955ea
JB
657 "Edit file FILENAME, in another frame.
658May create a new frame, or reuse an existing one.
5bbbceb1 659See the function `display-buffer'."
912192d1
KH
660 (interactive "FFind file in other frame: ")
661 (switch-to-buffer-other-frame (find-file-noselect filename)))
5bbbceb1 662
912192d1 663(defun find-file-read-only (filename)
b4da00e9
RM
664 "Edit file FILENAME but don't allow changes.
665Like \\[find-file] but marks buffer as read-only.
666Use \\[toggle-read-only] to permit editing."
912192d1
KH
667 (interactive "fFind file read-only: ")
668 (find-file filename)
2a9fe1e2 669 (toggle-read-only 1)
320b4233 670 (current-buffer))
b4da00e9 671
912192d1 672(defun find-file-read-only-other-window (filename)
b4da00e9
RM
673 "Edit file FILENAME in another window but don't allow changes.
674Like \\[find-file-other-window] but marks buffer as read-only.
675Use \\[toggle-read-only] to permit editing."
912192d1
KH
676 (interactive "fFind file read-only other window: ")
677 (find-file-other-window filename)
2a9fe1e2 678 (toggle-read-only 1)
320b4233 679 (current-buffer))
b4da00e9 680
912192d1 681(defun find-file-read-only-other-frame (filename)
f98955ea
JB
682 "Edit file FILENAME in another frame but don't allow changes.
683Like \\[find-file-other-frame] but marks buffer as read-only.
5bbbceb1 684Use \\[toggle-read-only] to permit editing."
912192d1
KH
685 (interactive "fFind file read-only other frame: ")
686 (find-file-other-frame filename)
2a9fe1e2 687 (toggle-read-only 1)
320b4233 688 (current-buffer))
5bbbceb1 689
912192d1 690(defun find-alternate-file-other-window (filename)
60eaf370 691 "Find file FILENAME as a replacement for the file in the next window.
912192d1 692This command does not select that window."
60eaf370
RS
693 (interactive
694 (save-selected-window
695 (other-window 1)
696 (let ((file buffer-file-name)
697 (file-name nil)
698 (file-dir nil))
699 (and file
700 (setq file-name (file-name-nondirectory file)
701 file-dir (file-name-directory file)))
702 (list (read-file-name
912192d1 703 "Find alternate file: " file-dir nil nil file-name)))))
60eaf370 704 (if (one-window-p)
912192d1 705 (find-file-other-window filename)
60eaf370
RS
706 (save-selected-window
707 (other-window 1)
912192d1 708 (find-alternate-file filename))))
60eaf370 709
912192d1 710(defun find-alternate-file (filename)
b4da00e9
RM
711 "Find file FILENAME, select its buffer, kill previous buffer.
712If the current buffer now contains an empty file that you just visited
912192d1 713\(presumably by mistake), use this command to visit the file you really want."
b4da00e9
RM
714 (interactive
715 (let ((file buffer-file-name)
716 (file-name nil)
717 (file-dir nil))
718 (and file
719 (setq file-name (file-name-nondirectory file)
720 file-dir (file-name-directory file)))
a61f59b4 721 (list (read-file-name
912192d1 722 "Find alternate file: " file-dir nil nil file-name))))
2aa8cc2d 723 (and (buffer-modified-p) (buffer-file-name)
b4da00e9
RM
724 ;; (not buffer-read-only)
725 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
726 (buffer-name))))
727 (error "Aborted"))
728 (let ((obuf (current-buffer))
729 (ofile buffer-file-name)
8bb27285
RS
730 (onum buffer-file-number)
731 (otrue buffer-file-truename)
b4da00e9 732 (oname (buffer-name)))
baf9b8c4
RS
733 (if (get-buffer " **lose**")
734 (kill-buffer " **lose**"))
b4da00e9 735 (rename-buffer " **lose**")
b4da00e9
RM
736 (unwind-protect
737 (progn
738 (unlock-buffer)
a4ad4d96
RS
739 (setq buffer-file-name nil)
740 (setq buffer-file-number nil)
741 (setq buffer-file-truename nil)
912192d1 742 (find-file filename))
b4da00e9
RM
743 (cond ((eq obuf (current-buffer))
744 (setq buffer-file-name ofile)
8bb27285
RS
745 (setq buffer-file-number onum)
746 (setq buffer-file-truename otrue)
b4da00e9
RM
747 (lock-buffer)
748 (rename-buffer oname))))
749 (or (eq (current-buffer) obuf)
750 (kill-buffer obuf))))
9b8ef27d 751\f
b4da00e9
RM
752(defun create-file-buffer (filename)
753 "Create a suitably named buffer for visiting FILENAME, and return it.
754FILENAME (sans directory) is used unchanged if that name is free;
755otherwise a string <2> or <3> or ... is appended to get an unused name."
756 (let ((lastname (file-name-nondirectory filename)))
757 (if (string= lastname "")
758 (setq lastname filename))
759 (generate-new-buffer lastname)))
760
5bbbceb1
JB
761(defun generate-new-buffer (name)
762 "Create and return a buffer with a name based on NAME.
29165787 763Choose the buffer's name using `generate-new-buffer-name'."
5bbbceb1
JB
764 (get-buffer-create (generate-new-buffer-name name)))
765
d7fa5aa2 766(defvar automount-dir-prefix "^/tmp_mnt/"
e373f201
JB
767 "Regexp to match the automounter prefix in a directory name.")
768
ffb3a4db 769(defvar abbreviated-home-dir nil
292297c6 770 "The user's homedir abbreviated according to `directory-abbrev-list'.")
ffb3a4db 771
5bbbceb1 772(defun abbreviate-file-name (filename)
29165787 773 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
5bbbceb1 774This also substitutes \"~\" for the user's home directory.
29165787 775Type \\[describe-variable] directory-abbrev-alist RET for more information."
e373f201 776 ;; Get rid of the prefixes added by the automounter.
a8f34fc0
RS
777 (if (and automount-dir-prefix
778 (string-match automount-dir-prefix filename)
e373f201
JB
779 (file-exists-p (file-name-directory
780 (substring filename (1- (match-end 0))))))
781 (setq filename (substring filename (1- (match-end 0)))))
5bbbceb1 782 (let ((tail directory-abbrev-alist))
ffb3a4db
RS
783 ;; If any elt of directory-abbrev-alist matches this name,
784 ;; abbreviate accordingly.
5bbbceb1
JB
785 (while tail
786 (if (string-match (car (car tail)) filename)
787 (setq filename
788 (concat (cdr (car tail)) (substring filename (match-end 0)))))
789 (setq tail (cdr tail)))
ffb3a4db
RS
790 ;; Compute and save the abbreviated homedir name.
791 ;; We defer computing this until the first time it's needed, to
792 ;; give time for directory-abbrev-alist to be set properly.
e98dda89
RS
793 ;; We include a slash at the end, to avoid spurious matches
794 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
ffb3a4db
RS
795 (or abbreviated-home-dir
796 (setq abbreviated-home-dir
797 (let ((abbreviated-home-dir "$foo"))
3a8a836d
RS
798 (concat "^" (abbreviate-file-name (expand-file-name "~"))
799 "\\(/\\|$\\)"))))
76d5492b 800
ffb3a4db
RS
801 ;; If FILENAME starts with the abbreviated homedir,
802 ;; make it start with `~' instead.
ca33ccb5
RS
803 (if (and (string-match abbreviated-home-dir filename)
804 ;; If the home dir is just /, don't change it.
805 (not (and (= (match-end 0) 1)
288201bd 806 (= (aref filename 0) ?/)))
567c1ca9
RS
807 ;; MS-DOS root directories can come with a drive letter;
808 ;; Novell Netware allows drive letters beyond `Z:'.
76d5492b 809 (not (and (or (eq system-type 'ms-dos)
c32d49e8 810 (eq system-type 'windows-nt))
288201bd 811 (save-match-data
567c1ca9 812 (string-match "^[a-zA-`]:/$" filename)))))
5bbbceb1 813 (setq filename
28dbf501 814 (concat "~"
3a8a836d 815 (substring filename (match-beginning 1) (match-end 1))
28dbf501 816 (substring filename (match-end 0)))))
5bbbceb1
JB
817 filename))
818
21540597 819(defcustom find-file-not-true-dirname-list nil
1770543d
RS
820 "*List of logical names for which visiting shouldn't save the true dirname.
821On VMS, when you visit a file using a logical name that searches a path,
822you may or may not want the visited file name to record the specific
823directory where the file was found. If you *do not* want that, add the logical
21540597
RS
824name to this list as a string."
825 :type '(repeat (string :tag "Name"))
826 :group 'find-file)
1770543d 827
138c44f6
KH
828(defun find-buffer-visiting (filename)
829 "Return the buffer visiting file FILENAME (a string).
830This is like `get-file-buffer', except that it checks for any buffer
831visiting the same file, possibly under a different name.
832If there is no such live buffer, return nil."
833 (let ((buf (get-file-buffer filename))
834 (truename (abbreviate-file-name (file-truename filename))))
835 (or buf
836 (let ((list (buffer-list)) found)
837 (while (and (not found) list)
838 (save-excursion
839 (set-buffer (car list))
840 (if (and buffer-file-name
841 (string= buffer-file-truename truename))
842 (setq found (car list))))
843 (setq list (cdr list)))
844 found)
0f933cf6 845 (let ((number (nthcdr 10 (file-attributes truename)))
138c44f6 846 (list (buffer-list)) found)
de88363f
RS
847 (and buffer-file-numbers-unique
848 number
181c830f
RS
849 (while (and (not found) list)
850 (save-excursion
851 (set-buffer (car list))
d49ab5a0
RS
852 (if (and buffer-file-name
853 (equal buffer-file-number number)
181c830f
RS
854 ;; Verify this buffer's file number
855 ;; still belongs to its file.
856 (file-exists-p buffer-file-name)
857 (equal (nthcdr 10 (file-attributes buffer-file-name))
858 number))
859 (setq found (car list))))
860 (setq list (cdr list))))
138c44f6 861 found))))
9b8ef27d 862\f
5de148a2
RS
863(defcustom find-file-wildcards t
864 "*Non-nil means file-visiting commands should handle wildcards.
865For example, if you specify `*.c', that would visit all the files
866whose names match the pattern."
867 :group 'files
868 :type 'boolean)
869
40dfe94d 870(defun find-file-noselect (filename &optional nowarn rawfile)
b4da00e9
RM
871 "Read file FILENAME into a buffer and return the buffer.
872If a buffer exists visiting FILENAME, return that one, but
873verify that the file has not changed since visited or saved.
82d0954a
KH
874The buffer is not selected, just returned to the caller.
875Optional first arg NOWARN non-nil means suppress any warning messages.
e65db7b8 876Optional second arg RAWFILE non-nil means the file is read literally."
e373f201
JB
877 (setq filename
878 (abbreviate-file-name
879 (expand-file-name filename)))
b4da00e9
RM
880 (if (file-directory-p filename)
881 (if find-file-run-dired
4147a3cc
KH
882 (dired-noselect (if find-file-visit-truename
883 (abbreviate-file-name (file-truename filename))
884 filename))
ba369f54 885 (error "%s is a directory" filename))
5de148a2
RS
886 (if (and find-file-wildcards
887 (string-match "[[*?]" filename))
888 (let ((files (file-expand-wildcards filename t))
889 (find-file-wildcards nil))
890 (car (mapcar #'(lambda (fn) (find-file-noselect fn))
891 files)))
892 (let* ((buf (get-file-buffer filename))
893 (truename (abbreviate-file-name (file-truename filename)))
894 (number (nthcdr 10 (file-attributes truename)))
895 ;; Find any buffer for a file which has same truename.
896 (other (and (not buf) (find-buffer-visiting filename))))
897 ;; Let user know if there is a buffer with the same truename.
898 (if other
899 (progn
900 (or nowarn
901 (string-equal filename (buffer-file-name other))
902 (message "%s and %s are the same file"
903 filename (buffer-file-name other)))
904 ;; Optionally also find that buffer.
905 (if (or find-file-existing-other-name find-file-visit-truename)
906 (setq buf other))))
907 (if buf
908 ;; We are using an existing buffer.
909 (progn
910 (or nowarn
911 (verify-visited-file-modtime buf)
912 (cond ((not (file-exists-p filename))
913 (error "File %s no longer exists!" filename))
914 ;; Certain files should be reverted automatically
915 ;; if they have changed on disk and not in the buffer.
916 ((and (not (buffer-modified-p buf))
917 (let ((tail revert-without-query)
918 (found nil))
919 (while tail
920 (if (string-match (car tail) filename)
921 (setq found t))
922 (setq tail (cdr tail)))
923 found))
924 (with-current-buffer buf
925 (message "Reverting file %s..." filename)
926 (revert-buffer t t)
927 (message "Reverting file %s...done" filename)))
928 ((yes-or-no-p
929 (if (string= (file-name-nondirectory filename)
930 (buffer-name buf))
931 (format
932 (if (buffer-modified-p buf)
933 "File %s changed on disk. Discard your edits? "
934 "File %s changed on disk. Reread from disk? ")
935 (file-name-nondirectory filename))
ddd64da9
RS
936 (format
937 (if (buffer-modified-p buf)
5de148a2
RS
938 "File %s changed on disk. Discard your edits in %s? "
939 "File %s changed on disk. Reread from disk into %s? ")
940 (file-name-nondirectory filename)
941 (buffer-name buf))))
942 (with-current-buffer buf
943 (revert-buffer t t)))))
944 (with-current-buffer buf
945 (when (not (eq (not (null rawfile))
946 (not (null find-file-literally))))
947 (if (buffer-modified-p)
ddd64da9 948 (if (y-or-n-p (if rawfile
5de148a2
RS
949 "Save file and revisit literally? "
950 "Save file and revisit non-literally? "))
951 (progn
952 (save-buffer)
953 (find-file-noselect-1 buf filename nowarn
954 rawfile truename number))
955 (if (y-or-n-p (if rawfile
956 "Discard your edits and revisit file literally? "
957 "Discard your edits and revisit file non-literally? "))
958 (find-file-noselect-1 buf filename nowarn
959 rawfile truename number)
960 (error (if rawfile "File already visited non-literally"
961 "File already visited literally"))))
962 (if (y-or-n-p (if rawfile
963 "Revisit file literally? "
964 "Revisit file non-literally? "))
965 (find-file-noselect-1 buf filename nowarn
966 rawfile truename number)
967 (error (if rawfile "File already visited non-literally"
968 "File already visited literally"))))))
969 ;; Return the buffer we are using.
970 buf)
971 ;; Create a new buffer.
972 (setq buf (create-file-buffer filename))
973 (set-buffer-major-mode buf)
974 ;; find-file-noselect-1 may use a different buffer.
975 (find-file-noselect-1 buf filename nowarn
976 rawfile truename number))))))
ddd64da9
RS
977
978(defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
666c1d8b
RS
979 (let ((inhibit-read-only t)
980 error)
ddd64da9
RS
981 (with-current-buffer buf
982 (kill-local-variable 'find-file-literally)
b296cbd4
RS
983 ;; Needed in case we are re-visiting the file with a different
984 ;; text representation.
e73ec04b 985 (kill-local-variable 'buffer-file-coding-system)
ddd64da9
RS
986 (erase-buffer)
987 (and (default-value 'enable-multibyte-characters)
988 (not rawfile)
989 (set-buffer-multibyte t))
990 (if rawfile
991 (condition-case ()
992 (insert-file-contents-literally filename t)
993 (file-error
994 (when (and (file-exists-p filename)
995 (not (file-readable-p filename)))
996 (kill-buffer buf)
997 (signal 'file-error (list "File is not readable"
998 filename)))
999 ;; Unconditionally set error
1000 (setq error t)))
1001 (condition-case ()
1002 (insert-file-contents filename t)
1003 (file-error
1004 (when (and (file-exists-p filename)
1005 (not (file-readable-p filename)))
1006 (kill-buffer buf)
1007 (signal 'file-error (list "File is not readable"
1008 filename)))
1009 ;; Run find-file-not-found-hooks until one returns non-nil.
1010 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
1011 ;; If they fail too, set error.
1012 (setq error t)))))
1013 ;; Find the file's truename, and maybe use that as visited name.
1014 (setq buffer-file-truename truename)
1015 (setq buffer-file-number number)
1016 ;; On VMS, we may want to remember which directory in a search list
1017 ;; the file was found in.
1018 (and (eq system-type 'vax-vms)
1019 (let (logical)
1020 (if (string-match ":" (file-name-directory filename))
1021 (setq logical (substring (file-name-directory filename)
1022 0 (match-beginning 0))))
1023 (not (member logical find-file-not-true-dirname-list)))
1024 (setq buffer-file-name buffer-file-truename))
1025 (if find-file-visit-truename
1026 (setq buffer-file-name
1027 (setq filename
1028 (expand-file-name buffer-file-truename))))
1029 ;; Set buffer's default directory to that of the file.
1030 (setq default-directory (file-name-directory filename))
1031 ;; Turn off backup files for certain file names. Since
1032 ;; this is a permanent local, the major mode won't eliminate it.
1033 (and (not (funcall backup-enable-predicate buffer-file-name))
1034 (progn
1035 (make-local-variable 'backup-inhibited)
1036 (setq backup-inhibited t)))
1037 (if rawfile
1038 (progn
1039 (set-buffer-multibyte nil)
1040 (setq buffer-file-coding-system 'no-conversion)
1041 (make-local-variable 'find-file-literally)
1042 (setq find-file-literally t))
b296cbd4
RS
1043 (after-find-file error (not nowarn)))
1044 (current-buffer))))
9b8ef27d
RS
1045\f
1046(defun insert-file-contents-literally (filename &optional visit beg end replace)
1047 "Like `insert-file-contents', but only reads in the file literally.
1048A buffer may be modified in several ways after reading into the buffer,
1049to Emacs features such as format decoding, character code
1050conversion, find-file-hooks, automatic uncompression, etc.
1051
1052This function ensures that none of these modifications will take place."
1053 (let ((format-alist nil)
1054 (after-insert-file-functions nil)
1055 (coding-system-for-read 'no-conversion)
1056 (coding-system-for-write 'no-conversion)
1057 (jka-compr-compression-info-list nil)
1058 (find-buffer-file-type-function
1059 (if (fboundp 'find-buffer-file-type)
1060 (symbol-function 'find-buffer-file-type)
1061 nil)))
1062 (unwind-protect
1063 (progn
1064 (fset 'find-buffer-file-type (lambda (filename) t))
1065 (insert-file-contents filename visit beg end replace))
1066 (if find-buffer-file-type-function
1067 (fset 'find-buffer-file-type find-buffer-file-type-function)
1068 (fmakunbound 'find-buffer-file-type)))))
1069
1070(defun insert-file-literally (filename)
1071 "Insert contents of file FILENAME into buffer after point with no conversion.
1072
1073This function is meant for the user to run interactively.
1074Don't call it from programs! Use `insert-file-contents-literally' instead.
1075\(Its calling sequence is different; see its documentation)."
1076 (interactive "*fInsert file literally: ")
1077 (if (file-directory-p filename)
1078 (signal 'file-error (list "Opening input file" "file is a directory"
1079 filename)))
1080 (let ((tem (insert-file-contents-literally filename)))
1081 (push-mark (+ (point) (car (cdr tem))))))
1082
1083(defvar find-file-literally nil
1084 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1085This is a permanent local.")
1086(put 'find-file-literally 'permanent-local t)
5fc196af
RS
1087
1088(defun find-file-literally (filename)
1089 "Visit file FILENAME with no conversion of any kind.
1090Format conversion and character code conversion are both disabled,
1091and multibyte characters are disabled in the resulting buffer.
e65db7b8
RS
1092The major mode used is Fundamental mode regardless of the file name,
1093and local variable specifications in the file are ignored.
9b8ef27d
RS
1094Automatic uncompression is also disabled.
1095
1096You cannot absolutely rely on this function to result in
b9aa9537 1097visiting the file literally. If Emacs already has a buffer
9b8ef27d
RS
1098which is visiting the file, you get the existing buffer,
1099regardless of whether it was created literally or not.
1100
1101In a Lisp program, if you want to be sure of accessing a file's
1102contents literally, you should create a temporary buffer and then read
1103the file contents into it using `insert-file-contents-literally'."
5fc196af 1104 (interactive "FFind file literally: ")
9b8ef27d 1105 (switch-to-buffer (find-file-noselect filename nil t)))
b4da00e9 1106\f
f7d786d0
RS
1107(defvar after-find-file-from-revert-buffer nil)
1108
e0ab8879 1109(defun after-find-file (&optional error warn noauto
9a30563f
RS
1110 after-find-file-from-revert-buffer
1111 nomodes)
b4da00e9
RM
1112 "Called after finding a file and by the default revert function.
1113Sets buffer mode, parses local variables.
8cfb9d46 1114Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
b4da00e9
RM
1115error in reading the file. WARN non-nil means warn if there
1116exists an auto-save file more recent than the visited file.
8cfb9d46 1117NOAUTO means don't mess with auto-save mode.
e0ab8879
RS
1118Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1119 means this call was from `revert-buffer'.
9a30563f
RS
1120Fifth arg NOMODES non-nil means don't alter the file's modes.
1121Finishes by calling the functions in `find-file-hooks'
1122unless NOMODES is non-nil."
b4da00e9
RM
1123 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1124 (if noninteractive
1125 nil
1126 (let* (not-serious
1127 (msg
1128 (cond ((and error (file-attributes buffer-file-name))
1129 (setq buffer-read-only t)
ff78d520 1130 "File exists, but cannot be read.")
b4da00e9
RM
1131 ((not buffer-read-only)
1132 (if (and warn
1133 (file-newer-than-file-p (make-auto-save-file-name)
1134 buffer-file-name))
6a6a0b8b
RS
1135 (format "%s has auto save data; consider M-x recover-file"
1136 (file-name-nondirectory buffer-file-name))
b4da00e9
RM
1137 (setq not-serious t)
1138 (if error "(New file)" nil)))
1139 ((not error)
1140 (setq not-serious t)
1141 "Note: file is write protected")
1142 ((file-attributes (directory-file-name default-directory))
1143 "File not found and directory write-protected")
4e43240a
RS
1144 ((file-exists-p (file-name-directory buffer-file-name))
1145 (setq buffer-read-only nil))
b4da00e9 1146 (t
5bbbceb1 1147 (setq buffer-read-only nil)
4e43240a
RS
1148 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1149 "Use M-x make-dir RET RET to create the directory"
1150 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
b4da00e9
RM
1151 (if msg
1152 (progn
1153 (message msg)
1154 (or not-serious (sit-for 1 nil t)))))
8cfb9d46 1155 (if (and auto-save-default (not noauto))
b4da00e9 1156 (auto-save-mode t)))
9a30563f
RS
1157 (if nomodes
1158 nil
1159 (normal-mode t)
2a9fe1e2
RS
1160 (if (and buffer-read-only view-read-only
1161 (not (eq (get major-mode 'mode-class) 'special)))
1162 (view-mode-enter))
9a30563f 1163 (run-hooks 'find-file-hooks)))
b4da00e9
RM
1164
1165(defun normal-mode (&optional find-file)
1166 "Choose the major mode for this buffer automatically.
1167Also sets up any specified local variables of the file.
1168Uses the visited file name, the -*- line, and the local variables spec.
1169
1170This function is called automatically from `find-file'. In that case,
1171we may set up specified local variables depending on the value of
1172`enable-local-variables': if it is t, we do; if it is nil, we don't;
1173otherwise, we query. `enable-local-variables' is ignored if you
1174run `normal-mode' explicitly."
1175 (interactive)
1176 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1177 (condition-case err
1178 (set-auto-mode)
1179 (error (message "File mode specification error: %s"
1180 (prin1-to-string err))))
1181 (condition-case err
7b3f3dc2
JB
1182 (let ((enable-local-variables (or (not find-file)
1183 enable-local-variables)))
1184 (hack-local-variables))
b4da00e9
RM
1185 (error (message "File local-variables error: %s"
1186 (prin1-to-string err)))))
1187
f76e0cd0 1188(defvar auto-mode-alist
567c1ca9 1189 '(("\\.te?xt\\'" . text-mode)
f76e0cd0
RS
1190 ("\\.c\\'" . c-mode)
1191 ("\\.h\\'" . c-mode)
1192 ("\\.tex\\'" . tex-mode)
1193 ("\\.ltx\\'" . latex-mode)
1194 ("\\.el\\'" . emacs-lisp-mode)
f76e0cd0
RS
1195 ("\\.scm\\'" . scheme-mode)
1196 ("\\.l\\'" . lisp-mode)
1197 ("\\.lisp\\'" . lisp-mode)
1198 ("\\.f\\'" . fortran-mode)
0254679b 1199 ("\\.F\\'" . fortran-mode)
f76e0cd0
RS
1200 ("\\.for\\'" . fortran-mode)
1201 ("\\.p\\'" . pascal-mode)
1202 ("\\.pas\\'" . pascal-mode)
f76e0cd0 1203 ("\\.ad[abs]\\'" . ada-mode)
ebff6b7d 1204 ("\\.\\([pP][Llm]\\|al\\)\\'" . perl-mode)
f89cbd61 1205 ("\\.s?html?\\'" . html-mode)
f76e0cd0
RS
1206 ("\\.cc\\'" . c++-mode)
1207 ("\\.hh\\'" . c++-mode)
bfc6cac9 1208 ("\\.hpp\\'" . c++-mode)
f76e0cd0
RS
1209 ("\\.C\\'" . c++-mode)
1210 ("\\.H\\'" . c++-mode)
1211 ("\\.cpp\\'" . c++-mode)
1212 ("\\.cxx\\'" . c++-mode)
1213 ("\\.hxx\\'" . c++-mode)
1214 ("\\.c\\+\\+\\'" . c++-mode)
1215 ("\\.h\\+\\+\\'" . c++-mode)
1fbd6d0f 1216 ("\\.m\\'" . objc-mode)
95b53225 1217 ("\\.java\\'" . java-mode)
f76e0cd0 1218 ("\\.mk\\'" . makefile-mode)
d5637fa5 1219 ("\\(M\\|m\\|GNUm\\)akefile\\(\\.in\\)?\\'" . makefile-mode)
3ad08c11 1220 ("\\.am\\'" . makefile-mode) ;For Automake.
7b3f3dc2
JB
1221;;; Less common extensions come here
1222;;; so more common ones above are found faster.
f76e0cd0 1223 ("\\.texinfo\\'" . texinfo-mode)
567c1ca9 1224 ("\\.te?xi\\'" . texinfo-mode)
f76e0cd0 1225 ("\\.s\\'" . asm-mode)
600a5f71
KH
1226 ("\\.S\\'" . asm-mode)
1227 ("\\.asm\\'" . asm-mode)
f76e0cd0 1228 ("ChangeLog\\'" . change-log-mode)
d5637fa5 1229 ("change\\.log\\'" . change-log-mode)
f76e0cd0 1230 ("changelo\\'" . change-log-mode)
d5637fa5 1231 ("ChangeLog\\.[0-9]+\\'" . change-log-mode)
6e6f5d9e
RS
1232 ;; for MSDOS and MS-Windows (which are case-insensitive)
1233 ("changelog\\'" . change-log-mode)
d5637fa5 1234 ("changelog\\.[0-9]+\\'" . change-log-mode)
f76e0cd0
RS
1235 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1236 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
7458cc35 1237 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
d45da3e1
KH
1238 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1239 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1240 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
1554c03b 1241 ("\\.m?spec$" . sh-mode)
823a266d
DN
1242 ("\\.mm\\'" . nroff-mode)
1243 ("\\.me\\'" . nroff-mode)
1244 ("\\.ms\\'" . nroff-mode)
1245 ("\\.man\\'" . nroff-mode)
c1fe251a
KH
1246;;; The following should come after the ChangeLog pattern
1247;;; for the sake of ChangeLog.1, etc.
1248;;; and after the .scm.[0-9] pattern too.
f76e0cd0
RS
1249 ("\\.[12345678]\\'" . nroff-mode)
1250 ("\\.TeX\\'" . tex-mode)
1251 ("\\.sty\\'" . latex-mode)
1252 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
16cb44dd 1253 ("\\.clo\\'" . latex-mode) ;LaTeX 2e class option
f76e0cd0
RS
1254 ("\\.bbl\\'" . latex-mode)
1255 ("\\.bib\\'" . bibtex-mode)
6c4fd436
RS
1256 ("\\.m4\\'" . m4-mode)
1257 ("\\.mc\\'" . m4-mode)
16cb44dd
RS
1258 ("\\.mf\\'" . metafont-mode)
1259 ("\\.mp\\'" . metapost-mode)
798f4b0a 1260 ("\\.vhdl?\\'" . vhdl-mode)
f76e0cd0
RS
1261 ("\\.article\\'" . text-mode)
1262 ("\\.letter\\'" . text-mode)
1263 ("\\.tcl\\'" . tcl-mode)
e1ec01c2 1264 ("\\.exp\\'" . tcl-mode)
c87c4cda
KH
1265 ("\\.itcl\\'" . tcl-mode)
1266 ("\\.itk\\'" . tcl-mode)
f89cbd61
RS
1267 ("\\.icn\\'" . icon-mode)
1268 ("\\.sim\\'" . simula-mode)
1269 ("\\.mss\\'" . scribe-mode)
f76e0cd0
RS
1270 ("\\.f90\\'" . f90-mode)
1271 ("\\.lsp\\'" . lisp-mode)
1272 ("\\.awk\\'" . awk-mode)
1273 ("\\.prolog\\'" . prolog-mode)
1274 ("\\.tar\\'" . tar-mode)
b1667e6c
GV
1275 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|jar\\)\\'" . archive-mode)
1276 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|JAR\\)\\'" . archive-mode)
f76e0cd0
RS
1277 ;; Mailer puts message to be edited in
1278 ;; /tmp/Re.... or Message
628b6035 1279 ("\\`/tmp/Re" . text-mode)
f76e0cd0
RS
1280 ("/Message[0-9]*\\'" . text-mode)
1281 ("/drafts/[0-9]+\\'" . mh-letter-mode)
e13322a0 1282 ("\\.zone\\'" . zone-mode)
f76e0cd0 1283 ;; some news reader is reported to use this
628b6035 1284 ("\\`/tmp/fol/" . text-mode)
f76e0cd0
RS
1285 ("\\.y\\'" . c-mode)
1286 ("\\.lex\\'" . c-mode)
1287 ("\\.oak\\'" . scheme-mode)
693f800d 1288 ("\\.sgml?\\'" . sgml-mode)
86e0d956 1289 ("\\.xml\\'" . sgml-mode)
f76e0cd0 1290 ("\\.dtd\\'" . sgml-mode)
c2c84cd7 1291 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
271e0f2c 1292 ("\\.idl\\'" . idl-mode)
f76e0cd0 1293 ;; .emacs following a directory delimiter
24813e13
RS
1294 ;; in Unix, MSDOG or VMS syntax.
1295 ("[]>:/\\]\\..*emacs\\'" . emacs-lisp-mode)
d5637fa5 1296 ("\\`\\..*emacs\\'" . emacs-lisp-mode)
f76e0cd0
RS
1297 ;; _emacs following a directory delimiter
1298 ;; in MsDos syntax
1299 ("[:/]_emacs\\'" . emacs-lisp-mode)
a2236dc6
KH
1300 ("\\.ml\\'" . lisp-mode)
1301 ("\\.asn$" . snmp-mode)
1302 ("\\.mib$" . snmp-mode)
1303 ("\\.smi$" . snmp-mode)
1304 ("\\.as2$" . snmpv2-mode)
1305 ("\\.mi2$" . snmpv2-mode)
1306 ("\\.sm2$" . snmpv2-mode))
7b3f3dc2
JB
1307 "\
1308Alist of filename patterns vs corresponding major mode functions.
116987ba
RS
1309Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1310\(NON-NIL stands for anything that is not nil; the value does not matter.)
1311Visiting a file whose name matches REGEXP specifies FUNCTION as the
1312mode function to use. FUNCTION will be called, unless it is nil.
1313
1314If the element has the form (REGEXP FUNCTION NON-NIL), then after
1315calling FUNCTION (if it's not nil), we delete the suffix that matched
1316REGEXP and search the list again for another match.")
7b3f3dc2 1317
e13322a0 1318
d7fa5aa2 1319(defvar interpreter-mode-alist
c907d156 1320 '(("perl" . perl-mode)
e049945b 1321 ("perl5" . perl-mode)
ebff6b7d 1322 ("miniperl" . perl-mode)
c907d156 1323 ("wish" . tcl-mode)
e3998da1 1324 ("wishx" . tcl-mode)
8db739de 1325 ("tcl" . tcl-mode)
e3998da1 1326 ("tclsh" . tcl-mode)
8db739de 1327 ("awk" . awk-mode)
dfeadd84 1328 ("mawk" . awk-mode)
d4f567a1 1329 ("nawk" . awk-mode)
8db739de 1330 ("gawk" . awk-mode)
d1194c85
RS
1331 ("scm" . scheme-mode)
1332 ("ash" . sh-mode)
1333 ("bash" . sh-mode)
1334 ("csh" . sh-mode)
1335 ("dtksh" . sh-mode)
1336 ("es" . sh-mode)
1337 ("itcsh" . sh-mode)
1338 ("jsh" . sh-mode)
1339 ("ksh" . sh-mode)
1340 ("oash" . sh-mode)
1341 ("pdksh" . sh-mode)
1342 ("rc" . sh-mode)
1554c03b 1343 ("rpm" . sh-mode)
d1194c85
RS
1344 ("sh" . sh-mode)
1345 ("sh5" . sh-mode)
1346 ("tcsh" . sh-mode)
1347 ("wksh" . sh-mode)
1348 ("wsh" . sh-mode)
1349 ("zsh" . sh-mode)
1350 ("tail" . text-mode)
1351 ("more" . text-mode)
1352 ("less" . text-mode)
1353 ("pg" . text-mode))
c907d156
RS
1354 "Alist mapping interpreter names to major modes.
1355This alist applies to files whose first line starts with `#!'.
1356Each element looks like (INTERPRETER . MODE).
1357The car of each element is compared with
1358the name of the interpreter specified in the first line.
1359If it matches, mode MODE is selected.")
1360
d7fa5aa2 1361(defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
45fb3bb8 1362 "List of regexps; if one matches a file name, don't look for `-*-'.")
a0c9f21b 1363
d7fa5aa2 1364(defvar inhibit-first-line-modes-suffixes nil
b20ff6d0
RS
1365 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1366When checking `inhibit-first-line-modes-regexps', we first discard
1367from the end of the file name anything that matches one of these regexps.")
1368
da09b92b
RS
1369(defvar user-init-file nil
1370 "File name, including directory, of user's initialization file.")
bb157910 1371
9de9b6a2 1372(defun set-auto-mode (&optional just-from-file-name)
b4da00e9 1373 "Select major mode appropriate for current buffer.
e3998da1
RS
1374This checks for a -*- mode tag in the buffer's text,
1375compares the filename against the entries in `auto-mode-alist',
1376or checks the interpreter that runs this file against
1377`interpreter-mode-alist'.
1378
1379It does not check for the `mode:' local variable in the
1380Local Variables section of the file; for that, use `hack-local-variables'.
7b3f3dc2 1381
f3e23606 1382If `enable-local-variables' is nil, this function does not check for a
9de9b6a2
RS
1383-*- mode tag.
1384
1385If the optional argument JUST-FROM-FILE-NAME is non-nil,
1386then we do not set anything but the major mode,
1387and we don't even do that unless it would come from the file name."
b4da00e9 1388 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
d0fc03ef 1389 (let (beg end done modes)
b4da00e9
RM
1390 (save-excursion
1391 (goto-char (point-min))
1392 (skip-chars-forward " \t\n")
9fa7bfe5 1393 (and enable-local-variables
da09b92b 1394 local-enable-local-variables
9fa7bfe5 1395 ;; Don't look for -*- if this file name matches any
45fb3bb8 1396 ;; of the regexps in inhibit-first-line-modes-regexps.
cae111fa 1397 (let ((temp inhibit-first-line-modes-regexps)
4bc3d240
RS
1398 (name (if buffer-file-name
1399 (file-name-sans-versions buffer-file-name)
1400 (buffer-name))))
38832b4c
KH
1401 (while (let ((sufs inhibit-first-line-modes-suffixes))
1402 (while (and sufs (not (string-match (car sufs) name)))
1403 (setq sufs (cdr sufs)))
1404 sufs)
1405 (setq name (substring name 0 (match-beginning 0))))
9fa7bfe5 1406 (while (and temp
b20ff6d0 1407 (not (string-match (car temp) name)))
9fa7bfe5
RS
1408 (setq temp (cdr temp)))
1409 (not temp))
1410 (search-forward "-*-" (save-excursion
1411 ;; If the file begins with "#!"
1412 ;; (exec interpreter magic), look
1413 ;; for mode frobs in the first two
1414 ;; lines. You cannot necessarily
1415 ;; put them in the first line of
1416 ;; such a file without screwing up
1417 ;; the interpreter invocation.
1418 (end-of-line (and (looking-at "^#!") 2))
1419 (point)) t)
1420 (progn
1421 (skip-chars-forward " \t")
1422 (setq beg (point))
1423 (search-forward "-*-"
1424 (save-excursion (end-of-line) (point))
1425 t))
1426 (progn
1427 (forward-char -3)
1428 (skip-chars-backward " \t")
1429 (setq end (point))
1430 (goto-char beg)
1431 (if (save-excursion (search-forward ":" end t))
1432 ;; Find all specifications for the `mode:' variable
57a0155c 1433 ;; and execute them left to right.
9fa7bfe5 1434 (while (let ((case-fold-search t))
6054fcc6
KH
1435 (or (and (looking-at "mode:")
1436 (goto-char (match-end 0)))
1437 (re-search-forward "[ \t;]mode:" end t)))
9fa7bfe5
RS
1438 (skip-chars-forward " \t")
1439 (setq beg (point))
1440 (if (search-forward ";" end t)
1441 (forward-char -1)
1442 (goto-char end))
1443 (skip-chars-backward " \t")
d0fc03ef
RS
1444 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1445 modes)))
9fa7bfe5 1446 ;; Simple -*-MODE-*- case.
d0fc03ef
RS
1447 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1448 "-mode"))
1449 modes))))))
1450 ;; If we found modes to use, invoke them now,
1451 ;; outside the save-excursion.
83c6f446
RS
1452 (when modes
1453 (unless just-from-file-name
1454 (mapcar 'funcall (nreverse modes)))
1455 (setq done t))
d0fc03ef
RS
1456 ;; If we didn't find a mode from a -*- line, try using the file name.
1457 (if (and (not done) buffer-file-name)
1458 (let ((name buffer-file-name)
1459 (keep-going t))
1460 ;; Remove backup-suffixes from file name.
1461 (setq name (file-name-sans-versions name))
1462 (while keep-going
1463 (setq keep-going nil)
1464 (let ((alist auto-mode-alist)
1465 (mode nil))
1466 ;; Find first matching alist entry.
76d5492b 1467 (let ((case-fold-search
d0fc03ef
RS
1468 (memq system-type '(vax-vms windows-nt))))
1469 (while (and (not mode) alist)
1470 (if (string-match (car (car alist)) name)
1471 (if (and (consp (cdr (car alist)))
1472 (nth 2 (car alist)))
1473 (progn
1474 (setq mode (car (cdr (car alist)))
1475 name (substring name 0 (match-beginning 0))
1476 keep-going t))
1477 (setq mode (cdr (car alist))
1478 keep-going nil)))
1479 (setq alist (cdr alist))))
1480 (if mode
3b9ffb77
RS
1481 ;; When JUST-FROM-FILE-NAME is set,
1482 ;; we are working on behalf of set-visited-file-name.
1483 ;; In that case, if the major mode specified is the
1484 ;; same one we already have, don't actually reset it.
1485 ;; We don't want to lose minor modes such as Font Lock.
1486 (unless (and just-from-file-name (eq mode major-mode))
1487 (funcall mode))
d0fc03ef
RS
1488 ;; If we can't deduce a mode from the file name,
1489 ;; look for an interpreter specified in the first line.
1540e4e9
KH
1490 ;; As a special case, allow for things like "#!/bin/env perl",
1491 ;; which finds the interpreter anywhere in $PATH.
d0fc03ef
RS
1492 (let ((interpreter
1493 (save-excursion
1494 (goto-char (point-min))
dfeadd84 1495 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1540e4e9
KH
1496 (buffer-substring (match-beginning 2)
1497 (match-end 2))
d0fc03ef
RS
1498 "")))
1499 elt)
1500 ;; Map interpreter name to a mode.
1501 (setq elt (assoc (file-name-nondirectory interpreter)
1502 interpreter-mode-alist))
9de9b6a2
RS
1503 (unless just-from-file-name
1504 (if elt
1505 (funcall (cdr elt))))))))))))
b4da00e9 1506
f3e23606
RS
1507(defun hack-local-variables-prop-line ()
1508 ;; Set local variables specified in the -*- line.
3fa0a9aa
KH
1509 ;; Ignore any specification for `mode:' and `coding:';
1510 ;; set-auto-mode should already have handled `mode:',
1511 ;; set-auto-coding should already have handled `coding:'.
f3e23606
RS
1512 (save-excursion
1513 (goto-char (point-min))
13a66180
KH
1514 (let ((result nil)
1515 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
f3e23606
RS
1516 ;; Parse the -*- line into the `result' alist.
1517 (cond ((not (search-forward "-*-" end t))
1518 ;; doesn't have one.
1519 nil)
1520 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
13a66180
KH
1521 ;; Simple form: "-*- MODENAME -*-". Already handled.
1522 nil)
f3e23606
RS
1523 (t
1524 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1525 ;; (last ";" is optional).
1526 (save-excursion
1527 (if (search-forward "-*-" end t)
1528 (setq end (- (point) 3))
1529 (error "-*- not terminated before end of line")))
1530 (while (< (point) end)
1531 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1532 (error "malformed -*- line"))
1533 (goto-char (match-end 0))
1c26a6f3
KH
1534 ;; There used to be a downcase here,
1535 ;; but the manual didn't say so,
1536 ;; and people want to set var names that aren't all lc.
1537 (let ((key (intern (buffer-substring
1538 (match-beginning 1)
1539 (match-end 1))))
f3e23606
RS
1540 (val (save-restriction
1541 (narrow-to-region (point) end)
1542 (read (current-buffer)))))
93a2702d
RS
1543 ;; It is traditional to ignore
1544 ;; case when checking for `mode' in set-auto-mode,
1545 ;; so we must do that here as well.
1546 ;; That is inconsistent, but we're stuck with it.
3fa0a9aa 1547 ;; The same can be said for `coding' in set-auto-coding.
93a2702d 1548 (or (equal (downcase (symbol-name key)) "mode")
3fa0a9aa 1549 (equal (downcase (symbol-name key)) "coding")
13a66180 1550 (setq result (cons (cons key val) result)))
f3e23606
RS
1551 (skip-chars-forward " \t;")))
1552 (setq result (nreverse result))))
76d5492b 1553
f3e23606
RS
1554 (if (and result
1555 (or (eq enable-local-variables t)
1556 (and enable-local-variables
1557 (save-window-excursion
6f931919
RS
1558 (condition-case nil
1559 (switch-to-buffer (current-buffer))
1560 (error
1561 ;; If we fail to switch in the selected window,
1562 ;; it is probably a minibuffer.
1563 ;; So try another window.
1564 (condition-case nil
1565 (switch-to-buffer-other-window (current-buffer))
1566 (error
1567 (switch-to-buffer-other-frame (current-buffer))))))
f3e23606
RS
1568 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1569 (file-name-nondirectory buffer-file-name)))))))
2837b9df
RS
1570 (let ((enable-local-eval enable-local-eval))
1571 (while result
1572 (hack-one-local-variable (car (car result)) (cdr (car result)))
1573 (setq result (cdr result))))))))
f3e23606 1574
1d517019
RS
1575(defvar hack-local-variables-hook nil
1576 "Normal hook run after processing a file's local variables specs.
1577Major modes can use this to examine user-specified local variables
1578in order to initialize other data structure based on them.")
1579
9de9b6a2
RS
1580(defun hack-local-variables (&optional mode-only)
1581 "Parse and put into effect this buffer's local variables spec.
1582If MODE-ONLY is non-nil, all we do is check whether the major mode
1583is specified, returning t if it is specified."
1584 (unless mode-only
1585 (hack-local-variables-prop-line))
b4da00e9 1586 ;; Look for "Local variables:" line in last page.
9de9b6a2
RS
1587 (let (mode-specified)
1588 (save-excursion
1589 (goto-char (point-max))
1590 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1591 (if (let ((case-fold-search t))
1592 (and (search-forward "Local Variables:" nil t)
1593 (or (eq enable-local-variables t)
1594 mode-only
1595 (and enable-local-variables
1596 (save-window-excursion
1597 (switch-to-buffer (current-buffer))
1598 (save-excursion
1599 (beginning-of-line)
1600 (set-window-start (selected-window) (point)))
1601 (y-or-n-p (format "Set local variables as specified at end of %s? "
1602 (if buffer-file-name
1603 (file-name-nondirectory
1604 buffer-file-name)
1605 (concat "buffer "
1606 (buffer-name))))))))))
1607 (let ((continue t)
1608 prefix prefixlen suffix beg
1609 mode-specified
1610 (enable-local-eval enable-local-eval))
1611 ;; The prefix is what comes before "local variables:" in its line.
1612 ;; The suffix is what comes after "local variables:" in its line.
b4da00e9 1613 (skip-chars-forward " \t")
9de9b6a2
RS
1614 (or (eolp)
1615 (setq suffix (buffer-substring (point)
1616 (progn (end-of-line) (point)))))
1617 (goto-char (match-beginning 0))
1618 (or (bolp)
1619 (setq prefix
1620 (buffer-substring (point)
1621 (progn (beginning-of-line) (point)))))
1622
1623 (if prefix (setq prefixlen (length prefix)
1624 prefix (regexp-quote prefix)))
1625 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1626 (while continue
1627 ;; Look at next local variable spec.
1628 (if selective-display (re-search-forward "[\n\C-m]")
1629 (forward-line 1))
1630 ;; Skip the prefix, if any.
1631 (if prefix
1632 (if (looking-at prefix)
1633 (forward-char prefixlen)
1634 (error "Local variables entry is missing the prefix")))
1635 ;; Find the variable name; strip whitespace.
1636 (skip-chars-forward " \t")
1637 (setq beg (point))
1638 (skip-chars-forward "^:\n")
1639 (if (eolp) (error "Missing colon in local variables entry"))
1640 (skip-chars-backward " \t")
1641 (let* ((str (buffer-substring beg (point)))
1642 (var (read str))
1643 val)
1644 ;; Setting variable named "end" means end of list.
1645 (if (string-equal (downcase str) "end")
1646 (setq continue nil)
1647 ;; Otherwise read the variable value.
1648 (skip-chars-forward "^:")
1649 (forward-char 1)
1650 (setq val (read (current-buffer)))
1651 (skip-chars-backward "\n")
1652 (skip-chars-forward " \t")
1653 (or (if suffix (looking-at suffix) (eolp))
1654 (error "Local variables entry is terminated incorrectly"))
1655 (if mode-only
1656 (if (eq var 'mode)
1657 (setq mode-specified t))
1658 ;; Set the variable. "Variables" mode and eval are funny.
1659 (hack-one-local-variable var val))))))))
1660 (unless mode-only
1661 (run-hooks 'hack-local-variables-hook))
1662 mode-specified))
f3e23606 1663
d7fa5aa2 1664(defvar ignored-local-variables
f3e23606
RS
1665 '(enable-local-eval)
1666 "Variables to be ignored in a file's local variable spec.")
1667
be0218a8 1668;; Get confirmation before setting these variables as locals in a file.
05ef1cda 1669(put 'debugger 'risky-local-variable t)
f6fa3ee3 1670(put 'enable-local-eval 'risky-local-variable t)
fce47eea 1671(put 'ignored-local-variables 'risky-local-variable t)
be0218a8
RS
1672(put 'eval 'risky-local-variable t)
1673(put 'file-name-handler-alist 'risky-local-variable t)
1674(put 'minor-mode-map-alist 'risky-local-variable t)
1675(put 'after-load-alist 'risky-local-variable t)
f6fa3ee3
RS
1676(put 'buffer-file-name 'risky-local-variable t)
1677(put 'buffer-auto-save-file-name 'risky-local-variable t)
1678(put 'buffer-file-truename 'risky-local-variable t)
b0ffcc0d
RS
1679(put 'exec-path 'risky-local-variable t)
1680(put 'load-path 'risky-local-variable t)
1681(put 'exec-directory 'risky-local-variable t)
1682(put 'process-environment 'risky-local-variable t)
eba1c87a
RS
1683(put 'dabbrev-case-fold-search 'risky-local-variable t)
1684(put 'dabbrev-case-replace 'risky-local-variable t)
9afa8bf7
RS
1685;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1686(put 'outline-level 'risky-local-variable t)
d98b741d 1687(put 'rmail-output-file-alist 'risky-local-variable t)
f6fa3ee3 1688
6672c42b
RS
1689;; This one is safe because the user gets to check it before it is used.
1690(put 'compile-command 'safe-local-variable t)
1691
d0bd3513
RS
1692(defun hack-one-local-variable-quotep (exp)
1693 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1694
f3e23606
RS
1695;; "Set" one variable in a local variables spec.
1696;; A few variable names are treated specially.
1697(defun hack-one-local-variable (var val)
1698 (cond ((eq var 'mode)
1699 (funcall (intern (concat (downcase (symbol-name val))
1700 "-mode"))))
3fa0a9aa
KH
1701 ((eq var 'coding)
1702 ;; We have already handled coding: tag in set-auto-coding.
1703 nil)
f3e23606
RS
1704 ((memq var ignored-local-variables)
1705 nil)
1706 ;; "Setting" eval means either eval it or do nothing.
7d3221d7 1707 ;; Likewise for setting hook variables.
be0218a8 1708 ((or (get var 'risky-local-variable)
6672c42b 1709 (and
04d807e6 1710 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$\\|-predicate$"
6672c42b
RS
1711 (symbol-name var))
1712 (not (get var 'safe-local-variable))))
0225ae5e 1713 ;; Permit evalling a put of a harmless property.
d0bd3513
RS
1714 ;; if the args do nothing tricky.
1715 (if (or (and (eq var 'eval)
1716 (consp val)
1717 (eq (car val) 'put)
1718 (hack-one-local-variable-quotep (nth 1 val))
1719 (hack-one-local-variable-quotep (nth 2 val))
1720 ;; Only allow safe values of lisp-indent-hook;
1721 ;; not functions.
1722 (or (numberp (nth 3 val))
dc417415 1723 (equal (nth 3 val) ''defun))
d0bd3513
RS
1724 (memq (nth 1 (nth 2 val))
1725 '(lisp-indent-hook)))
1726 ;; Permit eval if not root and user says ok.
c7e62660 1727 (and (not (zerop (user-uid)))
d0bd3513
RS
1728 (or (eq enable-local-eval t)
1729 (and enable-local-eval
1730 (save-window-excursion
1731 (switch-to-buffer (current-buffer))
1732 (save-excursion
1733 (beginning-of-line)
1734 (set-window-start (selected-window) (point)))
1735 (setq enable-local-eval
1736 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1737 (file-name-nondirectory buffer-file-name)))))))))
7d3221d7
RS
1738 (if (eq var 'eval)
1739 (save-excursion (eval val))
1740 (make-local-variable var)
1741 (set var val))
f3e23606
RS
1742 (message "Ignoring `eval:' in file's local variables")))
1743 ;; Ordinary variable, really set it.
1744 (t (make-local-variable var)
1745 (set var val))))
1746
b4da00e9 1747\f
21540597 1748(defcustom change-major-mode-with-file-name t
9de9b6a2
RS
1749 "*Non-nil means \\[write-file] should set the major mode from the file name.
1750However, the mode will not be changed if
1751\(1) a local variables list or the `-*-' line specifies a major mode, or
1752\(2) the current major mode is a \"special\" mode,
8609911b 1753\ not suitable for ordinary files, or
21540597
RS
1754\(3) the new file name does not particularly specify any mode."
1755 :type 'boolean
1756 :group 'editing-basics)
9de9b6a2 1757
f36012a6 1758(defun set-visited-file-name (filename &optional no-query along-with-file)
b4da00e9
RM
1759 "Change name of file visited in current buffer to FILENAME.
1760The next time the buffer is saved it will go in the newly specified file.
1761nil or empty string as argument means make buffer not be visiting any file.
1762Remember to delete the initial contents of the minibuffer
6a6b62f8
RS
1763if you wish to pass an empty string as the argument.
1764
1765The optional second argument NO-QUERY, if non-nil, inhibits asking for
f36012a6
RS
1766confirmation in the case where another buffer is already visiting FILENAME.
1767
1768The optional third argument ALONG-WITH-FILE, if non-nil, means that
1769the old visited file has been renamed to the new name FILENAME."
b4da00e9 1770 (interactive "FSet visited file name: ")
c11a94fe
RS
1771 (if (buffer-base-buffer)
1772 (error "An indirect buffer cannot visit a file"))
a522e5bf
RS
1773 (let (truename)
1774 (if filename
1775 (setq filename
1776 (if (string-equal filename "")
1777 nil
1778 (expand-file-name filename))))
1779 (if filename
1780 (progn
1781 (setq truename (file-truename filename))
1782 (if find-file-visit-truename
a522e5bf 1783 (setq filename truename))))
11e314fa 1784 (let ((buffer (and filename (find-buffer-visiting filename))))
7b89d38e 1785 (and buffer (not (eq buffer (current-buffer)))
6a6b62f8 1786 (not no-query)
7b89d38e
RS
1787 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1788 filename)))
1789 (error "Aborted")))
a522e5bf
RS
1790 (or (equal filename buffer-file-name)
1791 (progn
1792 (and filename (lock-buffer filename))
1793 (unlock-buffer)))
1794 (setq buffer-file-name filename)
1795 (if filename ; make buffer name reflect filename.
1796 (let ((new-name (file-name-nondirectory buffer-file-name)))
1797 (if (string= new-name "")
1798 (error "Empty file name"))
1799 (if (eq system-type 'vax-vms)
1800 (setq new-name (downcase new-name)))
1801 (setq default-directory (file-name-directory buffer-file-name))
1802 (or (string= new-name (buffer-name))
1803 (rename-buffer new-name t))))
1804 (setq buffer-backed-up nil)
f36012a6
RS
1805 (or along-with-file
1806 (clear-visited-file-modtime))
8ccdc29e 1807 ;; Abbreviate the file names of the buffer.
4826e97f 1808 (if truename
8ccdc29e
RS
1809 (progn
1810 (setq buffer-file-truename (abbreviate-file-name truename))
1811 (if find-file-visit-truename
1812 (setq buffer-file-name buffer-file-truename))))
a522e5bf
RS
1813 (setq buffer-file-number
1814 (if filename
2a47b4f5 1815 (nthcdr 10 (file-attributes buffer-file-name))
a522e5bf 1816 nil)))
b4da00e9
RM
1817 ;; write-file-hooks is normally used for things like ftp-find-file
1818 ;; that visit things that are not local files as if they were files.
1819 ;; Changing to visit an ordinary local file instead should flush the hook.
1820 (kill-local-variable 'write-file-hooks)
c9dca4e0 1821 (kill-local-variable 'local-write-file-hooks)
b4da00e9
RM
1822 (kill-local-variable 'revert-buffer-function)
1823 (kill-local-variable 'backup-inhibited)
ee81c959
RS
1824 ;; If buffer was read-only because of version control,
1825 ;; that reason is gone now, so make it writable.
1826 (if vc-mode
1827 (setq buffer-read-only nil))
1828 (kill-local-variable 'vc-mode)
b4da00e9
RM
1829 ;; Turn off backup files for certain file names.
1830 ;; Since this is a permanent local, the major mode won't eliminate it.
4d49551a
KH
1831 (and buffer-file-name
1832 (not (funcall backup-enable-predicate buffer-file-name))
b4da00e9
RM
1833 (progn
1834 (make-local-variable 'backup-inhibited)
1835 (setq backup-inhibited t)))
c77a81cf
RS
1836 (let ((oauto buffer-auto-save-file-name))
1837 ;; If auto-save was not already on, turn it on if appropriate.
1838 (if (not buffer-auto-save-file-name)
1839 (and buffer-file-name auto-save-default
1840 (auto-save-mode t))
1841 ;; If auto save is on, start using a new name.
1842 ;; We deliberately don't rename or delete the old auto save
1843 ;; for the old visited file name. This is because perhaps
1844 ;; the user wants to save the new state and then compare with the
1845 ;; previous state from the auto save file.
1846 (setq buffer-auto-save-file-name
1847 (make-auto-save-file-name)))
1848 ;; Rename the old auto save file if any.
1849 (and oauto buffer-auto-save-file-name
e6f0e76c 1850 (file-exists-p oauto)
c77a81cf 1851 (rename-file oauto buffer-auto-save-file-name t)))
f36012a6
RS
1852 (and buffer-file-name
1853 (not along-with-file)
9de9b6a2
RS
1854 (set-buffer-modified-p t))
1855 ;; Update the major mode, if the file name determines it.
1856 (condition-case nil
1857 ;; Don't change the mode if it is special.
1858 (or (not change-major-mode-with-file-name)
1859 (get major-mode 'mode-class)
1860 ;; Don't change the mode if the local variable list specifies it.
1861 (hack-local-variables t)
1862 (set-auto-mode t))
1863 (error nil)))
b4da00e9 1864
912192d1 1865(defun write-file (filename &optional confirm)
b4da00e9 1866 "Write current buffer into file FILENAME.
41f48cb1
RS
1867Makes buffer visit that file, and marks it not modified.
1868If the buffer is already visiting a file, you can specify
1869a directory name as FILENAME, to write a file of the same
c2fb8488 1870old name in that directory.
7458cc35 1871
c2fb8488 1872If optional second arg CONFIRM is non-nil,
7458cc35 1873ask for confirmation for overwriting an existing file.
912192d1 1874Interactively, confirmation is required unless you supply a prefix argument."
b4da00e9
RM
1875;; (interactive "FWrite file: ")
1876 (interactive
1877 (list (if buffer-file-name
1878 (read-file-name "Write file: "
1879 nil nil nil nil)
1880 (read-file-name "Write file: "
1881 (cdr (assq 'default-directory
1882 (buffer-local-variables)))
04d807e6 1883 nil nil (file-name-nondirectory (buffer-name))))
912192d1 1884 (not current-prefix-arg)))
b4da00e9 1885 (or (null filename) (string-equal filename "")
41f48cb1
RS
1886 (progn
1887 ;; If arg is just a directory,
1888 ;; use same file name, but in that directory.
1889 (if (and (file-directory-p filename) buffer-file-name)
1890 (setq filename (concat (file-name-as-directory filename)
1891 (file-name-nondirectory buffer-file-name))))
c2fb8488
RS
1892 (and confirm
1893 (file-exists-p filename)
1894 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1895 (error "Canceled")))
5f65549e 1896 (set-visited-file-name filename (not confirm))))
b4da00e9 1897 (set-buffer-modified-p t)
6492b55d
KH
1898 ;; Make buffer writable if file is writable.
1899 (and buffer-file-name
1900 (file-writable-p buffer-file-name)
1901 (setq buffer-read-only nil))
912192d1 1902 (save-buffer))
b4da00e9
RM
1903\f
1904(defun backup-buffer ()
1905 "Make a backup of the disk file visited by the current buffer, if appropriate.
1906This is normally done before saving the buffer the first time.
1907If the value is non-nil, it is the result of `file-modes' on the original
1908file; this means that the caller, after saving the buffer, should change
27ab6944
KH
1909the modes of the new file to agree with the old modes.
1910
1911A backup may be done by renaming or by copying; see documentation of
1912variable `make-backup-files'. If it's done by renaming, then the file is
1913no longer accessible under its old name."
b4da00e9
RM
1914 (if (and make-backup-files (not backup-inhibited)
1915 (not buffer-backed-up)
1916 (file-exists-p buffer-file-name)
1917 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1918 '(?- ?l)))
1919 (let ((real-file-name buffer-file-name)
1920 backup-info backupname targets setmodes)
1921 ;; If specified name is a symbolic link, chase it to the target.
1922 ;; Thus we make the backups in the directory where the real file is.
5dadeb29 1923 (setq real-file-name (file-chase-links real-file-name))
b4da00e9
RM
1924 (setq backup-info (find-backup-file-name real-file-name)
1925 backupname (car backup-info)
1926 targets (cdr backup-info))
1927;;; (if (file-directory-p buffer-file-name)
1928;;; (error "Cannot save buffer in directory %s" buffer-file-name))
eb650569
RS
1929 (if backup-info
1930 (condition-case ()
1931 (let ((delete-old-versions
1932 ;; If have old versions to maybe delete,
1933 ;; ask the user to confirm now, before doing anything.
1934 ;; But don't actually delete til later.
1935 (and targets
1936 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1937 (or delete-old-versions
1938 (y-or-n-p (format "Delete excess backup versions of %s? "
1939 real-file-name))))))
1940 ;; Actually write the back up file.
1941 (condition-case ()
1942 (if (or file-precious-flag
1943 ; (file-symlink-p buffer-file-name)
1944 backup-by-copying
1945 (and backup-by-copying-when-linked
1946 (> (file-nlinks real-file-name) 1))
1947 (and backup-by-copying-when-mismatch
1948 (let ((attr (file-attributes real-file-name)))
1949 (or (nth 9 attr)
1950 (not (file-ownership-preserved-p real-file-name))))))
1951 (condition-case ()
1952 (copy-file real-file-name backupname t t)
1953 (file-error
1954 ;; If copying fails because file BACKUPNAME
1955 ;; is not writable, delete that file and try again.
1956 (if (and (file-exists-p backupname)
1957 (not (file-writable-p backupname)))
1958 (delete-file backupname))
1959 (copy-file real-file-name backupname t t)))
1960 ;; rename-file should delete old backup.
1961 (rename-file real-file-name backupname t)
1962 (setq setmodes (file-modes backupname)))
1963 (file-error
1964 ;; If trouble writing the backup, write it in ~.
567c1ca9
RS
1965 (setq backupname (expand-file-name
1966 (convert-standard-filename
1967 "~/%backup%~")))
1968 (message "Cannot write backup file; backing up in %s"
1969 (file-name-nondirectory backupname))
eb650569
RS
1970 (sleep-for 1)
1971 (condition-case ()
1972 (copy-file real-file-name backupname t t)
1973 (file-error
1974 ;; If copying fails because file BACKUPNAME
1975 ;; is not writable, delete that file and try again.
1976 (if (and (file-exists-p backupname)
1977 (not (file-writable-p backupname)))
1978 (delete-file backupname))
1979 (copy-file real-file-name backupname t t)))))
1980 (setq buffer-backed-up t)
1981 ;; Now delete the old versions, if desired.
1982 (if delete-old-versions
1983 (while targets
1984 (condition-case ()
1985 (delete-file (car targets))
1986 (file-error nil))
1987 (setq targets (cdr targets))))
1988 setmodes)
1989 (file-error nil))))))
b4da00e9 1990
c3554e95 1991(defun file-name-sans-versions (name &optional keep-backup-version)
b4da00e9
RM
1992 "Return FILENAME sans backup versions or strings.
1993This is a separate procedure so your site-init or startup file can
c3554e95
RS
1994redefine it.
1995If the optional argument KEEP-BACKUP-VERSION is non-nil,
1996we do not remove backup version numbers, only true file version numbers."
6eaebaa2 1997 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
c3554e95
RS
1998 (if handler
1999 (funcall handler 'file-name-sans-versions name keep-backup-version)
2000 (substring name 0
2001 (if (eq system-type 'vax-vms)
2002 ;; VMS version number is (a) semicolon, optional
2003 ;; sign, zero or more digits or (b) period, option
2004 ;; sign, zero or more digits, provided this is the
2005 ;; second period encountered outside of the
2006 ;; device/directory part of the file name.
26add1bf
KH
2007 (or (string-match ";[-+]?[0-9]*\\'" name)
2008 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
c3554e95
RS
2009 name)
2010 (match-beginning 1))
2011 (length name))
2012 (if keep-backup-version
2013 (length name)
dbb12f2c 2014 (or (string-match "\\.~[0-9.]+~\\'" name)
c3554e95
RS
2015 (string-match "~\\'" name)
2016 (length name))))))))
b4da00e9 2017
cb0cd911
RS
2018(defun file-ownership-preserved-p (file)
2019 "Returns t if deleting FILE and rewriting it would preserve the owner."
2020 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
2021 (if handler
2022 (funcall handler 'file-ownership-preserved-p file)
ec5533be 2023 (let ((attributes (file-attributes file)))
306faa42
RS
2024 ;; Return t if the file doesn't exist, since it's true that no
2025 ;; information would be lost by an (attempted) delete and create.
2026 (or (null attributes)
2027 (= (nth 2 attributes) (user-uid)))))))
cb0cd911 2028
20b5d24c
RS
2029(defun file-name-sans-extension (filename)
2030 "Return FILENAME sans final \"extension\".
2031The extension, in a file name, is the part that follows the last `.'."
2032 (save-match-data
2033 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
2034 directory)
2035 (if (string-match "\\.[^.]*\\'" file)
2036 (if (setq directory (file-name-directory filename))
2037 (expand-file-name (substring file 0 (match-beginning 0))
2038 directory)
2039 (substring file 0 (match-beginning 0)))
2040 filename))))
2041
93a2702d
RS
2042(defun file-name-extension (filename &optional period)
2043 "Return FILENAME's final \"extension\".
2044The extension, in a file name, is the part that follows the last `.'.
2045Return nil for extensionless file names such as `foo'.
2046Return the empty string for file names such as `foo.'.
2047
2048If PERIOD is non-nil, then the returned value includes the period
2049that delimits the extension, and if FILENAME has no extension,
2050the value is \"\"."
2051 (save-match-data
2052 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
2053 (if (string-match "\\.[^.]*\\'" file)
2054 (substring file (+ (match-beginning 0) (if period 0 1)))
2055 (if period
2056 "")))))
2057
b4da00e9
RM
2058(defun make-backup-file-name (file)
2059 "Create the non-numeric backup file name for FILE.
2060This is a separate function so you can redefine it for customization."
28ee503c
KH
2061 (if (and (eq system-type 'ms-dos)
2062 (not (msdos-long-file-names)))
bb157910
RS
2063 (let ((fn (file-name-nondirectory file)))
2064 (concat (file-name-directory file)
066327ae
KH
2065 (or
2066 (and (string-match "\\`[^.]+\\'" fn)
2067 (concat (match-string 0 fn) ".~"))
2068 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
2069 (concat (match-string 0 fn) "~")))))
bb157910 2070 (concat file "~")))
b4da00e9
RM
2071
2072(defun backup-file-name-p (file)
2073 "Return non-nil if FILE is a backup file name (numeric or not).
2074This is a separate function so you can redefine it for customization.
2075You may need to redefine `file-name-sans-versions' as well."
066327ae 2076 (string-match "~\\'" file))
b4da00e9 2077
e2b30772
RS
2078(defvar backup-extract-version-start)
2079
2d051399
RS
2080;; This is used in various files.
2081;; The usage of bv-length is not very clean,
2082;; but I can't see a good alternative,
2083;; so as of now I am leaving it alone.
2084(defun backup-extract-version (fn)
2085 "Given the name of a numeric backup file, return the backup number.
e2b30772 2086Uses the free variable `backup-extract-version-start', whose value should be
2d051399 2087the index in the name where the version number begins."
e2b30772
RS
2088 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
2089 (= (match-beginning 0) backup-extract-version-start))
2090 (string-to-int (substring fn backup-extract-version-start -1))
2d051399
RS
2091 0))
2092
b4da00e9
RM
2093;; I believe there is no need to alter this behavior for VMS;
2094;; since backup files are not made on VMS, it should not get called.
2095(defun find-backup-file-name (fn)
2096 "Find a file name for a backup file, and suggestions for deletions.
2097Value is a list whose car is the name for the backup file
eb650569
RS
2098 and whose cdr is a list of old versions to consider deleting now.
2099If the value is nil, don't make a backup."
2100 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2101 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2102 (if handler
2103 (funcall handler 'find-backup-file-name fn)
2104 (if (eq version-control 'never)
b4da00e9 2105 (list (make-backup-file-name fn))
eb650569 2106 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
e2b30772 2107 (backup-extract-version-start (length base-versions))
eb650569
RS
2108 possibilities
2109 (versions nil)
2110 (high-water-mark 0)
2111 (deserve-versions-p nil)
2112 (number-to-delete 0))
2113 (condition-case ()
2114 (setq possibilities (file-name-all-completions
2115 base-versions
2116 (file-name-directory fn))
2117 versions (sort (mapcar
2118 (function backup-extract-version)
2119 possibilities)
2120 '<)
2121 high-water-mark (apply 'max 0 versions)
2122 deserve-versions-p (or version-control
2123 (> high-water-mark 0))
2124 number-to-delete (- (length versions)
2125 kept-old-versions kept-new-versions -1))
2126 (file-error
2127 (setq possibilities nil)))
2128 (if (not deserve-versions-p)
2129 (list (make-backup-file-name fn))
2130 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
2131 (if (and (> number-to-delete 0)
2132 ;; Delete nothing if there is overflow
2133 ;; in the number of versions to keep.
2134 (>= (+ kept-new-versions kept-old-versions -1) 0))
2135 (mapcar (function (lambda (n)
2136 (concat fn ".~" (int-to-string n) "~")))
2137 (let ((v (nthcdr kept-old-versions versions)))
2138 (rplacd (nthcdr (1- number-to-delete) v) ())
2139 v))))))))))
b4da00e9 2140
b4da00e9
RM
2141(defun file-nlinks (filename)
2142 "Return number of names file FILENAME has."
2143 (car (cdr (file-attributes filename))))
6c636af9
RM
2144
2145(defun file-relative-name (filename &optional directory)
2d6562a5
RS
2146 "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
2147This function returns a relative file name which is equivalent to FILENAME
2148when used with that default directory as the default.
2149If this is impossible (which can happen on MSDOS and Windows
2150when the file name and directory use different drive names)
2151then it returns FILENAME."
96c188b0 2152 (save-match-data
e2b30772
RS
2153 (let ((fname (expand-file-name filename)))
2154 (setq directory (file-name-as-directory
2155 (expand-file-name (or directory default-directory))))
2156 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2157 ;; drive names, they can't be relative, so return the absolute name.
2158 (if (and (or (eq system-type 'ms-dos)
2159 (eq system-type 'windows-nt))
2160 (not (string-equal (substring fname 0 2)
2161 (substring directory 0 2))))
2162 filename
9695aac6
RS
2163 (let ((ancestor ".")
2164 (fname-dir (file-name-as-directory fname)))
2165 (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
2166 (not (string-match (concat "^" (regexp-quote directory)) fname)))
e2b30772 2167 (setq directory (file-name-directory (substring directory 0 -1))
9695aac6
RS
2168 ancestor (if (equal ancestor ".")
2169 ".."
2170 (concat "../" ancestor))))
2171 ;; Now ancestor is empty, or .., or ../.., etc.
2172 (if (string-match (concat "^" (regexp-quote directory)) fname)
2173 ;; We matched within FNAME's directory part.
2174 ;; Add the rest of FNAME onto ANCESTOR.
2175 (let ((rest (substring fname (match-end 0))))
2176 (if (and (equal ancestor ".")
2177 (not (equal rest "")))
2178 ;; But don't bother with ANCESTOR if it would give us `./'.
2179 rest
2180 (concat (file-name-as-directory ancestor) rest)))
2181 ;; We matched FNAME's directory equivalent.
2182 ancestor))))))
b4da00e9
RM
2183\f
2184(defun save-buffer (&optional args)
2185 "Save current buffer in visited file if modified. Versions described below.
2186By default, makes the previous version into a backup file
2187 if previously requested or if this is the first save.
ac9650be 2188With 1 \\[universal-argument], marks this version
b4da00e9 2189 to become a backup when the next save is done.
ac9650be 2190With 2 \\[universal-argument]'s,
b4da00e9 2191 unconditionally makes the previous version into a backup file.
ac9650be
RS
2192With 3 \\[universal-argument]'s, marks this version
2193 to become a backup when the next save is done,
2194 and unconditionally makes the previous version into a backup file.
2195
749d2ee6 2196With argument of 0, never make the previous version into a backup file.
b4da00e9
RM
2197
2198If a file's name is FOO, the names of its numbered backup versions are
2199 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2200Numeric backups (rather than FOO~) will be made if value of
2201 `version-control' is not the atom `never' and either there are already
2202 numeric versions of the file being backed up, or `version-control' is
2203 non-nil.
2204We don't want excessive versions piling up, so there are variables
2205 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2206 and `kept-new-versions', which tells how many newest versions to keep.
2207 Defaults are 2 old versions and 2 new.
2208`dired-kept-versions' controls dired's clean-directory (.) command.
de7d5e1b 2209If `delete-old-versions' is nil, system will query user
e73ec04b
RS
2210 before trimming versions. Otherwise it does it silently.
2211
749d2ee6
RS
2212If `vc-make-backup-files' is nil, which is the default,
2213 no backup files are made for files managed by version control.
2214 (This is because the version control system itself records previous versions.)
2215
e73ec04b 2216See the subroutine `basic-save-buffer' for more information."
b4da00e9
RM
2217 (interactive "p")
2218 (let ((modp (buffer-modified-p))
2219 (large (> (buffer-size) 50000))
b5a8e0fc
RS
2220 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2221 (memq args '(16 64)))))
b4da00e9
RM
2222 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2223 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
2224 (basic-save-buffer)
2225 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2226
2227(defun delete-auto-save-file-if-necessary (&optional force)
2228 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2229Normally delete only if the file was written by this Emacs since
2230the last real save, but optional arg FORCE non-nil means delete anyway."
2231 (and buffer-auto-save-file-name delete-auto-save-files
2232 (not (string= buffer-file-name buffer-auto-save-file-name))
2233 (or force (recent-auto-save-p))
2234 (progn
2235 (condition-case ()
2236 (delete-file buffer-auto-save-file-name)
2237 (file-error nil))
2238 (set-buffer-auto-saved))))
2239
1cc852cc
RS
2240(defvar after-save-hook nil
2241 "Normal hook that is run after a buffer is saved to its file.")
2242
0516edee
RS
2243(defvar save-buffer-coding-system nil
2244 "If non-nil, use this coding system for saving the buffer.
2245More precisely, use this coding system in place of the
2246value of `buffer-file-coding-system', when saving the buffer.
2247Calling `write-region' for any purpose other than saving the buffer
2248will still use `buffer-file-coding-system'; this variable has no effect
2249in such cases.")
2250
d5fe94cc
RS
2251(make-variable-buffer-local 'save-buffer-coding-system)
2252(put 'save-buffer-coding-system 'permanent-local t)
2253
b4da00e9 2254(defun basic-save-buffer ()
1cc852cc 2255 "Save the current buffer in its visited file, if it has been modified.
e73ec04b
RS
2256The hooks `write-contents-hooks', `local-write-file-hooks' and
2257`write-file-hooks' get a chance to do the job of saving; if they do not,
2258then the buffer is saved in the visited file file in the usual way.
2259After saving the buffer, this function runs `after-save-hook'."
b4da00e9 2260 (interactive)
19618231 2261 (save-current-buffer
c11a94fe
RS
2262 ;; In an indirect buffer, save its base buffer instead.
2263 (if (buffer-base-buffer)
2264 (set-buffer (buffer-base-buffer)))
2265 (if (buffer-modified-p)
2266 (let ((recent-save (recent-auto-save-p))
2267 setmodes tempsetmodes)
2268 ;; On VMS, rename file and buffer to get rid of version number.
2269 (if (and (eq system-type 'vax-vms)
2270 (not (string= buffer-file-name
2271 (file-name-sans-versions buffer-file-name))))
2272 (let (buffer-new-name)
2273 ;; Strip VMS version number before save.
2274 (setq buffer-file-name
2275 (file-name-sans-versions buffer-file-name))
2276 ;; Construct a (unique) buffer name to correspond.
2277 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2278 (setq buffer-new-name (buffer-name buf))
2279 (kill-buffer buf))
2280 (rename-buffer buffer-new-name)))
2281 ;; If buffer has no file name, ask user for one.
2282 (or buffer-file-name
182891ef
RS
2283 (let ((filename
2284 (expand-file-name
2285 (read-file-name "File to save in: ") nil)))
2286 (and (file-exists-p filename)
2287 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2288 filename))
2289 (error "Canceled")))
2290 (set-visited-file-name filename)))
c11a94fe
RS
2291 (or (verify-visited-file-modtime (current-buffer))
2292 (not (file-exists-p buffer-file-name))
2293 (yes-or-no-p
2294 (format "%s has changed since visited or saved. Save anyway? "
2295 (file-name-nondirectory buffer-file-name)))
2296 (error "Save not confirmed"))
2297 (save-restriction
2298 (widen)
19618231
RS
2299 (save-excursion
2300 (and (> (point-max) 1)
2301 (/= (char-after (1- (point-max))) ?\n)
2302 (not (and (eq selective-display t)
2303 (= (char-after (1- (point-max))) ?\r)))
2304 (or (eq require-final-newline t)
2305 (and require-final-newline
2306 (y-or-n-p
2307 (format "Buffer %s does not end in newline. Add one? "
2308 (buffer-name)))))
2309 (save-excursion
2310 (goto-char (point-max))
2311 (insert ?\n))))
c11a94fe
RS
2312 (or (run-hook-with-args-until-success 'write-contents-hooks)
2313 (run-hook-with-args-until-success 'local-write-file-hooks)
2314 (run-hook-with-args-until-success 'write-file-hooks)
2315 ;; If a hook returned t, file is already "written".
2316 ;; Otherwise, write it the usual way now.
2317 (setq setmodes (basic-save-buffer-1)))
d6e8ea6f
KH
2318 ;; Now we have saved the current buffer. Let's make sure
2319 ;; that buffer-file-coding-system is fixed to what
2320 ;; actually used for saving by binding it locally.
0516edee
RS
2321 (if save-buffer-coding-system
2322 (setq save-buffer-coding-system last-coding-system-used)
2323 (setq buffer-file-coding-system last-coding-system-used))
2a47b4f5
RS
2324 (setq buffer-file-number
2325 (nthcdr 10 (file-attributes buffer-file-name)))
c11a94fe
RS
2326 (if setmodes
2327 (condition-case ()
2328 (set-file-modes buffer-file-name setmodes)
2329 (error nil))))
2330 ;; If the auto-save file was recent before this command,
2331 ;; delete it now.
2332 (delete-auto-save-file-if-necessary recent-save)
49530862
RS
2333 ;; Support VC `implicit' locking.
2334 (vc-after-save)
c11a94fe
RS
2335 (run-hooks 'after-save-hook))
2336 (message "(No changes need to be saved)"))))
b4da00e9 2337
87d26afc
RS
2338;; This does the "real job" of writing a buffer into its visited file
2339;; and making a backup file. This is what is normally done
2340;; but inhibited if one of write-file-hooks returns non-nil.
2341;; It returns a value to store in setmodes.
2342(defun basic-save-buffer-1 ()
d5fe94cc
RS
2343 (if save-buffer-coding-system
2344 (let ((coding-system-for-write save-buffer-coding-system))
2345 (basic-save-buffer-2))
2346 (basic-save-buffer-2)))
2347
2348(defun basic-save-buffer-2 ()
2349 (let (tempsetmodes setmodes)
87d26afc
RS
2350 (if (not (file-writable-p buffer-file-name))
2351 (let ((dir (file-name-directory buffer-file-name)))
2352 (if (not (file-directory-p dir))
83c6f446
RS
2353 (if (file-exists-p dir)
2354 (error "%s is not a directory" dir)
cb2fdcfa 2355 (error "%s: no such directory" buffer-file-name))
87d26afc
RS
2356 (if (not (file-exists-p buffer-file-name))
2357 (error "Directory %s write-protected" dir)
2358 (if (yes-or-no-p
2359 (format "File %s is write-protected; try to save anyway? "
2360 (file-name-nondirectory
2361 buffer-file-name)))
2362 (setq tempsetmodes t)
2363 (error "Attempt to save to a file which you aren't allowed to write"))))))
2364 (or buffer-backed-up
2365 (setq setmodes (backup-buffer)))
76d5492b 2366 (let ((dir (file-name-directory buffer-file-name)))
f4a0f59b
RS
2367 (if (and file-precious-flag
2368 (file-writable-p dir))
2369 ;; If file is precious, write temp name, then rename it.
2370 ;; This requires write access to the containing dir,
2371 ;; which is why we don't try it if we don't have that access.
2372 (let ((realname buffer-file-name)
6782610c
RS
2373 tempname temp nogood i succeed
2374 (old-modtime (visited-file-modtime)))
f4a0f59b
RS
2375 (setq i 0)
2376 (setq nogood t)
2377 ;; Find the temporary name to write under.
2378 (while nogood
567c1ca9 2379 (setq tempname (format
28ee503c
KH
2380 (if (and (eq system-type 'ms-dos)
2381 (not (msdos-long-file-names)))
567c1ca9
RS
2382 "%s#%d.tm#" ; MSDOS limits files to 8+3
2383 "%s#tmp#%d")
2384 dir i))
f4a0f59b
RS
2385 (setq nogood (file-exists-p tempname))
2386 (setq i (1+ i)))
2387 (unwind-protect
2388 (progn (clear-visited-file-modtime)
2389 (write-region (point-min) (point-max)
89095962
RS
2390 tempname nil realname
2391 buffer-file-truename)
f4a0f59b
RS
2392 (setq succeed t))
2393 ;; If writing the temp file fails,
2394 ;; delete the temp file.
76d5492b 2395 (or succeed
6782610c
RS
2396 (progn
2397 (delete-file tempname)
2398 (set-visited-file-modtime old-modtime))))
f4a0f59b
RS
2399 ;; Since we have created an entirely new file
2400 ;; and renamed it, make sure it gets the
2401 ;; right permission bits set.
2402 (setq setmodes (file-modes buffer-file-name))
2403 ;; We succeeded in writing the temp file,
2404 ;; so rename it.
2405 (rename-file tempname buffer-file-name t))
2406 ;; If file not writable, see if we can make it writable
2407 ;; temporarily while we write it.
2408 ;; But no need to do so if we have just backed it up
2409 ;; (setmodes is set) because that says we're superseding.
2410 (cond ((and tempsetmodes (not setmodes))
2411 ;; Change the mode back, after writing.
2412 (setq setmodes (file-modes buffer-file-name))
2413 (set-file-modes buffer-file-name 511)))
2414 (write-region (point-min) (point-max)
89095962 2415 buffer-file-name nil t buffer-file-truename)))
87d26afc
RS
2416 setmodes))
2417
b4da00e9
RM
2418(defun save-some-buffers (&optional arg exiting)
2419 "Save some modified file-visiting buffers. Asks user about each one.
5bbbceb1
JB
2420Optional argument (the prefix) non-nil means save all with no questions.
2421Optional second argument EXITING means ask about certain non-file buffers
2422 as well as about file buffers."
b4da00e9 2423 (interactive "P")
907482b9 2424 (save-window-excursion
76d5492b
RM
2425 (let* ((queried nil)
2426 (files-done
2427 (map-y-or-n-p
2428 (function
2429 (lambda (buffer)
2430 (and (buffer-modified-p buffer)
2431 (not (buffer-base-buffer buffer))
2432 (or
2433 (buffer-file-name buffer)
2434 (and exiting
2435 (progn
2436 (set-buffer buffer)
2437 (and buffer-offer-save (> (buffer-size) 0)))))
2438 (if arg
2439 t
2440 (setq queried t)
2441 (if (buffer-file-name buffer)
2442 (format "Save file %s? "
2443 (buffer-file-name buffer))
2444 (format "Save buffer %s? "
2445 (buffer-name buffer)))))))
2446 (function
2447 (lambda (buffer)
2448 (set-buffer buffer)
2449 (save-buffer)))
2450 (buffer-list)
2451 '("buffer" "buffers" "save")
2452 (list (list ?\C-r (lambda (buf)
2a9fe1e2
RS
2453 (view-buffer buf
2454 (function
2455 (lambda (ignore)
2456 (exit-recursive-edit))))
76d5492b
RM
2457 (recursive-edit)
2458 ;; Return nil to ask about BUF again.
2459 nil)
2460 "display the current buffer"))))
2461 (abbrevs-done
2462 (and save-abbrevs abbrevs-changed
2463 (progn
2464 (if (or arg
2465 (y-or-n-p (format "Save abbrevs in %s? "
2466 abbrev-file-name)))
2467 (write-abbrev-file nil))
2468 ;; Don't keep bothering user if he says no.
2469 (setq abbrevs-changed nil)
2470 t))))
2471 (or queried (> files-done 0) abbrevs-done
5625c2fc 2472 (message "(No files need saving)")))))
b4da00e9
RM
2473\f
2474(defun not-modified (&optional arg)
2475 "Mark current buffer as unmodified, not needing to be saved.
a641f9a1
RM
2476With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2477
2478It is not a good idea to use this function in Lisp programs, because it
2479prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
b4da00e9
RM
2480 (interactive "P")
2481 (message (if arg "Modification-flag set"
2482 "Modification-flag cleared"))
2483 (set-buffer-modified-p arg))
2484
2485(defun toggle-read-only (&optional arg)
2486 "Change whether this buffer is visiting its file read-only.
2a9fe1e2
RS
2487With arg, set read-only iff arg is positive.
2488If visiting file read-only and `view-read-only' is non-nil, enter view mode."
b4da00e9 2489 (interactive "P")
2a9fe1e2
RS
2490 (cond
2491 ((and arg (if (> (prefix-numeric-value arg) 0) buffer-read-only
2492 (not buffer-read-only))) ; If buffer-read-only is set correctly,
2493 nil) ; do nothing.
2494 ;; Toggle.
2495 ((and buffer-read-only view-mode)
ca597f41
KH
2496 (View-exit-and-edit)
2497 (make-local-variable 'view-read-only)
2498 (setq view-read-only t)) ; Must leave view mode.
2a9fe1e2
RS
2499 ((and (not buffer-read-only) view-read-only
2500 (not (eq (get major-mode 'mode-class) 'special)))
2501 (view-mode-enter))
2502 (t (setq buffer-read-only (not buffer-read-only))
2503 (force-mode-line-update))))
b4da00e9 2504
912192d1 2505(defun insert-file (filename)
b4da00e9
RM
2506 "Insert contents of file FILENAME into buffer after point.
2507Set mark after the inserted text.
2508
2509This function is meant for the user to run interactively.
2510Don't call it from programs! Use `insert-file-contents' instead.
2511\(Its calling sequence is different; see its documentation)."
912192d1 2512 (interactive "*fInsert file: ")
3be6243a
RS
2513 (if (file-directory-p filename)
2514 (signal 'file-error (list "Opening input file" "file is a directory"
2515 filename)))
912192d1 2516 (let ((tem (insert-file-contents filename)))
b4da00e9
RM
2517 (push-mark (+ (point) (car (cdr tem))))))
2518
912192d1 2519(defun append-to-file (start end filename)
b4da00e9
RM
2520 "Append the contents of the region to the end of file FILENAME.
2521When called from a function, expects three arguments,
2522START, END and FILENAME. START and END are buffer positions
da30bf98 2523saying what text to write."
912192d1
KH
2524 (interactive "r\nFAppend to file: ")
2525 (write-region start end filename t))
b4da00e9
RM
2526
2527(defun file-newest-backup (filename)
2528 "Return most recent backup file for FILENAME or nil if no backups exist."
2529 (let* ((filename (expand-file-name filename))
2530 (file (file-name-nondirectory filename))
2531 (dir (file-name-directory filename))
2532 (comp (file-name-all-completions file dir))
cf7e94a0
RS
2533 (newest nil)
2534 tem)
b4da00e9 2535 (while comp
cf7e94a0 2536 (setq tem (car comp)
b4da00e9 2537 comp (cdr comp))
cf7e94a0
RS
2538 (cond ((and (backup-file-name-p tem)
2539 (string= (file-name-sans-versions tem) file))
2540 (setq tem (concat dir tem))
2541 (if (or (null newest)
2542 (file-newer-than-file-p tem newest))
2543 (setq newest tem)))))
b4da00e9
RM
2544 newest))
2545
2546(defun rename-uniquely ()
2547 "Rename current buffer to a similar name not already taken.
2548This function is useful for creating multiple shell process buffers
2549or multiple mail buffers, etc."
2550 (interactive)
40eb8038 2551 (save-match-data
e0df3aef
KH
2552 (let ((base-name (buffer-name)))
2553 (and (string-match "<[0-9]+>\\'" base-name)
2554 (not (and buffer-file-name
2555 (string= base-name
2556 (file-name-nondirectory buffer-file-name))))
2557 ;; If the existing buffer name has a <NNN>,
2558 ;; which isn't part of the file name (if any),
2559 ;; then get rid of that.
2560 (setq base-name (substring base-name 0 (match-beginning 0))))
2561 (rename-buffer (generate-new-buffer-name base-name))
3941fe2c 2562 (force-mode-line-update))))
5bbbceb1 2563
4e43240a 2564(defun make-directory (dir &optional parents)
5ce8bb89
RS
2565 "Create the directory DIR and any nonexistent parent dirs.
2566Interactively, the default choice of directory to create
2567is the current default directory for file names.
0225ae5e 2568That is useful when you have visited a file in a nonexistent directory.
5ce8bb89
RS
2569
2570Noninteractively, the second (optional) argument PARENTS says whether
2571to create parent directories if they don't exist."
2572 (interactive
2573 (list (read-file-name "Make directory: " default-directory default-directory
2574 nil nil)
2575 t))
6eaebaa2 2576 (let ((handler (find-file-name-handler dir 'make-directory)))
4e43240a
RS
2577 (if handler
2578 (funcall handler 'make-directory dir parents)
2579 (if (not parents)
2580 (make-directory-internal dir)
2581 (let ((dir (directory-file-name (expand-file-name dir)))
2582 create-list)
2583 (while (not (file-exists-p dir))
76d5492b 2584 (setq create-list (cons dir create-list)
4e43240a
RS
2585 dir (directory-file-name (file-name-directory dir))))
2586 (while create-list
2587 (make-directory-internal (car create-list))
2588 (setq create-list (cdr create-list))))))))
b4da00e9
RM
2589\f
2590(put 'revert-buffer-function 'permanent-local t)
2591(defvar revert-buffer-function nil
0973d78b
RS
2592 "Function to use to revert this buffer, or nil to do the default.
2593The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2594which are the arguments that `revert-buffer' received.")
b4da00e9
RM
2595
2596(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2597(defvar revert-buffer-insert-file-contents-function nil
2598 "Function to use to insert contents when reverting this buffer.
2599Gets two args, first the nominal file name to use,
2600and second, t if reading the auto-save file.")
2601
5f76e7d4
KH
2602(defvar before-revert-hook nil
2603 "Normal hook for `revert-buffer' to run before reverting.
2604If `revert-buffer-function' is used to override the normal revert
2605mechanism, this hook is not used.")
2606
2607(defvar after-revert-hook nil
2608 "Normal hook for `revert-buffer' to run after reverting.
2609Note that the hook value that it runs is the value that was in effect
2610before reverting; that makes a difference if you have buffer-local
2611hook functions.
2612
2613If `revert-buffer-function' is used to override the normal revert
2614mechanism, this hook is not used.")
2615
1554c03b
RS
2616(defvar revert-buffer-internal-hook)
2617
9a30563f 2618(defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
7e7c9c4e 2619 "Replace current buffer text with the text of the visited file on disk.
b4da00e9 2620This undoes all changes since the file was visited or saved.
8c0e7b73
JB
2621With a prefix argument, offer to revert from latest auto-save file, if
2622that is more recent than the visited file.
1ab31687 2623
7e7c9c4e
RS
2624This command also works for special buffers that contain text which
2625doesn't come from a file, but reflects some other data base instead:
2626for example, Dired buffers and buffer-list buffers. In these cases,
2627it reconstructs the buffer contents from the appropriate data base.
2628
65ee6096 2629When called from Lisp, the first argument is IGNORE-AUTO; only offer
1ab31687
JB
2630to revert from the auto-save file when this is nil. Note that the
2631sense of this argument is the reverse of the prefix argument, for the
2632sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2633to nil.
2634
2635Optional second argument NOCONFIRM means don't ask for confirmation at
d1f04130
RS
2636all. (The local variable `revert-without-query', if non-nil, prevents
2637confirmation.)
b4da00e9 2638
5b2b26d5
RS
2639Optional third argument PRESERVE-MODES non-nil means don't alter
2640the files modes. Normally we reinitialize them using `normal-mode'.
2641
8c0e7b73 2642If the value of `revert-buffer-function' is non-nil, it is called to
7e7c9c4e
RS
2643do all the work for this command. Otherwise, the hooks
2644`before-revert-hook' and `after-revert-hook' are run at the beginning
2645and the end, and if `revert-buffer-insert-file-contents-function' is
2646non-nil, it is called instead of rereading visited file contents."
fb6208a6 2647
1ab31687
JB
2648 ;; I admit it's odd to reverse the sense of the prefix argument, but
2649 ;; there is a lot of code out there which assumes that the first
2650 ;; argument should be t to avoid consulting the auto-save file, and
2651 ;; there's no straightforward way to encourage authors to notice a
2652 ;; reversal of the argument sense. So I'm just changing the user
2653 ;; interface, but leaving the programmatic interface the same.
e0867e99 2654 (interactive (list (not current-prefix-arg)))
b4da00e9 2655 (if revert-buffer-function
1ab31687 2656 (funcall revert-buffer-function ignore-auto noconfirm)
b4da00e9 2657 (let* ((opoint (point))
1ab31687
JB
2658 (auto-save-p (and (not ignore-auto)
2659 (recent-auto-save-p)
b4da00e9
RM
2660 buffer-auto-save-file-name
2661 (file-readable-p buffer-auto-save-file-name)
2662 (y-or-n-p
2663 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2664 (file-name (if auto-save-p
2665 buffer-auto-save-file-name
2666 buffer-file-name)))
2667 (cond ((null file-name)
2668 (error "Buffer does not seem to be associated with any file"))
2669 ((or noconfirm
db8c4866
RS
2670 (and (not (buffer-modified-p))
2671 (let ((tail revert-without-query)
2672 (found nil))
2673 (while tail
2674 (if (string-match (car tail) file-name)
2675 (setq found t))
2676 (setq tail (cdr tail)))
2677 found))
b4da00e9
RM
2678 (yes-or-no-p (format "Revert buffer from file %s? "
2679 file-name)))
4fbf62ee 2680 (run-hooks 'before-revert-hook)
b4da00e9
RM
2681 ;; If file was backed up but has changed since,
2682 ;; we shd make another backup.
2683 (and (not auto-save-p)
5bbbceb1 2684 (not (verify-visited-file-modtime (current-buffer)))
b4da00e9
RM
2685 (setq buffer-backed-up nil))
2686 ;; Get rid of all undo records for this buffer.
2687 (or (eq buffer-undo-list t)
2688 (setq buffer-undo-list nil))
ba5c8c93
KH
2689 ;; Effectively copy the after-revert-hook status,
2690 ;; since after-find-file will clobber it.
2691 (let ((global-hook (default-value 'after-revert-hook))
2692 (local-hook-p (local-variable-p 'after-revert-hook))
2693 (local-hook (and (local-variable-p 'after-revert-hook)
2694 after-revert-hook)))
2695 (let (buffer-read-only
2696 ;; Don't make undo records for the reversion.
2697 (buffer-undo-list t))
2698 (if revert-buffer-insert-file-contents-function
2699 (funcall revert-buffer-insert-file-contents-function
2700 file-name auto-save-p)
2701 (if (not (file-exists-p file-name))
2702 (error "File %s no longer exists!" file-name))
2703 ;; Bind buffer-file-name to nil
2704 ;; so that we don't try to lock the file.
2705 (let ((buffer-file-name nil))
2706 (or auto-save-p
2707 (unlock-buffer)))
2708 (widen)
b77d8211
KH
2709 (let ((coding-system-for-read
2710 ;; Auto-saved file shoule be read without
2711 ;; any code conversion.
2712 (if auto-save-p 'no-conversion
2713 coding-system-for-read)))
2714 (insert-file-contents file-name (not auto-save-p)
2715 nil nil t))))
ba5c8c93
KH
2716 (goto-char (min opoint (point-max)))
2717 ;; Recompute the truename in case changes in symlinks
2718 ;; have changed the truename.
2719 (setq buffer-file-truename
2720 (abbreviate-file-name (file-truename buffer-file-name)))
9a30563f 2721 (after-find-file nil nil t t preserve-modes)
ba5c8c93
KH
2722 ;; Run after-revert-hook as it was before we reverted.
2723 (setq-default revert-buffer-internal-hook global-hook)
2724 (if local-hook-p
2725 (progn
2726 (make-local-variable 'revert-buffer-internal-hook)
2727 (setq revert-buffer-internal-hook local-hook))
2728 (kill-local-variable 'revert-buffer-internal-hook))
2729 (run-hooks 'revert-buffer-internal-hook))
4fbf62ee 2730 t)))))
b4da00e9
RM
2731
2732(defun recover-file (file)
2733 "Visit file FILE, but get contents from its last auto-save file."
10f7c7fc
RS
2734 ;; Actually putting the file name in the minibuffer should be used
2735 ;; only rarely.
2736 ;; Not just because users often use the default.
e1dadc17 2737 (interactive "FRecover file: ")
b4da00e9 2738 (setq file (expand-file-name file))
f7da6740
RS
2739 (if (auto-save-file-name-p (file-name-nondirectory file))
2740 (error "%s is an auto-save file" file))
b4da00e9
RM
2741 (let ((file-name (let ((buffer-file-name file))
2742 (make-auto-save-file-name))))
945e1965
RS
2743 (cond ((if (file-exists-p file)
2744 (not (file-newer-than-file-p file-name file))
2745 (not (file-exists-p file-name)))
b4da00e9
RM
2746 (error "Auto-save file %s not current" file-name))
2747 ((save-window-excursion
b1667e6c 2748 (if (not (memq system-type '(vax-vms windows-nt)))
b4da00e9
RM
2749 (with-output-to-temp-buffer "*Directory*"
2750 (buffer-disable-undo standard-output)
2751 (call-process "ls" nil standard-output nil
2dc2b736
RS
2752 (if (file-symlink-p file) "-lL" "-l")
2753 file file-name)))
b4da00e9
RM
2754 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2755 (switch-to-buffer (find-file-noselect file t))
82d0954a
KH
2756 (let ((buffer-read-only nil)
2757 ;; Auto-saved file shoule be read without any code conversion.
2758 (coding-system-for-read 'no-conversion))
b4da00e9
RM
2759 (erase-buffer)
2760 (insert-file-contents file-name nil))
8cfb9d46 2761 (after-find-file nil nil t))
ffa7ab70 2762 (t (error "Recover-file cancelled")))))
b4da00e9 2763
6598027d 2764(defun recover-session ()
9aee5392
RS
2765 "Recover auto save files from a previous Emacs session.
2766This command first displays a Dired buffer showing you the
2767previous sessions that you could recover from.
2768To choose one, move point to the proper line and then type C-c C-c.
2769Then you'll be asked about a number of files to recover."
2770 (interactive)
363a5030
RS
2771 (if (null auto-save-list-file-prefix)
2772 (error "You set `auto-save-list-file-prefix' to disable making session files"))
6f4983e6 2773 (let ((ls-lisp-support-shell-wildcards t))
7b3478a5
RS
2774 (dired (concat auto-save-list-file-prefix "*")
2775 (concat dired-listing-switches "t")))
9aee5392
RS
2776 (goto-char (point-min))
2777 (or (looking-at "Move to the session you want to recover,")
2778 (let ((inhibit-read-only t))
d6046e45
RS
2779 ;; Each line starts with a space
2780 ;; so that Font Lock mode won't highlight the first character.
2781 (insert " Move to the session you want to recover,\n"
2782 " then type C-c C-c to select it.\n\n"
2783 " You can also delete some of these files;\n"
2784 " type d on a line to mark that file for deletion.\n\n")))
9aee5392 2785 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
80280bb7 2786 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
9aee5392 2787
80280bb7 2788(defun recover-session-finish ()
9aee5392
RS
2789 "Choose one saved session to recover auto-save files from.
2790This command is used in the special Dired buffer created by
80280bb7 2791\\[recover-session]."
9aee5392
RS
2792 (interactive)
2793 ;; Get the name of the session file to recover from.
2794 (let ((file (dired-get-filename))
953a03b2 2795 files
9aee5392 2796 (buffer (get-buffer-create " *recover*")))
c11032b9 2797 (dired-unmark 1)
033ef863 2798 (dired-do-flagged-delete t)
9aee5392
RS
2799 (unwind-protect
2800 (save-excursion
2801 ;; Read in the auto-save-list file.
2802 (set-buffer buffer)
2803 (erase-buffer)
2804 (insert-file-contents file)
953a03b2
RS
2805 ;; Loop thru the text of that file
2806 ;; and get out the names of the files to recover.
2807 (while (not (eobp))
2808 (let (thisfile autofile)
2809 (if (eolp)
2810 ;; This is a pair of lines for a non-file-visiting buffer.
2811 ;; Get the auto-save file name and manufacture
2812 ;; a "visited file name" from that.
2813 (progn
2814 (forward-line 1)
2815 (setq autofile
2816 (buffer-substring-no-properties
2817 (point)
2818 (save-excursion
2819 (end-of-line)
2820 (point))))
2821 (setq thisfile
2822 (expand-file-name
2823 (substring
2824 (file-name-nondirectory autofile)
2825 1 -1)
2826 (file-name-directory autofile)))
2827 (forward-line 1))
2828 ;; This pair of lines is a file-visiting
2829 ;; buffer. Use the visited file name.
2830 (progn
2831 (setq thisfile
2832 (buffer-substring-no-properties
2833 (point) (progn (end-of-line) (point))))
2834 (forward-line 1)
2835 (setq autofile
2836 (buffer-substring-no-properties
2837 (point) (progn (end-of-line) (point))))
2838 (forward-line 1)))
2839 ;; Ignore a file if its auto-save file does not exist now.
2840 (if (file-exists-p autofile)
2841 (setq files (cons thisfile files)))))
2842 (setq files (nreverse files))
945e1965
RS
2843 ;; The file contains a pair of line for each auto-saved buffer.
2844 ;; The first line of the pair contains the visited file name
2845 ;; or is empty if the buffer was not visiting a file.
2846 ;; The second line is the auto-save file name.
953a03b2
RS
2847 (if files
2848 (map-y-or-n-p "Recover %s? "
2849 (lambda (file)
2850 (condition-case nil
2851 (save-excursion (recover-file file))
76d5492b 2852 (error
953a03b2
RS
2853 "Failed to recover `%s'" file)))
2854 files
2855 '("file" "files" "recover"))
2856 (message "No files can be recovered from this session now")))
9aee5392
RS
2857 (kill-buffer buffer))))
2858
73ba610a
RS
2859(defun kill-some-buffers (&optional list)
2860 "For each buffer in LIST, ask whether to kill it.
2861LIST defaults to all existing live buffers."
b4da00e9 2862 (interactive)
73ba610a
RS
2863 (if (null list)
2864 (setq list (buffer-list)))
2865 (while list
2866 (let* ((buffer (car list))
2867 (name (buffer-name buffer)))
2868 (and (not (string-equal name ""))
2869 (/= (aref name 0) ? )
2870 (yes-or-no-p
2871 (format "Buffer %s %s. Kill? "
2872 name
2873 (if (buffer-modified-p buffer)
2874 "HAS BEEN EDITED" "is unmodified")))
2875 (kill-buffer buffer)))
2876 (setq list (cdr list))))
b4da00e9
RM
2877\f
2878(defun auto-save-mode (arg)
2879 "Toggle auto-saving of contents of current buffer.
f3e23606 2880With prefix argument ARG, turn auto-saving on if positive, else off."
b4da00e9
RM
2881 (interactive "P")
2882 (setq buffer-auto-save-file-name
2883 (and (if (null arg)
74b9c2af 2884 (or (not buffer-auto-save-file-name)
4e0c8650 2885 ;; If auto-save is off because buffer has shrunk,
74b9c2af
RS
2886 ;; then toggling should turn it on.
2887 (< buffer-saved-size 0))
b4da00e9
RM
2888 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2889 (if (and buffer-file-name auto-save-visited-file-name
2890 (not buffer-read-only))
2891 buffer-file-name
2892 (make-auto-save-file-name))))
0b7f1ef2
RS
2893 ;; If -1 was stored here, to temporarily turn off saving,
2894 ;; turn it back on.
2895 (and (< buffer-saved-size 0)
2896 (setq buffer-saved-size 0))
b4da00e9
RM
2897 (if (interactive-p)
2898 (message "Auto-save %s (in this buffer)"
2899 (if buffer-auto-save-file-name "on" "off")))
2900 buffer-auto-save-file-name)
2901
2902(defun rename-auto-save-file ()
2903 "Adjust current buffer's auto save file name for current conditions.
2904Also rename any existing auto save file, if it was made in this session."
2905 (let ((osave buffer-auto-save-file-name))
2906 (setq buffer-auto-save-file-name
2907 (make-auto-save-file-name))
2908 (if (and osave buffer-auto-save-file-name
2909 (not (string= buffer-auto-save-file-name buffer-file-name))
2910 (not (string= buffer-auto-save-file-name osave))
2911 (file-exists-p osave)
2912 (recent-auto-save-p))
2913 (rename-file osave buffer-auto-save-file-name t))))
2914
2915(defun make-auto-save-file-name ()
2916 "Return file name to use for auto-saves of current buffer.
2917Does not consider `auto-save-visited-file-name' as that variable is checked
2918before calling this function. You can redefine this for customization.
2919See also `auto-save-file-name-p'."
2920 (if buffer-file-name
28ee503c
KH
2921 (if (and (eq system-type 'ms-dos)
2922 (not (msdos-long-file-names)))
4503dacb 2923 (let ((fn (file-name-nondirectory buffer-file-name)))
5b4dd2e2 2924 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
4503dacb
RS
2925 (concat (file-name-directory buffer-file-name)
2926 "#" (match-string 1 fn)
2927 "." (match-string 3 fn) "#"))
2928 (concat (file-name-directory buffer-file-name)
2929 "#"
2930 (file-name-nondirectory buffer-file-name)
2931 "#"))
0a1763b4
RS
2932
2933 ;; Deal with buffers that don't have any associated files. (Mail
2934 ;; mode tends to create a good number of these.)
2935
7d483e8c 2936 (let ((buffer-name (buffer-name))
0a1763b4 2937 (limit 0))
c3348e10
RS
2938 ;; Eliminate all slashes and backslashes by
2939 ;; replacing them with sequences that start with %.
2940 ;; Quote % also, to keep distinct names distinct.
2941 (while (string-match "[/\\%]" buffer-name limit)
2942 (let* ((character (aref buffer-name (match-beginning 0)))
2943 (replacement
2944 (cond ((eq character ?%) "%%")
2945 ((eq character ?/) "%+")
2946 ((eq character ?\\) "%-"))))
2947 (setq buffer-name (replace-match replacement t t buffer-name))
2948 (setq limit (1+ (match-end 0)))))
a8abaf83
RS
2949 ;; Generate the file name.
2950 (expand-file-name
2951 (format "#%s#%s#" buffer-name (make-temp-name ""))
2952 ;; Try a few alternative directories, to get one we can write it.
2953 (cond
2954 ((file-writable-p default-directory) default-directory)
2955 ((file-writable-p "/var/tmp/") "/var/tmp/")
2956 ("~/"))))))
b4da00e9
RM
2957
2958(defun auto-save-file-name-p (filename)
2959 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2960FILENAME should lack slashes. You can redefine this for customization."
2961 (string-match "^#.*#$" filename))
2962\f
6f4983e6
RS
2963(defun wildcard-to-regexp (wildcard)
2964 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2965The generated regexp will match a filename iff the filename
2966matches that wildcard according to shell rules. Only wildcards known
2967by `sh' are supported."
2968 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2969 ;; Copy the initial run of non-special characters.
2970 (result (substring wildcard 0 i))
2971 (len (length wildcard)))
2972 ;; If no special characters, we're almost done.
2973 (if i
2974 (while (< i len)
2975 (let ((ch (aref wildcard i))
2976 j)
2977 (setq
2978 result
2979 (concat result
2980 (cond
7e7c9c4e
RS
2981 ((and (eq ch ?\[)
2982 (< (1+ i) len)
2983 (eq (aref wildcard (1+ i)) ?\]))
2984 "\\[")
6f4983e6
RS
2985 ((eq ch ?\[) ; [...] maps to regexp char class
2986 (progn
2987 (setq i (1+ i))
2988 (concat
2989 (cond
2990 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2991 (progn
2992 (setq i (1+ i))
2993 (if (eq (aref wildcard i) ?\])
2994 (progn
2995 (setq i (1+ i))
2996 "[^]")
2997 "[^")))
2998 ((eq (aref wildcard i) ?^)
2999 ;; Found "[^". Insert a `\0' character
3000 ;; (which cannot happen in a filename)
3001 ;; into the character class, so that `^'
3002 ;; is not the first character after `[',
3003 ;; and thus non-special in a regexp.
3004 (progn
3005 (setq i (1+ i))
3006 "[\000^"))
3007 ((eq (aref wildcard i) ?\])
3008 ;; I don't think `]' can appear in a
3009 ;; character class in a wildcard, but
3010 ;; let's be general here.
3011 (progn
3012 (setq i (1+ i))
3013 "[]"))
3014 (t "["))
3015 (prog1 ; copy everything upto next `]'.
3016 (substring wildcard
3017 i
3018 (setq j (string-match
3019 "]" wildcard i)))
3020 (setq i (if j (1- j) (1- len)))))))
3021 ((eq ch ?.) "\\.")
3022 ((eq ch ?*) "[^\000]*")
3023 ((eq ch ?+) "\\+")
3024 ((eq ch ?^) "\\^")
3025 ((eq ch ?$) "\\$")
3026 ((eq ch ?\\) "\\\\") ; probably cannot happen...
3027 ((eq ch ??) "[^\000]")
3028 (t (char-to-string ch)))))
3029 (setq i (1+ i)))))
3030 ;; Shell wildcards should match the entire filename,
3031 ;; not its part. Make the regexp say so.
3032 (concat "\\`" result "\\'")))
3033\f
21540597 3034(defcustom list-directory-brief-switches
b4da00e9 3035 (if (eq system-type 'vax-vms) "" "-CF")
21540597
RS
3036 "*Switches for list-directory to pass to `ls' for brief listing,"
3037 :type 'string
3038 :group 'dired)
b4da00e9 3039
21540597 3040(defcustom list-directory-verbose-switches
b4da00e9
RM
3041 (if (eq system-type 'vax-vms)
3042 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
3043 "-l")
21540597
RS
3044 "*Switches for list-directory to pass to `ls' for verbose listing,"
3045 :type 'string
3046 :group 'dired)
b4da00e9 3047
5de148a2
RS
3048(defun file-expand-wildcards (pattern &optional full)
3049 "Expand wildcard pattern PATTERN.
3050This returns a list of file names which match the pattern."
3051 (directory-files (file-name-directory pattern) full
3052 (wildcard-to-regexp (file-name-nondirectory pattern))))
3053
b4da00e9
RM
3054(defun list-directory (dirname &optional verbose)
3055 "Display a list of files in or matching DIRNAME, a la `ls'.
3056DIRNAME is globbed by the shell if necessary.
3057Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
3058Actions controlled by variables `list-directory-brief-switches'
3059and `list-directory-verbose-switches'."
3060 (interactive (let ((pfx current-prefix-arg))
3061 (list (read-file-name (if pfx "List directory (verbose): "
3062 "List directory (brief): ")
3063 nil default-directory nil)
3064 pfx)))
3065 (let ((switches (if verbose list-directory-verbose-switches
3066 list-directory-brief-switches)))
3067 (or dirname (setq dirname default-directory))
3068 (setq dirname (expand-file-name dirname))
3069 (with-output-to-temp-buffer "*Directory*"
3070 (buffer-disable-undo standard-output)
3071 (princ "Directory ")
3072 (princ dirname)
3073 (terpri)
c3554e95
RS
3074 (save-excursion
3075 (set-buffer "*Directory*")
5a8a160e
RS
3076 (setq default-directory
3077 (if (file-directory-p dirname)
3078 (file-name-as-directory dirname)
3079 (file-name-directory dirname)))
c3554e95
RS
3080 (let ((wildcard (not (file-directory-p dirname))))
3081 (insert-directory dirname switches wildcard (not wildcard)))))))
3082
3083(defvar insert-directory-program "ls"
3084 "Absolute or relative name of the `ls' program used by `insert-directory'.")
3085
3086;; insert-directory
3087;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3088;; FULL-DIRECTORY-P is nil.
3089;; The single line of output must display FILE's name as it was
3090;; given, namely, an absolute path name.
3091;; - must insert exactly one line for each file if WILDCARD or
3092;; FULL-DIRECTORY-P is t, plus one optional "total" line
3093;; before the file lines, plus optional text after the file lines.
3094;; Lines are delimited by "\n", so filenames containing "\n" are not
3095;; allowed.
3096;; File lines should display the basename.
3097;; - must be consistent with
3098;; - functions dired-move-to-filename, (these two define what a file line is)
3099;; dired-move-to-end-of-filename,
3100;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
3101;; dired-insert-headerline
3102;; dired-after-subdir-garbage (defines what a "total" line is)
3103;; - variable dired-subdir-regexp
3104(defun insert-directory (file switches &optional wildcard full-directory-p)
a18b7c81 3105 "Insert directory listing for FILE, formatted according to SWITCHES.
c3554e95 3106Leaves point after the inserted text.
727d277d 3107SWITCHES may be a string of options, or a list of strings.
c3554e95
RS
3108Optional third arg WILDCARD means treat FILE as shell wildcard.
3109Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3110switches do not contain `d', so that a full listing is expected.
3111
3112This works by running a directory listing program
406e12d9 3113whose name is in the variable `insert-directory-program'.
c3554e95 3114If WILDCARD, it also runs the shell specified by `shell-file-name'."
c870ab8e
RS
3115 ;; We need the directory in order to find the right handler.
3116 (let ((handler (find-file-name-handler (expand-file-name file)
3117 'insert-directory)))
c3554e95
RS
3118 (if handler
3119 (funcall handler 'insert-directory file switches
3120 wildcard full-directory-p)
b4da00e9 3121 (if (eq system-type 'vax-vms)
c3554e95 3122 (vms-read-directory file switches (current-buffer))
73ba53dc
KH
3123 (let* ((coding-system-for-read
3124 (and enable-multibyte-characters
3125 (or file-name-coding-system
3126 default-file-name-coding-system)))
6a97049b 3127 ;; This is to control encoding the arguments in call-process.
a9173359 3128 (coding-system-for-write coding-system-for-read)
73ba53dc
KH
3129 (result
3130 (if wildcard
3131 ;; Run ls in the directory of the file pattern we asked for.
3132 (let ((default-directory
3133 (if (file-name-absolute-p file)
3134 (file-name-directory file)
3135 (file-name-directory (expand-file-name file))))
3136 (pattern (file-name-nondirectory file))
3137 (beg 0))
3138 ;; Quote some characters that have special meanings in shells;
3139 ;; but don't quote the wildcards--we want them to be special.
3140 ;; We also currently don't quote the quoting characters
3141 ;; in case people want to use them explicitly to quote
3142 ;; wildcard characters.
3143 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
3144 (setq pattern
3145 (concat (substring pattern 0 (match-beginning 0))
3146 "\\"
3147 (substring pattern (match-beginning 0)))
3148 beg (1+ (match-end 0))))
3149 (call-process shell-file-name nil t nil
3150 "-c" (concat "\\";; Disregard shell aliases!
3151 insert-directory-program
3152 " -d "
3153 (if (stringp switches)
3154 switches
3155 (mapconcat 'identity switches " "))
3156 " -- "
a9173359 3157 pattern)))
73ba53dc
KH
3158 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3159 ;; directory if FILE is a symbolic link.
3160 (apply 'call-process
3161 insert-directory-program nil t nil
3162 (let (list)
3163 (if (listp switches)
3164 (setq list switches)
3165 (if (not (equal switches ""))
3166 (progn
3167 ;; Split the switches at any spaces
3168 ;; so we can pass separate options as separate args.
3169 (while (string-match " " switches)
3170 (setq list (cons (substring switches 0 (match-beginning 0))
3171 list)
3172 switches (substring switches (match-end 0))))
3173 (setq list (nreverse (cons switches list))))))
3174 (append list
3175 ;; Avoid lossage if FILE starts with `-'.
3176 '("--")
6a97049b
RS
3177 (progn
3178 (if (string-match "\\`~" file)
3179 (setq file (expand-file-name file)))
3180 (list
3181 (if full-directory-p
3182 (concat (file-name-as-directory file) ".")
3183 file)))))))))
73ba53dc
KH
3184 (if (/= result 0)
3185 ;; We get here if ls failed.
3186 ;; Access the file to get a suitable error.
3187 (access-file file "Reading directory")))))))
b4da00e9 3188
88902b35 3189(defvar kill-emacs-query-functions nil
65d5c6de 3190 "Functions to call with no arguments to query about killing Emacs.
78c793d1
RS
3191If any of these functions returns nil, killing Emacs is cancelled.
3192`save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3193but `kill-emacs', the low level primitive, does not.
3194See also `kill-emacs-hook'.")
88902b35 3195
b4da00e9
RM
3196(defun save-buffers-kill-emacs (&optional arg)
3197 "Offer to save each buffer, then kill this Emacs process.
3198With prefix arg, silently save all file-visiting buffers, then kill."
3199 (interactive "P")
3200 (save-some-buffers arg t)
3201 (and (or (not (memq t (mapcar (function
3202 (lambda (buf) (and (buffer-file-name buf)
3203 (buffer-modified-p buf))))
3204 (buffer-list))))
3205 (yes-or-no-p "Modified buffers exist; exit anyway? "))
3206 (or (not (fboundp 'process-list))
3207 ;; process-list is not defined on VMS.
3208 (let ((processes (process-list))
3209 active)
3210 (while processes
528415e7 3211 (and (memq (process-status (car processes)) '(run stop open))
b4da00e9
RM
3212 (let ((val (process-kill-without-query (car processes))))
3213 (process-kill-without-query (car processes) val)
3214 val)
3215 (setq active t))
3216 (setq processes (cdr processes)))
3217 (or (not active)
3218 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
88902b35 3219 ;; Query the user for other things, perhaps.
fb15c113 3220 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
b4da00e9
RM
3221 (kill-emacs)))
3222\f
47afc068
RS
3223;; We use /: as a prefix to "quote" a file name
3224;; so that magic file name handlers will not apply to it.
3225
3226(setq file-name-handler-alist
3227 (cons '("\\`/:" . file-name-non-special)
3228 file-name-handler-alist))
3229
3230;; We depend on being the last handler on the list,
3231;; so that anything else which does need handling
3232;; has been handled already.
3233;; So it is safe for us to inhibit *all* magic file name handlers.
3234
3235(defun file-name-non-special (operation &rest arguments)
3236 (let ((file-name-handler-alist nil)
5cb1f728
KH
3237 (default-directory
3238 (if (eq operation 'insert-directory)
3239 (directory-file-name
3240 (expand-file-name
3241 (unhandled-file-name-directory default-directory)))
3242 default-directory))
47afc068
RS
3243 ;; Get a list of the indices of the args which are file names.
3244 (file-arg-indices
3245 (cdr (or (assq operation
3246 ;; The first four are special because they
3247 ;; return a file name. We want to include the /:
3248 ;; in the return value.
3249 ;; So just avoid stripping it in the first place.
3250 '((expand-file-name . nil)
18b9dced
RS
3251 ;; `identity' means just return the first arg
3252 ;; as stripped of its quoting.
3253 (substitute-in-file-name . identity)
47afc068
RS
3254 (file-name-directory . nil)
3255 (file-name-as-directory . nil)
3256 (directory-file-name . nil)
feaec97d
RS
3257 (file-name-completion 0 1)
3258 (file-name-all-completions 0 1)
47afc068
RS
3259 (rename-file 0 1)
3260 (copy-file 0 1)
3261 (make-symbolic-link 0 1)
3262 (add-name-to-file 0 1)))
3263 ;; For all other operations, treat the first argument only
3264 ;; as the file name.
3265 '(nil 0))))
3266 ;; Copy ARGUMENTS so we can replace elements in it.
3267 (arguments (copy-sequence arguments)))
3268 ;; Strip off the /: from the file names that have this handler.
3269 (save-match-data
18b9dced 3270 (while (consp file-arg-indices)
fe4d9852
KH
3271 (let ((pair (nthcdr (car file-arg-indices) arguments)))
3272 (and (car pair)
3273 (string-match "\\`/:" (car pair))
3274 (setcar pair
3275 (if (= (length (car pair)) 2)
3276 "/"
3277 (substring (car pair) 2)))))
47afc068 3278 (setq file-arg-indices (cdr file-arg-indices))))
18b9dced
RS
3279 (if (eq file-arg-indices 'identity)
3280 (car arguments)
3281 (apply operation arguments))))
47afc068 3282\f
b4da00e9 3283(define-key ctl-x-map "\C-f" 'find-file)
b4da00e9
RM
3284(define-key ctl-x-map "\C-r" 'find-file-read-only)
3285(define-key ctl-x-map "\C-v" 'find-alternate-file)
3286(define-key ctl-x-map "\C-s" 'save-buffer)
3287(define-key ctl-x-map "s" 'save-some-buffers)
3288(define-key ctl-x-map "\C-w" 'write-file)
3289(define-key ctl-x-map "i" 'insert-file)
3290(define-key esc-map "~" 'not-modified)
3291(define-key ctl-x-map "\C-d" 'list-directory)
3292(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3293
3294(define-key ctl-x-4-map "f" 'find-file-other-window)
3295(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3296(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3297(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
924f0a24 3298(define-key ctl-x-4-map "\C-o" 'display-buffer)
5bbbceb1 3299
f98955ea
JB
3300(define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3301(define-key ctl-x-5-map "f" 'find-file-other-frame)
3302(define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3303(define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
c0274f38
ER
3304
3305;;; files.el ends here