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