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