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