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