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