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