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