merge from upstream
[bpt/emacs.git] / 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 (bidi-display-reordering . booleanp))) ;; C source code
2809
2810 (put 'bidi-paragraph-direction 'safe-local-variable
2811 (lambda (v) (memq v '(nil right-to-left left-to-right))))
2812
2813 (put 'c-set-style 'safe-local-eval-function t)
2814
2815 (defvar file-local-variables-alist nil
2816 "Alist of file-local variable settings in the current buffer.
2817 Each element in this list has the form (VAR . VALUE), where VAR
2818 is a file-local variable (a symbol) and VALUE is the value
2819 specified. The actual value in the buffer may differ from VALUE,
2820 if it is changed by the major or minor modes, or by the user.")
2821 (make-variable-buffer-local 'file-local-variables-alist)
2822
2823 (defvar dir-local-variables-alist nil
2824 "Alist of directory-local variable settings in the current buffer.
2825 Each element in this list has the form (VAR . VALUE), where VAR
2826 is a directory-local variable (a symbol) and VALUE is the value
2827 specified in .dir-locals.el. The actual value in the buffer
2828 may differ from VALUE, if it is changed by the major or minor modes,
2829 or by the user.")
2830 (make-variable-buffer-local 'dir-local-variables-alist)
2831
2832 (defvar before-hack-local-variables-hook nil
2833 "Normal hook run before setting file-local variables.
2834 It is called after checking for unsafe/risky variables and
2835 setting `file-local-variables-alist', and before applying the
2836 variables stored in `file-local-variables-alist'. A hook
2837 function is allowed to change the contents of this alist.
2838
2839 This hook is called only if there is at least one file-local
2840 variable to set.")
2841
2842 (defun hack-local-variables-confirm (all-vars unsafe-vars risky-vars dir-name)
2843 "Get confirmation before setting up local variable values.
2844 ALL-VARS is the list of all variables to be set up.
2845 UNSAFE-VARS is the list of those that aren't marked as safe or risky.
2846 RISKY-VARS is the list of those that are marked as risky.
2847 DIR-NAME is a directory name if these settings come from
2848 directory-local variables, or nil otherwise."
2849 (if noninteractive
2850 nil
2851 (let ((name (or dir-name
2852 (if buffer-file-name
2853 (file-name-nondirectory buffer-file-name)
2854 (concat "buffer " (buffer-name)))))
2855 (offer-save (and (eq enable-local-variables t) unsafe-vars))
2856 prompt char)
2857 (save-window-excursion
2858 (let ((buf (get-buffer-create "*Local Variables*")))
2859 (pop-to-buffer buf)
2860 (set (make-local-variable 'cursor-type) nil)
2861 (erase-buffer)
2862 (if unsafe-vars
2863 (insert "The local variables list in " name
2864 "\ncontains values that may not be safe (*)"
2865 (if risky-vars
2866 ", and variables that are risky (**)."
2867 "."))
2868 (if risky-vars
2869 (insert "The local variables list in " name
2870 "\ncontains variables that are risky (**).")
2871 (insert "A local variables list is specified in " name ".")))
2872 (insert "\n\nDo you want to apply it? You can type
2873 y -- to apply the local variables list.
2874 n -- to ignore the local variables list.")
2875 (if offer-save
2876 (insert "
2877 ! -- to apply the local variables list, and permanently mark these
2878 values (*) as safe (in the future, they will be set automatically.)\n\n")
2879 (insert "\n\n"))
2880 (dolist (elt all-vars)
2881 (cond ((member elt unsafe-vars)
2882 (insert " * "))
2883 ((member elt risky-vars)
2884 (insert " ** "))
2885 (t
2886 (insert " ")))
2887 (princ (car elt) buf)
2888 (insert " : ")
2889 ;; Make strings with embedded whitespace easier to read.
2890 (let ((print-escape-newlines t))
2891 (prin1 (cdr elt) buf))
2892 (insert "\n"))
2893 (setq prompt
2894 (format "Please type %s%s: "
2895 (if offer-save "y, n, or !" "y or n")
2896 (if (< (line-number-at-pos) (window-body-height))
2897 ""
2898 ", or C-v to scroll")))
2899 (goto-char (point-min))
2900 (let ((cursor-in-echo-area t)
2901 (executing-kbd-macro executing-kbd-macro)
2902 (exit-chars
2903 (if offer-save '(?! ?y ?n ?\s ?\C-g) '(?y ?n ?\s ?\C-g)))
2904 done)
2905 (while (not done)
2906 (message "%s" prompt)
2907 (setq char (read-event))
2908 (if (numberp char)
2909 (cond ((eq char ?\C-v)
2910 (condition-case nil
2911 (scroll-up)
2912 (error (goto-char (point-min)))))
2913 ;; read-event returns -1 if we are in a kbd
2914 ;; macro and there are no more events in the
2915 ;; macro. In that case, attempt to get an
2916 ;; event interactively.
2917 ((and executing-kbd-macro (= char -1))
2918 (setq executing-kbd-macro nil))
2919 (t (setq done (memq (downcase char) exit-chars)))))))
2920 (setq char (downcase char))
2921 (when (and offer-save (= char ?!) unsafe-vars)
2922 (dolist (elt unsafe-vars)
2923 (add-to-list 'safe-local-variable-values elt))
2924 ;; When this is called from desktop-restore-file-buffer,
2925 ;; coding-system-for-read may be non-nil. Reset it before
2926 ;; writing to .emacs.
2927 (if (or custom-file user-init-file)
2928 (let ((coding-system-for-read nil))
2929 (customize-save-variable
2930 'safe-local-variable-values
2931 safe-local-variable-values))))
2932 (kill-buffer buf)
2933 (or (= char ?!)
2934 (= char ?\s)
2935 (= char ?y)))))))
2936
2937 (defun hack-local-variables-prop-line (&optional mode-only)
2938 "Return local variables specified in the -*- line.
2939 Ignore any specification for `mode:' and `coding:';
2940 `set-auto-mode' should already have handled `mode:',
2941 `set-auto-coding' should already have handled `coding:'.
2942
2943 If MODE-ONLY is non-nil, all we do is check whether the major
2944 mode is specified, returning t if it is specified. Otherwise,
2945 return an alist of elements (VAR . VAL), where VAR is a variable
2946 and VAL is the specified value."
2947 (save-excursion
2948 (goto-char (point-min))
2949 (let ((end (set-auto-mode-1))
2950 result mode-specified)
2951 ;; Parse the -*- line into the RESULT alist.
2952 ;; Also set MODE-SPECIFIED if we see a spec or `mode'.
2953 (cond ((not end)
2954 nil)
2955 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
2956 ;; Simple form: "-*- MODENAME -*-". Already handled.
2957 (setq mode-specified t)
2958 nil)
2959 (t
2960 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
2961 ;; (last ";" is optional).
2962 (while (< (point) end)
2963 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
2964 (error "Malformed -*- line"))
2965 (goto-char (match-end 0))
2966 ;; There used to be a downcase here,
2967 ;; but the manual didn't say so,
2968 ;; and people want to set var names that aren't all lc.
2969 (let ((key (intern (match-string 1)))
2970 (val (save-restriction
2971 (narrow-to-region (point) end)
2972 (let ((read-circle nil))
2973 (read (current-buffer))))))
2974 ;; It is traditional to ignore
2975 ;; case when checking for `mode' in set-auto-mode,
2976 ;; so we must do that here as well.
2977 ;; That is inconsistent, but we're stuck with it.
2978 ;; The same can be said for `coding' in set-auto-coding.
2979 (or (and (equal (downcase (symbol-name key)) "mode")
2980 (setq mode-specified t))
2981 (equal (downcase (symbol-name key)) "coding")
2982 (condition-case nil
2983 (push (cons (if (eq key 'eval)
2984 'eval
2985 (indirect-variable key))
2986 val) result)
2987 (error nil)))
2988 (skip-chars-forward " \t;")))))
2989
2990 (if mode-only
2991 mode-specified
2992 result))))
2993
2994 (defun hack-local-variables-filter (variables dir-name)
2995 "Filter local variable settings, querying the user if necessary.
2996 VARIABLES is the alist of variable-value settings. This alist is
2997 filtered based on the values of `ignored-local-variables',
2998 `enable-local-eval', `enable-local-variables', and (if necessary)
2999 user interaction. The results are added to
3000 `file-local-variables-alist', without applying them.
3001 DIR-NAME is a directory name if these settings come from
3002 directory-local variables, or nil otherwise."
3003 ;; Find those variables that we may want to save to
3004 ;; `safe-local-variable-values'.
3005 (let (all-vars risky-vars unsafe-vars)
3006 (dolist (elt variables)
3007 (let ((var (car elt))
3008 (val (cdr elt)))
3009 (cond ((memq var ignored-local-variables)
3010 ;; Ignore any variable in `ignored-local-variables'.
3011 nil)
3012 ;; Obey `enable-local-eval'.
3013 ((eq var 'eval)
3014 (when enable-local-eval
3015 (push elt all-vars)
3016 (or (eq enable-local-eval t)
3017 (hack-one-local-variable-eval-safep (eval (quote val)))
3018 (safe-local-variable-p var val)
3019 (push elt unsafe-vars))))
3020 ;; Ignore duplicates (except `mode') in the present list.
3021 ((and (assq var all-vars) (not (eq var 'mode))) nil)
3022 ;; Accept known-safe variables.
3023 ((or (memq var '(mode unibyte coding))
3024 (safe-local-variable-p var val))
3025 (push elt all-vars))
3026 ;; The variable is either risky or unsafe:
3027 ((not (eq enable-local-variables :safe))
3028 (push elt all-vars)
3029 (if (risky-local-variable-p var val)
3030 (push elt risky-vars)
3031 (push elt unsafe-vars))))))
3032 (and all-vars
3033 ;; Query, unless all vars are safe or user wants no querying.
3034 (or (and (eq enable-local-variables t)
3035 (null unsafe-vars)
3036 (null risky-vars))
3037 (memq enable-local-variables '(:all :safe))
3038 (hack-local-variables-confirm all-vars unsafe-vars
3039 risky-vars dir-name))
3040 (dolist (elt all-vars)
3041 (unless (memq (car elt) '(eval mode))
3042 (unless dir-name
3043 (setq dir-local-variables-alist
3044 (assq-delete-all (car elt) dir-local-variables-alist)))
3045 (setq file-local-variables-alist
3046 (assq-delete-all (car elt) file-local-variables-alist)))
3047 (push elt file-local-variables-alist)))))
3048
3049 (defun hack-local-variables (&optional mode-only)
3050 "Parse and put into effect this buffer's local variables spec.
3051 If MODE-ONLY is non-nil, all we do is check whether the major mode
3052 is specified, returning t if it is specified."
3053 (let ((enable-local-variables
3054 (and local-enable-local-variables enable-local-variables))
3055 result)
3056 (unless mode-only
3057 (setq file-local-variables-alist nil)
3058 (report-errors "Directory-local variables error: %s"
3059 (hack-dir-local-variables)))
3060 (when (or mode-only enable-local-variables)
3061 (setq result (hack-local-variables-prop-line mode-only))
3062 ;; Look for "Local variables:" line in last page.
3063 (save-excursion
3064 (goto-char (point-max))
3065 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min))
3066 'move)
3067 (when (let ((case-fold-search t))
3068 (search-forward "Local Variables:" nil t))
3069 (skip-chars-forward " \t")
3070 ;; suffix is what comes after "local variables:" in its line.
3071 ;; prefix is what comes before "local variables:" in its line.
3072 (let ((suffix
3073 (concat
3074 (regexp-quote (buffer-substring (point)
3075 (line-end-position)))
3076 "$"))
3077 (prefix
3078 (concat "^" (regexp-quote
3079 (buffer-substring (line-beginning-position)
3080 (match-beginning 0)))))
3081 beg)
3082
3083 (forward-line 1)
3084 (let ((startpos (point))
3085 endpos
3086 (thisbuf (current-buffer)))
3087 (save-excursion
3088 (unless (let ((case-fold-search t))
3089 (re-search-forward
3090 (concat prefix "[ \t]*End:[ \t]*" suffix)
3091 nil t))
3092 ;; This used to be an error, but really all it means is
3093 ;; that this may simply not be a local-variables section,
3094 ;; so just ignore it.
3095 (message "Local variables list is not properly terminated"))
3096 (beginning-of-line)
3097 (setq endpos (point)))
3098
3099 (with-temp-buffer
3100 (insert-buffer-substring thisbuf startpos endpos)
3101 (goto-char (point-min))
3102 (subst-char-in-region (point) (point-max) ?\^m ?\n)
3103 (while (not (eobp))
3104 ;; Discard the prefix.
3105 (if (looking-at prefix)
3106 (delete-region (point) (match-end 0))
3107 (error "Local variables entry is missing the prefix"))
3108 (end-of-line)
3109 ;; Discard the suffix.
3110 (if (looking-back suffix)
3111 (delete-region (match-beginning 0) (point))
3112 (error "Local variables entry is missing the suffix"))
3113 (forward-line 1))
3114 (goto-char (point-min))
3115
3116 (while (not (eobp))
3117 ;; Find the variable name; strip whitespace.
3118 (skip-chars-forward " \t")
3119 (setq beg (point))
3120 (skip-chars-forward "^:\n")
3121 (if (eolp) (error "Missing colon in local variables entry"))
3122 (skip-chars-backward " \t")
3123 (let* ((str (buffer-substring beg (point)))
3124 (var (let ((read-circle nil))
3125 (read str)))
3126 val)
3127 ;; Read the variable value.
3128 (skip-chars-forward "^:")
3129 (forward-char 1)
3130 (let ((read-circle nil))
3131 (setq val (read (current-buffer))))
3132 (if mode-only
3133 (if (eq var 'mode)
3134 (setq result t))
3135 (unless (eq var 'coding)
3136 (condition-case nil
3137 (push (cons (if (eq var 'eval)
3138 'eval
3139 (indirect-variable var))
3140 val) result)
3141 (error nil)))))
3142 (forward-line 1))))))))
3143 ;; Now we've read all the local variables.
3144 ;; If MODE-ONLY is non-nil, return whether the mode was specified.
3145 (cond (mode-only result)
3146 ;; Otherwise, set the variables.
3147 (enable-local-variables
3148 (hack-local-variables-filter result nil)
3149 (hack-local-variables-apply)))))
3150
3151 (defun hack-local-variables-apply ()
3152 (when file-local-variables-alist
3153 ;; Any 'evals must run in the Right sequence.
3154 (setq file-local-variables-alist
3155 (nreverse file-local-variables-alist))
3156 (run-hooks 'before-hack-local-variables-hook)
3157 (dolist (elt file-local-variables-alist)
3158 (hack-one-local-variable (car elt) (cdr elt))))
3159 (run-hooks 'hack-local-variables-hook))
3160
3161 (defun safe-local-variable-p (sym val)
3162 "Non-nil if SYM is safe as a file-local variable with value VAL.
3163 It is safe if any of these conditions are met:
3164
3165 * There is a matching entry (SYM . VAL) in the
3166 `safe-local-variable-values' user option.
3167
3168 * The `safe-local-variable' property of SYM is a function that
3169 evaluates to a non-nil value with VAL as an argument."
3170 (or (member (cons sym val) safe-local-variable-values)
3171 (let ((safep (get sym 'safe-local-variable)))
3172 (and (functionp safep) (funcall safep val)))))
3173
3174 (defun risky-local-variable-p (sym &optional ignored)
3175 "Non-nil if SYM could be dangerous as a file-local variable.
3176 It is dangerous if either of these conditions are met:
3177
3178 * Its `risky-local-variable' property is non-nil.
3179
3180 * Its name ends with \"hook(s)\", \"function(s)\", \"form(s)\", \"map\",
3181 \"program\", \"command(s)\", \"predicate(s)\", \"frame-alist\",
3182 \"mode-alist\", \"font-lock-(syntactic-)keyword*\",
3183 \"map-alist\", or \"bindat-spec\"."
3184 ;; If this is an alias, check the base name.
3185 (condition-case nil
3186 (setq sym (indirect-variable sym))
3187 (error nil))
3188 (or (get sym 'risky-local-variable)
3189 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|\
3190 -commands?$\\|-predicates?$\\|font-lock-keywords$\\|font-lock-keywords\
3191 -[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|\
3192 -map$\\|-map-alist$\\|-bindat-spec$" (symbol-name sym))))
3193
3194 (defun hack-one-local-variable-quotep (exp)
3195 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
3196
3197 (defun hack-one-local-variable-constantp (exp)
3198 (or (and (not (symbolp exp)) (not (consp exp)))
3199 (memq exp '(t nil))
3200 (keywordp exp)
3201 (hack-one-local-variable-quotep exp)))
3202
3203 (defun hack-one-local-variable-eval-safep (exp)
3204 "Return t if it is safe to eval EXP when it is found in a file."
3205 (or (not (consp exp))
3206 ;; Detect certain `put' expressions.
3207 (and (eq (car exp) 'put)
3208 (hack-one-local-variable-quotep (nth 1 exp))
3209 (hack-one-local-variable-quotep (nth 2 exp))
3210 (let ((prop (nth 1 (nth 2 exp)))
3211 (val (nth 3 exp)))
3212 (cond ((memq prop '(lisp-indent-hook
3213 lisp-indent-function
3214 scheme-indent-function))
3215 ;; Only allow safe values (not functions).
3216 (or (numberp val)
3217 (and (hack-one-local-variable-quotep val)
3218 (eq (nth 1 val) 'defun))))
3219 ((eq prop 'edebug-form-spec)
3220 ;; Only allow indirect form specs.
3221 ;; During bootstrapping, edebug-basic-spec might not be
3222 ;; defined yet.
3223 (and (fboundp 'edebug-basic-spec)
3224 (hack-one-local-variable-quotep val)
3225 (edebug-basic-spec (nth 1 val)))))))
3226 ;; Allow expressions that the user requested.
3227 (member exp safe-local-eval-forms)
3228 ;; Certain functions can be allowed with safe arguments
3229 ;; or can specify verification functions to try.
3230 (and (symbolp (car exp))
3231 (let ((prop (get (car exp) 'safe-local-eval-function)))
3232 (cond ((eq prop t)
3233 (let ((ok t))
3234 (dolist (arg (cdr exp))
3235 (unless (hack-one-local-variable-constantp arg)
3236 (setq ok nil)))
3237 ok))
3238 ((functionp prop)
3239 (funcall prop exp))
3240 ((listp prop)
3241 (let ((ok nil))
3242 (dolist (function prop)
3243 (if (funcall function exp)
3244 (setq ok t)))
3245 ok)))))))
3246
3247 (defun hack-one-local-variable (var val)
3248 "Set local variable VAR with value VAL.
3249 If VAR is `mode', call `VAL-mode' as a function unless it's
3250 already the major mode."
3251 (cond ((eq var 'mode)
3252 (let ((mode (intern (concat (downcase (symbol-name val))
3253 "-mode"))))
3254 (unless (eq (indirect-function mode)
3255 (indirect-function major-mode))
3256 (if (memq mode minor-mode-list)
3257 ;; A minor mode must be passed an argument.
3258 ;; Otherwise, if the user enables the minor mode in a
3259 ;; major mode hook, this would toggle it off.
3260 (funcall mode 1)
3261 (funcall mode)))))
3262 ((eq var 'eval)
3263 (save-excursion (eval val)))
3264 (t
3265 ;; Make sure the string has no text properties.
3266 ;; Some text properties can get evaluated in various ways,
3267 ;; so it is risky to put them on with a local variable list.
3268 (if (stringp val)
3269 (set-text-properties 0 (length val) nil val))
3270 (set (make-local-variable var) val))))
3271 \f
3272 ;;; Handling directory-local variables, aka project settings.
3273
3274 (defvar dir-locals-class-alist '()
3275 "Alist mapping directory-local variable classes (symbols) to variable lists.")
3276
3277 (defvar dir-locals-directory-cache '()
3278 "List of cached directory roots for directory-local variable classes.
3279 Each element in this list has the form (DIR CLASS MTIME).
3280 DIR is the name of the directory.
3281 CLASS is the name of a variable class (a symbol).
3282 MTIME is the recorded modification time of the directory-local
3283 variables file associated with this entry. This time is a list
3284 of two integers (the same format as `file-attributes'), and is
3285 used to test whether the cache entry is still valid.
3286 Alternatively, MTIME can be nil, which means the entry is always
3287 considered valid.")
3288
3289 (defsubst dir-locals-get-class-variables (class)
3290 "Return the variable list for CLASS."
3291 (cdr (assq class dir-locals-class-alist)))
3292
3293 (defun dir-locals-collect-mode-variables (mode-variables variables)
3294 "Collect directory-local variables from MODE-VARIABLES.
3295 VARIABLES is the initial list of variables.
3296 Returns the new list."
3297 (dolist (pair mode-variables variables)
3298 (let* ((variable (car pair))
3299 (value (cdr pair))
3300 (slot (assq variable variables)))
3301 ;; If variables are specified more than once, only use the last. (Why?)
3302 ;; The pseudo-variables mode and eval are different (bug#3430).
3303 (if (and slot (not (memq variable '(mode eval))))
3304 (setcdr slot value)
3305 ;; Need a new cons in case we setcdr later.
3306 (push (cons variable value) variables)))))
3307
3308 (defun dir-locals-collect-variables (class-variables root variables)
3309 "Collect entries from CLASS-VARIABLES into VARIABLES.
3310 ROOT is the root directory of the project.
3311 Return the new variables list."
3312 (let* ((file-name (buffer-file-name))
3313 (sub-file-name (if file-name
3314 (substring file-name (length root)))))
3315 (dolist (entry class-variables variables)
3316 (let ((key (car entry)))
3317 (cond
3318 ((stringp key)
3319 ;; Don't include this in the previous condition, because we
3320 ;; want to filter all strings before the next condition.
3321 (when (and sub-file-name
3322 (>= (length sub-file-name) (length key))
3323 (string= key (substring sub-file-name 0 (length key))))
3324 (setq variables (dir-locals-collect-variables
3325 (cdr entry) root variables))))
3326 ((or (not key)
3327 (derived-mode-p key))
3328 (setq variables (dir-locals-collect-mode-variables
3329 (cdr entry) variables))))))))
3330
3331 (defun dir-locals-set-directory-class (directory class &optional mtime)
3332 "Declare that the DIRECTORY root is an instance of CLASS.
3333 DIRECTORY is the name of a directory, a string.
3334 CLASS is the name of a project class, a symbol.
3335 MTIME is either the modification time of the directory-local
3336 variables file that defined this class, or nil.
3337
3338 When a file beneath DIRECTORY is visited, the mode-specific
3339 variables from CLASS are applied to the buffer. The variables
3340 for a class are defined using `dir-locals-set-class-variables'."
3341 (setq directory (file-name-as-directory (expand-file-name directory)))
3342 (unless (assq class dir-locals-class-alist)
3343 (error "No such class `%s'" (symbol-name class)))
3344 (push (list directory class mtime) dir-locals-directory-cache))
3345
3346 (defun dir-locals-set-class-variables (class variables)
3347 "Map the type CLASS to a list of variable settings.
3348 CLASS is the project class, a symbol. VARIABLES is a list
3349 that declares directory-local variables for the class.
3350 An element in VARIABLES is either of the form:
3351 (MAJOR-MODE . ALIST)
3352 or
3353 (DIRECTORY . LIST)
3354
3355 In the first form, MAJOR-MODE is a symbol, and ALIST is an alist
3356 whose elements are of the form (VARIABLE . VALUE).
3357
3358 In the second form, DIRECTORY is a directory name (a string), and
3359 LIST is a list of the form accepted by the function.
3360
3361 When a file is visited, the file's class is found. A directory
3362 may be assigned a class using `dir-locals-set-directory-class'.
3363 Then variables are set in the file's buffer according to the
3364 class' LIST. The list is processed in order.
3365
3366 * If the element is of the form (MAJOR-MODE . ALIST), and the
3367 buffer's major mode is derived from MAJOR-MODE (as determined
3368 by `derived-mode-p'), then all the variables in ALIST are
3369 applied. A MAJOR-MODE of nil may be used to match any buffer.
3370 `make-local-variable' is called for each variable before it is
3371 set.
3372
3373 * If the element is of the form (DIRECTORY . LIST), and DIRECTORY
3374 is an initial substring of the file's directory, then LIST is
3375 applied by recursively following these rules."
3376 (let ((elt (assq class dir-locals-class-alist)))
3377 (if elt
3378 (setcdr elt variables)
3379 (push (cons class variables) dir-locals-class-alist))))
3380
3381 (defconst dir-locals-file ".dir-locals.el"
3382 "File that contains directory-local variables.
3383 It has to be constant to enforce uniform values
3384 across different environments and users.")
3385
3386 (defun dir-locals-find-file (file)
3387 "Find the directory-local variables for FILE.
3388 This searches upward in the directory tree from FILE.
3389 If the directory root of FILE has been registered in
3390 `dir-locals-directory-cache' and the directory-local variables
3391 file has not been modified, return the matching entry in
3392 `dir-locals-directory-cache'.
3393 Otherwise, if a directory-local variables file is found, return
3394 the file name.
3395 Otherwise, return nil."
3396 (setq file (expand-file-name file))
3397 (let* ((dir-locals-file-name
3398 (if (eq system-type 'ms-dos)
3399 (dosified-file-name dir-locals-file)
3400 dir-locals-file))
3401 (locals-file (locate-dominating-file file dir-locals-file-name))
3402 (dir-elt nil))
3403 ;; `locate-dominating-file' may have abbreviated the name.
3404 (when locals-file
3405 (setq locals-file (expand-file-name dir-locals-file-name locals-file)))
3406 ;; Find the best cached value in `dir-locals-directory-cache'.
3407 (dolist (elt dir-locals-directory-cache)
3408 (when (and (eq t (compare-strings file nil (length (car elt))
3409 (car elt) nil nil
3410 (memq system-type
3411 '(windows-nt cygwin ms-dos))))
3412 (> (length (car elt)) (length (car dir-elt))))
3413 (setq dir-elt elt)))
3414 (let ((use-cache (and dir-elt
3415 (or (null locals-file)
3416 (<= (length (file-name-directory locals-file))
3417 (length (car dir-elt)))))))
3418 (if use-cache
3419 ;; Check the validity of the cache.
3420 (if (and (file-readable-p (car dir-elt))
3421 (or (null (nth 2 dir-elt))
3422 (equal (nth 2 dir-elt)
3423 (nth 5 (file-attributes (car dir-elt))))))
3424 ;; This cache entry is OK.
3425 dir-elt
3426 ;; This cache entry is invalid; clear it.
3427 (setq dir-locals-directory-cache
3428 (delq dir-elt dir-locals-directory-cache))
3429 locals-file)
3430 locals-file))))
3431
3432 (defun dir-locals-read-from-file (file)
3433 "Load a variables FILE and register a new class and instance.
3434 FILE is the name of the file holding the variables to apply.
3435 The new class name is the same as the directory in which FILE
3436 is found. Returns the new class name."
3437 (with-temp-buffer
3438 (insert-file-contents file)
3439 (let* ((dir-name (file-name-directory file))
3440 (class-name (intern dir-name))
3441 (variables (let ((read-circle nil))
3442 (read (current-buffer)))))
3443 (dir-locals-set-class-variables class-name variables)
3444 (dir-locals-set-directory-class dir-name class-name
3445 (nth 5 (file-attributes file)))
3446 class-name)))
3447
3448 (defun hack-dir-local-variables ()
3449 "Read per-directory local variables for the current buffer.
3450 Store the directory-local variables in `dir-local-variables-alist'
3451 and `file-local-variables-alist', without applying them."
3452 (when (and enable-local-variables
3453 (not (file-remote-p (or (buffer-file-name) default-directory))))
3454 ;; Find the variables file.
3455 (let ((variables-file (dir-locals-find-file (or (buffer-file-name) default-directory)))
3456 (class nil)
3457 (dir-name nil))
3458 (cond
3459 ((stringp variables-file)
3460 (setq dir-name (if (buffer-file-name) (file-name-directory (buffer-file-name)) default-directory))
3461 (setq class (dir-locals-read-from-file variables-file)))
3462 ((consp variables-file)
3463 (setq dir-name (nth 0 variables-file))
3464 (setq class (nth 1 variables-file))))
3465 (when class
3466 (let ((variables
3467 (dir-locals-collect-variables
3468 (dir-locals-get-class-variables class) dir-name nil)))
3469 (when variables
3470 (dolist (elt variables)
3471 (unless (memq (car elt) '(eval mode))
3472 (setq dir-local-variables-alist
3473 (assq-delete-all (car elt) dir-local-variables-alist)))
3474 (push elt dir-local-variables-alist))
3475 (hack-local-variables-filter variables dir-name)))))))
3476
3477 (defun hack-dir-local-variables-non-file-buffer ()
3478 (hack-dir-local-variables)
3479 (hack-local-variables-apply))
3480
3481 \f
3482 (defcustom change-major-mode-with-file-name t
3483 "Non-nil means \\[write-file] should set the major mode from the file name.
3484 However, the mode will not be changed if
3485 \(1) a local variables list or the `-*-' line specifies a major mode, or
3486 \(2) the current major mode is a \"special\" mode,
3487 \ not suitable for ordinary files, or
3488 \(3) the new file name does not particularly specify any mode."
3489 :type 'boolean
3490 :group 'editing-basics)
3491
3492 (defun set-visited-file-name (filename &optional no-query along-with-file)
3493 "Change name of file visited in current buffer to FILENAME.
3494 This also renames the buffer to correspond to the new file.
3495 The next time the buffer is saved it will go in the newly specified file.
3496 FILENAME nil or an empty string means mark buffer as not visiting any file.
3497 Remember to delete the initial contents of the minibuffer
3498 if you wish to pass an empty string as the argument.
3499
3500 The optional second argument NO-QUERY, if non-nil, inhibits asking for
3501 confirmation in the case where another buffer is already visiting FILENAME.
3502
3503 The optional third argument ALONG-WITH-FILE, if non-nil, means that
3504 the old visited file has been renamed to the new name FILENAME."
3505 (interactive "FSet visited file name: ")
3506 (if (buffer-base-buffer)
3507 (error "An indirect buffer cannot visit a file"))
3508 (let (truename)
3509 (if filename
3510 (setq filename
3511 (if (string-equal filename "")
3512 nil
3513 (expand-file-name filename))))
3514 (if filename
3515 (progn
3516 (setq truename (file-truename filename))
3517 (if find-file-visit-truename
3518 (setq filename truename))))
3519 (if filename
3520 (let ((new-name (file-name-nondirectory filename)))
3521 (if (string= new-name "")
3522 (error "Empty file name"))))
3523 (let ((buffer (and filename (find-buffer-visiting filename))))
3524 (and buffer (not (eq buffer (current-buffer)))
3525 (not no-query)
3526 (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
3527 filename)))
3528 (error "Aborted")))
3529 (or (equal filename buffer-file-name)
3530 (progn
3531 (and filename (lock-buffer filename))
3532 (unlock-buffer)))
3533 (setq buffer-file-name filename)
3534 (if filename ; make buffer name reflect filename.
3535 (let ((new-name (file-name-nondirectory buffer-file-name)))
3536 (setq default-directory (file-name-directory buffer-file-name))
3537 ;; If new-name == old-name, renaming would add a spurious <2>
3538 ;; and it's considered as a feature in rename-buffer.
3539 (or (string= new-name (buffer-name))
3540 (rename-buffer new-name t))))
3541 (setq buffer-backed-up nil)
3542 (or along-with-file
3543 (clear-visited-file-modtime))
3544 ;; Abbreviate the file names of the buffer.
3545 (if truename
3546 (progn
3547 (setq buffer-file-truename (abbreviate-file-name truename))
3548 (if find-file-visit-truename
3549 (setq buffer-file-name truename))))
3550 (setq buffer-file-number
3551 (if filename
3552 (nthcdr 10 (file-attributes buffer-file-name))
3553 nil)))
3554 ;; write-file-functions is normally used for things like ftp-find-file
3555 ;; that visit things that are not local files as if they were files.
3556 ;; Changing to visit an ordinary local file instead should flush the hook.
3557 (kill-local-variable 'write-file-functions)
3558 (kill-local-variable 'local-write-file-hooks)
3559 (kill-local-variable 'revert-buffer-function)
3560 (kill-local-variable 'backup-inhibited)
3561 ;; If buffer was read-only because of version control,
3562 ;; that reason is gone now, so make it writable.
3563 (if vc-mode
3564 (setq buffer-read-only nil))
3565 (kill-local-variable 'vc-mode)
3566 ;; Turn off backup files for certain file names.
3567 ;; Since this is a permanent local, the major mode won't eliminate it.
3568 (and buffer-file-name
3569 backup-enable-predicate
3570 (not (funcall backup-enable-predicate buffer-file-name))
3571 (progn
3572 (make-local-variable 'backup-inhibited)
3573 (setq backup-inhibited t)))
3574 (let ((oauto buffer-auto-save-file-name))
3575 ;; If auto-save was not already on, turn it on if appropriate.
3576 (if (not buffer-auto-save-file-name)
3577 (and buffer-file-name auto-save-default
3578 (auto-save-mode t))
3579 ;; If auto save is on, start using a new name.
3580 ;; We deliberately don't rename or delete the old auto save
3581 ;; for the old visited file name. This is because perhaps
3582 ;; the user wants to save the new state and then compare with the
3583 ;; previous state from the auto save file.
3584 (setq buffer-auto-save-file-name
3585 (make-auto-save-file-name)))
3586 ;; Rename the old auto save file if any.
3587 (and oauto buffer-auto-save-file-name
3588 (file-exists-p oauto)
3589 (rename-file oauto buffer-auto-save-file-name t)))
3590 (and buffer-file-name
3591 (not along-with-file)
3592 (set-buffer-modified-p t))
3593 ;; Update the major mode, if the file name determines it.
3594 (condition-case nil
3595 ;; Don't change the mode if it is special.
3596 (or (not change-major-mode-with-file-name)
3597 (get major-mode 'mode-class)
3598 ;; Don't change the mode if the local variable list specifies it.
3599 (hack-local-variables t)
3600 (set-auto-mode t))
3601 (error nil)))
3602
3603 (defun write-file (filename &optional confirm)
3604 "Write current buffer into file FILENAME.
3605 This makes the buffer visit that file, and marks it as not modified.
3606
3607 If you specify just a directory name as FILENAME, that means to use
3608 the default file name but in that directory. You can also yank
3609 the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
3610
3611 If the buffer is not already visiting a file, the default file name
3612 for the output file is the buffer name.
3613
3614 If optional second arg CONFIRM is non-nil, this function
3615 asks for confirmation before overwriting an existing file.
3616 Interactively, confirmation is required unless you supply a prefix argument."
3617 ;; (interactive "FWrite file: ")
3618 (interactive
3619 (list (if buffer-file-name
3620 (read-file-name "Write file: "
3621 nil nil nil nil)
3622 (read-file-name "Write file: " default-directory
3623 (expand-file-name
3624 (file-name-nondirectory (buffer-name))
3625 default-directory)
3626 nil nil))
3627 (not current-prefix-arg)))
3628 (or (null filename) (string-equal filename "")
3629 (progn
3630 ;; If arg is just a directory,
3631 ;; use the default file name, but in that directory.
3632 (if (file-directory-p filename)
3633 (setq filename (concat (file-name-as-directory filename)
3634 (file-name-nondirectory
3635 (or buffer-file-name (buffer-name))))))
3636 (and confirm
3637 (file-exists-p filename)
3638 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
3639 (error "Canceled")))
3640 (set-visited-file-name filename (not confirm))))
3641 (set-buffer-modified-p t)
3642 ;; Make buffer writable if file is writable.
3643 (and buffer-file-name
3644 (file-writable-p buffer-file-name)
3645 (setq buffer-read-only nil))
3646 (save-buffer)
3647 ;; It's likely that the VC status at the new location is different from
3648 ;; the one at the old location.
3649 (vc-find-file-hook))
3650 \f
3651 (defun backup-buffer ()
3652 "Make a backup of the disk file visited by the current buffer, if appropriate.
3653 This is normally done before saving the buffer the first time.
3654
3655 A backup may be done by renaming or by copying; see documentation of
3656 variable `make-backup-files'. If it's done by renaming, then the file is
3657 no longer accessible under its old name.
3658
3659 The value is non-nil after a backup was made by renaming.
3660 It has the form (MODES SELINUXCONTEXT BACKUPNAME).
3661 MODES is the result of `file-modes' on the original
3662 file; this means that the caller, after saving the buffer, should change
3663 the modes of the new file to agree with the old modes.
3664 SELINUXCONTEXT is the result of `file-selinux-context' on the original
3665 file; this means that the caller, after saving the buffer, should change
3666 the SELinux context of the new file to agree with the old context.
3667 BACKUPNAME is the backup file name, which is the old file renamed."
3668 (if (and make-backup-files (not backup-inhibited)
3669 (not buffer-backed-up)
3670 (file-exists-p buffer-file-name)
3671 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
3672 '(?- ?l)))
3673 (let ((real-file-name buffer-file-name)
3674 backup-info backupname targets setmodes)
3675 ;; If specified name is a symbolic link, chase it to the target.
3676 ;; Thus we make the backups in the directory where the real file is.
3677 (setq real-file-name (file-chase-links real-file-name))
3678 (setq backup-info (find-backup-file-name real-file-name)
3679 backupname (car backup-info)
3680 targets (cdr backup-info))
3681 ;; (if (file-directory-p buffer-file-name)
3682 ;; (error "Cannot save buffer in directory %s" buffer-file-name))
3683 (if backup-info
3684 (condition-case ()
3685 (let ((delete-old-versions
3686 ;; If have old versions to maybe delete,
3687 ;; ask the user to confirm now, before doing anything.
3688 ;; But don't actually delete til later.
3689 (and targets
3690 (or (eq delete-old-versions t) (eq delete-old-versions nil))
3691 (or delete-old-versions
3692 (y-or-n-p (format "Delete excess backup versions of %s? "
3693 real-file-name)))))
3694 (modes (file-modes buffer-file-name))
3695 (context (file-selinux-context buffer-file-name)))
3696 ;; Actually write the back up file.
3697 (condition-case ()
3698 (if (or file-precious-flag
3699 ; (file-symlink-p buffer-file-name)
3700 backup-by-copying
3701 ;; Don't rename a suid or sgid file.
3702 (and modes (< 0 (logand modes #o6000)))
3703 (not (file-writable-p (file-name-directory real-file-name)))
3704 (and backup-by-copying-when-linked
3705 (> (file-nlinks real-file-name) 1))
3706 (and (or backup-by-copying-when-mismatch
3707 (integerp backup-by-copying-when-privileged-mismatch))
3708 (let ((attr (file-attributes real-file-name)))
3709 (and (or backup-by-copying-when-mismatch
3710 (and (integerp (nth 2 attr))
3711 (integerp backup-by-copying-when-privileged-mismatch)
3712 (<= (nth 2 attr) backup-by-copying-when-privileged-mismatch)))
3713 (or (nth 9 attr)
3714 (not (file-ownership-preserved-p real-file-name)))))))
3715 (backup-buffer-copy real-file-name backupname modes context)
3716 ;; rename-file should delete old backup.
3717 (rename-file real-file-name backupname t)
3718 (setq setmodes (list modes context backupname)))
3719 (file-error
3720 ;; If trouble writing the backup, write it in ~.
3721 (setq backupname (expand-file-name
3722 (convert-standard-filename
3723 "~/%backup%~")))
3724 (message "Cannot write backup file; backing up in %s"
3725 backupname)
3726 (sleep-for 1)
3727 (backup-buffer-copy real-file-name backupname modes context)))
3728 (setq buffer-backed-up t)
3729 ;; Now delete the old versions, if desired.
3730 (if delete-old-versions
3731 (while targets
3732 (condition-case ()
3733 (delete-file (car targets))
3734 (file-error nil))
3735 (setq targets (cdr targets))))
3736 setmodes)
3737 (file-error nil))))))
3738
3739 (defun backup-buffer-copy (from-name to-name modes context)
3740 (let ((umask (default-file-modes)))
3741 (unwind-protect
3742 (progn
3743 ;; Create temp files with strict access rights. It's easy to
3744 ;; loosen them later, whereas it's impossible to close the
3745 ;; time-window of loose permissions otherwise.
3746 (set-default-file-modes ?\700)
3747 (when (condition-case nil
3748 ;; Try to overwrite old backup first.
3749 (copy-file from-name to-name t t t)
3750 (error t))
3751 (while (condition-case nil
3752 (progn
3753 (when (file-exists-p to-name)
3754 (delete-file to-name))
3755 (copy-file from-name to-name nil t t)
3756 nil)
3757 (file-already-exists t))
3758 ;; The file was somehow created by someone else between
3759 ;; `delete-file' and `copy-file', so let's try again.
3760 ;; rms says "I think there is also a possible race
3761 ;; condition for making backup files" (emacs-devel 20070821).
3762 nil)))
3763 ;; Reset the umask.
3764 (set-default-file-modes umask)))
3765 (and modes
3766 (set-file-modes to-name (logand modes #o1777)))
3767 (and context
3768 (set-file-selinux-context to-name context)))
3769
3770 (defun file-name-sans-versions (name &optional keep-backup-version)
3771 "Return file NAME sans backup versions or strings.
3772 This is a separate procedure so your site-init or startup file can
3773 redefine it.
3774 If the optional argument KEEP-BACKUP-VERSION is non-nil,
3775 we do not remove backup version numbers, only true file version numbers."
3776 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
3777 (if handler
3778 (funcall handler 'file-name-sans-versions name keep-backup-version)
3779 (substring name 0
3780 (if keep-backup-version
3781 (length name)
3782 (or (string-match "\\.~[-[:alnum:]:#@^._]+~\\'" name)
3783 (string-match "~\\'" name)
3784 (length name)))))))
3785
3786 (defun file-ownership-preserved-p (file)
3787 "Return t if deleting FILE and rewriting it would preserve the owner."
3788 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
3789 (if handler
3790 (funcall handler 'file-ownership-preserved-p file)
3791 (let ((attributes (file-attributes file)))
3792 ;; Return t if the file doesn't exist, since it's true that no
3793 ;; information would be lost by an (attempted) delete and create.
3794 (or (null attributes)
3795 (= (nth 2 attributes) (user-uid)))))))
3796
3797 (defun file-name-sans-extension (filename)
3798 "Return FILENAME sans final \"extension\".
3799 The extension, in a file name, is the part that follows the last `.',
3800 except that a leading `.', if any, doesn't count."
3801 (save-match-data
3802 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
3803 directory)
3804 (if (and (string-match "\\.[^.]*\\'" file)
3805 (not (eq 0 (match-beginning 0))))
3806 (if (setq directory (file-name-directory filename))
3807 ;; Don't use expand-file-name here; if DIRECTORY is relative,
3808 ;; we don't want to expand it.
3809 (concat directory (substring file 0 (match-beginning 0)))
3810 (substring file 0 (match-beginning 0)))
3811 filename))))
3812
3813 (defun file-name-extension (filename &optional period)
3814 "Return FILENAME's final \"extension\".
3815 The extension, in a file name, is the part that follows the last `.',
3816 excluding version numbers and backup suffixes,
3817 except that a leading `.', if any, doesn't count.
3818 Return nil for extensionless file names such as `foo'.
3819 Return the empty string for file names such as `foo.'.
3820
3821 If PERIOD is non-nil, then the returned value includes the period
3822 that delimits the extension, and if FILENAME has no extension,
3823 the value is \"\"."
3824 (save-match-data
3825 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
3826 (if (and (string-match "\\.[^.]*\\'" file)
3827 (not (eq 0 (match-beginning 0))))
3828 (substring file (+ (match-beginning 0) (if period 0 1)))
3829 (if period
3830 "")))))
3831
3832 (defcustom make-backup-file-name-function nil
3833 "A function to use instead of the default `make-backup-file-name'.
3834 A value of nil gives the default `make-backup-file-name' behavior.
3835
3836 This could be buffer-local to do something special for specific
3837 files. If you define it, you may need to change `backup-file-name-p'
3838 and `file-name-sans-versions' too.
3839
3840 See also `backup-directory-alist'."
3841 :group 'backup
3842 :type '(choice (const :tag "Default" nil)
3843 (function :tag "Your function")))
3844
3845 (defcustom backup-directory-alist nil
3846 "Alist of filename patterns and backup directory names.
3847 Each element looks like (REGEXP . DIRECTORY). Backups of files with
3848 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
3849 relative or absolute. If it is absolute, so that all matching files
3850 are backed up into the same directory, the file names in this
3851 directory will be the full name of the file backed up with all
3852 directory separators changed to `!' to prevent clashes. This will not
3853 work correctly if your filesystem truncates the resulting name.
3854
3855 For the common case of all backups going into one directory, the alist
3856 should contain a single element pairing \".\" with the appropriate
3857 directory name.
3858
3859 If this variable is nil, or it fails to match a filename, the backup
3860 is made in the original file's directory.
3861
3862 On MS-DOS filesystems without long names this variable is always
3863 ignored."
3864 :group 'backup
3865 :type '(repeat (cons (regexp :tag "Regexp matching filename")
3866 (directory :tag "Backup directory name"))))
3867
3868 (defun normal-backup-enable-predicate (name)
3869 "Default `backup-enable-predicate' function.
3870 Checks for files in `temporary-file-directory',
3871 `small-temporary-file-directory', and /tmp."
3872 (not (or (let ((comp (compare-strings temporary-file-directory 0 nil
3873 name 0 nil)))
3874 ;; Directory is under temporary-file-directory.
3875 (and (not (eq comp t))
3876 (< comp (- (length temporary-file-directory)))))
3877 (let ((comp (compare-strings "/tmp" 0 nil
3878 name 0 nil)))
3879 ;; Directory is under /tmp.
3880 (and (not (eq comp t))
3881 (< comp (- (length "/tmp")))))
3882 (if small-temporary-file-directory
3883 (let ((comp (compare-strings small-temporary-file-directory
3884 0 nil
3885 name 0 nil)))
3886 ;; Directory is under small-temporary-file-directory.
3887 (and (not (eq comp t))
3888 (< comp (- (length small-temporary-file-directory)))))))))
3889
3890 (defun make-backup-file-name (file)
3891 "Create the non-numeric backup file name for FILE.
3892 Normally this will just be the file's name with `~' appended.
3893 Customization hooks are provided as follows.
3894
3895 If the variable `make-backup-file-name-function' is non-nil, its value
3896 should be a function which will be called with FILE as its argument;
3897 the resulting name is used.
3898
3899 Otherwise a match for FILE is sought in `backup-directory-alist'; see
3900 the documentation of that variable. If the directory for the backup
3901 doesn't exist, it is created."
3902 (if make-backup-file-name-function
3903 (funcall make-backup-file-name-function file)
3904 (if (and (eq system-type 'ms-dos)
3905 (not (msdos-long-file-names)))
3906 (let ((fn (file-name-nondirectory file)))
3907 (concat (file-name-directory file)
3908 (or (and (string-match "\\`[^.]+\\'" fn)
3909 (concat (match-string 0 fn) ".~"))
3910 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
3911 (concat (match-string 0 fn) "~")))))
3912 (concat (make-backup-file-name-1 file) "~"))))
3913
3914 (defun make-backup-file-name-1 (file)
3915 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
3916 (let ((alist backup-directory-alist)
3917 elt backup-directory abs-backup-directory)
3918 (while alist
3919 (setq elt (pop alist))
3920 (if (string-match (car elt) file)
3921 (setq backup-directory (cdr elt)
3922 alist nil)))
3923 ;; If backup-directory is relative, it should be relative to the
3924 ;; file's directory. By expanding explicitly here, we avoid
3925 ;; depending on default-directory.
3926 (if backup-directory
3927 (setq abs-backup-directory
3928 (expand-file-name backup-directory
3929 (file-name-directory file))))
3930 (if (and abs-backup-directory (not (file-exists-p abs-backup-directory)))
3931 (condition-case nil
3932 (make-directory abs-backup-directory 'parents)
3933 (file-error (setq backup-directory nil
3934 abs-backup-directory nil))))
3935 (if (null backup-directory)
3936 file
3937 (if (file-name-absolute-p backup-directory)
3938 (progn
3939 (when (memq system-type '(windows-nt ms-dos cygwin))
3940 ;; Normalize DOSish file names: downcase the drive
3941 ;; letter, if any, and replace the leading "x:" with
3942 ;; "/drive_x".
3943 (or (file-name-absolute-p file)
3944 (setq file (expand-file-name file))) ; make defaults explicit
3945 ;; Replace any invalid file-name characters (for the
3946 ;; case of backing up remote files).
3947 (setq file (expand-file-name (convert-standard-filename file)))
3948 (if (eq (aref file 1) ?:)
3949 (setq file (concat "/"
3950 "drive_"
3951 (char-to-string (downcase (aref file 0)))
3952 (if (eq (aref file 2) ?/)
3953 ""
3954 "/")
3955 (substring file 2)))))
3956 ;; Make the name unique by substituting directory
3957 ;; separators. It may not really be worth bothering about
3958 ;; doubling `!'s in the original name...
3959 (expand-file-name
3960 (subst-char-in-string
3961 ?/ ?!
3962 (replace-regexp-in-string "!" "!!" file))
3963 backup-directory))
3964 (expand-file-name (file-name-nondirectory file)
3965 (file-name-as-directory abs-backup-directory))))))
3966
3967 (defun backup-file-name-p (file)
3968 "Return non-nil if FILE is a backup file name (numeric or not).
3969 This is a separate function so you can redefine it for customization.
3970 You may need to redefine `file-name-sans-versions' as well."
3971 (string-match "~\\'" file))
3972
3973 (defvar backup-extract-version-start)
3974
3975 ;; This is used in various files.
3976 ;; The usage of backup-extract-version-start is not very clean,
3977 ;; but I can't see a good alternative, so as of now I am leaving it alone.
3978 (defun backup-extract-version (fn)
3979 "Given the name of a numeric backup file, FN, return the backup number.
3980 Uses the free variable `backup-extract-version-start', whose value should be
3981 the index in the name where the version number begins."
3982 (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start)
3983 (= (match-beginning 0) backup-extract-version-start))
3984 (string-to-number (substring fn backup-extract-version-start -1))
3985 0))
3986
3987 (defun find-backup-file-name (fn)
3988 "Find a file name for a backup file FN, and suggestions for deletions.
3989 Value is a list whose car is the name for the backup file
3990 and whose cdr is a list of old versions to consider deleting now.
3991 If the value is nil, don't make a backup.
3992 Uses `backup-directory-alist' in the same way as does
3993 `make-backup-file-name'."
3994 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
3995 ;; Run a handler for this function so that ange-ftp can refuse to do it.
3996 (if handler
3997 (funcall handler 'find-backup-file-name fn)
3998 (if (or (eq version-control 'never)
3999 ;; We don't support numbered backups on plain MS-DOS
4000 ;; when long file names are unavailable.
4001 (and (eq system-type 'ms-dos)
4002 (not (msdos-long-file-names))))
4003 (list (make-backup-file-name fn))
4004 (let* ((basic-name (make-backup-file-name-1 fn))
4005 (base-versions (concat (file-name-nondirectory basic-name)
4006 ".~"))
4007 (backup-extract-version-start (length base-versions))
4008 (high-water-mark 0)
4009 (number-to-delete 0)
4010 possibilities deserve-versions-p versions)
4011 (condition-case ()
4012 (setq possibilities (file-name-all-completions
4013 base-versions
4014 (file-name-directory basic-name))
4015 versions (sort (mapcar #'backup-extract-version
4016 possibilities)
4017 #'<)
4018 high-water-mark (apply 'max 0 versions)
4019 deserve-versions-p (or version-control
4020 (> high-water-mark 0))
4021 number-to-delete (- (length versions)
4022 kept-old-versions
4023 kept-new-versions
4024 -1))
4025 (file-error (setq possibilities nil)))
4026 (if (not deserve-versions-p)
4027 (list (make-backup-file-name fn))
4028 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
4029 (if (and (> number-to-delete 0)
4030 ;; Delete nothing if there is overflow
4031 ;; in the number of versions to keep.
4032 (>= (+ kept-new-versions kept-old-versions -1) 0))
4033 (mapcar (lambda (n)
4034 (format "%s.~%d~" basic-name n))
4035 (let ((v (nthcdr kept-old-versions versions)))
4036 (rplacd (nthcdr (1- number-to-delete) v) ())
4037 v))))))))))
4038
4039 (defun file-nlinks (filename)
4040 "Return number of names file FILENAME has."
4041 (car (cdr (file-attributes filename))))
4042
4043 ;; (defun file-relative-name (filename &optional directory)
4044 ;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4045 ;; This function returns a relative file name which is equivalent to FILENAME
4046 ;; when used with that default directory as the default.
4047 ;; If this is impossible (which can happen on MSDOS and Windows
4048 ;; when the file name and directory use different drive names)
4049 ;; then it returns FILENAME."
4050 ;; (save-match-data
4051 ;; (let ((fname (expand-file-name filename)))
4052 ;; (setq directory (file-name-as-directory
4053 ;; (expand-file-name (or directory default-directory))))
4054 ;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
4055 ;; ;; drive names, they can't be relative, so return the absolute name.
4056 ;; (if (and (or (eq system-type 'ms-dos)
4057 ;; (eq system-type 'cygwin)
4058 ;; (eq system-type 'windows-nt))
4059 ;; (not (string-equal (substring fname 0 2)
4060 ;; (substring directory 0 2))))
4061 ;; filename
4062 ;; (let ((ancestor ".")
4063 ;; (fname-dir (file-name-as-directory fname)))
4064 ;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
4065 ;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
4066 ;; (setq directory (file-name-directory (substring directory 0 -1))
4067 ;; ancestor (if (equal ancestor ".")
4068 ;; ".."
4069 ;; (concat "../" ancestor))))
4070 ;; ;; Now ancestor is empty, or .., or ../.., etc.
4071 ;; (if (string-match (concat "^" (regexp-quote directory)) fname)
4072 ;; ;; We matched within FNAME's directory part.
4073 ;; ;; Add the rest of FNAME onto ANCESTOR.
4074 ;; (let ((rest (substring fname (match-end 0))))
4075 ;; (if (and (equal ancestor ".")
4076 ;; (not (equal rest "")))
4077 ;; ;; But don't bother with ANCESTOR if it would give us `./'.
4078 ;; rest
4079 ;; (concat (file-name-as-directory ancestor) rest)))
4080 ;; ;; We matched FNAME's directory equivalent.
4081 ;; ancestor))))))
4082
4083 (defun file-relative-name (filename &optional directory)
4084 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4085 This function returns a relative file name which is equivalent to FILENAME
4086 when used with that default directory as the default.
4087 If FILENAME and DIRECTORY lie on different machines or on different drives
4088 on a DOS/Windows machine, it returns FILENAME in expanded form."
4089 (save-match-data
4090 (setq directory
4091 (file-name-as-directory (expand-file-name (or directory
4092 default-directory))))
4093 (setq filename (expand-file-name filename))
4094 (let ((fremote (file-remote-p filename))
4095 (dremote (file-remote-p directory)))
4096 (if ;; Conditions for separate trees
4097 (or
4098 ;; Test for different drives on DOS/Windows
4099 (and
4100 ;; Should `cygwin' really be included here? --stef
4101 (memq system-type '(ms-dos cygwin windows-nt))
4102 (not (eq t (compare-strings filename 0 2 directory 0 2))))
4103 ;; Test for different remote file system identification
4104 (not (equal fremote dremote)))
4105 filename
4106 (let ((ancestor ".")
4107 (filename-dir (file-name-as-directory filename)))
4108 (while (not
4109 (or
4110 (eq t (compare-strings filename-dir nil (length directory)
4111 directory nil nil case-fold-search))
4112 (eq t (compare-strings filename nil (length directory)
4113 directory nil nil case-fold-search))))
4114 (setq directory (file-name-directory (substring directory 0 -1))
4115 ancestor (if (equal ancestor ".")
4116 ".."
4117 (concat "../" ancestor))))
4118 ;; Now ancestor is empty, or .., or ../.., etc.
4119 (if (eq t (compare-strings filename nil (length directory)
4120 directory nil nil case-fold-search))
4121 ;; We matched within FILENAME's directory part.
4122 ;; Add the rest of FILENAME onto ANCESTOR.
4123 (let ((rest (substring filename (length directory))))
4124 (if (and (equal ancestor ".") (not (equal rest "")))
4125 ;; But don't bother with ANCESTOR if it would give us `./'.
4126 rest
4127 (concat (file-name-as-directory ancestor) rest)))
4128 ;; We matched FILENAME's directory equivalent.
4129 ancestor))))))
4130 \f
4131 (defun save-buffer (&optional args)
4132 "Save current buffer in visited file if modified.
4133 Variations are described below.
4134
4135 By default, makes the previous version into a backup file
4136 if previously requested or if this is the first save.
4137 Prefixed with one \\[universal-argument], marks this version
4138 to become a backup when the next save is done.
4139 Prefixed with two \\[universal-argument]'s,
4140 unconditionally makes the previous version into a backup file.
4141 Prefixed with three \\[universal-argument]'s, marks this version
4142 to become a backup when the next save is done,
4143 and unconditionally makes the previous version into a backup file.
4144
4145 With a numeric argument of 0, never make the previous version
4146 into a backup file.
4147
4148 If a file's name is FOO, the names of its numbered backup versions are
4149 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
4150 Numeric backups (rather than FOO~) will be made if value of
4151 `version-control' is not the atom `never' and either there are already
4152 numeric versions of the file being backed up, or `version-control' is
4153 non-nil.
4154 We don't want excessive versions piling up, so there are variables
4155 `kept-old-versions', which tells Emacs how many oldest versions to keep,
4156 and `kept-new-versions', which tells how many newest versions to keep.
4157 Defaults are 2 old versions and 2 new.
4158 `dired-kept-versions' controls dired's clean-directory (.) command.
4159 If `delete-old-versions' is nil, system will query user
4160 before trimming versions. Otherwise it does it silently.
4161
4162 If `vc-make-backup-files' is nil, which is the default,
4163 no backup files are made for files managed by version control.
4164 (This is because the version control system itself records previous versions.)
4165
4166 See the subroutine `basic-save-buffer' for more information."
4167 (interactive "p")
4168 (let ((modp (buffer-modified-p))
4169 (make-backup-files (or (and make-backup-files (not (eq args 0)))
4170 (memq args '(16 64)))))
4171 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
4172 ;; We used to display the message below only for files > 50KB, but
4173 ;; then Rmail-mbox never displays it due to buffer swapping. If
4174 ;; the test is ever re-introduced, be sure to handle saving of
4175 ;; Rmail files.
4176 (if (and modp (buffer-file-name))
4177 (message "Saving file %s..." (buffer-file-name)))
4178 (basic-save-buffer)
4179 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
4180
4181 (defun delete-auto-save-file-if-necessary (&optional force)
4182 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
4183 Normally delete only if the file was written by this Emacs since
4184 the last real save, but optional arg FORCE non-nil means delete anyway."
4185 (and buffer-auto-save-file-name delete-auto-save-files
4186 (not (string= buffer-file-name buffer-auto-save-file-name))
4187 (or force (recent-auto-save-p))
4188 (progn
4189 (condition-case ()
4190 (delete-file buffer-auto-save-file-name)
4191 (file-error nil))
4192 (set-buffer-auto-saved))))
4193
4194 (defvar auto-save-hook nil
4195 "Normal hook run just before auto-saving.")
4196
4197 (defcustom before-save-hook nil
4198 "Normal hook that is run before a buffer is saved to its file."
4199 :options '(copyright-update time-stamp)
4200 :type 'hook
4201 :group 'files)
4202
4203 (defcustom after-save-hook nil
4204 "Normal hook that is run after a buffer is saved to its file."
4205 :options '(executable-make-buffer-file-executable-if-script-p)
4206 :type 'hook
4207 :group 'files)
4208
4209 (defvar save-buffer-coding-system nil
4210 "If non-nil, use this coding system for saving the buffer.
4211 More precisely, use this coding system in place of the
4212 value of `buffer-file-coding-system', when saving the buffer.
4213 Calling `write-region' for any purpose other than saving the buffer
4214 will still use `buffer-file-coding-system'; this variable has no effect
4215 in such cases.")
4216
4217 (make-variable-buffer-local 'save-buffer-coding-system)
4218 (put 'save-buffer-coding-system 'permanent-local t)
4219
4220 (defun basic-save-buffer ()
4221 "Save the current buffer in its visited file, if it has been modified.
4222 The hooks `write-contents-functions' and `write-file-functions' get a chance
4223 to do the job of saving; if they do not, then the buffer is saved in
4224 the visited file in the usual way.
4225 Before and after saving the buffer, this function runs
4226 `before-save-hook' and `after-save-hook', respectively."
4227 (interactive)
4228 (save-current-buffer
4229 ;; In an indirect buffer, save its base buffer instead.
4230 (if (buffer-base-buffer)
4231 (set-buffer (buffer-base-buffer)))
4232 (if (buffer-modified-p)
4233 (let ((recent-save (recent-auto-save-p))
4234 setmodes)
4235 ;; If buffer has no file name, ask user for one.
4236 (or buffer-file-name
4237 (let ((filename
4238 (expand-file-name
4239 (read-file-name "File to save in: ") nil)))
4240 (if (file-exists-p filename)
4241 (if (file-directory-p filename)
4242 ;; Signal an error if the user specified the name of an
4243 ;; existing directory.
4244 (error "%s is a directory" filename)
4245 (unless (y-or-n-p (format "File `%s' exists; overwrite? "
4246 filename))
4247 (error "Canceled")))
4248 ;; Signal an error if the specified name refers to a
4249 ;; non-existing directory.
4250 (let ((dir (file-name-directory filename)))
4251 (unless (file-directory-p dir)
4252 (if (file-exists-p dir)
4253 (error "%s is not a directory" dir)
4254 (error "%s: no such directory" dir)))))
4255 (set-visited-file-name filename)))
4256 (or (verify-visited-file-modtime (current-buffer))
4257 (not (file-exists-p buffer-file-name))
4258 (yes-or-no-p
4259 (format "%s has changed since visited or saved. Save anyway? "
4260 (file-name-nondirectory buffer-file-name)))
4261 (error "Save not confirmed"))
4262 (save-restriction
4263 (widen)
4264 (save-excursion
4265 (and (> (point-max) (point-min))
4266 (not find-file-literally)
4267 (/= (char-after (1- (point-max))) ?\n)
4268 (not (and (eq selective-display t)
4269 (= (char-after (1- (point-max))) ?\r)))
4270 (or (eq require-final-newline t)
4271 (eq require-final-newline 'visit-save)
4272 (and require-final-newline
4273 (y-or-n-p
4274 (format "Buffer %s does not end in newline. Add one? "
4275 (buffer-name)))))
4276 (save-excursion
4277 (goto-char (point-max))
4278 (insert ?\n))))
4279 ;; Support VC version backups.
4280 (vc-before-save)
4281 (run-hooks 'before-save-hook)
4282 (or (run-hook-with-args-until-success 'write-contents-functions)
4283 (run-hook-with-args-until-success 'local-write-file-hooks)
4284 (run-hook-with-args-until-success 'write-file-functions)
4285 ;; If a hook returned t, file is already "written".
4286 ;; Otherwise, write it the usual way now.
4287 (setq setmodes (basic-save-buffer-1)))
4288 ;; Now we have saved the current buffer. Let's make sure
4289 ;; that buffer-file-coding-system is fixed to what
4290 ;; actually used for saving by binding it locally.
4291 (if save-buffer-coding-system
4292 (setq save-buffer-coding-system last-coding-system-used)
4293 (setq buffer-file-coding-system last-coding-system-used))
4294 (setq buffer-file-number
4295 (nthcdr 10 (file-attributes buffer-file-name)))
4296 (if setmodes
4297 (condition-case ()
4298 (progn
4299 (set-file-modes buffer-file-name (car setmodes))
4300 (set-file-selinux-context buffer-file-name (nth 1 setmodes)))
4301 (error nil))))
4302 ;; If the auto-save file was recent before this command,
4303 ;; delete it now.
4304 (delete-auto-save-file-if-necessary recent-save)
4305 ;; Support VC `implicit' locking.
4306 (vc-after-save)
4307 (run-hooks 'after-save-hook))
4308 (message "(No changes need to be saved)"))))
4309
4310 ;; This does the "real job" of writing a buffer into its visited file
4311 ;; and making a backup file. This is what is normally done
4312 ;; but inhibited if one of write-file-functions returns non-nil.
4313 ;; It returns a value (MODES SELINUXCONTEXT BACKUPNAME), like backup-buffer.
4314 (defun basic-save-buffer-1 ()
4315 (prog1
4316 (if save-buffer-coding-system
4317 (let ((coding-system-for-write save-buffer-coding-system))
4318 (basic-save-buffer-2))
4319 (basic-save-buffer-2))
4320 (if buffer-file-coding-system-explicit
4321 (setcar buffer-file-coding-system-explicit last-coding-system-used)
4322 (setq buffer-file-coding-system-explicit
4323 (cons last-coding-system-used nil)))))
4324
4325 ;; This returns a value (MODES SELINUXCONTEXT BACKUPNAME), like backup-buffer.
4326 (defun basic-save-buffer-2 ()
4327 (let (tempsetmodes setmodes)
4328 (if (not (file-writable-p buffer-file-name))
4329 (let ((dir (file-name-directory buffer-file-name)))
4330 (if (not (file-directory-p dir))
4331 (if (file-exists-p dir)
4332 (error "%s is not a directory" dir)
4333 (error "%s: no such directory" dir))
4334 (if (not (file-exists-p buffer-file-name))
4335 (error "Directory %s write-protected" dir)
4336 (if (yes-or-no-p
4337 (format "File %s is write-protected; try to save anyway? "
4338 (file-name-nondirectory
4339 buffer-file-name)))
4340 (setq tempsetmodes t)
4341 (error "Attempt to save to a file which you aren't allowed to write"))))))
4342 (or buffer-backed-up
4343 (setq setmodes (backup-buffer)))
4344 (let* ((dir (file-name-directory buffer-file-name))
4345 (dir-writable (file-writable-p dir)))
4346 (if (or (and file-precious-flag dir-writable)
4347 (and break-hardlink-on-save
4348 (> (file-nlinks buffer-file-name) 1)
4349 (or dir-writable
4350 (error (concat (format
4351 "Directory %s write-protected; " dir)
4352 "cannot break hardlink when saving")))))
4353 ;; Write temp name, then rename it.
4354 ;; This requires write access to the containing dir,
4355 ;; which is why we don't try it if we don't have that access.
4356 (let ((realname buffer-file-name)
4357 tempname succeed
4358 (umask (default-file-modes))
4359 (old-modtime (visited-file-modtime)))
4360 ;; Create temp files with strict access rights. It's easy to
4361 ;; loosen them later, whereas it's impossible to close the
4362 ;; time-window of loose permissions otherwise.
4363 (unwind-protect
4364 (progn
4365 (clear-visited-file-modtime)
4366 (set-default-file-modes ?\700)
4367 ;; Try various temporary names.
4368 ;; This code follows the example of make-temp-file,
4369 ;; but it calls write-region in the appropriate way
4370 ;; for saving the buffer.
4371 (while (condition-case ()
4372 (progn
4373 (setq tempname
4374 (make-temp-name
4375 (expand-file-name "tmp" dir)))
4376 ;; Pass in nil&nil rather than point-min&max
4377 ;; cause we're saving the whole buffer.
4378 ;; write-region-annotate-functions may use it.
4379 (write-region nil nil
4380 tempname nil realname
4381 buffer-file-truename 'excl)
4382 nil)
4383 (file-already-exists t))
4384 ;; The file was somehow created by someone else between
4385 ;; `make-temp-name' and `write-region', let's try again.
4386 nil)
4387 (setq succeed t))
4388 ;; Reset the umask.
4389 (set-default-file-modes umask)
4390 ;; If we failed, restore the buffer's modtime.
4391 (unless succeed
4392 (set-visited-file-modtime old-modtime)))
4393 ;; Since we have created an entirely new file,
4394 ;; make sure it gets the right permission bits set.
4395 (setq setmodes (or setmodes
4396 (list (or (file-modes buffer-file-name)
4397 (logand ?\666 umask))
4398 (file-selinux-context buffer-file-name)
4399 buffer-file-name)))
4400 ;; We succeeded in writing the temp file,
4401 ;; so rename it.
4402 (rename-file tempname buffer-file-name t))
4403 ;; If file not writable, see if we can make it writable
4404 ;; temporarily while we write it.
4405 ;; But no need to do so if we have just backed it up
4406 ;; (setmodes is set) because that says we're superseding.
4407 (cond ((and tempsetmodes (not setmodes))
4408 ;; Change the mode back, after writing.
4409 (setq setmodes (list (file-modes buffer-file-name)
4410 (file-selinux-context buffer-file-name)
4411 buffer-file-name))
4412 (set-file-modes buffer-file-name (logior (car setmodes) 128))
4413 (set-file-selinux-context buffer-file-name (nth 1 setmodes)))))
4414 (let (success)
4415 (unwind-protect
4416 (progn
4417 ;; Pass in nil&nil rather than point-min&max to indicate
4418 ;; we're saving the buffer rather than just a region.
4419 ;; write-region-annotate-functions may make us of it.
4420 (write-region nil nil
4421 buffer-file-name nil t buffer-file-truename)
4422 (setq success t))
4423 ;; If we get an error writing the new file, and we made
4424 ;; the backup by renaming, undo the backing-up.
4425 (and setmodes (not success)
4426 (progn
4427 (rename-file (nth 2 setmodes) buffer-file-name t)
4428 (setq buffer-backed-up nil))))))
4429 setmodes))
4430
4431 (defun diff-buffer-with-file (&optional buffer)
4432 "View the differences between BUFFER and its associated file.
4433 This requires the external program `diff' to be in your `exec-path'."
4434 (interactive "bBuffer: ")
4435 (with-current-buffer (get-buffer (or buffer (current-buffer)))
4436 (if (and buffer-file-name
4437 (file-exists-p buffer-file-name))
4438 (let ((tempfile (make-temp-file "buffer-content-")))
4439 (unwind-protect
4440 (progn
4441 (write-region nil nil tempfile nil 'nomessage)
4442 (diff buffer-file-name tempfile nil t)
4443 (sit-for 0))
4444 (when (file-exists-p tempfile)
4445 (delete-file tempfile))))
4446 (message "Buffer %s has no associated file on disc" (buffer-name))
4447 ;; Display that message for 1 second so that user can read it
4448 ;; in the minibuffer.
4449 (sit-for 1)))
4450 ;; return always nil, so that save-buffers-kill-emacs will not move
4451 ;; over to the next unsaved buffer when calling `d'.
4452 nil)
4453
4454 (defvar save-some-buffers-action-alist
4455 `((?\C-r
4456 ,(lambda (buf)
4457 (if (not enable-recursive-minibuffers)
4458 (progn (display-buffer buf)
4459 (setq other-window-scroll-buffer buf))
4460 (view-buffer buf (lambda (_) (exit-recursive-edit)))
4461 (recursive-edit))
4462 ;; Return nil to ask about BUF again.
4463 nil)
4464 ,(purecopy "view this buffer"))
4465 (?d ,(lambda (buf)
4466 (if (null (buffer-file-name buf))
4467 (message "Not applicable: no file")
4468 (save-window-excursion (diff-buffer-with-file buf))
4469 (if (not enable-recursive-minibuffers)
4470 (progn (display-buffer (get-buffer-create "*Diff*"))
4471 (setq other-window-scroll-buffer "*Diff*"))
4472 (view-buffer (get-buffer-create "*Diff*")
4473 (lambda (_) (exit-recursive-edit)))
4474 (recursive-edit)))
4475 ;; Return nil to ask about BUF again.
4476 nil)
4477 ,(purecopy "view changes in this buffer")))
4478 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
4479 (put 'save-some-buffers-action-alist 'risky-local-variable t)
4480
4481 (defvar buffer-save-without-query nil
4482 "Non-nil means `save-some-buffers' should save this buffer without asking.")
4483 (make-variable-buffer-local 'buffer-save-without-query)
4484
4485 (defun save-some-buffers (&optional arg pred)
4486 "Save some modified file-visiting buffers. Asks user about each one.
4487 You can answer `y' to save, `n' not to save, `C-r' to look at the
4488 buffer in question with `view-buffer' before deciding or `d' to
4489 view the differences using `diff-buffer-with-file'.
4490
4491 Optional argument (the prefix) non-nil means save all with no questions.
4492 Optional second argument PRED determines which buffers are considered:
4493 If PRED is nil, all the file-visiting buffers are considered.
4494 If PRED is t, then certain non-file buffers will also be considered.
4495 If PRED is a zero-argument function, it indicates for each buffer whether
4496 to consider it or not when called with that buffer current.
4497
4498 See `save-some-buffers-action-alist' if you want to
4499 change the additional actions you can take on files."
4500 (interactive "P")
4501 (save-window-excursion
4502 (let* (queried some-automatic
4503 files-done abbrevs-done)
4504 (dolist (buffer (buffer-list))
4505 ;; First save any buffers that we're supposed to save unconditionally.
4506 ;; That way the following code won't ask about them.
4507 (with-current-buffer buffer
4508 (when (and buffer-save-without-query (buffer-modified-p))
4509 (setq some-automatic t)
4510 (save-buffer))))
4511 ;; Ask about those buffers that merit it,
4512 ;; and record the number thus saved.
4513 (setq files-done
4514 (map-y-or-n-p
4515 (lambda (buffer)
4516 ;; Note that killing some buffers may kill others via
4517 ;; hooks (e.g. Rmail and its viewing buffer).
4518 (and (buffer-live-p buffer)
4519 (buffer-modified-p buffer)
4520 (not (buffer-base-buffer buffer))
4521 (or
4522 (buffer-file-name buffer)
4523 (and pred
4524 (progn
4525 (set-buffer buffer)
4526 (and buffer-offer-save (> (buffer-size) 0)))))
4527 (or (not (functionp pred))
4528 (with-current-buffer buffer (funcall pred)))
4529 (if arg
4530 t
4531 (setq queried t)
4532 (if (buffer-file-name buffer)
4533 (format "Save file %s? "
4534 (buffer-file-name buffer))
4535 (format "Save buffer %s? "
4536 (buffer-name buffer))))))
4537 (lambda (buffer)
4538 (with-current-buffer buffer
4539 (save-buffer)))
4540 (buffer-list)
4541 '("buffer" "buffers" "save")
4542 save-some-buffers-action-alist))
4543 ;; Maybe to save abbrevs, and record whether
4544 ;; we either saved them or asked to.
4545 (and save-abbrevs abbrevs-changed
4546 (progn
4547 (if (or arg
4548 (eq save-abbrevs 'silently)
4549 (y-or-n-p (format "Save abbrevs in %s? "
4550 abbrev-file-name)))
4551 (write-abbrev-file nil))
4552 ;; Don't keep bothering user if he says no.
4553 (setq abbrevs-changed nil)
4554 (setq abbrevs-done t)))
4555 (or queried (> files-done 0) abbrevs-done
4556 (message (if some-automatic
4557 "(Some special files were saved without asking)"
4558 "(No files need saving)"))))))
4559 \f
4560 (defun not-modified (&optional arg)
4561 "Mark current buffer as unmodified, not needing to be saved.
4562 With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
4563
4564 It is not a good idea to use this function in Lisp programs, because it
4565 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
4566 (interactive "P")
4567 (message (if arg "Modification-flag set"
4568 "Modification-flag cleared"))
4569 (set-buffer-modified-p arg))
4570
4571 (defun toggle-read-only (&optional arg)
4572 "Change whether this buffer is read-only.
4573 With prefix argument ARG, make the buffer read-only if ARG is
4574 positive, otherwise make it writable. If buffer is read-only
4575 and `view-read-only' is non-nil, enter view mode."
4576 (interactive "P")
4577 (if (and arg
4578 (if (> (prefix-numeric-value arg) 0) buffer-read-only
4579 (not buffer-read-only))) ; If buffer-read-only is set correctly,
4580 nil ; do nothing.
4581 ;; Toggle.
4582 (cond
4583 ((and buffer-read-only view-mode)
4584 (View-exit-and-edit)
4585 (make-local-variable 'view-read-only)
4586 (setq view-read-only t)) ; Must leave view mode.
4587 ((and (not buffer-read-only) view-read-only
4588 ;; If view-mode is already active, `view-mode-enter' is a nop.
4589 (not view-mode)
4590 (not (eq (get major-mode 'mode-class) 'special)))
4591 (view-mode-enter))
4592 (t (setq buffer-read-only (not buffer-read-only))
4593 (force-mode-line-update)))
4594 (if (vc-backend buffer-file-name)
4595 (message "%s" (substitute-command-keys
4596 (concat "File is under version-control; "
4597 "use \\[vc-next-action] to check in/out"))))))
4598
4599 (defun insert-file (filename)
4600 "Insert contents of file FILENAME into buffer after point.
4601 Set mark after the inserted text.
4602
4603 This function is meant for the user to run interactively.
4604 Don't call it from programs! Use `insert-file-contents' instead.
4605 \(Its calling sequence is different; see its documentation)."
4606 (interactive "*fInsert file: ")
4607 (insert-file-1 filename #'insert-file-contents))
4608
4609 (defun append-to-file (start end filename)
4610 "Append the contents of the region to the end of file FILENAME.
4611 When called from a function, expects three arguments,
4612 START, END and FILENAME. START and END are normally buffer positions
4613 specifying the part of the buffer to write.
4614 If START is nil, that means to use the entire buffer contents.
4615 If START is a string, then output that string to the file
4616 instead of any buffer contents; END is ignored.
4617
4618 This does character code conversion and applies annotations
4619 like `write-region' does."
4620 (interactive "r\nFAppend to file: ")
4621 (write-region start end filename t))
4622
4623 (defun file-newest-backup (filename)
4624 "Return most recent backup file for FILENAME or nil if no backups exist."
4625 ;; `make-backup-file-name' will get us the right directory for
4626 ;; ordinary or numeric backups. It might create a directory for
4627 ;; backups as a side-effect, according to `backup-directory-alist'.
4628 (let* ((filename (file-name-sans-versions
4629 (make-backup-file-name (expand-file-name filename))))
4630 (file (file-name-nondirectory filename))
4631 (dir (file-name-directory filename))
4632 (comp (file-name-all-completions file dir))
4633 (newest nil)
4634 tem)
4635 (while comp
4636 (setq tem (pop comp))
4637 (cond ((and (backup-file-name-p tem)
4638 (string= (file-name-sans-versions tem) file))
4639 (setq tem (concat dir tem))
4640 (if (or (null newest)
4641 (file-newer-than-file-p tem newest))
4642 (setq newest tem)))))
4643 newest))
4644
4645 (defun rename-uniquely ()
4646 "Rename current buffer to a similar name not already taken.
4647 This function is useful for creating multiple shell process buffers
4648 or multiple mail buffers, etc."
4649 (interactive)
4650 (save-match-data
4651 (let ((base-name (buffer-name)))
4652 (and (string-match "<[0-9]+>\\'" base-name)
4653 (not (and buffer-file-name
4654 (string= base-name
4655 (file-name-nondirectory buffer-file-name))))
4656 ;; If the existing buffer name has a <NNN>,
4657 ;; which isn't part of the file name (if any),
4658 ;; then get rid of that.
4659 (setq base-name (substring base-name 0 (match-beginning 0))))
4660 (rename-buffer (generate-new-buffer-name base-name))
4661 (force-mode-line-update))))
4662
4663 (defun make-directory (dir &optional parents)
4664 "Create the directory DIR and optionally any nonexistent parent dirs.
4665 If DIR already exists as a directory, signal an error, unless
4666 PARENTS is non-nil.
4667
4668 Interactively, the default choice of directory to create is the
4669 current buffer's default directory. That is useful when you have
4670 visited a file in a nonexistent directory.
4671
4672 Noninteractively, the second (optional) argument PARENTS, if
4673 non-nil, says whether to create parent directories that don't
4674 exist. Interactively, this happens by default."
4675 (interactive
4676 (list (read-file-name "Make directory: " default-directory default-directory
4677 nil nil)
4678 t))
4679 ;; If default-directory is a remote directory,
4680 ;; make sure we find its make-directory handler.
4681 (setq dir (expand-file-name dir))
4682 (let ((handler (find-file-name-handler dir 'make-directory)))
4683 (if handler
4684 (funcall handler 'make-directory dir parents)
4685 (if (not parents)
4686 (make-directory-internal dir)
4687 (let ((dir (directory-file-name (expand-file-name dir)))
4688 create-list)
4689 (while (and (not (file-exists-p dir))
4690 ;; If directory is its own parent, then we can't
4691 ;; keep looping forever
4692 (not (equal dir
4693 (directory-file-name
4694 (file-name-directory dir)))))
4695 (setq create-list (cons dir create-list)
4696 dir (directory-file-name (file-name-directory dir))))
4697 (while create-list
4698 (make-directory-internal (car create-list))
4699 (setq create-list (cdr create-list))))))))
4700
4701 (defconst directory-files-no-dot-files-regexp
4702 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"
4703 "Regexp matching any file name except \".\" and \"..\".")
4704
4705 (defun delete-directory (directory &optional recursive trash)
4706 "Delete the directory named DIRECTORY. Does not follow symlinks.
4707 If RECURSIVE is non-nil, all files in DIRECTORY are deleted as well.
4708 TRASH non-nil means to trash the directory instead, provided
4709 `delete-by-moving-to-trash' is non-nil.
4710
4711 When called interactively, TRASH is t if no prefix argument is
4712 given. With a prefix argument, TRASH is nil."
4713 (interactive
4714 (let* ((trashing (and delete-by-moving-to-trash
4715 (null current-prefix-arg)))
4716 (dir (expand-file-name
4717 (read-file-name
4718 (if trashing
4719 "Move directory to trash: "
4720 "Delete directory: ")
4721 default-directory default-directory nil nil))))
4722 (list dir
4723 (if (directory-files dir nil directory-files-no-dot-files-regexp)
4724 (y-or-n-p
4725 (format "Directory `%s' is not empty, really %s? "
4726 dir (if trashing "trash" "delete")))
4727 nil)
4728 (null current-prefix-arg))))
4729 ;; If default-directory is a remote directory, make sure we find its
4730 ;; delete-directory handler.
4731 (setq directory (directory-file-name (expand-file-name directory)))
4732 (let ((handler (find-file-name-handler directory 'delete-directory)))
4733 (cond
4734 (handler
4735 (funcall handler 'delete-directory directory recursive))
4736 ((and delete-by-moving-to-trash trash)
4737 ;; Only move non-empty dir to trash if recursive deletion was
4738 ;; requested. This mimics the non-`delete-by-moving-to-trash'
4739 ;; case, where the operation fails in delete-directory-internal.
4740 ;; As `move-file-to-trash' trashes directories (empty or
4741 ;; otherwise) as a unit, we do not need to recurse here.
4742 (if (and (not recursive)
4743 ;; Check if directory is empty apart from "." and "..".
4744 (directory-files
4745 directory 'full directory-files-no-dot-files-regexp))
4746 (error "Directory is not empty, not moving to trash")
4747 (move-file-to-trash directory)))
4748 ;; Otherwise, call outselves recursively if needed.
4749 (t
4750 (if (and recursive (not (file-symlink-p directory)))
4751 (mapc (lambda (file)
4752 ;; This test is equivalent to
4753 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
4754 ;; but more efficient
4755 (if (eq t (car (file-attributes file)))
4756 (delete-directory file recursive nil)
4757 (delete-file file nil)))
4758 ;; We do not want to delete "." and "..".
4759 (directory-files
4760 directory 'full directory-files-no-dot-files-regexp)))
4761 (delete-directory-internal directory)))))
4762
4763 (defun copy-directory (directory newname &optional keep-time parents)
4764 "Copy DIRECTORY to NEWNAME. Both args must be strings.
4765 If NEWNAME names an existing directory, copy DIRECTORY as subdirectory there.
4766
4767 This function always sets the file modes of the output files to match
4768 the corresponding input file.
4769
4770 The third arg KEEP-TIME non-nil means give the output files the same
4771 last-modified time as the old ones. (This works on only some systems.)
4772
4773 A prefix arg makes KEEP-TIME non-nil.
4774
4775 Noninteractively, the last argument PARENTS says whether to
4776 create parent directories if they don't exist. Interactively,
4777 this happens by default."
4778 (interactive
4779 (let ((dir (read-directory-name
4780 "Copy directory: " default-directory default-directory t nil)))
4781 (list dir
4782 (read-file-name
4783 (format "Copy directory %s to: " dir)
4784 default-directory default-directory nil nil)
4785 current-prefix-arg t)))
4786 ;; If default-directory is a remote directory, make sure we find its
4787 ;; copy-directory handler.
4788 (let ((handler (or (find-file-name-handler directory 'copy-directory)
4789 (find-file-name-handler newname 'copy-directory))))
4790 (if handler
4791 (funcall handler 'copy-directory directory newname keep-time parents)
4792
4793 ;; Compute target name.
4794 (setq directory (directory-file-name (expand-file-name directory))
4795 newname (directory-file-name (expand-file-name newname)))
4796 (if (not (file-directory-p newname)) (make-directory newname parents))
4797
4798 ;; Copy recursively.
4799 (mapc
4800 (lambda (file)
4801 (let ((target (expand-file-name
4802 (file-name-nondirectory file) newname))
4803 (attrs (file-attributes file)))
4804 (cond ((file-directory-p file)
4805 (copy-directory file target keep-time parents))
4806 ((stringp (car attrs)) ; Symbolic link
4807 (make-symbolic-link (car attrs) target t))
4808 (t
4809 (copy-file file target t keep-time)))))
4810 ;; We do not want to copy "." and "..".
4811 (directory-files directory 'full directory-files-no-dot-files-regexp))
4812
4813 ;; Set directory attributes.
4814 (set-file-modes newname (file-modes directory))
4815 (if keep-time
4816 (set-file-times newname (nth 5 (file-attributes directory)))))))
4817 \f
4818 (put 'revert-buffer-function 'permanent-local t)
4819 (defvar revert-buffer-function nil
4820 "Function to use to revert this buffer, or nil to do the default.
4821 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
4822 which are the arguments that `revert-buffer' received.")
4823
4824 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
4825 (defvar revert-buffer-insert-file-contents-function nil
4826 "Function to use to insert contents when reverting this buffer.
4827 Gets two args, first the nominal file name to use,
4828 and second, t if reading the auto-save file.
4829
4830 The function you specify is responsible for updating (or preserving) point.")
4831
4832 (defvar buffer-stale-function nil
4833 "Function to check whether a non-file buffer needs reverting.
4834 This should be a function with one optional argument NOCONFIRM.
4835 Auto Revert Mode passes t for NOCONFIRM. The function should return
4836 non-nil if the buffer should be reverted. A return value of
4837 `fast' means that the need for reverting was not checked, but
4838 that reverting the buffer is fast. The buffer is current when
4839 this function is called.
4840
4841 The idea behind the NOCONFIRM argument is that it should be
4842 non-nil if the buffer is going to be reverted without asking the
4843 user. In such situations, one has to be careful with potentially
4844 time consuming operations.
4845
4846 For more information on how this variable is used by Auto Revert mode,
4847 see Info node `(emacs)Supporting additional buffers'.")
4848
4849 (defvar before-revert-hook nil
4850 "Normal hook for `revert-buffer' to run before reverting.
4851 If `revert-buffer-function' is used to override the normal revert
4852 mechanism, this hook is not used.")
4853
4854 (defvar after-revert-hook nil
4855 "Normal hook for `revert-buffer' to run after reverting.
4856 Note that the hook value that it runs is the value that was in effect
4857 before reverting; that makes a difference if you have buffer-local
4858 hook functions.
4859
4860 If `revert-buffer-function' is used to override the normal revert
4861 mechanism, this hook is not used.")
4862
4863 (defvar revert-buffer-internal-hook)
4864
4865 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
4866 "Replace current buffer text with the text of the visited file on disk.
4867 This undoes all changes since the file was visited or saved.
4868 With a prefix argument, offer to revert from latest auto-save file, if
4869 that is more recent than the visited file.
4870
4871 This command also implements an interface for special buffers
4872 that contain text which doesn't come from a file, but reflects
4873 some other data instead (e.g. Dired buffers, `buffer-list'
4874 buffers). This is done via the variable `revert-buffer-function'.
4875 In these cases, it should reconstruct the buffer contents from the
4876 appropriate data.
4877
4878 When called from Lisp, the first argument is IGNORE-AUTO; only offer
4879 to revert from the auto-save file when this is nil. Note that the
4880 sense of this argument is the reverse of the prefix argument, for the
4881 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
4882 to nil.
4883
4884 Optional second argument NOCONFIRM means don't ask for confirmation
4885 at all. \(The variable `revert-without-query' offers another way to
4886 revert buffers without querying for confirmation.)
4887
4888 Optional third argument PRESERVE-MODES non-nil means don't alter
4889 the files modes. Normally we reinitialize them using `normal-mode'.
4890
4891 If the value of `revert-buffer-function' is non-nil, it is called to
4892 do all the work for this command. Otherwise, the hooks
4893 `before-revert-hook' and `after-revert-hook' are run at the beginning
4894 and the end, and if `revert-buffer-insert-file-contents-function' is
4895 non-nil, it is called instead of rereading visited file contents."
4896
4897 ;; I admit it's odd to reverse the sense of the prefix argument, but
4898 ;; there is a lot of code out there which assumes that the first
4899 ;; argument should be t to avoid consulting the auto-save file, and
4900 ;; there's no straightforward way to encourage authors to notice a
4901 ;; reversal of the argument sense. So I'm just changing the user
4902 ;; interface, but leaving the programmatic interface the same.
4903 (interactive (list (not current-prefix-arg)))
4904 (if revert-buffer-function
4905 (funcall revert-buffer-function ignore-auto noconfirm)
4906 (with-current-buffer (or (buffer-base-buffer (current-buffer))
4907 (current-buffer))
4908 (let* ((auto-save-p (and (not ignore-auto)
4909 (recent-auto-save-p)
4910 buffer-auto-save-file-name
4911 (file-readable-p buffer-auto-save-file-name)
4912 (y-or-n-p
4913 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
4914 (file-name (if auto-save-p
4915 buffer-auto-save-file-name
4916 buffer-file-name)))
4917 (cond ((null file-name)
4918 (error "Buffer does not seem to be associated with any file"))
4919 ((or noconfirm
4920 (and (not (buffer-modified-p))
4921 (catch 'found
4922 (dolist (regexp revert-without-query)
4923 (when (string-match regexp file-name)
4924 (throw 'found t)))))
4925 (yes-or-no-p (format "Revert buffer from file %s? "
4926 file-name)))
4927 (run-hooks 'before-revert-hook)
4928 ;; If file was backed up but has changed since,
4929 ;; we should make another backup.
4930 (and (not auto-save-p)
4931 (not (verify-visited-file-modtime (current-buffer)))
4932 (setq buffer-backed-up nil))
4933 ;; Effectively copy the after-revert-hook status,
4934 ;; since after-find-file will clobber it.
4935 (let ((global-hook (default-value 'after-revert-hook))
4936 (local-hook (when (local-variable-p 'after-revert-hook)
4937 after-revert-hook))
4938 (inhibit-read-only t))
4939 (cond
4940 (revert-buffer-insert-file-contents-function
4941 (unless (eq buffer-undo-list t)
4942 ;; Get rid of all undo records for this buffer.
4943 (setq buffer-undo-list nil))
4944 ;; Don't make undo records for the reversion.
4945 (let ((buffer-undo-list t))
4946 (funcall revert-buffer-insert-file-contents-function
4947 file-name auto-save-p)))
4948 ((not (file-exists-p file-name))
4949 (error (if buffer-file-number
4950 "File %s no longer exists!"
4951 "Cannot revert nonexistent file %s")
4952 file-name))
4953 ((not (file-readable-p file-name))
4954 (error (if buffer-file-number
4955 "File %s no longer readable!"
4956 "Cannot revert unreadable file %s")
4957 file-name))
4958 (t
4959 ;; Bind buffer-file-name to nil
4960 ;; so that we don't try to lock the file.
4961 (let ((buffer-file-name nil))
4962 (or auto-save-p
4963 (unlock-buffer)))
4964 (widen)
4965 (let ((coding-system-for-read
4966 ;; Auto-saved file should be read by Emacs'
4967 ;; internal coding.
4968 (if auto-save-p 'auto-save-coding
4969 (or coding-system-for-read
4970 (and
4971 buffer-file-coding-system-explicit
4972 (car buffer-file-coding-system-explicit))))))
4973 (if (and (not enable-multibyte-characters)
4974 coding-system-for-read
4975 (not (memq (coding-system-base
4976 coding-system-for-read)
4977 '(no-conversion raw-text))))
4978 ;; As a coding system suitable for multibyte
4979 ;; buffer is specified, make the current
4980 ;; buffer multibyte.
4981 (set-buffer-multibyte t))
4982
4983 ;; This force after-insert-file-set-coding
4984 ;; (called from insert-file-contents) to set
4985 ;; buffer-file-coding-system to a proper value.
4986 (kill-local-variable 'buffer-file-coding-system)
4987
4988 ;; Note that this preserves point in an intelligent way.
4989 (if preserve-modes
4990 (let ((buffer-file-format buffer-file-format))
4991 (insert-file-contents file-name (not auto-save-p)
4992 nil nil t))
4993 (insert-file-contents file-name (not auto-save-p)
4994 nil nil t)))))
4995 ;; Recompute the truename in case changes in symlinks
4996 ;; have changed the truename.
4997 (setq buffer-file-truename
4998 (abbreviate-file-name (file-truename buffer-file-name)))
4999 (after-find-file nil nil t t preserve-modes)
5000 ;; Run after-revert-hook as it was before we reverted.
5001 (setq-default revert-buffer-internal-hook global-hook)
5002 (if local-hook
5003 (set (make-local-variable 'revert-buffer-internal-hook)
5004 local-hook)
5005 (kill-local-variable 'revert-buffer-internal-hook))
5006 (run-hooks 'revert-buffer-internal-hook))
5007 t))))))
5008
5009 (defun recover-this-file ()
5010 "Recover the visited file--get contents from its last auto-save file."
5011 (interactive)
5012 (recover-file buffer-file-name))
5013
5014 (defun recover-file (file)
5015 "Visit file FILE, but get contents from its last auto-save file."
5016 ;; Actually putting the file name in the minibuffer should be used
5017 ;; only rarely.
5018 ;; Not just because users often use the default.
5019 (interactive "FRecover file: ")
5020 (setq file (expand-file-name file))
5021 (if (auto-save-file-name-p (file-name-nondirectory file))
5022 (error "%s is an auto-save file" (abbreviate-file-name file)))
5023 (let ((file-name (let ((buffer-file-name file))
5024 (make-auto-save-file-name))))
5025 (cond ((if (file-exists-p file)
5026 (not (file-newer-than-file-p file-name file))
5027 (not (file-exists-p file-name)))
5028 (error "Auto-save file %s not current"
5029 (abbreviate-file-name file-name)))
5030 ((save-window-excursion
5031 (with-output-to-temp-buffer "*Directory*"
5032 (buffer-disable-undo standard-output)
5033 (save-excursion
5034 (let ((switches dired-listing-switches))
5035 (if (file-symlink-p file)
5036 (setq switches (concat switches "L")))
5037 (set-buffer standard-output)
5038 ;; Use insert-directory-safely, not insert-directory,
5039 ;; because these files might not exist. In particular,
5040 ;; FILE might not exist if the auto-save file was for
5041 ;; a buffer that didn't visit a file, such as "*mail*".
5042 ;; The code in v20.x called `ls' directly, so we need
5043 ;; to emulate what `ls' did in that case.
5044 (insert-directory-safely file switches)
5045 (insert-directory-safely file-name switches))))
5046 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5047 (switch-to-buffer (find-file-noselect file t))
5048 (let ((inhibit-read-only t)
5049 ;; Keep the current buffer-file-coding-system.
5050 (coding-system buffer-file-coding-system)
5051 ;; Auto-saved file should be read with special coding.
5052 (coding-system-for-read 'auto-save-coding))
5053 (erase-buffer)
5054 (insert-file-contents file-name nil)
5055 (set-buffer-file-coding-system coding-system))
5056 (after-find-file nil nil t))
5057 (t (error "Recover-file cancelled")))))
5058
5059 (defun recover-session ()
5060 "Recover auto save files from a previous Emacs session.
5061 This command first displays a Dired buffer showing you the
5062 previous sessions that you could recover from.
5063 To choose one, move point to the proper line and then type C-c C-c.
5064 Then you'll be asked about a number of files to recover."
5065 (interactive)
5066 (if (null auto-save-list-file-prefix)
5067 (error "You set `auto-save-list-file-prefix' to disable making session files"))
5068 (let ((dir (file-name-directory auto-save-list-file-prefix)))
5069 (unless (file-directory-p dir)
5070 (make-directory dir t))
5071 (unless (directory-files dir nil
5072 (concat "\\`" (regexp-quote
5073 (file-name-nondirectory
5074 auto-save-list-file-prefix)))
5075 t)
5076 (error "No previous sessions to recover")))
5077 (let ((ls-lisp-support-shell-wildcards t))
5078 (dired (concat auto-save-list-file-prefix "*")
5079 (concat dired-listing-switches "t")))
5080 (save-excursion
5081 (goto-char (point-min))
5082 (or (looking-at " Move to the session you want to recover,")
5083 (let ((inhibit-read-only t))
5084 ;; Each line starts with a space
5085 ;; so that Font Lock mode won't highlight the first character.
5086 (insert " Move to the session you want to recover,\n"
5087 " then type C-c C-c to select it.\n\n"
5088 " You can also delete some of these files;\n"
5089 " type d on a line to mark that file for deletion.\n\n"))))
5090 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
5091 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
5092
5093 (defun recover-session-finish ()
5094 "Choose one saved session to recover auto-save files from.
5095 This command is used in the special Dired buffer created by
5096 \\[recover-session]."
5097 (interactive)
5098 ;; Get the name of the session file to recover from.
5099 (let ((file (dired-get-filename))
5100 files
5101 (buffer (get-buffer-create " *recover*")))
5102 (dired-unmark 1)
5103 (dired-do-flagged-delete t)
5104 (unwind-protect
5105 (with-current-buffer buffer
5106 ;; Read in the auto-save-list file.
5107 (erase-buffer)
5108 (insert-file-contents file)
5109 ;; Loop thru the text of that file
5110 ;; and get out the names of the files to recover.
5111 (while (not (eobp))
5112 (let (thisfile autofile)
5113 (if (eolp)
5114 ;; This is a pair of lines for a non-file-visiting buffer.
5115 ;; Get the auto-save file name and manufacture
5116 ;; a "visited file name" from that.
5117 (progn
5118 (forward-line 1)
5119 ;; If there is no auto-save file name, the
5120 ;; auto-save-list file is probably corrupted.
5121 (unless (eolp)
5122 (setq autofile
5123 (buffer-substring-no-properties
5124 (point)
5125 (line-end-position)))
5126 (setq thisfile
5127 (expand-file-name
5128 (substring
5129 (file-name-nondirectory autofile)
5130 1 -1)
5131 (file-name-directory autofile))))
5132 (forward-line 1))
5133 ;; This pair of lines is a file-visiting
5134 ;; buffer. Use the visited file name.
5135 (progn
5136 (setq thisfile
5137 (buffer-substring-no-properties
5138 (point) (progn (end-of-line) (point))))
5139 (forward-line 1)
5140 (setq autofile
5141 (buffer-substring-no-properties
5142 (point) (progn (end-of-line) (point))))
5143 (forward-line 1)))
5144 ;; Ignore a file if its auto-save file does not exist now.
5145 (if (and autofile (file-exists-p autofile))
5146 (setq files (cons thisfile files)))))
5147 (setq files (nreverse files))
5148 ;; The file contains a pair of line for each auto-saved buffer.
5149 ;; The first line of the pair contains the visited file name
5150 ;; or is empty if the buffer was not visiting a file.
5151 ;; The second line is the auto-save file name.
5152 (if files
5153 (map-y-or-n-p "Recover %s? "
5154 (lambda (file)
5155 (condition-case nil
5156 (save-excursion (recover-file file))
5157 (error
5158 "Failed to recover `%s'" file)))
5159 files
5160 '("file" "files" "recover"))
5161 (message "No files can be recovered from this session now")))
5162 (kill-buffer buffer))))
5163
5164 (defun kill-buffer-ask (buffer)
5165 "Kill BUFFER if confirmed."
5166 (when (yes-or-no-p
5167 (format "Buffer %s %s. Kill? " (buffer-name buffer)
5168 (if (buffer-modified-p buffer)
5169 "HAS BEEN EDITED" "is unmodified")))
5170 (kill-buffer buffer)))
5171
5172 (defun kill-some-buffers (&optional list)
5173 "Kill some buffers. Asks the user whether to kill each one of them.
5174 Non-interactively, if optional argument LIST is non-nil, it
5175 specifies the list of buffers to kill, asking for approval for each one."
5176 (interactive)
5177 (if (null list)
5178 (setq list (buffer-list)))
5179 (while list
5180 (let* ((buffer (car list))
5181 (name (buffer-name buffer)))
5182 (and name ; Can be nil for an indirect buffer
5183 ; if we killed the base buffer.
5184 (not (string-equal name ""))
5185 (/= (aref name 0) ?\s)
5186 (kill-buffer-ask buffer)))
5187 (setq list (cdr list))))
5188
5189 (defun kill-matching-buffers (regexp &optional internal-too)
5190 "Kill buffers whose name matches the specified REGEXP.
5191 The optional second argument indicates whether to kill internal buffers too."
5192 (interactive "sKill buffers matching this regular expression: \nP")
5193 (dolist (buffer (buffer-list))
5194 (let ((name (buffer-name buffer)))
5195 (when (and name (not (string-equal name ""))
5196 (or internal-too (/= (aref name 0) ?\s))
5197 (string-match regexp name))
5198 (kill-buffer-ask buffer)))))
5199
5200 \f
5201 (defun rename-auto-save-file ()
5202 "Adjust current buffer's auto save file name for current conditions.
5203 Also rename any existing auto save file, if it was made in this session."
5204 (let ((osave buffer-auto-save-file-name))
5205 (setq buffer-auto-save-file-name
5206 (make-auto-save-file-name))
5207 (if (and osave buffer-auto-save-file-name
5208 (not (string= buffer-auto-save-file-name buffer-file-name))
5209 (not (string= buffer-auto-save-file-name osave))
5210 (file-exists-p osave)
5211 (recent-auto-save-p))
5212 (rename-file osave buffer-auto-save-file-name t))))
5213
5214 (defun make-auto-save-file-name ()
5215 "Return file name to use for auto-saves of current buffer.
5216 Does not consider `auto-save-visited-file-name' as that variable is checked
5217 before calling this function. You can redefine this for customization.
5218 See also `auto-save-file-name-p'."
5219 (if buffer-file-name
5220 (let ((handler (find-file-name-handler buffer-file-name
5221 'make-auto-save-file-name)))
5222 (if handler
5223 (funcall handler 'make-auto-save-file-name)
5224 (let ((list auto-save-file-name-transforms)
5225 (filename buffer-file-name)
5226 result uniq)
5227 ;; Apply user-specified translations
5228 ;; to the file name.
5229 (while (and list (not result))
5230 (if (string-match (car (car list)) filename)
5231 (setq result (replace-match (cadr (car list)) t nil
5232 filename)
5233 uniq (car (cddr (car list)))))
5234 (setq list (cdr list)))
5235 (if result
5236 (if uniq
5237 (setq filename (concat
5238 (file-name-directory result)
5239 (subst-char-in-string
5240 ?/ ?!
5241 (replace-regexp-in-string "!" "!!"
5242 filename))))
5243 (setq filename result)))
5244 (setq result
5245 (if (and (eq system-type 'ms-dos)
5246 (not (msdos-long-file-names)))
5247 ;; We truncate the file name to DOS 8+3 limits
5248 ;; before doing anything else, because the regexp
5249 ;; passed to string-match below cannot handle
5250 ;; extensions longer than 3 characters, multiple
5251 ;; dots, and other atrocities.
5252 (let ((fn (dos-8+3-filename
5253 (file-name-nondirectory buffer-file-name))))
5254 (string-match
5255 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
5256 fn)
5257 (concat (file-name-directory buffer-file-name)
5258 "#" (match-string 1 fn)
5259 "." (match-string 3 fn) "#"))
5260 (concat (file-name-directory filename)
5261 "#"
5262 (file-name-nondirectory filename)
5263 "#")))
5264 ;; Make sure auto-save file names don't contain characters
5265 ;; invalid for the underlying filesystem.
5266 (if (and (memq system-type '(ms-dos windows-nt cygwin))
5267 ;; Don't modify remote (ange-ftp) filenames
5268 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result)))
5269 (convert-standard-filename result)
5270 result))))
5271
5272 ;; Deal with buffers that don't have any associated files. (Mail
5273 ;; mode tends to create a good number of these.)
5274
5275 (let ((buffer-name (buffer-name))
5276 (limit 0)
5277 file-name)
5278 ;; Restrict the characters used in the file name to those which
5279 ;; are known to be safe on all filesystems, url-encoding the
5280 ;; rest.
5281 ;; We do this on all platforms, because even if we are not
5282 ;; running on DOS/Windows, the current directory may be on a
5283 ;; mounted VFAT filesystem, such as a USB memory stick.
5284 (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit)
5285 (let* ((character (aref buffer-name (match-beginning 0)))
5286 (replacement
5287 ;; For multibyte characters, this will produce more than
5288 ;; 2 hex digits, so is not true URL encoding.
5289 (format "%%%02X" character)))
5290 (setq buffer-name (replace-match replacement t t buffer-name))
5291 (setq limit (1+ (match-end 0)))))
5292 ;; Generate the file name.
5293 (setq file-name
5294 (make-temp-file
5295 (let ((fname
5296 (expand-file-name
5297 (format "#%s#" buffer-name)
5298 ;; Try a few alternative directories, to get one we can
5299 ;; write it.
5300 (cond
5301 ((file-writable-p default-directory) default-directory)
5302 ((file-writable-p "/var/tmp/") "/var/tmp/")
5303 ("~/")))))
5304 (if (and (memq system-type '(ms-dos windows-nt cygwin))
5305 ;; Don't modify remote (ange-ftp) filenames
5306 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname)))
5307 ;; The call to convert-standard-filename is in case
5308 ;; buffer-name includes characters not allowed by the
5309 ;; DOS/Windows filesystems. make-temp-file writes to the
5310 ;; file it creates, so we must fix the file name _before_
5311 ;; make-temp-file is called.
5312 (convert-standard-filename fname)
5313 fname))
5314 nil "#"))
5315 ;; make-temp-file creates the file,
5316 ;; but we don't want it to exist until we do an auto-save.
5317 (condition-case ()
5318 (delete-file file-name)
5319 (file-error nil))
5320 file-name)))
5321
5322 (defun auto-save-file-name-p (filename)
5323 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
5324 FILENAME should lack slashes. You can redefine this for customization."
5325 (string-match "^#.*#$" filename))
5326 \f
5327 (defun wildcard-to-regexp (wildcard)
5328 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
5329 The generated regexp will match a filename only if the filename
5330 matches that wildcard according to shell rules. Only wildcards known
5331 by `sh' are supported."
5332 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
5333 ;; Copy the initial run of non-special characters.
5334 (result (substring wildcard 0 i))
5335 (len (length wildcard)))
5336 ;; If no special characters, we're almost done.
5337 (if i
5338 (while (< i len)
5339 (let ((ch (aref wildcard i))
5340 j)
5341 (setq
5342 result
5343 (concat result
5344 (cond
5345 ((and (eq ch ?\[)
5346 (< (1+ i) len)
5347 (eq (aref wildcard (1+ i)) ?\]))
5348 "\\[")
5349 ((eq ch ?\[) ; [...] maps to regexp char class
5350 (progn
5351 (setq i (1+ i))
5352 (concat
5353 (cond
5354 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
5355 (progn
5356 (setq i (1+ i))
5357 (if (eq (aref wildcard i) ?\])
5358 (progn
5359 (setq i (1+ i))
5360 "[^]")
5361 "[^")))
5362 ((eq (aref wildcard i) ?^)
5363 ;; Found "[^". Insert a `\0' character
5364 ;; (which cannot happen in a filename)
5365 ;; into the character class, so that `^'
5366 ;; is not the first character after `[',
5367 ;; and thus non-special in a regexp.
5368 (progn
5369 (setq i (1+ i))
5370 "[\000^"))
5371 ((eq (aref wildcard i) ?\])
5372 ;; I don't think `]' can appear in a
5373 ;; character class in a wildcard, but
5374 ;; let's be general here.
5375 (progn
5376 (setq i (1+ i))
5377 "[]"))
5378 (t "["))
5379 (prog1 ; copy everything upto next `]'.
5380 (substring wildcard
5381 i
5382 (setq j (string-match
5383 "]" wildcard i)))
5384 (setq i (if j (1- j) (1- len)))))))
5385 ((eq ch ?.) "\\.")
5386 ((eq ch ?*) "[^\000]*")
5387 ((eq ch ?+) "\\+")
5388 ((eq ch ?^) "\\^")
5389 ((eq ch ?$) "\\$")
5390 ((eq ch ?\\) "\\\\") ; probably cannot happen...
5391 ((eq ch ??) "[^\000]")
5392 (t (char-to-string ch)))))
5393 (setq i (1+ i)))))
5394 ;; Shell wildcards should match the entire filename,
5395 ;; not its part. Make the regexp say so.
5396 (concat "\\`" result "\\'")))
5397 \f
5398 (defcustom list-directory-brief-switches
5399 (purecopy "-CF")
5400 "Switches for `list-directory' to pass to `ls' for brief listing."
5401 :type 'string
5402 :group 'dired)
5403
5404 (defcustom list-directory-verbose-switches
5405 (purecopy "-l")
5406 "Switches for `list-directory' to pass to `ls' for verbose listing."
5407 :type 'string
5408 :group 'dired)
5409
5410 (defun file-expand-wildcards (pattern &optional full)
5411 "Expand wildcard pattern PATTERN.
5412 This returns a list of file names which match the pattern.
5413
5414 If PATTERN is written as an absolute file name,
5415 the values are absolute also.
5416
5417 If PATTERN is written as a relative file name, it is interpreted
5418 relative to the current default directory, `default-directory'.
5419 The file names returned are normally also relative to the current
5420 default directory. However, if FULL is non-nil, they are absolute."
5421 (save-match-data
5422 (let* ((nondir (file-name-nondirectory pattern))
5423 (dirpart (file-name-directory pattern))
5424 ;; A list of all dirs that DIRPART specifies.
5425 ;; This can be more than one dir
5426 ;; if DIRPART contains wildcards.
5427 (dirs (if (and dirpart
5428 (string-match "[[*?]"
5429 (or (file-remote-p dirpart 'localname)
5430 dirpart)))
5431 (mapcar 'file-name-as-directory
5432 (file-expand-wildcards (directory-file-name dirpart)))
5433 (list dirpart)))
5434 contents)
5435 (while dirs
5436 (when (or (null (car dirs)) ; Possible if DIRPART is not wild.
5437 (file-directory-p (directory-file-name (car dirs))))
5438 (let ((this-dir-contents
5439 ;; Filter out "." and ".."
5440 (delq nil
5441 (mapcar #'(lambda (name)
5442 (unless (string-match "\\`\\.\\.?\\'"
5443 (file-name-nondirectory name))
5444 name))
5445 (directory-files (or (car dirs) ".") full
5446 (wildcard-to-regexp nondir))))))
5447 (setq contents
5448 (nconc
5449 (if (and (car dirs) (not full))
5450 (mapcar (function (lambda (name) (concat (car dirs) name)))
5451 this-dir-contents)
5452 this-dir-contents)
5453 contents))))
5454 (setq dirs (cdr dirs)))
5455 contents)))
5456
5457 ;; Let Tramp know that `file-expand-wildcards' does not need an advice.
5458 (provide 'files '(remote-wildcards))
5459
5460 (defun list-directory (dirname &optional verbose)
5461 "Display a list of files in or matching DIRNAME, a la `ls'.
5462 DIRNAME is globbed by the shell if necessary.
5463 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
5464 Actions controlled by variables `list-directory-brief-switches'
5465 and `list-directory-verbose-switches'."
5466 (interactive (let ((pfx current-prefix-arg))
5467 (list (read-file-name (if pfx "List directory (verbose): "
5468 "List directory (brief): ")
5469 nil default-directory nil)
5470 pfx)))
5471 (let ((switches (if verbose list-directory-verbose-switches
5472 list-directory-brief-switches))
5473 buffer)
5474 (or dirname (setq dirname default-directory))
5475 (setq dirname (expand-file-name dirname))
5476 (with-output-to-temp-buffer "*Directory*"
5477 (setq buffer standard-output)
5478 (buffer-disable-undo standard-output)
5479 (princ "Directory ")
5480 (princ dirname)
5481 (terpri)
5482 (with-current-buffer "*Directory*"
5483 (let ((wildcard (not (file-directory-p dirname))))
5484 (insert-directory dirname switches wildcard (not wildcard)))))
5485 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
5486 (with-current-buffer buffer
5487 (setq default-directory
5488 (if (file-directory-p dirname)
5489 (file-name-as-directory dirname)
5490 (file-name-directory dirname))))))
5491
5492 (defun shell-quote-wildcard-pattern (pattern)
5493 "Quote characters special to the shell in PATTERN, leave wildcards alone.
5494
5495 PATTERN is assumed to represent a file-name wildcard suitable for the
5496 underlying filesystem. For Unix and GNU/Linux, each character from the
5497 set [ \\t\\n;<>&|()'\"#$] is quoted with a backslash; for DOS/Windows, all
5498 the parts of the pattern which don't include wildcard characters are
5499 quoted with double quotes.
5500
5501 This function leaves alone existing quote characters (\\ on Unix and \"
5502 on Windows), so PATTERN can use them to quote wildcard characters that
5503 need to be passed verbatim to shell commands."
5504 (save-match-data
5505 (cond
5506 ((memq system-type '(ms-dos windows-nt cygwin))
5507 ;; DOS/Windows don't allow `"' in file names. So if the
5508 ;; argument has quotes, we can safely assume it is already
5509 ;; quoted by the caller.
5510 (if (or (string-match "[\"]" pattern)
5511 ;; We quote [&()#$'] in case their shell is a port of a
5512 ;; Unixy shell. We quote [,=+] because stock DOS and
5513 ;; Windows shells require that in some cases, such as
5514 ;; passing arguments to batch files that use positional
5515 ;; arguments like %1.
5516 (not (string-match "[ \t;&()#$',=+]" pattern)))
5517 pattern
5518 (let ((result "\"")
5519 (beg 0)
5520 end)
5521 (while (string-match "[*?]+" pattern beg)
5522 (setq end (match-beginning 0)
5523 result (concat result (substring pattern beg end)
5524 "\""
5525 (substring pattern end (match-end 0))
5526 "\"")
5527 beg (match-end 0)))
5528 (concat result (substring pattern beg) "\""))))
5529 (t
5530 (let ((beg 0))
5531 (while (string-match "[ \t\n;<>&|()'\"#$]" pattern beg)
5532 (setq pattern
5533 (concat (substring pattern 0 (match-beginning 0))
5534 "\\"
5535 (substring pattern (match-beginning 0)))
5536 beg (1+ (match-end 0)))))
5537 pattern))))
5538
5539
5540 (defvar insert-directory-program (purecopy "ls")
5541 "Absolute or relative name of the `ls' program used by `insert-directory'.")
5542
5543 (defcustom directory-free-space-program (purecopy "df")
5544 "Program to get the amount of free space on a file system.
5545 We assume the output has the format of `df'.
5546 The value of this variable must be just a command name or file name;
5547 if you want to specify options, use `directory-free-space-args'.
5548
5549 A value of nil disables this feature.
5550
5551 If the function `file-system-info' is defined, it is always used in
5552 preference to the program given by this variable."
5553 :type '(choice (string :tag "Program") (const :tag "None" nil))
5554 :group 'dired)
5555
5556 (defcustom directory-free-space-args
5557 (purecopy (if (eq system-type 'darwin) "-k" "-Pk"))
5558 "Options to use when running `directory-free-space-program'."
5559 :type 'string
5560 :group 'dired)
5561
5562 (defun get-free-disk-space (dir)
5563 "Return the amount of free space on directory DIR's file system.
5564 The result is a string that gives the number of free 1KB blocks,
5565 or nil if the system call or the program which retrieve the information
5566 fail. It returns also nil when DIR is a remote directory.
5567
5568 This function calls `file-system-info' if it is available, or invokes the
5569 program specified by `directory-free-space-program' if that is non-nil."
5570 (unless (file-remote-p dir)
5571 ;; Try to find the number of free blocks. Non-Posix systems don't
5572 ;; always have df, but might have an equivalent system call.
5573 (if (fboundp 'file-system-info)
5574 (let ((fsinfo (file-system-info dir)))
5575 (if fsinfo
5576 (format "%.0f" (/ (nth 2 fsinfo) 1024))))
5577 (setq dir (expand-file-name dir))
5578 (save-match-data
5579 (with-temp-buffer
5580 (when (and directory-free-space-program
5581 ;; Avoid failure if the default directory does
5582 ;; not exist (Bug#2631, Bug#3911).
5583 (let ((default-directory "/"))
5584 (eq (call-process directory-free-space-program
5585 nil t nil
5586 directory-free-space-args
5587 dir)
5588 0)))
5589 ;; Usual format is a header line followed by a line of
5590 ;; numbers.
5591 (goto-char (point-min))
5592 (forward-line 1)
5593 (if (not (eobp))
5594 (progn
5595 ;; Move to the end of the "available blocks" number.
5596 (skip-chars-forward "^ \t")
5597 (forward-word 3)
5598 ;; Copy it into AVAILABLE.
5599 (let ((end (point)))
5600 (forward-word -1)
5601 (buffer-substring (point) end))))))))))
5602
5603 ;; The following expression replaces `dired-move-to-filename-regexp'.
5604 (defvar directory-listing-before-filename-regexp
5605 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
5606 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
5607 ;; In some locales, month abbreviations are as short as 2 letters,
5608 ;; and they can be followed by ".".
5609 ;; In Breton, a month name can include a quote character.
5610 (month (concat l-or-quote l-or-quote "+\\.?"))
5611 (s " ")
5612 (yyyy "[0-9][0-9][0-9][0-9]")
5613 (dd "[ 0-3][0-9]")
5614 (HH:MM "[ 0-2][0-9][:.][0-5][0-9]")
5615 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
5616 (zone "[-+][0-2][0-9][0-5][0-9]")
5617 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
5618 (iso-time (concat HH:MM "\\(:" seconds "\\( ?" zone "\\)?\\)?"))
5619 (iso (concat "\\(\\(" yyyy "-\\)?" iso-mm-dd "[ T]" iso-time
5620 "\\|" yyyy "-" iso-mm-dd "\\)"))
5621 (western (concat "\\(" month s "+" dd "\\|" dd "\\.?" s month "\\)"
5622 s "+"
5623 "\\(" HH:MM "\\|" yyyy "\\)"))
5624 (western-comma (concat month s "+" dd "," s "+" yyyy))
5625 ;; Japanese MS-Windows ls-lisp has one-digit months, and
5626 ;; omits the Kanji characters after month and day-of-month.
5627 ;; On Mac OS X 10.3, the date format in East Asian locales is
5628 ;; day-of-month digits followed by month digits.
5629 (mm "[ 0-1]?[0-9]")
5630 (east-asian
5631 (concat "\\(" mm l "?" s dd l "?" s "+"
5632 "\\|" dd s mm s "+" "\\)"
5633 "\\(" HH:MM "\\|" yyyy l "?" "\\)")))
5634 ;; The "[0-9]" below requires the previous column to end in a digit.
5635 ;; This avoids recognizing `1 may 1997' as a date in the line:
5636 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
5637
5638 ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
5639
5640 ;; For non-iso date formats, we add the ".*" in order to find
5641 ;; the last possible match. This avoids recognizing
5642 ;; `jservice 10 1024' as a date in the line:
5643 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
5644
5645 ;; vc dired listings provide the state or blanks between file
5646 ;; permissions and date. The state is always surrounded by
5647 ;; parantheses:
5648 ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
5649 ;; This is not supported yet.
5650 (purecopy (concat "\\([0-9][BkKMGTPEZY]? " iso
5651 "\\|.*[0-9][BkKMGTPEZY]? "
5652 "\\(" western "\\|" western-comma "\\|" east-asian "\\)"
5653 "\\) +")))
5654 "Regular expression to match up to the file name in a directory listing.
5655 The default value is designed to recognize dates and times
5656 regardless of the language.")
5657
5658 (defvar insert-directory-ls-version 'unknown)
5659
5660 ;; insert-directory
5661 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
5662 ;; FULL-DIRECTORY-P is nil.
5663 ;; The single line of output must display FILE's name as it was
5664 ;; given, namely, an absolute path name.
5665 ;; - must insert exactly one line for each file if WILDCARD or
5666 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
5667 ;; before the file lines, plus optional text after the file lines.
5668 ;; Lines are delimited by "\n", so filenames containing "\n" are not
5669 ;; allowed.
5670 ;; File lines should display the basename.
5671 ;; - must be consistent with
5672 ;; - functions dired-move-to-filename, (these two define what a file line is)
5673 ;; dired-move-to-end-of-filename,
5674 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
5675 ;; dired-insert-headerline
5676 ;; dired-after-subdir-garbage (defines what a "total" line is)
5677 ;; - variable dired-subdir-regexp
5678 ;; - may be passed "--dired" as the first argument in SWITCHES.
5679 ;; Filename handlers might have to remove this switch if their
5680 ;; "ls" command does not support it.
5681 (defun insert-directory (file switches &optional wildcard full-directory-p)
5682 "Insert directory listing for FILE, formatted according to SWITCHES.
5683 Leaves point after the inserted text.
5684 SWITCHES may be a string of options, or a list of strings
5685 representing individual options.
5686 Optional third arg WILDCARD means treat FILE as shell wildcard.
5687 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
5688 switches do not contain `d', so that a full listing is expected.
5689
5690 This works by running a directory listing program
5691 whose name is in the variable `insert-directory-program'.
5692 If WILDCARD, it also runs the shell specified by `shell-file-name'.
5693
5694 When SWITCHES contains the long `--dired' option, this function
5695 treats it specially, for the sake of dired. However, the
5696 normally equivalent short `-D' option is just passed on to
5697 `insert-directory-program', as any other option."
5698 ;; We need the directory in order to find the right handler.
5699 (let ((handler (find-file-name-handler (expand-file-name file)
5700 'insert-directory)))
5701 (if handler
5702 (funcall handler 'insert-directory file switches
5703 wildcard full-directory-p)
5704 (let (result (beg (point)))
5705
5706 ;; Read the actual directory using `insert-directory-program'.
5707 ;; RESULT gets the status code.
5708 (let* (;; We at first read by no-conversion, then after
5709 ;; putting text property `dired-filename, decode one
5710 ;; bunch by one to preserve that property.
5711 (coding-system-for-read 'no-conversion)
5712 ;; This is to control encoding the arguments in call-process.
5713 (coding-system-for-write
5714 (and enable-multibyte-characters
5715 (or file-name-coding-system
5716 default-file-name-coding-system))))
5717 (setq result
5718 (if wildcard
5719 ;; Run ls in the directory part of the file pattern
5720 ;; using the last component as argument.
5721 (let ((default-directory
5722 (if (file-name-absolute-p file)
5723 (file-name-directory file)
5724 (file-name-directory (expand-file-name file))))
5725 (pattern (file-name-nondirectory file)))
5726 (call-process
5727 shell-file-name nil t nil
5728 "-c"
5729 (concat (if (memq system-type '(ms-dos windows-nt))
5730 ""
5731 "\\") ; Disregard Unix shell aliases!
5732 insert-directory-program
5733 " -d "
5734 (if (stringp switches)
5735 switches
5736 (mapconcat 'identity switches " "))
5737 " -- "
5738 ;; Quote some characters that have
5739 ;; special meanings in shells; but
5740 ;; don't quote the wildcards--we want
5741 ;; them to be special. We also
5742 ;; currently don't quote the quoting
5743 ;; characters in case people want to
5744 ;; use them explicitly to quote
5745 ;; wildcard characters.
5746 (shell-quote-wildcard-pattern pattern))))
5747 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
5748 ;; directory if FILE is a symbolic link.
5749 (unless full-directory-p
5750 (setq switches
5751 (if (stringp switches)
5752 (concat switches " -d")
5753 (add-to-list 'switches "-d" 'append))))
5754 (apply 'call-process
5755 insert-directory-program nil t nil
5756 (append
5757 (if (listp switches) switches
5758 (unless (equal switches "")
5759 ;; Split the switches at any spaces so we can
5760 ;; pass separate options as separate args.
5761 (split-string switches)))
5762 ;; Avoid lossage if FILE starts with `-'.
5763 '("--")
5764 (progn
5765 (if (string-match "\\`~" file)
5766 (setq file (expand-file-name file)))
5767 (list
5768 (if full-directory-p
5769 (concat (file-name-as-directory file) ".")
5770 file))))))))
5771
5772 ;; If we got "//DIRED//" in the output, it means we got a real
5773 ;; directory listing, even if `ls' returned nonzero.
5774 ;; So ignore any errors.
5775 (when (if (stringp switches)
5776 (string-match "--dired\\>" switches)
5777 (member "--dired" switches))
5778 (save-excursion
5779 (forward-line -2)
5780 (when (looking-at "//SUBDIRED//")
5781 (forward-line -1))
5782 (if (looking-at "//DIRED//")
5783 (setq result 0))))
5784
5785 (when (and (not (eq 0 result))
5786 (eq insert-directory-ls-version 'unknown))
5787 ;; The first time ls returns an error,
5788 ;; find the version numbers of ls,
5789 ;; and set insert-directory-ls-version
5790 ;; to > if it is more than 5.2.1, < if it is less, nil if it
5791 ;; is equal or if the info cannot be obtained.
5792 ;; (That can mean it isn't GNU ls.)
5793 (let ((version-out
5794 (with-temp-buffer
5795 (call-process "ls" nil t nil "--version")
5796 (buffer-string))))
5797 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out)
5798 (let* ((version (match-string 1 version-out))
5799 (split (split-string version "[.]"))
5800 (numbers (mapcar 'string-to-number split))
5801 (min '(5 2 1))
5802 comparison)
5803 (while (and (not comparison) (or numbers min))
5804 (cond ((null min)
5805 (setq comparison '>))
5806 ((null numbers)
5807 (setq comparison '<))
5808 ((> (car numbers) (car min))
5809 (setq comparison '>))
5810 ((< (car numbers) (car min))
5811 (setq comparison '<))
5812 (t
5813 (setq numbers (cdr numbers)
5814 min (cdr min)))))
5815 (setq insert-directory-ls-version (or comparison '=)))
5816 (setq insert-directory-ls-version nil))))
5817
5818 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
5819 (when (and (eq 1 result) (eq insert-directory-ls-version '>))
5820 (setq result 0))
5821
5822 ;; If `insert-directory-program' failed, signal an error.
5823 (unless (eq 0 result)
5824 ;; Delete the error message it may have output.
5825 (delete-region beg (point))
5826 ;; On non-Posix systems, we cannot open a directory, so
5827 ;; don't even try, because that will always result in
5828 ;; the ubiquitous "Access denied". Instead, show the
5829 ;; command line so the user can try to guess what went wrong.
5830 (if (and (file-directory-p file)
5831 (memq system-type '(ms-dos windows-nt)))
5832 (error
5833 "Reading directory: \"%s %s -- %s\" exited with status %s"
5834 insert-directory-program
5835 (if (listp switches) (concat switches) switches)
5836 file result)
5837 ;; Unix. Access the file to get a suitable error.
5838 (access-file file "Reading directory")
5839 (error "Listing directory failed but `access-file' worked")))
5840
5841 (when (if (stringp switches)
5842 (string-match "--dired\\>" switches)
5843 (member "--dired" switches))
5844 ;; The following overshoots by one line for an empty
5845 ;; directory listed with "--dired", but without "-a"
5846 ;; switch, where the ls output contains a
5847 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
5848 ;; We take care of that case later.
5849 (forward-line -2)
5850 (when (looking-at "//SUBDIRED//")
5851 (delete-region (point) (progn (forward-line 1) (point)))
5852 (forward-line -1))
5853 (if (looking-at "//DIRED//")
5854 (let ((end (line-end-position))
5855 (linebeg (point))
5856 error-lines)
5857 ;; Find all the lines that are error messages,
5858 ;; and record the bounds of each one.
5859 (goto-char beg)
5860 (while (< (point) linebeg)
5861 (or (eql (following-char) ?\s)
5862 (push (list (point) (line-end-position)) error-lines))
5863 (forward-line 1))
5864 (setq error-lines (nreverse error-lines))
5865 ;; Now read the numeric positions of file names.
5866 (goto-char linebeg)
5867 (forward-word 1)
5868 (forward-char 3)
5869 (while (< (point) end)
5870 (let ((start (insert-directory-adj-pos
5871 (+ beg (read (current-buffer)))
5872 error-lines))
5873 (end (insert-directory-adj-pos
5874 (+ beg (read (current-buffer)))
5875 error-lines)))
5876 (if (memq (char-after end) '(?\n ?\s))
5877 ;; End is followed by \n or by " -> ".
5878 (put-text-property start end 'dired-filename t)
5879 ;; It seems that we can't trust ls's output as to
5880 ;; byte positions of filenames.
5881 (put-text-property beg (point) 'dired-filename nil)
5882 (end-of-line))))
5883 (goto-char end)
5884 (beginning-of-line)
5885 (delete-region (point) (progn (forward-line 1) (point))))
5886 ;; Take care of the case where the ls output contains a
5887 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
5888 ;; and we went one line too far back (see above).
5889 (forward-line 1))
5890 (if (looking-at "//DIRED-OPTIONS//")
5891 (delete-region (point) (progn (forward-line 1) (point)))))
5892
5893 ;; Now decode what read if necessary.
5894 (let ((coding (or coding-system-for-read
5895 file-name-coding-system
5896 default-file-name-coding-system
5897 'undecided))
5898 coding-no-eol
5899 val pos)
5900 (when (and enable-multibyte-characters
5901 (not (memq (coding-system-base coding)
5902 '(raw-text no-conversion))))
5903 ;; If no coding system is specified or detection is
5904 ;; requested, detect the coding.
5905 (if (eq (coding-system-base coding) 'undecided)
5906 (setq coding (detect-coding-region beg (point) t)))
5907 (if (not (eq (coding-system-base coding) 'undecided))
5908 (save-restriction
5909 (setq coding-no-eol
5910 (coding-system-change-eol-conversion coding 'unix))
5911 (narrow-to-region beg (point))
5912 (goto-char (point-min))
5913 (while (not (eobp))
5914 (setq pos (point)
5915 val (get-text-property (point) 'dired-filename))
5916 (goto-char (next-single-property-change
5917 (point) 'dired-filename nil (point-max)))
5918 ;; Force no eol conversion on a file name, so
5919 ;; that CR is preserved.
5920 (decode-coding-region pos (point)
5921 (if val coding-no-eol coding))
5922 (if val
5923 (put-text-property pos (point)
5924 'dired-filename t)))))))
5925
5926 (if full-directory-p
5927 ;; Try to insert the amount of free space.
5928 (save-excursion
5929 (goto-char beg)
5930 ;; First find the line to put it on.
5931 (when (re-search-forward "^ *\\(total\\)" nil t)
5932 (let ((available (get-free-disk-space ".")))
5933 (when available
5934 ;; Replace "total" with "used", to avoid confusion.
5935 (replace-match "total used in directory" nil nil nil 1)
5936 (end-of-line)
5937 (insert " available " available))))))))))
5938
5939 (defun insert-directory-adj-pos (pos error-lines)
5940 "Convert `ls --dired' file name position value POS to a buffer position.
5941 File name position values returned in ls --dired output
5942 count only stdout; they don't count the error messages sent to stderr.
5943 So this function converts to them to real buffer positions.
5944 ERROR-LINES is a list of buffer positions of error message lines,
5945 of the form (START END)."
5946 (while (and error-lines (< (caar error-lines) pos))
5947 (setq pos (+ pos (- (nth 1 (car error-lines)) (nth 0 (car error-lines)))))
5948 (pop error-lines))
5949 pos)
5950
5951 (defun insert-directory-safely (file switches
5952 &optional wildcard full-directory-p)
5953 "Insert directory listing for FILE, formatted according to SWITCHES.
5954
5955 Like `insert-directory', but if FILE does not exist, it inserts a
5956 message to that effect instead of signaling an error."
5957 (if (file-exists-p file)
5958 (insert-directory file switches wildcard full-directory-p)
5959 ;; Simulate the message printed by `ls'.
5960 (insert (format "%s: No such file or directory\n" file))))
5961
5962 (defvar kill-emacs-query-functions nil
5963 "Functions to call with no arguments to query about killing Emacs.
5964 If any of these functions returns nil, killing Emacs is cancelled.
5965 `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
5966 the low level primitive, does not. See also `kill-emacs-hook'.")
5967
5968 (defcustom confirm-kill-emacs nil
5969 "How to ask for confirmation when leaving Emacs.
5970 If nil, the default, don't ask at all. If the value is non-nil, it should
5971 be a predicate function such as `yes-or-no-p'."
5972 :type '(choice (const :tag "Ask with yes-or-no-p" yes-or-no-p)
5973 (const :tag "Ask with y-or-n-p" y-or-n-p)
5974 (const :tag "Don't confirm" nil))
5975 :group 'convenience
5976 :version "21.1")
5977
5978 (defun save-buffers-kill-emacs (&optional arg)
5979 "Offer to save each buffer, then kill this Emacs process.
5980 With prefix ARG, silently save all file-visiting buffers, then kill."
5981 (interactive "P")
5982 (save-some-buffers arg t)
5983 (and (or (not (memq t (mapcar (function
5984 (lambda (buf) (and (buffer-file-name buf)
5985 (buffer-modified-p buf))))
5986 (buffer-list))))
5987 (yes-or-no-p "Modified buffers exist; exit anyway? "))
5988 (or (not (fboundp 'process-list))
5989 ;; process-list is not defined on MSDOS.
5990 (let ((processes (process-list))
5991 active)
5992 (while processes
5993 (and (memq (process-status (car processes)) '(run stop open listen))
5994 (process-query-on-exit-flag (car processes))
5995 (setq active t))
5996 (setq processes (cdr processes)))
5997 (or (not active)
5998 (list-processes t)
5999 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
6000 ;; Query the user for other things, perhaps.
6001 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
6002 (or (null confirm-kill-emacs)
6003 (funcall confirm-kill-emacs "Really exit Emacs? "))
6004 (kill-emacs)))
6005
6006 (defun save-buffers-kill-terminal (&optional arg)
6007 "Offer to save each buffer, then kill the current connection.
6008 If the current frame has no client, kill Emacs itself.
6009
6010 With prefix ARG, silently save all file-visiting buffers, then kill.
6011
6012 If emacsclient was started with a list of filenames to edit, then
6013 only these files will be asked to be saved."
6014 (interactive "P")
6015 (if (frame-parameter (selected-frame) 'client)
6016 (server-save-buffers-kill-terminal arg)
6017 (save-buffers-kill-emacs arg)))
6018 \f
6019 ;; We use /: as a prefix to "quote" a file name
6020 ;; so that magic file name handlers will not apply to it.
6021
6022 (setq file-name-handler-alist
6023 (cons (cons (purecopy "\\`/:") 'file-name-non-special)
6024 file-name-handler-alist))
6025
6026 ;; We depend on being the last handler on the list,
6027 ;; so that anything else which does need handling
6028 ;; has been handled already.
6029 ;; So it is safe for us to inhibit *all* magic file name handlers.
6030
6031 (defun file-name-non-special (operation &rest arguments)
6032 (let ((file-name-handler-alist nil)
6033 (default-directory
6034 (if (eq operation 'insert-directory)
6035 (directory-file-name
6036 (expand-file-name
6037 (unhandled-file-name-directory default-directory)))
6038 default-directory))
6039 ;; Get a list of the indices of the args which are file names.
6040 (file-arg-indices
6041 (cdr (or (assq operation
6042 ;; The first six are special because they
6043 ;; return a file name. We want to include the /:
6044 ;; in the return value.
6045 ;; So just avoid stripping it in the first place.
6046 '((expand-file-name . nil)
6047 (file-name-directory . nil)
6048 (file-name-as-directory . nil)
6049 (directory-file-name . nil)
6050 (file-name-sans-versions . nil)
6051 (find-backup-file-name . nil)
6052 ;; `identity' means just return the first arg
6053 ;; not stripped of its quoting.
6054 (substitute-in-file-name identity)
6055 ;; `add' means add "/:" to the result.
6056 (file-truename add 0)
6057 ;; `quote' means add "/:" to buffer-file-name.
6058 (insert-file-contents quote 0)
6059 ;; `unquote-then-quote' means set buffer-file-name
6060 ;; temporarily to unquoted filename.
6061 (verify-visited-file-modtime unquote-then-quote)
6062 ;; List the arguments which are filenames.
6063 (file-name-completion 1)
6064 (file-name-all-completions 1)
6065 (write-region 2 5)
6066 (rename-file 0 1)
6067 (copy-file 0 1)
6068 (make-symbolic-link 0 1)
6069 (add-name-to-file 0 1)))
6070 ;; For all other operations, treat the first argument only
6071 ;; as the file name.
6072 '(nil 0))))
6073 method
6074 ;; Copy ARGUMENTS so we can replace elements in it.
6075 (arguments (copy-sequence arguments)))
6076 (if (symbolp (car file-arg-indices))
6077 (setq method (pop file-arg-indices)))
6078 ;; Strip off the /: from the file names that have it.
6079 (save-match-data
6080 (while (consp file-arg-indices)
6081 (let ((pair (nthcdr (car file-arg-indices) arguments)))
6082 (and (car pair)
6083 (string-match "\\`/:" (car pair))
6084 (setcar pair
6085 (if (= (length (car pair)) 2)
6086 "/"
6087 (substring (car pair) 2)))))
6088 (setq file-arg-indices (cdr file-arg-indices))))
6089 (cond ((eq method 'identity)
6090 (car arguments))
6091 ((eq method 'add)
6092 (concat "/:" (apply operation arguments)))
6093 ((eq method 'quote)
6094 (unwind-protect
6095 (apply operation arguments)
6096 (setq buffer-file-name (concat "/:" buffer-file-name))))
6097 ((eq method 'unquote-then-quote)
6098 (let (res)
6099 (setq buffer-file-name (substring buffer-file-name 2))
6100 (setq res (apply operation arguments))
6101 (setq buffer-file-name (concat "/:" buffer-file-name))
6102 res))
6103 (t
6104 (apply operation arguments)))))
6105 \f
6106 ;; Symbolic modes and read-file-modes.
6107
6108 (defun file-modes-char-to-who (char)
6109 "Convert CHAR to a numeric bit-mask for extracting mode bits.
6110 CHAR is in [ugoa] and represents the category of users (Owner, Group,
6111 Others, or All) for whom to produce the mask.
6112 The bit-mask that is returned extracts from mode bits the access rights
6113 for the specified category of users."
6114 (cond ((= char ?u) #o4700)
6115 ((= char ?g) #o2070)
6116 ((= char ?o) #o1007)
6117 ((= char ?a) #o7777)
6118 (t (error "%c: bad `who' character" char))))
6119
6120 (defun file-modes-char-to-right (char &optional from)
6121 "Convert CHAR to a numeric value of mode bits.
6122 CHAR is in [rwxXstugo] and represents symbolic access permissions.
6123 If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
6124 (or from (setq from 0))
6125 (cond ((= char ?r) #o0444)
6126 ((= char ?w) #o0222)
6127 ((= char ?x) #o0111)
6128 ((= char ?s) #o1000)
6129 ((= char ?t) #o6000)
6130 ;; Rights relative to the previous file modes.
6131 ((= char ?X) (if (= (logand from #o111) 0) 0 #o0111))
6132 ((= char ?u) (let ((uright (logand #o4700 from)))
6133 (+ uright (/ uright #o10) (/ uright #o100))))
6134 ((= char ?g) (let ((gright (logand #o2070 from)))
6135 (+ gright (/ gright #o10) (* gright #o10))))
6136 ((= char ?o) (let ((oright (logand #o1007 from)))
6137 (+ oright (* oright #o10) (* oright #o100))))
6138 (t (error "%c: bad right character" char))))
6139
6140 (defun file-modes-rights-to-number (rights who-mask &optional from)
6141 "Convert a symbolic mode string specification to an equivalent number.
6142 RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]*)+\".
6143 WHO-MASK is the bit-mask specifying the category of users to which to
6144 apply the access permissions. See `file-modes-char-to-who'.
6145 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6146 RIGHTS request to add, remove, or set permissions based on existing ones,
6147 as in \"og+rX-w\"."
6148 (let* ((num-rights (or from 0))
6149 (list-rights (string-to-list rights))
6150 (op (pop list-rights)))
6151 (while (memq op '(?+ ?- ?=))
6152 (let ((num-right 0)
6153 char-right)
6154 (while (memq (setq char-right (pop list-rights))
6155 '(?r ?w ?x ?X ?s ?t ?u ?g ?o))
6156 (setq num-right
6157 (logior num-right
6158 (file-modes-char-to-right char-right num-rights))))
6159 (setq num-right (logand who-mask num-right)
6160 num-rights
6161 (cond ((= op ?+) (logior num-rights num-right))
6162 ((= op ?-) (logand num-rights (lognot num-right)))
6163 (t (logior (logand num-rights (lognot who-mask)) num-right)))
6164 op char-right)))
6165 num-rights))
6166
6167 (defun file-modes-symbolic-to-number (modes &optional from)
6168 "Convert symbolic file modes to numeric file modes.
6169 MODES is the string to convert, it should match
6170 \"[ugoa]*([+-=][rwxXstugo]*)+,...\".
6171 See (info \"(coreutils)File permissions\") for more information on this
6172 notation.
6173 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6174 MODES request to add, remove, or set permissions based on existing ones,
6175 as in \"og+rX-w\"."
6176 (save-match-data
6177 (let ((case-fold-search nil)
6178 (num-modes (or from 0)))
6179 (while (/= (string-to-char modes) 0)
6180 (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]*\\)+\\(,\\|\\)" modes)
6181 (let ((num-who (apply 'logior 0
6182 (mapcar 'file-modes-char-to-who
6183 (match-string 1 modes)))))
6184 (when (= num-who 0)
6185 (setq num-who (default-file-modes)))
6186 (setq num-modes
6187 (file-modes-rights-to-number (substring modes (match-end 1))
6188 num-who num-modes)
6189 modes (substring modes (match-end 3))))
6190 (error "Parse error in modes near `%s'" (substring modes 0))))
6191 num-modes)))
6192
6193 (defun read-file-modes (&optional prompt orig-file)
6194 "Read file modes in octal or symbolic notation and return its numeric value.
6195 PROMPT is used as the prompt, default to `File modes (octal or symbolic): '.
6196 ORIG-FILE is the name of a file on whose mode bits to base returned
6197 permissions if what user types requests to add, remove, or set permissions
6198 based on existing mode bits, as in \"og+rX-w\"."
6199 (let* ((modes (or (if orig-file (file-modes orig-file) 0)
6200 (error "File not found")))
6201 (modestr (and (stringp orig-file)
6202 (nth 8 (file-attributes orig-file))))
6203 (default
6204 (and (stringp modestr)
6205 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr)
6206 (replace-regexp-in-string
6207 "-" ""
6208 (format "u=%s,g=%s,o=%s"
6209 (match-string 1 modestr)
6210 (match-string 2 modestr)
6211 (match-string 3 modestr)))))
6212 (value (read-string (or prompt "File modes (octal or symbolic): ")
6213 nil nil default)))
6214 (save-match-data
6215 (if (string-match "^[0-7]+" value)
6216 (string-to-number value 8)
6217 (file-modes-symbolic-to-number value modes)))))
6218
6219 \f
6220 ;; Trashcan handling.
6221 (defcustom trash-directory nil
6222 "Directory for `move-file-to-trash' to move files and directories to.
6223 This directory is only used when the function `system-move-file-to-trash'
6224 is not defined.
6225 Relative paths are interpreted relative to `default-directory'.
6226 If the value is nil, Emacs uses a freedesktop.org-style trashcan."
6227 :type '(choice (const nil) directory)
6228 :group 'auto-save
6229 :version "23.2")
6230
6231 (defvar trash--hexify-table)
6232
6233 (declare-function system-move-file-to-trash "w32fns.c" (filename))
6234
6235 (defun move-file-to-trash (filename)
6236 "Move the file (or directory) named FILENAME to the trash.
6237 When `delete-by-moving-to-trash' is non-nil, this function is
6238 called by `delete-file' and `delete-directory' instead of
6239 deleting files outright.
6240
6241 If the function `system-move-file-to-trash' is defined, call it
6242 with FILENAME as an argument.
6243 Otherwise, if `trash-directory' is non-nil, move FILENAME to that
6244 directory.
6245 Otherwise, trash FILENAME using the freedesktop.org conventions,
6246 like the GNOME, KDE and XFCE desktop environments. Emacs only
6247 moves files to \"home trash\", ignoring per-volume trashcans."
6248 (interactive "fMove file to trash: ")
6249 (cond (trash-directory
6250 ;; If `trash-directory' is non-nil, move the file there.
6251 (let* ((trash-dir (expand-file-name trash-directory))
6252 (fn (directory-file-name (expand-file-name filename)))
6253 (new-fn (expand-file-name (file-name-nondirectory fn)
6254 trash-dir)))
6255 ;; We can't trash a parent directory of trash-directory.
6256 (if (string-match fn trash-dir)
6257 (error "Trash directory `%s' is a subdirectory of `%s'"
6258 trash-dir filename))
6259 (unless (file-directory-p trash-dir)
6260 (make-directory trash-dir t))
6261 ;; Ensure that the trashed file-name is unique.
6262 (if (file-exists-p new-fn)
6263 (let ((version-control t)
6264 (backup-directory-alist nil))
6265 (setq new-fn (car (find-backup-file-name new-fn)))))
6266 (let (delete-by-moving-to-trash)
6267 (rename-file fn new-fn))))
6268 ;; If `system-move-file-to-trash' is defined, use it.
6269 ((fboundp 'system-move-file-to-trash)
6270 (system-move-file-to-trash filename))
6271 ;; Otherwise, use the freedesktop.org method, as specified at
6272 ;; http://freedesktop.org/wiki/Specifications/trash-spec
6273 (t
6274 (let* ((xdg-data-dir
6275 (directory-file-name
6276 (expand-file-name "Trash"
6277 (or (getenv "XDG_DATA_HOME")
6278 "~/.local/share"))))
6279 (trash-files-dir (expand-file-name "files" xdg-data-dir))
6280 (trash-info-dir (expand-file-name "info" xdg-data-dir))
6281 (fn (directory-file-name (expand-file-name filename))))
6282
6283 ;; Check if we have permissions to delete.
6284 (unless (file-writable-p (directory-file-name
6285 (file-name-directory fn)))
6286 (error "Cannot move %s to trash: Permission denied" filename))
6287 ;; The trashed file cannot be the trash dir or its parent.
6288 (if (string-match fn trash-files-dir)
6289 (error "The trash directory %s is a subdirectory of %s"
6290 trash-files-dir filename))
6291 (if (string-match fn trash-info-dir)
6292 (error "The trash directory %s is a subdirectory of %s"
6293 trash-info-dir filename))
6294
6295 ;; Ensure that the trash directory exists; otherwise, create it.
6296 (let ((saved-default-file-modes (default-file-modes)))
6297 (set-default-file-modes ?\700)
6298 (unless (file-exists-p trash-files-dir)
6299 (make-directory trash-files-dir t))
6300 (unless (file-exists-p trash-info-dir)
6301 (make-directory trash-info-dir t))
6302 (set-default-file-modes saved-default-file-modes))
6303
6304 ;; Try to move to trash with .trashinfo undo information
6305 (save-excursion
6306 (with-temp-buffer
6307 (set-buffer-file-coding-system 'utf-8-unix)
6308 (insert "[Trash Info]\nPath=")
6309 ;; Perform url-encoding on FN. For compatibility with
6310 ;; other programs (e.g. XFCE Thunar), allow literal "/"
6311 ;; for path separators.
6312 (unless (boundp 'trash--hexify-table)
6313 (setq trash--hexify-table (make-vector 256 nil))
6314 (let ((unreserved-chars
6315 (list ?/ ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m
6316 ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A
6317 ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O
6318 ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?0 ?1 ?2
6319 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?- ?_ ?. ?! ?~ ?* ?'
6320 ?\( ?\))))
6321 (dotimes (byte 256)
6322 (aset trash--hexify-table byte
6323 (if (memq byte unreserved-chars)
6324 (char-to-string byte)
6325 (format "%%%02x" byte))))))
6326 (mapc (lambda (byte)
6327 (insert (aref trash--hexify-table byte)))
6328 (if (multibyte-string-p fn)
6329 (encode-coding-string fn 'utf-8)
6330 fn))
6331 (insert "\nDeletionDate="
6332 (format-time-string "%Y-%m-%dT%T")
6333 "\n")
6334
6335 ;; Attempt to make .trashinfo file, trying up to 5
6336 ;; times. The .trashinfo file is opened with O_EXCL,
6337 ;; as per trash-spec 0.7, even if that can be a problem
6338 ;; on old NFS versions...
6339 (let* ((tries 5)
6340 (base-fn (expand-file-name
6341 (file-name-nondirectory fn)
6342 trash-files-dir))
6343 (new-fn base-fn)
6344 success info-fn)
6345 (while (> tries 0)
6346 (setq info-fn (expand-file-name
6347 (concat (file-name-nondirectory new-fn)
6348 ".trashinfo")
6349 trash-info-dir))
6350 (unless (condition-case nil
6351 (progn
6352 (write-region nil nil info-fn nil
6353 'quiet info-fn 'excl)
6354 (setq tries 0 success t))
6355 (file-already-exists nil))
6356 (setq tries (1- tries))
6357 ;; Uniqify new-fn. (Some file managers do not
6358 ;; like Emacs-style backup file names---e.g. bug
6359 ;; 170956 in Konqueror bug tracker.)
6360 (setq new-fn (make-temp-name (concat base-fn "_")))))
6361 (unless success
6362 (error "Cannot move %s to trash: Lock failed" filename))
6363
6364 ;; Finally, try to move the file to the trashcan.
6365 (let ((delete-by-moving-to-trash nil))
6366 (rename-file fn new-fn)))))))))
6367
6368 \f
6369 (define-key ctl-x-map "\C-f" 'find-file)
6370 (define-key ctl-x-map "\C-r" 'find-file-read-only)
6371 (define-key ctl-x-map "\C-v" 'find-alternate-file)
6372 (define-key ctl-x-map "\C-s" 'save-buffer)
6373 (define-key ctl-x-map "s" 'save-some-buffers)
6374 (define-key ctl-x-map "\C-w" 'write-file)
6375 (define-key ctl-x-map "i" 'insert-file)
6376 (define-key esc-map "~" 'not-modified)
6377 (define-key ctl-x-map "\C-d" 'list-directory)
6378 (define-key ctl-x-map "\C-c" 'save-buffers-kill-terminal)
6379 (define-key ctl-x-map "\C-q" 'toggle-read-only)
6380
6381 (define-key ctl-x-4-map "f" 'find-file-other-window)
6382 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
6383 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
6384 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
6385 (define-key ctl-x-4-map "\C-o" 'display-buffer)
6386
6387 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
6388 (define-key ctl-x-5-map "f" 'find-file-other-frame)
6389 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
6390 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
6391 (define-key ctl-x-5-map "\C-o" 'display-buffer-other-frame)
6392
6393 ;; arch-tag: bc68d3ea-19ca-468b-aac6-3a4a7766101f
6394 ;;; files.el ends here