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