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