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