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