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