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