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