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