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