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