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