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