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