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