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