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