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