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