1 ;;; files.el --- file input and output commands for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1987, 1992-2018 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
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.
33 (require 'easy-mmode
)) ; For `define-minor-mode'.
35 (defvar font-lock-keywords
)
38 "Backups of edited data files."
41 (defgroup find-file nil
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."
54 (defcustom directory-abbrev-alist
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"
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'."
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'."
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."
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."
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
)
146 (defvar backup-enable-predicate
'normal-backup-enable-predicate
147 "Predicate that looks at a file name and decides whether to make backups.
148 Called with an absolute file name as argument, it returns t to enable backup.")
150 (defcustom buffer-offer-save nil
151 "Non-nil in a buffer means always offer to save buffer on exit.
152 Do so even if the buffer is not visiting a file.
153 Automatically local in all buffers.
155 Set to the symbol `always' to offer to save buffer whenever
156 `save-some-buffers' is called."
157 :type
'(choice (const :tag
"Never" nil
)
158 (const :tag
"On Emacs exit" t
)
159 (const :tag
"Whenever save-some-buffers is called" always
))
161 (make-variable-buffer-local 'buffer-offer-save
)
162 (put 'buffer-offer-save
'permanent-local t
)
164 (defcustom find-file-existing-other-name t
165 "Non-nil means find a file under alternative names, in existing buffers.
166 This means if any existing buffer is visiting the file you want
167 under another name, you get the existing buffer instead of a new buffer."
171 (defcustom find-file-visit-truename nil
172 "Non-nil means visiting a file uses its truename as the visited-file name.
173 That is, the buffer visiting the file has the truename as the
174 value of `buffer-file-name'. The truename of a file is found by
175 chasing all links both at the file level and at the levels of the
176 containing directories."
179 (put 'find-file-visit-truename
'safe-local-variable
'booleanp
)
181 (defcustom revert-without-query nil
182 "Specify which files should be reverted without query.
183 The value is a list of regular expressions.
184 If the file name matches one of these regular expressions,
185 then `revert-buffer' reverts the file without querying
186 if the file has changed on disk and you have not edited the buffer."
187 :type
'(repeat regexp
)
190 (defvar buffer-file-number nil
191 "The device number and file number of the file visited in the current buffer.
192 The value is a list of the form (FILENUM DEVNUM).
193 This pair of numbers uniquely identifies the file.
194 If the buffer is visiting a new file, the value is nil.")
195 (make-variable-buffer-local 'buffer-file-number
)
196 (put 'buffer-file-number
'permanent-local t
)
198 (defvar buffer-file-numbers-unique
(not (memq system-type
'(windows-nt)))
199 "Non-nil means that `buffer-file-number' uniquely identifies files.")
201 (defvar buffer-file-read-only nil
202 "Non-nil if visited file was read-only when visited.")
203 (make-variable-buffer-local 'buffer-file-read-only
)
205 (defcustom small-temporary-file-directory
206 (if (eq system-type
'ms-dos
) (getenv "TMPDIR"))
207 "The directory for writing small temporary files.
208 If non-nil, this directory is used instead of `temporary-file-directory'
209 by programs that create small temporary files. This is for systems that
210 have fast storage with limited space, such as a RAM disk."
212 :initialize
'custom-initialize-delay
213 :type
'(choice (const nil
) directory
))
215 ;; The system null device. (Should reference NULL_DEVICE from C.)
216 (defvar null-device
(purecopy "/dev/null") "The system null device.")
218 (declare-function msdos-long-file-names
"msdos.c")
219 (declare-function w32-long-file-name
"w32proc.c")
220 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
221 (declare-function dired-unmark
"dired" (arg &optional interactive
))
222 (declare-function dired-do-flagged-delete
"dired" (&optional nomessage
))
223 (declare-function dos-8
+3-filename
"dos-fns" (filename))
224 (declare-function dosified-file-name
"dos-fns" (file-name))
226 (defvar file-name-invalid-regexp
227 (cond ((and (eq system-type
'ms-dos
) (not (msdos-long-file-names)))
229 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
230 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
231 "[\000-\037]\\|" ; control characters
232 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
233 "\\(/[^/.]+\\.[^/.]*\\.\\)"))) ; more than a single dot
234 ((memq system-type
'(ms-dos windows-nt cygwin
))
236 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
237 "[|<>\"?*\000-\037]"))) ; invalid characters
238 (t (purecopy "[\000]")))
239 "Regexp recognizing file names which aren't allowed by the filesystem.")
241 (defcustom file-precious-flag nil
242 "Non-nil means protect against I/O errors while saving files.
243 Some modes set this non-nil in particular buffers.
245 This feature works by writing the new contents into a temporary file
246 and then renaming the temporary file to replace the original.
247 In this way, any I/O error in writing leaves the original untouched,
248 and there is never any instant where the file is nonexistent.
250 Note that this feature forces backups to be made by copying.
251 Yet, at the same time, saving a precious file
252 breaks any hard links between it and other files.
254 This feature is advisory: for example, if the directory in which the
255 file is being saved is not writable, Emacs may ignore a non-nil value
256 of `file-precious-flag' and write directly into the file.
258 See also: `break-hardlink-on-save'."
262 (defcustom break-hardlink-on-save nil
263 "Whether to allow breaking hardlinks when saving files.
264 If non-nil, then when saving a file that exists under several
265 names \(i.e., has multiple hardlinks), break the hardlink
266 associated with `buffer-file-name' and write to a new file, so
267 that the other instances of the file are not affected by the
270 If `buffer-file-name' refers to a symlink, do not break the symlink.
272 Unlike `file-precious-flag', `break-hardlink-on-save' is not advisory.
273 For example, if the directory in which a file is being saved is not
274 itself writable, then error instead of saving in some
275 hardlink-nonbreaking way.
277 See also `backup-by-copying' and `backup-by-copying-when-linked'."
282 (defcustom version-control nil
283 "Control use of version numbers for backup files.
284 When t, make numeric backup versions unconditionally.
285 When nil, make them for files that have some already.
286 The value `never' means do not make them."
287 :type
'(choice (const :tag
"Never" never
)
288 (const :tag
"If existing" nil
)
289 (other :tag
"Always" t
))
292 (defun version-control-safe-local-p (x)
293 "Return whether X is safe as local value for `version-control'."
294 (or (booleanp x
) (equal x
'never
)))
296 (put 'version-control
'safe-local-variable
297 #'version-control-safe-local-p
)
299 (defcustom dired-kept-versions
2
300 "When cleaning directory, number of versions to keep."
305 (defcustom delete-old-versions nil
306 "If t, delete excess backup versions silently.
307 If nil, ask confirmation. Any other value prevents any trimming."
308 :type
'(choice (const :tag
"Delete" t
)
309 (const :tag
"Ask" nil
)
310 (other :tag
"Leave" other
))
313 (defcustom kept-old-versions
2
314 "Number of oldest versions to keep when a new numbered backup is made."
317 (put 'kept-old-versions
'safe-local-variable
'integerp
)
319 (defcustom kept-new-versions
2
320 "Number of newest versions to keep when a new numbered backup is made.
321 Includes the new backup. Must be > 0"
324 (put 'kept-new-versions
'safe-local-variable
'integerp
)
326 (defcustom require-final-newline nil
327 "Whether to add a newline automatically at the end of the file.
329 A value of t means do this only when the file is about to be saved.
330 A value of `visit' means do this right after the file is visited.
331 A value of `visit-save' means do it at both of those times.
332 Any other non-nil value means ask user whether to add a newline, when saving.
333 A value of nil means don't add newlines.
335 Certain major modes set this locally to the value obtained
336 from `mode-require-final-newline'."
338 :type
'(choice (const :tag
"When visiting" visit
)
339 (const :tag
"When saving" t
)
340 (const :tag
"When visiting or saving" visit-save
)
341 (const :tag
"Don't add newlines" nil
)
342 (other :tag
"Ask each time" ask
))
343 :group
'editing-basics
)
345 (defcustom mode-require-final-newline t
346 "Whether to add a newline at end of file, in certain major modes.
347 Those modes set `require-final-newline' to this value when you enable them.
348 They do so because they are often used for files that are supposed
349 to end in newlines, and the question is how to arrange that.
351 A value of t means do this only when the file is about to be saved.
352 A value of `visit' means do this right after the file is visited.
353 A value of `visit-save' means do it at both of those times.
354 Any other non-nil value means ask user whether to add a newline, when saving.
356 A value of nil means do not add newlines. That is a risky choice in this
357 variable since this value is used for modes for files that ought to have
358 final newlines. So if you set this to nil, you must explicitly check and
359 add a final newline, whenever you save a file that really needs one."
360 :type
'(choice (const :tag
"When visiting" visit
)
361 (const :tag
"When saving" t
)
362 (const :tag
"When visiting or saving" visit-save
)
363 (const :tag
"Don't add newlines" nil
)
364 (other :tag
"Ask each time" ask
))
365 :group
'editing-basics
368 (defcustom auto-save-default t
369 "Non-nil says by default do auto-saving of every file-visiting buffer."
373 (defcustom auto-save-file-name-transforms
374 `(("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'"
375 ;; Don't put "\\2" inside expand-file-name, since it will be
376 ;; transformed to "/2" on DOS/Windows.
377 ,(concat temporary-file-directory
"\\2") t
))
378 "Transforms to apply to buffer file name before making auto-save file name.
379 Each transform is a list (REGEXP REPLACEMENT UNIQUIFY):
380 REGEXP is a regular expression to match against the file name.
381 If it matches, `replace-match' is used to replace the
382 matching part with REPLACEMENT.
383 If the optional element UNIQUIFY is non-nil, the auto-save file name is
384 constructed by taking the directory part of the replaced file-name,
385 concatenated with the buffer file name with all directory separators
386 changed to `!' to prevent clashes. This will not work
387 correctly if your filesystem truncates the resulting name.
389 All the transforms in the list are tried, in the order they are listed.
390 When one transform applies, its result is final;
391 no further transforms are tried.
393 The default value is set up to put the auto-save file into the
394 temporary directory (see the variable `temporary-file-directory') for
395 editing a remote file.
397 On MS-DOS filesystems without long names this variable is always
400 :type
'(repeat (list (string :tag
"Regexp") (string :tag
"Replacement")
401 (boolean :tag
"Uniquify")))
402 :initialize
'custom-initialize-delay
405 (defvar auto-save--timer nil
"Timer for `auto-save-visited-mode'.")
407 (defcustom auto-save-visited-interval
5
408 "Interval in seconds for `auto-save-visited-mode'.
409 If `auto-save-visited-mode' is enabled, Emacs will save all
410 buffers visiting a file to the visited file after it has been
411 idle for `auto-save-visited-interval' seconds."
415 :set
(lambda (symbol value
)
416 (set-default symbol value
)
417 (when auto-save--timer
418 (timer-set-idle-time auto-save--timer value
:repeat
))))
420 (define-minor-mode auto-save-visited-mode
421 "Toggle automatic saving to file-visiting buffers on or off.
422 With a prefix argument ARG, enable regular saving of all buffers
423 visiting a file if ARG is positive, and disable it otherwise.
424 Unlike `auto-save-mode', this mode will auto-save buffer contents
425 to the visited files directly and will also run all save-related
426 hooks. See Info node `Saving' for details of the save process.
428 If called from Lisp, enable the mode if ARG is omitted or nil,
429 and toggle it if ARG is `toggle'."
432 (when auto-save--timer
(cancel-timer auto-save--timer
))
433 (setq auto-save--timer
434 (when auto-save-visited-mode
436 auto-save-visited-interval
:repeat
437 #'save-some-buffers
:no-prompt
439 (not (and buffer-auto-save-file-name
440 auto-save-visited-file-name
)))))))
442 ;; The 'set' part is so we don't get a warning for using this variable
443 ;; above, while still catching code that _sets_ the variable to get
444 ;; the same effect as the new auto-save-visited-mode.
445 (make-obsolete-variable 'auto-save-visited-file-name
'auto-save-visited-mode
448 (defcustom save-abbrevs t
449 "Non-nil means save word abbrevs too when files are saved.
450 If `silently', don't ask the user before saving."
451 :type
'(choice (const t
) (const nil
) (const silently
))
454 (defcustom find-file-run-dired t
455 "Non-nil means allow `find-file' to visit directories.
456 To visit the directory, `find-file' runs `find-directory-functions'."
460 (defcustom find-directory-functions
'(cvs-dired-noselect dired-noselect
)
461 "List of functions to try in sequence to visit a directory.
462 Each function is called with the directory name as the sole argument
463 and should return either a buffer or nil."
464 :type
'(hook :options
(cvs-dired-noselect dired-noselect
))
467 ;; FIXME: also add a hook for `(thing-at-point 'filename)'
468 (defcustom file-name-at-point-functions
'(ffap-guess-file-name-at-point)
469 "List of functions to try in sequence to get a file name at point.
470 Each function should return either nil or a file name found at the
471 location of point in the current buffer."
472 :type
'(hook :options
(ffap-guess-file-name-at-point))
475 ;;;It is not useful to make this a local variable.
476 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
477 (define-obsolete-variable-alias 'find-file-not-found-hooks
478 'find-file-not-found-functions
"22.1")
479 (defvar find-file-not-found-functions nil
480 "List of functions to be called for `find-file' on nonexistent file.
481 These functions are called as soon as the error is detected.
482 Variable `buffer-file-name' is already set up.
483 The functions are called in the order given until one of them returns non-nil.")
485 ;;;It is not useful to make this a local variable.
486 ;;;(put 'find-file-hooks 'permanent-local t)
487 (define-obsolete-variable-alias 'find-file-hooks
'find-file-hook
"22.1")
488 (defcustom find-file-hook nil
489 "List of functions to be called after a buffer is loaded from a file.
490 The buffer's local variables (if any) will have been processed before the
491 functions are called."
494 :options
'(auto-insert)
497 (define-obsolete-variable-alias 'write-file-hooks
'write-file-functions
"22.1")
498 (defvar write-file-functions nil
499 "List of functions to be called before saving a buffer to a file.
500 Only used by `save-buffer'.
501 If one of them returns non-nil, the file is considered already written
502 and the rest are not called.
503 These hooks are considered to pertain to the visited file.
504 So any buffer-local binding of this variable is discarded if you change
505 the visited file name with \\[set-visited-file-name], but not when you
506 change the major mode.
508 This hook is not run if any of the functions in
509 `write-contents-functions' returns non-nil. Both hooks pertain
510 to how to save a buffer to file, for instance, choosing a suitable
511 coding system and setting mode bits. (See Info
512 node `(elisp)Saving Buffers'.) To perform various checks or
513 updates before the buffer is saved, use `before-save-hook'.")
514 (put 'write-file-functions
'permanent-local t
)
516 (defvar local-write-file-hooks nil
)
517 (make-variable-buffer-local 'local-write-file-hooks
)
518 (put 'local-write-file-hooks
'permanent-local t
)
519 (make-obsolete-variable 'local-write-file-hooks
'write-file-functions
"22.1")
521 (define-obsolete-variable-alias 'write-contents-hooks
522 'write-contents-functions
"22.1")
523 (defvar write-contents-functions nil
524 "List of functions to be called before writing out a buffer to a file.
526 Only used by `save-buffer'. If one of them returns non-nil, the
527 file is considered already written and the rest are not called
528 and neither are the functions in `write-file-functions'. This
529 hook can thus be used to create save behavior for buffers that
530 are not visiting a file at all.
532 This variable is meant to be used for hooks that pertain to the
533 buffer's contents, not to the particular visited file; thus,
534 `set-visited-file-name' does not clear this variable; but changing the
535 major mode does clear it.
537 For hooks that _do_ pertain to the particular visited file, use
538 `write-file-functions'. Both this variable and
539 `write-file-functions' relate to how a buffer is saved to file.
540 To perform various checks or updates before the buffer is saved,
541 use `before-save-hook'.")
542 (make-variable-buffer-local 'write-contents-functions
)
544 (defcustom enable-local-variables t
545 "Control use of local variables in files you visit.
546 The value can be t, nil, :safe, :all, or something else.
548 A value of t means file local variables specifications are obeyed
549 if all the specified variable values are safe; if any values are
550 not safe, Emacs queries you, once, whether to set them all.
551 \(When you say yes to certain values, they are remembered as safe.)
553 :safe means set the safe variables, and ignore the rest.
554 :all means set all variables, whether safe or not.
555 (Don't set it permanently to :all.)
556 A value of nil means always ignore the file local variables.
558 Any other value means always query you once whether to set them all.
559 \(When you say yes to certain values, they are remembered as safe, but
560 this has no effect when `enable-local-variables' is \"something else\".)
562 This variable also controls use of major modes specified in
565 The command \\[normal-mode], when used interactively,
566 always obeys file local variable specifications and the -*- line,
567 and ignores this variable."
569 :type
'(choice (const :tag
"Query Unsafe" t
)
570 (const :tag
"Safe Only" :safe
)
571 (const :tag
"Do all" :all
)
572 (const :tag
"Ignore" nil
)
573 (other :tag
"Query" other
))
576 (defvar enable-dir-local-variables t
577 "Non-nil means enable use of directory-local variables.
578 Some modes may wish to set this to nil to prevent directory-local
579 settings being applied, but still respect file-local ones.")
581 ;; This is an odd variable IMO.
582 ;; You might wonder why it is needed, when we could just do:
583 ;; (set (make-local-variable 'enable-local-variables) nil)
584 ;; These two are not precisely the same.
585 ;; Setting this variable does not cause -*- mode settings to be
586 ;; ignored, whereas setting enable-local-variables does.
587 ;; Only three places in Emacs use this variable: tar and arc modes,
588 ;; and rmail. The first two don't need it. They already use
589 ;; inhibit-local-variables-regexps, which is probably enough, and
590 ;; could also just set enable-local-variables locally to nil.
591 ;; Them setting it has the side-effect that dir-locals cannot apply to
592 ;; eg tar files (?). FIXME Is this appropriate?
593 ;; AFAICS, rmail is the only thing that needs this, and the only
594 ;; reason it uses it is for BABYL files (which are obsolete).
595 ;; These contain "-*- rmail -*-" in the first line, which rmail wants
596 ;; to respect, so that find-file on a BABYL file will switch to
597 ;; rmail-mode automatically (this is nice, but hardly essential,
598 ;; since most people are used to explicitly running a command to
599 ;; access their mail; M-x gnus etc). Rmail files may happen to
600 ;; contain Local Variables sections in messages, which Rmail wants to
601 ;; ignore. So AFAICS the only reason this variable exists is for a
602 ;; minor convenience feature for handling of an obsolete Rmail file format.
603 (defvar local-enable-local-variables t
604 "Like `enable-local-variables', except for major mode in a -*- line.
605 The meaningful values are nil and non-nil. The default is non-nil.
606 It should be set in a buffer-local fashion.
608 Setting this to nil has the same effect as setting `enable-local-variables'
609 to nil, except that it does not ignore any mode: setting in a -*- line.
610 Unless this difference matters to you, you should set `enable-local-variables'
611 instead of this variable.")
613 (defcustom enable-local-eval
'maybe
614 "Control processing of the \"variable\" `eval' in a file's local variables.
615 The value can be t, nil or something else.
616 A value of t means obey `eval' variables.
617 A value of nil means ignore them; anything else means query."
619 :type
'(choice (const :tag
"Obey" t
)
620 (const :tag
"Ignore" nil
)
621 (other :tag
"Query" other
))
624 (defcustom view-read-only nil
625 "Non-nil means buffers visiting files read-only do so in view mode.
626 In fact, this means that all read-only buffers normally have
627 View mode enabled, including buffers that are read-only because
628 you visit a file you cannot alter, and buffers you make read-only
629 using \\[read-only-mode]."
633 (defvar file-name-history nil
634 "History list of file names entered in the minibuffer.
636 Maximum length of the history list is determined by the value
637 of `history-length', which see.")
639 (defvar save-silently nil
640 "If non-nil, avoid messages when saving files.
641 Error-related messages will still be printed, but all other
645 (put 'ange-ftp-completion-hook-function
'safe-magic t
)
646 (defun ange-ftp-completion-hook-function (op &rest args
)
647 "Provides support for ange-ftp host name completion.
648 Runs the usual ange-ftp hook, but only for completion operations."
649 ;; Having this here avoids the need to load ange-ftp when it's not
651 (if (memq op
'(file-name-completion file-name-all-completions
))
652 (apply 'ange-ftp-hook-function op args
)
653 (let ((inhibit-file-name-handlers
654 (cons 'ange-ftp-completion-hook-function
655 (and (eq inhibit-file-name-operation op
)
656 inhibit-file-name-handlers
)))
657 (inhibit-file-name-operation op
))
660 (declare-function dos-convert-standard-filename
"dos-fns.el" (filename))
661 (declare-function w32-convert-standard-filename
"w32-fns.el" (filename))
663 (defun convert-standard-filename (filename)
664 "Convert a standard file's name to something suitable for the OS.
665 This means to guarantee valid names and perhaps to canonicalize
668 FILENAME should be an absolute file name since the conversion rules
669 sometimes vary depending on the position in the file name. E.g. c:/foo
670 is a valid DOS file name, but c:/bar/c:/foo is not.
672 This function's standard definition is trivial; it just returns
673 the argument. However, on Windows and DOS, replace invalid
674 characters. On DOS, make sure to obey the 8.3 limitations.
675 In the native Windows build, turn Cygwin names into native names.
677 See Info node `(elisp)Standard File Names' for more details."
679 ((eq system-type
'cygwin
)
680 (let ((name (copy-sequence filename
))
682 ;; Replace invalid filename characters with !
683 (while (string-match "[?*:<>|\"\000-\037]" name start
)
684 (aset name
(match-beginning 0) ?
!)
685 (setq start
(match-end 0)))
687 ((eq system-type
'windows-nt
)
688 (w32-convert-standard-filename filename
))
689 ((eq system-type
'ms-dos
)
690 (dos-convert-standard-filename filename
))
693 (defun read-directory-name (prompt &optional dir default-dirname mustmatch initial
)
694 "Read directory name, prompting with PROMPT and completing in directory DIR.
695 Value is not expanded---you must call `expand-file-name' yourself.
696 Default name to DEFAULT-DIRNAME if user exits with the same
697 non-empty string that was inserted by this function.
698 (If DEFAULT-DIRNAME is omitted, DIR combined with INITIAL is used,
699 or just DIR if INITIAL is nil.)
700 If the user exits with an empty minibuffer, this function returns
701 an empty string. (This can only happen if the user erased the
702 pre-inserted contents or if `insert-default-directory' is nil.)
703 Fourth arg MUSTMATCH non-nil means require existing directory's name.
704 Non-nil and non-t means also require confirmation after completion.
705 Fifth arg INITIAL specifies text to start with.
706 DIR should be an absolute directory name. It defaults to
707 the value of `default-directory'."
709 (setq dir default-directory
))
710 (read-file-name prompt dir
(or default-dirname
711 (if initial
(expand-file-name initial dir
)
717 (defun pwd (&optional insert
)
718 "Show the current default directory.
719 With prefix argument INSERT, insert the current default directory
723 (insert default-directory
)
724 (message "Directory %s" default-directory
)))
727 "Value of the CDPATH environment variable, as a list.
728 Not actually set up until the first time you use it.")
730 (defun parse-colon-path (search-path)
731 "Explode a search path into a list of directory names.
732 Directories are separated by `path-separator' (which is colon in
733 GNU and Unix systems). Substitute environment variables into the
734 resulting list of directory names. For an empty path element (i.e.,
735 a leading or trailing separator, or two adjacent separators), return
736 nil (meaning `default-directory') as the associated list element."
737 (when (stringp search-path
)
740 (substitute-in-file-name (file-name-as-directory f
))))
741 (split-string search-path path-separator
))))
743 (defun cd-absolute (dir)
744 "Change current directory to given absolute file name DIR."
745 ;; Put the name into directory syntax now,
746 ;; because otherwise expand-file-name may give some bad results.
747 (setq dir
(file-name-as-directory dir
))
748 ;; We used to additionally call abbreviate-file-name here, for an
749 ;; unknown reason. Problem is that most buffers are setup
750 ;; without going through cd-absolute and don't call
751 ;; abbreviate-file-name on their default-directory, so the few that
752 ;; do end up using a superficially different directory.
753 (setq dir
(expand-file-name dir
))
754 (if (not (file-directory-p dir
))
755 (if (file-exists-p dir
)
756 (error "%s is not a directory" dir
)
757 (error "%s: no such directory" dir
))
758 (unless (file-accessible-directory-p dir
)
759 (error "Cannot cd to %s: Permission denied" dir
))
760 (setq default-directory dir
)
761 (setq list-buffers-directory dir
)))
764 "Make DIR become the current buffer's default directory.
765 If your environment includes a `CDPATH' variable, try each one of
766 that list of directories (separated by occurrences of
767 `path-separator') when resolving a relative directory name.
768 The path separator is colon in GNU and GNU-like systems."
771 ;; FIXME: There's a subtle bug in the completion below. Seems linked
772 ;; to a fundamental difficulty of implementing `predicate' correctly.
773 ;; The manifestation is that TAB may list non-directories in the case where
774 ;; those files also correspond to valid directories (if your cd-path is (A/
775 ;; B/) and you have A/a a file and B/a a directory, then both `a' and `a/'
776 ;; will be listed as valid completions).
777 ;; This is because `a' (listed because of A/a) is indeed a valid choice
778 ;; (which will lead to the use of B/a).
779 (minibuffer-with-setup-hook
781 (setq-local minibuffer-completion-table
782 (apply-partially #'locate-file-completion-table
784 (setq-local minibuffer-completion-predicate
786 (locate-file dir cd-path nil
787 (lambda (f) (and (file-directory-p f
) 'dir-ok
))))))
789 (setq cd-path
(or (parse-colon-path (getenv "CDPATH"))
791 (read-directory-name "Change default directory: "
792 default-directory default-directory
795 (setq cd-path
(or (parse-colon-path (getenv "CDPATH"))
798 (or (locate-file dir cd-path nil
799 (lambda (f) (and (file-directory-p f
) 'dir-ok
)))
800 (error "No such directory found via CDPATH environment variable"))))
802 (defun directory-files-recursively (dir regexp
&optional include-directories
)
803 "Return list of all files under DIR that have file names matching REGEXP.
804 This function works recursively. Files are returned in \"depth first\"
805 order, and files from each directory are sorted in alphabetical order.
806 Each file name appears in the returned list in its absolute form.
807 Optional argument INCLUDE-DIRECTORIES non-nil means also include in the
808 output directories whose names match REGEXP."
811 ;; When DIR is "/", remote file names like "/method:" could
812 ;; also be offered. We shall suppress them.
813 (tramp-mode (and tramp-mode
(file-remote-p (expand-file-name dir
)))))
814 (dolist (file (sort (file-name-all-completions "" dir
)
816 (unless (member file
'("./" "../"))
817 (if (directory-name-p file
)
818 (let* ((leaf (substring file
0 (1- (length file
))))
819 (full-file (expand-file-name leaf dir
)))
820 ;; Don't follow symlinks to other directories.
821 (unless (file-symlink-p full-file
)
823 (nconc result
(directory-files-recursively
824 full-file regexp include-directories
))))
825 (when (and include-directories
826 (string-match regexp leaf
))
827 (setq result
(nconc result
(list full-file
)))))
828 (when (string-match regexp file
)
829 (push (expand-file-name file dir
) files
)))))
830 (nconc result
(nreverse files
))))
832 (defvar module-file-suffix
)
834 (defun load-file (file)
835 "Load the Lisp file named FILE."
836 ;; This is a case where .elc and .so/.dll make a lot of sense.
837 (interactive (list (let ((completion-ignored-extensions
838 (remove module-file-suffix
840 completion-ignored-extensions
))))
841 (read-file-name "Load file: " nil nil
'lambda
))))
842 (load (expand-file-name file
) nil nil t
))
844 (defun locate-file (filename path
&optional suffixes predicate
)
845 "Search for FILENAME through PATH.
846 If found, return the absolute file name of FILENAME; otherwise
848 PATH should be a list of directories to look in, like the lists in
849 `exec-path' or `load-path'.
850 If SUFFIXES is non-nil, it should be a list of suffixes to append to
851 file name when searching. If SUFFIXES is nil, it is equivalent to (\"\").
852 Use (\"/\") to disable PATH search, but still try the suffixes in SUFFIXES.
853 If non-nil, PREDICATE is used instead of `file-readable-p'.
855 This function will normally skip directories, so if you want it to find
856 directories, make sure the PREDICATE function returns `dir-ok' for them.
858 PREDICATE can also be an integer to pass to the `access' system call,
859 in which case file-name handlers are ignored. This usage is deprecated.
860 For compatibility, PREDICATE can also be one of the symbols
861 `executable', `readable', `writable', or `exists', or a list of
862 one or more of those symbols."
863 (if (and predicate
(symbolp predicate
) (not (functionp predicate
)))
864 (setq predicate
(list predicate
)))
865 (when (and (consp predicate
) (not (functionp predicate
)))
867 (logior (if (memq 'executable predicate
) 1 0)
868 (if (memq 'writable predicate
) 2 0)
869 (if (memq 'readable predicate
) 4 0))))
870 (locate-file-internal filename path suffixes predicate
))
872 (defun locate-file-completion-table (dirs suffixes string pred action
)
873 "Do completion for file names passed to `locate-file'."
875 ((file-name-absolute-p string
)
876 ;; FIXME: maybe we should use completion-file-name-table instead,
877 ;; tho at least for `load', the arg is passed through
878 ;; substitute-in-file-name for historical reasons.
879 (read-file-name-internal string pred action
))
880 ((eq (car-safe action
) 'boundaries
)
881 (let ((suffix (cdr action
)))
883 ,(length (file-name-directory string
))
884 ,@(let ((x (file-name-directory suffix
)))
885 (if x
(1- (length x
)) (length suffix
))))))
888 ;; If we have files like "foo.el" and "foo.elc", we could load one of
889 ;; them with "foo.el", "foo.elc", or "foo", where just "foo" is the
890 ;; preferred way. So if we list all 3, that gives a lot of redundant
891 ;; entries for the poor soul looking just for "foo". OTOH, sometimes
892 ;; the user does want to pay attention to the extension. We try to
893 ;; diffuse this tension by stripping the suffix, except when the
894 ;; result is a single element (i.e. usually we only list "foo" unless
895 ;; it's the only remaining element in the list, in which case we do
896 ;; list "foo", "foo.elc" and "foo.el").
898 (suffix (concat (regexp-opt suffixes t
) "\\'"))
899 (string-dir (file-name-directory string
))
900 (string-file (file-name-nondirectory string
)))
903 (setq dir default-directory
))
904 (if string-dir
(setq dir
(expand-file-name string-dir dir
)))
905 (when (file-directory-p dir
)
906 (dolist (file (file-name-all-completions
908 (if (not (string-match suffix file
))
910 (push file fullnames
)
911 (push (substring file
0 (match-beginning 0)) names
)))))
912 ;; Switching from names to names+fullnames creates a non-monotonicity
913 ;; which can cause problems with things like partial-completion.
914 ;; To minimize the problem, filter out completion-regexp-list, so that
915 ;; M-x load-library RET t/x.e TAB finds some files. Also remove elements
916 ;; from `names' which only matched `string' when they still had
918 (setq names
(all-completions string names
))
919 ;; Remove duplicates of the first element, so that we can easily check
920 ;; if `names' really only contains a single element.
921 (when (cdr names
) (setcdr names
(delete (car names
) (cdr names
))))
923 ;; There's no more than one matching non-suffixed element, so expand
924 ;; the list by adding the suffixed elements as well.
925 (setq names
(nconc names fullnames
)))
926 (completion-table-with-context
927 string-dir names string-file pred action
)))))
929 (defun locate-file-completion (string path-and-suffixes action
)
930 "Do completion for file names passed to `locate-file'.
931 PATH-AND-SUFFIXES is a pair of lists, (DIRECTORIES . SUFFIXES)."
932 (declare (obsolete locate-file-completion-table
"23.1"))
933 (locate-file-completion-table (car path-and-suffixes
)
934 (cdr path-and-suffixes
)
937 (defvar locate-dominating-stop-dir-regexp
938 (purecopy "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'")
939 "Regexp of directory names which stop the search in `locate-dominating-file'.
940 Any directory whose name matches this regexp will be treated like
941 a kind of root directory by `locate-dominating-file' which will stop its search
942 when it bumps into it.
943 The default regexp prevents fruitless and time-consuming attempts to find
944 special files in directories in which filenames are interpreted as hostnames,
945 or mount points potentially requiring authentication as a different user.")
947 (defun locate-dominating-file (file name
)
948 "Starting at FILE, look up directory hierarchy for directory containing NAME.
949 FILE can be a file or a directory. If it's a file, its directory will
950 serve as the starting point for searching the hierarchy of directories.
951 Stop at the first parent directory containing a file NAME,
952 and return the directory. Return nil if not found.
953 Instead of a string, NAME can also be a predicate taking one argument
954 \(a directory) and returning a non-nil value if that directory is the one for
955 which we're looking. The predicate will be called with every file/directory
956 the function needs to examine, starting with FILE."
957 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
958 ;; `name' in /home or in /.
959 (setq file
(abbreviate-file-name (expand-file-name file
)))
964 (string-match locate-dominating-stop-dir-regexp file
)))
965 (setq try
(if (stringp name
)
966 (and (file-directory-p file
)
967 (file-exists-p (expand-file-name name file
)))
968 (funcall name file
)))
969 (cond (try (setq root file
))
970 ((equal file
(setq file
(file-name-directory
971 (directory-file-name file
))))
973 (if root
(file-name-as-directory root
))))
975 (defcustom user-emacs-directory-warning t
976 "Non-nil means warn if cannot access `user-emacs-directory'.
977 Set this to nil at your own risk..."
979 :group
'initialization
982 (defun locate-user-emacs-file (new-name &optional old-name
)
983 "Return an absolute per-user Emacs-specific file name.
984 If NEW-NAME exists in `user-emacs-directory', return it.
985 Else if OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
986 Else return NEW-NAME in `user-emacs-directory', creating the
987 directory if it does not exist."
988 (convert-standard-filename
989 (let* ((home (concat "~" (or init-file-user
"")))
990 (at-home (and old-name
(expand-file-name old-name home
)))
991 (bestname (abbreviate-file-name
992 (expand-file-name new-name user-emacs-directory
))))
993 (if (and at-home
(not (file-readable-p bestname
))
994 (file-readable-p at-home
))
996 ;; Make sure `user-emacs-directory' exists,
997 ;; unless we're in batch mode or dumping Emacs.
1001 (if (file-directory-p user-emacs-directory
)
1002 (or (file-accessible-directory-p user-emacs-directory
)
1003 (setq errtype
"access"))
1004 (with-file-modes ?
\700
1006 (make-directory user-emacs-directory
)
1007 (error (setq errtype
"create")))))
1009 user-emacs-directory-warning
1010 (not (get 'user-emacs-directory-warning
'this-session
)))
1011 ;; Only warn once per Emacs session.
1012 (put 'user-emacs-directory-warning
'this-session t
)
1013 (display-warning 'initialization
1015 Unable to %s `user-emacs-directory' (%s).
1016 Any data that would normally be written there may be lost!
1017 If you never want to see this message again,
1018 customize the variable `user-emacs-directory-warning'."
1019 errtype user-emacs-directory
)))))
1023 (defun executable-find (command)
1024 "Search for COMMAND in `exec-path' and return the absolute file name.
1025 Return nil if COMMAND is not found anywhere in `exec-path'."
1026 ;; Use 1 rather than file-executable-p to better match the behavior of
1028 (locate-file command exec-path exec-suffixes
1))
1030 (defun load-library (library)
1031 "Load the Emacs Lisp library named LIBRARY.
1032 LIBRARY should be a string.
1033 This is an interface to the function `load'. LIBRARY is searched
1034 for in `load-path', both with and without `load-suffixes' (as
1035 well as `load-file-rep-suffixes').
1037 See Info node `(emacs)Lisp Libraries' for more details.
1038 See `load-file' for a different interface to `load'."
1040 (let (completion-ignored-extensions)
1041 (list (completing-read "Load library: "
1042 (apply-partially 'locate-file-completion-table
1044 (get-load-suffixes))))))
1047 (defun file-remote-p (file &optional identification connected
)
1048 "Test whether FILE specifies a location on a remote system.
1049 A file is considered remote if accessing it is likely to
1050 be slower or less reliable than accessing local files.
1052 `file-remote-p' never opens a new remote connection. It can
1053 only reuse a connection that is already open.
1055 Return nil or a string identifying the remote connection
1056 \(ideally a prefix of FILE). Return nil if FILE is a relative
1059 When IDENTIFICATION is nil, the returned string is a complete
1060 remote identifier: with components method, user, and host. The
1061 components are those present in FILE, with defaults filled in for
1062 any that are missing.
1064 IDENTIFICATION can specify which part of the identification to
1065 return. IDENTIFICATION can be the symbol `method', `user',
1066 `host', or `localname'. Any other value is handled like nil and
1067 means to return the complete identification. The string returned
1068 for IDENTIFICATION `localname' can differ depending on whether
1069 there is an existing connection.
1071 If CONNECTED is non-nil, return an identification only if FILE is
1072 located on a remote system and a connection is established to
1075 Tip: You can use this expansion of remote identifier components
1076 to derive a new remote file name from an existing one. For
1077 example, if FILE is \"/sudo::/path/to/file\" then
1079 (concat (file-remote-p FILE) \"/bin/sh\")
1081 returns a remote file name for file \"/bin/sh\" that has the
1082 same remote identifier as FILE but expanded; a name such as
1083 \"/sudo:root@myhost:/bin/sh\"."
1084 (let ((handler (find-file-name-handler file
'file-remote-p
)))
1086 (funcall handler
'file-remote-p file identification connected
)
1089 ;; Probably this entire variable should be obsolete now, in favor of
1090 ;; something Tramp-related (?). It is not used in many places.
1091 ;; It's not clear what the best file for this to be in is, but given
1092 ;; it uses custom-initialize-delay, it is easier if it is preloaded
1093 ;; rather than autoloaded.
1094 (defcustom remote-shell-program
1095 ;; This used to try various hard-coded places for remsh, rsh, and
1096 ;; rcmd, trying to guess based on location whether "rsh" was
1097 ;; "restricted shell" or "remote shell", but I don't see the point
1098 ;; in this day and age. Almost everyone will use ssh, and have
1099 ;; whatever command they want to use in PATH.
1101 (let ((list '("ssh" "remsh" "rcmd" "rsh")))
1103 (not (executable-find (car list
)))
1104 (setq list
(cdr list
))))
1105 (or (car list
) "ssh")))
1106 "Program to use to execute commands on a remote host (e.g. ssh or rsh)."
1107 :version
"24.3" ; ssh rather than rsh, etc
1108 :initialize
'custom-initialize-delay
1112 (defcustom remote-file-name-inhibit-cache
10
1113 "Whether to use the remote file-name cache for read access.
1114 When nil, never expire cached values (caution)
1115 When t, never use the cache (safe, but may be slow)
1116 A number means use cached values for that amount of seconds since caching.
1118 The attributes of remote files are cached for better performance.
1119 If they are changed outside of Emacs's control, the cached values
1120 become invalid, and must be reread. If you are sure that nothing
1121 other than Emacs changes the files, you can set this variable to nil.
1123 If a remote file is checked regularly, it might be a good idea to
1124 let-bind this variable to a value less than the interval between
1125 consecutive checks. For example:
1127 (defun display-time-file-nonempty-p (file)
1128 (let ((remote-file-name-inhibit-cache (- display-time-interval 5)))
1129 (and (file-exists-p file)
1130 (< 0 (nth 7 (file-attributes (file-chase-links file)))))))"
1134 (const :tag
"Do not inhibit file name cache" nil
)
1135 (const :tag
"Do not use file name cache" t
)
1136 (integer :tag
"Do not use file name cache"
1137 :format
"Do not use file name cache older then %v seconds"
1140 (defun file-local-name (file)
1141 "Return the local name component of FILE.
1142 It returns a file name which can be used directly as argument of
1143 `process-file', `start-file-process', or `shell-command'."
1144 (or (file-remote-p file
'localname
) file
))
1146 (defun file-local-copy (file)
1147 "Copy the file FILE into a temporary file on this machine.
1148 Returns the name of the local copy, or nil, if FILE is directly
1150 ;; This formerly had an optional BUFFER argument that wasn't used by
1152 (let ((handler (find-file-name-handler file
'file-local-copy
)))
1154 (funcall handler
'file-local-copy file
)
1157 (defun files--name-absolute-system-p (file)
1158 "Return non-nil if FILE is an absolute name to the operating system.
1159 This is like `file-name-absolute-p', except that it returns nil for
1160 names beginning with `~'."
1161 (and (file-name-absolute-p file
)
1162 (not (eq (aref file
0) ?~
))))
1164 (defun files--splice-dirname-file (dirname file
)
1165 "Splice DIRNAME to FILE like the operating system would.
1166 If FILE is relative, return DIRNAME concatenated to FILE.
1167 Otherwise return FILE, quoted as needed if DIRNAME and FILE have
1168 different handlers; although this quoting is dubious if DIRNAME
1169 is magic, it is not clear what would be better. This function
1170 differs from `expand-file-name' in that DIRNAME must be a
1171 directory name and leading `~' and `/:' are not special in FILE."
1172 (let ((unquoted (if (files--name-absolute-system-p file
)
1174 (concat dirname file
))))
1175 (if (eq (find-file-name-handler dirname
'file-symlink-p
)
1176 (find-file-name-handler unquoted
'file-symlink-p
))
1178 (let (file-name-handler-alist) (file-name-quote unquoted
)))))
1180 (defun file-truename (filename &optional counter prev-dirs
)
1181 "Return the truename of FILENAME.
1182 If FILENAME is not absolute, first expands it against `default-directory'.
1183 The truename of a file name is found by chasing symbolic links
1184 both at the level of the file and at the level of the directories
1185 containing it, until no links are left at any level.
1187 \(fn FILENAME)" ;; Don't document the optional arguments.
1188 ;; COUNTER and PREV-DIRS are only used in recursive calls.
1189 ;; COUNTER can be a cons cell whose car is the count of how many
1190 ;; more links to chase before getting an error.
1191 ;; PREV-DIRS can be a cons cell whose car is an alist
1192 ;; of truenames we've just recently computed.
1193 (cond ((or (string= filename
"") (string= filename
"~"))
1194 (setq filename
(expand-file-name filename
))
1195 (if (string= filename
"")
1196 (setq filename
"/")))
1197 ((and (string= (substring filename
0 1) "~")
1198 (string-match "~[^/]*/?" filename
))
1200 (substring filename
0 (match-end 0)))
1201 (rest (substring filename
(match-end 0))))
1202 (setq filename
(concat (expand-file-name first-part
) rest
)))))
1204 (or counter
(setq counter
(list 100)))
1206 ;; For speed, remove the ange-ftp completion handler from the list.
1207 ;; We know it's not needed here.
1208 ;; For even more speed, do this only on the outermost call.
1209 (file-name-handler-alist
1210 (if prev-dirs file-name-handler-alist
1211 (let ((tem (copy-sequence file-name-handler-alist
)))
1212 (delq (rassq 'ange-ftp-completion-hook-function tem
) tem
)))))
1213 (or prev-dirs
(setq prev-dirs
(list nil
)))
1215 ;; andrewi@harlequin.co.uk - on Windows, there is an issue with
1216 ;; case differences being ignored by the OS, and short "8.3 DOS"
1217 ;; name aliases existing for all files. (The short names are not
1218 ;; reported by directory-files, but can be used to refer to files.)
1219 ;; It seems appropriate for file-truename to resolve these issues in
1220 ;; the most natural way, which on Windows is to call the function
1221 ;; `w32-long-file-name' - this returns the exact name of a file as
1222 ;; it is stored on disk (expanding short name aliases with the full
1223 ;; name in the process).
1224 (if (eq system-type
'windows-nt
)
1225 (unless (string-match "[[*?]" filename
)
1226 ;; If filename exists, use its long name. If it doesn't
1227 ;; exist, the recursion below on the directory of filename
1228 ;; will drill down until we find a directory that exists,
1229 ;; and use the long name of that, with the extra
1230 ;; non-existent path components concatenated.
1231 (let ((longname (w32-long-file-name filename
)))
1233 (setq filename longname
)))))
1235 ;; If this file directly leads to a link, process that iteratively
1236 ;; so that we don't use lots of stack.
1238 (setcar counter
(1- (car counter
)))
1239 (if (< (car counter
) 0)
1240 (error "Apparent cycle of symbolic links for %s" filename
))
1241 (let ((handler (find-file-name-handler filename
'file-truename
)))
1242 ;; For file name that has a special handler, call handler.
1243 ;; This is so that ange-ftp can save time by doing a no-op.
1245 (setq filename
(funcall handler
'file-truename filename
)
1247 (let ((dir (or (file-name-directory filename
) default-directory
))
1249 ;; Get the truename of the directory.
1250 (setq dirfile
(directory-file-name dir
))
1251 ;; If these are equal, we have the (or a) root directory.
1252 (or (string= dir dirfile
)
1253 (and (file-name-case-insensitive-p dir
)
1254 (eq (compare-strings dir
0 nil dirfile
0 nil t
) t
))
1255 ;; If this is the same dir we last got the truename for,
1256 ;; save time--don't recalculate.
1257 (if (assoc dir
(car prev-dirs
))
1258 (setq dir
(cdr (assoc dir
(car prev-dirs
))))
1260 (new (file-name-as-directory (file-truename dirfile counter prev-dirs
))))
1261 (setcar prev-dirs
(cons (cons old new
) (car prev-dirs
)))
1263 (if (equal ".." (file-name-nondirectory filename
))
1265 (directory-file-name (file-name-directory (directory-file-name dir
)))
1267 (if (equal "." (file-name-nondirectory filename
))
1268 (setq filename
(directory-file-name dir
)
1270 ;; Put it back on the file name.
1271 (setq filename
(concat dir
(file-name-nondirectory filename
)))
1272 ;; Is the file name the name of a link?
1273 (setq target
(file-symlink-p filename
))
1275 ;; Yes => chase that link, then start all over
1276 ;; since the link may point to a directory name that uses links.
1277 ;; We can't safely use expand-file-name here
1278 ;; since target might look like foo/../bar where foo
1279 ;; is itself a link. Instead, we handle . and .. above.
1280 (setq filename
(files--splice-dirname-file dir target
)
1283 (setq done t
))))))))
1286 (defun file-chase-links (filename &optional limit
)
1287 "Chase links in FILENAME until a name that is not a link.
1288 Unlike `file-truename', this does not check whether a parent
1289 directory name is a symbolic link.
1290 If the optional argument LIMIT is a number,
1291 it means chase no more than that many links and then stop."
1292 (let (tem (newname filename
)
1294 (while (and (or (null limit
) (< count limit
))
1295 (setq tem
(file-symlink-p newname
)))
1297 (if (and (null limit
) (= count
100))
1298 (error "Apparent cycle of symbolic links for %s" filename
))
1299 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
1300 (while (string-match "//+" tem
)
1301 (setq tem
(replace-match "/" nil nil tem
)))
1302 ;; Handle `..' by hand, since it needs to work in the
1303 ;; target of any directory symlink.
1304 ;; This code is not quite complete; it does not handle
1305 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
1306 (while (string-match "\\`\\.\\./" tem
)
1307 (setq tem
(substring tem
3))
1308 (setq newname
(expand-file-name newname
))
1309 ;; Chase links in the default dir of the symlink.
1312 (directory-file-name (file-name-directory newname
))))
1313 ;; Now find the parent of that dir.
1314 (setq newname
(file-name-directory newname
)))
1315 (setq newname
(files--splice-dirname-file (file-name-directory newname
)
1317 (setq count
(1+ count
))))
1320 ;; A handy function to display file sizes in human-readable form.
1321 ;; See http://en.wikipedia.org/wiki/Kibibyte for the reference.
1322 (defun file-size-human-readable (file-size &optional flavor
)
1323 "Produce a string showing FILE-SIZE in human-readable form.
1325 Optional second argument FLAVOR controls the units and the display format:
1327 If FLAVOR is nil or omitted, each kilobyte is 1024 bytes and the produced
1328 suffixes are \"k\", \"M\", \"G\", \"T\", etc.
1329 If FLAVOR is `si', each kilobyte is 1000 bytes and the produced suffixes
1330 are \"k\", \"M\", \"G\", \"T\", etc.
1331 If FLAVOR is `iec', each kilobyte is 1024 bytes and the produced suffixes
1332 are \"KiB\", \"MiB\", \"GiB\", \"TiB\", etc."
1333 (let ((power (if (or (null flavor
) (eq flavor
'iec
))
1337 ;; none, kilo, mega, giga, tera, peta, exa, zetta, yotta
1338 (list "" "k" "M" "G" "T" "P" "E" "Z" "Y")))
1339 (while (and (>= file-size power
) (cdr post-fixes
))
1340 (setq file-size
(/ file-size power
)
1341 post-fixes
(cdr post-fixes
)))
1342 (format (if (> (mod file-size
1.0) 0.05)
1346 (if (and (eq flavor
'iec
) (string= (car post-fixes
) "k"))
1349 (if (eq flavor
'iec
) "iB" ""))))
1351 (defcustom mounted-file-systems
1352 (if (memq system-type
'(windows-nt cygwin
))
1354 ;; regexp-opt.el is not dumped into emacs binary.
1356 ;; "^" (regexp-opt '("/afs/" "/media/" "/mnt" "/net/" "/tmp_mnt/"))))
1357 "^\\(?:/\\(?:afs/\\|m\\(?:edia/\\|nt\\)\\|\\(?:ne\\|tmp_mn\\)t/\\)\\)")
1358 "File systems which ought to be mounted."
1361 :require
'regexp-opt
1364 (defun temporary-file-directory ()
1365 "The directory for writing temporary files.
1366 In case of a remote `default-directory', this is a directory for
1367 temporary files on that remote host. If such a directory does
1368 not exist, or `default-directory' ought to be located on a
1369 mounted file system (see `mounted-file-systems'), the function
1370 returns `default-directory'.
1371 For a non-remote and non-mounted `default-directory', the value of
1372 the variable `temporary-file-directory' is returned."
1373 (let ((handler (find-file-name-handler
1374 default-directory
'temporary-file-directory
)))
1376 (funcall handler
'temporary-file-directory
)
1377 (if (string-match mounted-file-systems default-directory
)
1379 temporary-file-directory
))))
1381 (defun make-temp-file (prefix &optional dir-flag suffix text
)
1382 "Create a temporary file.
1383 The returned file name (created by appending some random characters at the end
1384 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1385 is guaranteed to point to a newly created file.
1386 You can then use `write-region' to write new data into the file.
1388 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1390 If SUFFIX is non-nil, add that at the end of the file name.
1392 If TEXT is a string, insert it into the new file; DIR-FLAG should be nil.
1393 Otherwise the file will be empty."
1394 (let ((absolute-prefix
1395 (if (or (zerop (length prefix
)) (member prefix
'("." "..")))
1396 (concat (file-name-as-directory temporary-file-directory
) prefix
)
1397 (expand-file-name prefix temporary-file-directory
))))
1398 (if (find-file-name-handler absolute-prefix
'write-region
)
1399 (files--make-magic-temp-file absolute-prefix dir-flag suffix text
)
1400 (make-temp-file-internal absolute-prefix
1401 (if dir-flag t
) (or suffix
"") text
))))
1403 (defun files--make-magic-temp-file (absolute-prefix
1404 &optional dir-flag suffix text
)
1405 "Implement (make-temp-file ABSOLUTE-PREFIX DIR-FLAG SUFFIX TEXT).
1406 This implementation works on magic file names."
1407 ;; Create temp files with strict access rights. It's easy to
1408 ;; loosen them later, whereas it's impossible to close the
1409 ;; time-window of loose permissions otherwise.
1410 (with-file-modes ?
\700
1411 (let ((contents (if (stringp text
) text
""))
1413 (while (condition-case ()
1415 (setq file
(make-temp-name absolute-prefix
))
1417 (setq file
(concat file suffix
)))
1419 (make-directory file
)
1420 (write-region contents nil file nil
'silent nil
'excl
))
1422 (file-already-exists t
))
1423 ;; the file was somehow created by someone else between
1424 ;; `make-temp-name' and `write-region', let's try again.
1428 (defun make-nearby-temp-file (prefix &optional dir-flag suffix
)
1429 "Create a temporary file as close as possible to `default-directory'.
1430 If PREFIX is a relative file name, and `default-directory' is a
1431 remote file name or located on a mounted file systems, the
1432 temporary file is created in the directory returned by the
1433 function `temporary-file-directory'. Otherwise, the function
1434 `make-temp-file' is used. PREFIX, DIR-FLAG and SUFFIX have the
1435 same meaning as in `make-temp-file'."
1436 (let ((handler (find-file-name-handler
1437 default-directory
'make-nearby-temp-file
)))
1438 (if (and handler
(not (file-name-absolute-p default-directory
)))
1439 (funcall handler
'make-nearby-temp-file prefix dir-flag suffix
)
1440 (let ((temporary-file-directory (temporary-file-directory)))
1441 (make-temp-file prefix dir-flag suffix
)))))
1443 (defun recode-file-name (file coding new-coding
&optional ok-if-already-exists
)
1444 "Change the encoding of FILE's name from CODING to NEW-CODING.
1445 The value is a new name of FILE.
1446 Signals a `file-already-exists' error if a file of the new name
1447 already exists unless optional fourth argument OK-IF-ALREADY-EXISTS
1448 is non-nil. A number as fourth arg means request confirmation if
1449 the new name already exists. This is what happens in interactive
1452 (let ((default-coding (or file-name-coding-system
1453 default-file-name-coding-system
))
1454 (filename (read-file-name "Recode filename: " nil nil t
))
1455 from-coding to-coding
)
1456 (if (and default-coding
1457 ;; We provide the default coding only when it seems that
1458 ;; the filename is correctly decoded by the default
1460 (let ((charsets (find-charset-string filename
)))
1461 (and (not (memq 'eight-bit-control charsets
))
1462 (not (memq 'eight-bit-graphic charsets
)))))
1463 (setq from-coding
(read-coding-system
1464 (format "Recode filename %s from (default %s): "
1465 filename default-coding
)
1467 (setq from-coding
(read-coding-system
1468 (format "Recode filename %s from: " filename
))))
1470 ;; We provide the default coding only when a user is going to
1471 ;; change the encoding not from the default coding.
1472 (if (eq from-coding default-coding
)
1473 (setq to-coding
(read-coding-system
1474 (format "Recode filename %s from %s to: "
1475 filename from-coding
)))
1476 (setq to-coding
(read-coding-system
1477 (format "Recode filename %s from %s to (default %s): "
1478 filename from-coding default-coding
)
1480 (list filename from-coding to-coding
)))
1482 (let* ((default-coding (or file-name-coding-system
1483 default-file-name-coding-system
))
1484 ;; FILE should have been decoded by DEFAULT-CODING.
1485 (encoded (encode-coding-string file default-coding
))
1486 (newname (decode-coding-string encoded coding
))
1487 (new-encoded (encode-coding-string newname new-coding
))
1488 ;; Suppress further encoding.
1489 (file-name-coding-system nil
)
1490 (default-file-name-coding-system nil
)
1491 (locale-coding-system nil
))
1492 (rename-file encoded new-encoded ok-if-already-exists
)
1495 (defcustom confirm-nonexistent-file-or-buffer
'after-completion
1496 "Whether confirmation is requested before visiting a new file or buffer.
1497 If nil, confirmation is not requested.
1498 If the value is `after-completion', confirmation is only
1499 requested if the user called `minibuffer-complete' right before
1500 `minibuffer-complete-and-exit'.
1501 Any other non-nil value means to request confirmation.
1503 This affects commands like `switch-to-buffer' and `find-file'."
1506 :type
'(choice (const :tag
"After completion" after-completion
)
1507 (const :tag
"Never" nil
)
1508 (other :tag
"Always" t
)))
1510 (defun confirm-nonexistent-file-or-buffer ()
1511 "Whether to request confirmation before visiting a new file or buffer.
1512 The variable `confirm-nonexistent-file-or-buffer' determines the
1513 return value, which may be passed as the REQUIRE-MATCH arg to
1514 `read-buffer' or `find-file-read-args'."
1515 (cond ((eq confirm-nonexistent-file-or-buffer
'after-completion
)
1516 'confirm-after-completion
)
1517 (confirm-nonexistent-file-or-buffer
1521 (defmacro minibuffer-with-setup-hook
(fun &rest body
)
1522 "Temporarily add FUN to `minibuffer-setup-hook' while executing BODY.
1524 By default, FUN is prepended to `minibuffer-setup-hook'. But if FUN is of
1525 the form `(:append FUN1)', FUN1 will be appended to `minibuffer-setup-hook'
1526 instead of prepending it.
1528 BODY should use the minibuffer at most once.
1529 Recursive uses of the minibuffer are unaffected (FUN is not
1530 called additional times).
1532 This macro actually adds an auxiliary function that calls FUN,
1533 rather than FUN itself, to `minibuffer-setup-hook'."
1534 (declare (indent 1) (debug t
))
1535 (let ((hook (make-symbol "setup-hook"))
1536 (funsym (make-symbol "fun"))
1538 (when (eq (car-safe fun
) :append
)
1539 (setq append
'(t) fun
(cadr fun
)))
1540 `(let ((,funsym
,fun
)
1544 ;; Clear out this hook so it does not interfere
1545 ;; with any recursive minibuffer usage.
1546 (remove-hook 'minibuffer-setup-hook
,hook
)
1550 (add-hook 'minibuffer-setup-hook
,hook
,@append
)
1552 (remove-hook 'minibuffer-setup-hook
,hook
)))))
1554 (defun find-file-read-args (prompt mustmatch
)
1555 (list (read-file-name prompt nil default-directory mustmatch
)
1558 (defun find-file (filename &optional wildcards
)
1559 "Edit file FILENAME.
1560 Switch to a buffer visiting file FILENAME,
1561 creating one if none already exists.
1562 Interactively, the default if you just type RET is the current directory,
1563 but the visited file name is available through the minibuffer history:
1564 type \\[next-history-element] to pull it into the minibuffer.
1566 The first time \\[next-history-element] is used after Emacs prompts for
1567 the file name, the result is affected by `file-name-at-point-functions',
1568 which by default try to guess the file name by looking at point in the
1569 current buffer. Customize the value of `file-name-at-point-functions'
1570 or set it to nil, if you want only the visited file name and the
1571 current directory to be available on first \\[next-history-element]
1574 You can visit files on remote machines by specifying something
1575 like /ssh:SOME_REMOTE_MACHINE:FILE for the file name. You can
1576 also visit local files as a different user by specifying
1577 /sudo::FILE for the file name.
1578 See the Info node `(tramp)File name Syntax' in the Tramp Info
1579 manual, for more about this.
1581 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1582 expand wildcards (if any) and visit multiple files. You can
1583 suppress wildcard expansion by setting `find-file-wildcards' to nil.
1585 To visit a file without any kind of conversion and without
1586 automatically choosing a major mode, use \\[find-file-literally]."
1588 (find-file-read-args "Find file: "
1589 (confirm-nonexistent-file-or-buffer)))
1590 (let ((value (find-file-noselect filename nil nil wildcards
)))
1592 (mapcar 'pop-to-buffer-same-window
(nreverse value
))
1593 (pop-to-buffer-same-window value
))))
1595 (defun find-file-other-window (filename &optional wildcards
)
1596 "Edit file FILENAME, in another window.
1598 Like \\[find-file] (which see), but creates a new window or reuses
1599 an existing one. See the function `display-buffer'.
1601 Interactively, the default if you just type RET is the current directory,
1602 but the visited file name is available through the minibuffer history:
1603 type \\[next-history-element] to pull it into the minibuffer.
1605 The first time \\[next-history-element] is used after Emacs prompts for
1606 the file name, the result is affected by `file-name-at-point-functions',
1607 which by default try to guess the file name by looking at point in the
1608 current buffer. Customize the value of `file-name-at-point-functions'
1609 or set it to nil, if you want only the visited file name and the
1610 current directory to be available on first \\[next-history-element]
1613 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1614 expand wildcards (if any) and visit multiple files."
1616 (find-file-read-args "Find file in other window: "
1617 (confirm-nonexistent-file-or-buffer)))
1618 (let ((value (find-file-noselect filename nil nil wildcards
)))
1621 (setq value
(nreverse value
))
1622 (switch-to-buffer-other-window (car value
))
1623 (mapc 'switch-to-buffer
(cdr value
))
1625 (switch-to-buffer-other-window value
))))
1627 (defun find-file-other-frame (filename &optional wildcards
)
1628 "Edit file FILENAME, in another frame.
1630 Like \\[find-file] (which see), but creates a new frame or reuses
1631 an existing one. See the function `display-buffer'.
1633 Interactively, the default if you just type RET is the current directory,
1634 but the visited file name is available through the minibuffer history:
1635 type \\[next-history-element] to pull it into the minibuffer.
1637 The first time \\[next-history-element] is used after Emacs prompts for
1638 the file name, the result is affected by `file-name-at-point-functions',
1639 which by default try to guess the file name by looking at point in the
1640 current buffer. Customize the value of `file-name-at-point-functions'
1641 or set it to nil, if you want only the visited file name and the
1642 current directory to be available on first \\[next-history-element]
1645 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1646 expand wildcards (if any) and visit multiple files."
1648 (find-file-read-args "Find file in other frame: "
1649 (confirm-nonexistent-file-or-buffer)))
1650 (let ((value (find-file-noselect filename nil nil wildcards
)))
1653 (setq value
(nreverse value
))
1654 (switch-to-buffer-other-frame (car value
))
1655 (mapc 'switch-to-buffer
(cdr value
))
1657 (switch-to-buffer-other-frame value
))))
1659 (defun find-file-existing (filename)
1660 "Edit the existing file FILENAME.
1661 Like \\[find-file], but only allow a file that exists, and do not allow
1662 file names with wildcards."
1663 (interactive (nbutlast (find-file-read-args "Find existing file: " t
)))
1664 (if (and (not (called-interactively-p 'interactive
))
1665 (not (file-exists-p filename
)))
1666 (error "%s does not exist" filename
)
1667 (find-file filename
)
1670 (defun find-file--read-only (fun filename wildcards
)
1671 (unless (or (and wildcards find-file-wildcards
1672 (not (file-name-quoted-p filename
))
1673 (string-match "[[*?]" filename
))
1674 (file-exists-p filename
))
1675 (error "%s does not exist" filename
))
1676 (let ((value (funcall fun filename wildcards
)))
1677 (mapc (lambda (b) (with-current-buffer b
(read-only-mode 1)))
1678 (if (listp value
) value
(list value
)))
1681 (defun find-file-read-only (filename &optional wildcards
)
1682 "Edit file FILENAME but don't allow changes.
1683 Like \\[find-file], but marks buffer as read-only.
1684 Use \\[read-only-mode] to permit editing."
1686 (find-file-read-args "Find file read-only: "
1687 (confirm-nonexistent-file-or-buffer)))
1688 (find-file--read-only #'find-file filename wildcards
))
1690 (defun find-file-read-only-other-window (filename &optional wildcards
)
1691 "Edit file FILENAME in another window but don't allow changes.
1692 Like \\[find-file-other-window], but marks buffer as read-only.
1693 Use \\[read-only-mode] to permit editing."
1695 (find-file-read-args "Find file read-only other window: "
1696 (confirm-nonexistent-file-or-buffer)))
1697 (find-file--read-only #'find-file-other-window filename wildcards
))
1699 (defun find-file-read-only-other-frame (filename &optional wildcards
)
1700 "Edit file FILENAME in another frame but don't allow changes.
1701 Like \\[find-file-other-frame], but marks buffer as read-only.
1702 Use \\[read-only-mode] to permit editing."
1704 (find-file-read-args "Find file read-only other frame: "
1705 (confirm-nonexistent-file-or-buffer)))
1706 (find-file--read-only #'find-file-other-frame filename wildcards
))
1708 (defun find-alternate-file-other-window (filename &optional wildcards
)
1709 "Find file FILENAME as a replacement for the file in the next window.
1710 This command does not select that window.
1712 See \\[find-file] for the possible forms of the FILENAME argument.
1714 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1715 expand wildcards (if any) and replace the file with multiple files."
1717 (save-selected-window
1719 (let ((file buffer-file-name
)
1723 (setq file-name
(file-name-nondirectory file
)
1724 file-dir
(file-name-directory file
)))
1725 (list (read-file-name
1726 "Find alternate file: " file-dir nil
1727 (confirm-nonexistent-file-or-buffer) file-name
)
1730 (find-file-other-window filename wildcards
)
1731 (save-selected-window
1733 (find-alternate-file filename wildcards
))))
1735 ;; Defined and used in buffer.c, but not as a DEFVAR_LISP.
1736 (defvar kill-buffer-hook nil
1737 "Hook run when a buffer is killed.
1738 The buffer being killed is current while the hook is running.
1741 Note: Be careful with let-binding this hook considering it is
1742 frequently used for cleanup.")
1744 (defun find-alternate-file (filename &optional wildcards
)
1745 "Find file FILENAME, select its buffer, kill previous buffer.
1746 If the current buffer now contains an empty file that you just visited
1747 \(presumably by mistake), use this command to visit the file you really want.
1749 See \\[find-file] for the possible forms of the FILENAME argument.
1751 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1752 expand wildcards (if any) and replace the file with multiple files.
1754 If the current buffer is an indirect buffer, or the base buffer
1755 for one or more indirect buffers, the other buffer(s) are not
1758 (let ((file buffer-file-name
)
1762 (setq file-name
(file-name-nondirectory file
)
1763 file-dir
(file-name-directory file
)))
1764 (list (read-file-name
1765 "Find alternate file: " file-dir nil
1766 (confirm-nonexistent-file-or-buffer) file-name
)
1768 (unless (run-hook-with-args-until-failure 'kill-buffer-query-functions
)
1769 (user-error "Aborted"))
1770 (and (buffer-modified-p) buffer-file-name
1772 (format-message "Kill and replace buffer `%s' without saving it? "
1774 (user-error "Aborted"))
1775 (let ((obuf (current-buffer))
1776 (ofile buffer-file-name
)
1777 (onum buffer-file-number
)
1778 (odir dired-directory
)
1779 (otrue buffer-file-truename
)
1780 (oname (buffer-name)))
1781 ;; Run `kill-buffer-hook' here. It needs to happen before
1782 ;; variables like `buffer-file-name' etc are set to nil below,
1783 ;; because some of the hooks that could be invoked
1784 ;; (e.g., `save-place-to-alist') depend on those variables.
1786 ;; Note that `kill-buffer-hook' is not what queries whether to
1787 ;; save a modified buffer visiting a file. Rather, `kill-buffer'
1788 ;; asks that itself. Thus, there's no need to temporarily do
1789 ;; `(set-buffer-modified-p nil)' before running this hook.
1790 (run-hooks 'kill-buffer-hook
)
1791 ;; Okay, now we can end-of-life the old buffer.
1792 (if (get-buffer " **lose**")
1793 (kill-buffer " **lose**"))
1794 (rename-buffer " **lose**")
1798 ;; This prevents us from finding the same buffer
1799 ;; if we specified the same file again.
1800 (setq buffer-file-name nil
)
1801 (setq buffer-file-number nil
)
1802 (setq buffer-file-truename nil
)
1803 ;; Likewise for dired buffers.
1804 (setq dired-directory nil
)
1805 ;; Don't use `find-file' because it may end up using another window
1806 ;; in some corner cases, e.g. when the selected window is
1807 ;; softly-dedicated.
1808 (let ((newbuf (find-file-noselect filename wildcards
)))
1809 (switch-to-buffer newbuf
)))
1810 (when (eq obuf
(current-buffer))
1811 ;; This executes if find-file gets an error
1812 ;; and does not really find anything.
1813 ;; We put things back as they were.
1814 ;; If find-file actually finds something, we kill obuf below.
1815 (setq buffer-file-name ofile
)
1816 (setq buffer-file-number onum
)
1817 (setq buffer-file-truename otrue
)
1818 (setq dired-directory odir
)
1820 (rename-buffer oname
)))
1821 (unless (eq (current-buffer) obuf
)
1822 (with-current-buffer obuf
1823 ;; We already ran these; don't run them again.
1824 (let (kill-buffer-query-functions kill-buffer-hook
)
1825 (kill-buffer obuf
))))))
1827 ;; FIXME we really need to fold the uniquify stuff in here by default,
1828 ;; not using advice, and add it to the doc string.
1829 (defun create-file-buffer (filename)
1830 "Create a suitably named buffer for visiting FILENAME, and return it.
1831 FILENAME (sans directory) is used unchanged if that name is free;
1832 otherwise a string <2> or <3> or ... is appended to get an unused name.
1834 Emacs treats buffers whose names begin with a space as internal buffers.
1835 To avoid confusion when visiting a file whose name begins with a space,
1836 this function prepends a \"|\" to the final result if necessary."
1837 (let ((lastname (file-name-nondirectory filename
)))
1838 (if (string= lastname
"")
1839 (setq lastname filename
))
1840 (generate-new-buffer (if (string-match-p "\\` " lastname
)
1841 (concat "|" lastname
)
1844 (defun generate-new-buffer (name)
1845 "Create and return a buffer with a name based on NAME.
1846 Choose the buffer's name using `generate-new-buffer-name'."
1847 (get-buffer-create (generate-new-buffer-name name
)))
1849 (defcustom automount-dir-prefix
(purecopy "^/tmp_mnt/")
1850 "Regexp to match the automounter prefix in a directory name."
1853 (make-obsolete-variable 'automount-dir-prefix
'directory-abbrev-alist
"24.3")
1855 (defvar abbreviated-home-dir nil
1856 "Regexp matching the user's homedir at the beginning of file name.
1857 The value includes abbreviation according to `directory-abbrev-alist'.")
1859 (defun abbreviate-file-name (filename)
1860 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
1861 This also substitutes \"~\" for the user's home directory (unless the
1862 home directory is a root directory) and removes automounter prefixes
1863 \(see the variable `automount-dir-prefix').
1865 When this function is first called, it caches the user's home
1866 directory as a regexp in `abbreviated-home-dir', and reuses it
1867 afterwards (so long as the home directory does not change;
1868 if you want to permanently change your home directory after having
1869 started Emacs, set `abbreviated-home-dir' to nil so it will be recalculated)."
1870 ;; Get rid of the prefixes added by the automounter.
1872 (if (and automount-dir-prefix
1873 (string-match automount-dir-prefix filename
)
1874 (file-exists-p (file-name-directory
1875 (substring filename
(1- (match-end 0))))))
1876 (setq filename
(substring filename
(1- (match-end 0)))))
1877 ;; Avoid treating /home/foo as /home/Foo during `~' substitution.
1878 (let ((case-fold-search (file-name-case-insensitive-p filename
)))
1879 ;; If any elt of directory-abbrev-alist matches this name,
1880 ;; abbreviate accordingly.
1881 (dolist (dir-abbrev directory-abbrev-alist
)
1882 (if (string-match (car dir-abbrev
) filename
)
1884 (concat (cdr dir-abbrev
)
1885 (substring filename
(match-end 0))))))
1886 ;; Compute and save the abbreviated homedir name.
1887 ;; We defer computing this until the first time it's needed, to
1888 ;; give time for directory-abbrev-alist to be set properly.
1889 ;; We include a slash at the end, to avoid spurious matches
1890 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
1891 (unless abbreviated-home-dir
1892 (put 'abbreviated-home-dir
'home
(expand-file-name "~"))
1893 (setq abbreviated-home-dir
1894 (let ((abbreviated-home-dir "$foo"))
1895 (setq abbreviated-home-dir
1897 (abbreviate-file-name
1898 (get 'abbreviated-home-dir
'home
))
1900 ;; Depending on whether default-directory does or
1901 ;; doesn't include non-ASCII characters, the value
1902 ;; of abbreviated-home-dir could be multibyte or
1903 ;; unibyte. In the latter case, we need to decode
1904 ;; it. Note that this function is called for the
1905 ;; first time (from startup.el) when
1906 ;; locale-coding-system is already set up.
1907 (if (multibyte-string-p abbreviated-home-dir
)
1908 abbreviated-home-dir
1909 (decode-coding-string abbreviated-home-dir
1910 (if (eq system-type
'windows-nt
)
1912 locale-coding-system
))))))
1914 ;; If FILENAME starts with the abbreviated homedir,
1915 ;; and ~ hasn't changed since abbreviated-home-dir was set,
1916 ;; make it start with `~' instead.
1917 ;; If ~ has changed, we ignore abbreviated-home-dir rather than
1918 ;; invalidating it, on the assumption that a change in HOME
1919 ;; is likely temporary (eg for testing).
1920 ;; FIXME Is it even worth caching abbreviated-home-dir?
1921 ;; Ref: https://debbugs.gnu.org/19657#20
1922 (if (and (string-match abbreviated-home-dir filename
)
1923 ;; If the home dir is just /, don't change it.
1924 (not (and (= (match-end 0) 1)
1925 (= (aref filename
0) ?
/)))
1926 ;; MS-DOS root directories can come with a drive letter;
1927 ;; Novell Netware allows drive letters beyond `Z:'.
1928 (not (and (memq system-type
'(ms-dos windows-nt cygwin
))
1930 (string-match "^[a-zA-`]:/$" filename
))))
1931 (equal (get 'abbreviated-home-dir
'home
)
1932 (expand-file-name "~")))
1935 (match-string 1 filename
)
1936 (substring filename
(match-end 0)))))
1939 (defun find-buffer-visiting (filename &optional predicate
)
1940 "Return the buffer visiting file FILENAME (a string).
1941 This is like `get-file-buffer', except that it checks for any buffer
1942 visiting the same file, possibly under a different name.
1943 If PREDICATE is non-nil, only buffers satisfying it are eligible,
1944 and others are ignored.
1945 If there is no such live buffer, return nil."
1946 (let ((predicate (or predicate
#'identity
))
1947 (truename (abbreviate-file-name (file-truename filename
))))
1948 (or (let ((buf (get-file-buffer filename
)))
1949 (when (and buf
(funcall predicate buf
)) buf
))
1950 (let ((list (buffer-list)) found
)
1951 (while (and (not found
) list
)
1952 (with-current-buffer (car list
)
1953 (if (and buffer-file-name
1954 (string= buffer-file-truename truename
)
1955 (funcall predicate
(current-buffer)))
1956 (setq found
(car list
))))
1957 (setq list
(cdr list
)))
1959 (let* ((attributes (file-attributes truename
))
1960 (number (nthcdr 10 attributes
))
1961 (list (buffer-list)) found
)
1962 (and buffer-file-numbers-unique
1963 (car-safe number
) ;Make sure the inode is not just nil.
1964 (while (and (not found
) list
)
1965 (with-current-buffer (car list
)
1966 (if (and buffer-file-name
1967 (equal buffer-file-number number
)
1968 ;; Verify this buffer's file number
1969 ;; still belongs to its file.
1970 (file-exists-p buffer-file-name
)
1971 (equal (file-attributes buffer-file-truename
)
1973 (funcall predicate
(current-buffer)))
1974 (setq found
(car list
))))
1975 (setq list
(cdr list
))))
1978 (defcustom find-file-wildcards t
1979 "Non-nil means file-visiting commands should handle wildcards.
1980 For example, if you specify `*.c', that would visit all the files
1981 whose names match the pattern."
1986 (defcustom find-file-suppress-same-file-warnings nil
1987 "Non-nil means suppress warning messages for symlinked files.
1988 When nil, Emacs prints a warning when visiting a file that is already
1989 visited, but with a different name. Setting this option to t
1990 suppresses this warning."
1995 (defcustom large-file-warning-threshold
10000000
1996 "Maximum size of file above which a confirmation is requested.
1997 When nil, never request confirmation."
2001 :type
'(choice integer
(const :tag
"Never request confirmation" nil
)))
2003 (defcustom out-of-memory-warning-percentage nil
2004 "Warn if file size exceeds this percentage of available free memory.
2005 When nil, never issue warning. Beware: This probably doesn't do what you
2006 think it does, because \"free\" is pretty hard to define in practice."
2010 :type
'(choice integer
(const :tag
"Never issue warning" nil
)))
2012 (defun abort-if-file-too-large (size op-type filename
)
2013 "If file SIZE larger than `large-file-warning-threshold', allow user to abort.
2014 OP-TYPE specifies the file operation being performed (for message to user)."
2015 (when (and large-file-warning-threshold size
2016 (> size large-file-warning-threshold
)
2017 (not (y-or-n-p (format "File %s is large (%s), really %s? "
2018 (file-name-nondirectory filename
)
2019 (file-size-human-readable size
) op-type
))))
2020 (user-error "Aborted")))
2022 (defun warn-maybe-out-of-memory (size)
2023 "Warn if an attempt to open file of SIZE bytes may run out of memory."
2024 (when (and (numberp size
) (not (zerop size
))
2025 (integerp out-of-memory-warning-percentage
))
2026 (let ((meminfo (memory-info)))
2027 (when (consp meminfo
)
2028 (let ((total-free-memory (float (+ (nth 1 meminfo
) (nth 3 meminfo
)))))
2029 (when (> (/ size
1024)
2030 (/ (* total-free-memory out-of-memory-warning-percentage
)
2033 "You are trying to open a file whose size (%s)
2034 exceeds the %S%% of currently available free memory (%s).
2035 If that fails, try to open it with `find-file-literally'
2036 \(but note that some characters might be displayed incorrectly)."
2037 (file-size-human-readable size
)
2038 out-of-memory-warning-percentage
2039 (file-size-human-readable (* total-free-memory
1024)))))))))
2041 (defun files--message (format &rest args
)
2042 "Like `message', except sometimes don't print to minibuffer.
2043 If the variable `save-silently' is non-nil, the message is not
2044 displayed on the minibuffer."
2045 (apply #'message format args
)
2046 (when save-silently
(message nil
)))
2048 (defun find-file-noselect (filename &optional nowarn rawfile wildcards
)
2049 "Read file FILENAME into a buffer and return the buffer.
2050 If a buffer exists visiting FILENAME, return that one, but
2051 verify that the file has not changed since visited or saved.
2052 The buffer is not selected, just returned to the caller.
2053 Optional second arg NOWARN non-nil means suppress any warning messages.
2054 Optional third arg RAWFILE non-nil means the file is read literally.
2055 Optional fourth arg WILDCARDS non-nil means do wildcard processing
2056 and visit all the matching files. When wildcards are actually
2057 used and expanded, return a list of buffers that are visiting
2060 (abbreviate-file-name
2061 (expand-file-name filename
)))
2062 (if (file-directory-p filename
)
2063 (or (and find-file-run-dired
2064 (run-hook-with-args-until-success
2065 'find-directory-functions
2066 (if find-file-visit-truename
2067 (abbreviate-file-name (file-truename filename
))
2069 (error "%s is a directory" filename
))
2072 (not (file-name-quoted-p filename
))
2073 (string-match "[[*?]" filename
))
2074 (let ((files (condition-case nil
2075 (file-expand-wildcards filename t
)
2076 (error (list filename
))))
2077 (find-file-wildcards nil
))
2079 (find-file-noselect filename
)
2080 (mapcar #'find-file-noselect files
)))
2081 (let* ((buf (get-file-buffer filename
))
2082 (truename (abbreviate-file-name (file-truename filename
)))
2083 (attributes (file-attributes truename
))
2084 (number (nthcdr 10 attributes
))
2085 ;; Find any buffer for a file which has same truename.
2086 (other (and (not buf
) (find-buffer-visiting filename
))))
2087 ;; Let user know if there is a buffer with the same truename.
2091 find-file-suppress-same-file-warnings
2092 (string-equal filename
(buffer-file-name other
))
2093 (files--message "%s and %s are the same file"
2094 filename
(buffer-file-name other
)))
2095 ;; Optionally also find that buffer.
2096 (if (or find-file-existing-other-name find-file-visit-truename
)
2098 ;; Check to see if the file looks uncommonly large.
2099 (when (not (or buf nowarn
))
2100 (abort-if-file-too-large (nth 7 attributes
) "open" filename
)
2101 (warn-maybe-out-of-memory (nth 7 attributes
)))
2103 ;; We are using an existing buffer.
2106 (verify-visited-file-modtime buf
)
2107 (cond ((not (file-exists-p filename
))
2108 (setq nonexistent t
)
2109 (message "File %s no longer exists!" filename
))
2110 ;; Certain files should be reverted automatically
2111 ;; if they have changed on disk and not in the buffer.
2112 ((and (not (buffer-modified-p buf
))
2113 (let ((tail revert-without-query
)
2116 (if (string-match (car tail
) filename
)
2118 (setq tail
(cdr tail
)))
2120 (with-current-buffer buf
2121 (message "Reverting file %s..." filename
)
2123 (message "Reverting file %s...done" filename
)))
2125 (if (string= (file-name-nondirectory filename
)
2128 (if (buffer-modified-p buf
)
2129 "File %s changed on disk. Discard your edits? "
2130 "File %s changed on disk. Reread from disk? ")
2131 (file-name-nondirectory filename
))
2133 (if (buffer-modified-p buf
)
2134 "File %s changed on disk. Discard your edits in %s? "
2135 "File %s changed on disk. Reread from disk into %s? ")
2136 (file-name-nondirectory filename
)
2137 (buffer-name buf
))))
2138 (with-current-buffer buf
2139 (revert-buffer t t
)))))
2140 (with-current-buffer buf
2142 ;; Check if a formerly read-only file has become
2143 ;; writable and vice versa, but if the buffer agrees
2144 ;; with the new state of the file, that is ok too.
2145 (let ((read-only (not (file-writable-p buffer-file-name
))))
2146 (unless (or nonexistent
2147 (eq read-only buffer-file-read-only
)
2148 (eq read-only buffer-read-only
))
2151 (if read-only
"read-only" "writable"))
2153 (format "File %s is %s on disk. Make buffer %s, too? "
2155 new-status new-status
)))
2156 (y-or-n-p question
)))
2157 (setq buffer-read-only read-only
)))
2158 (setq buffer-file-read-only read-only
))
2160 (unless (or (eq (null rawfile
) (null find-file-literally
))
2162 ;; It is confusing to ask whether to visit
2163 ;; non-literally if they have the file in
2164 ;; hexl-mode or image-mode.
2165 (memq major-mode
'(hexl-mode image-mode
)))
2166 (if (buffer-modified-p)
2170 "The file %s is already visited normally,
2171 and you have edited the buffer. Now you have asked to visit it literally,
2172 meaning no coding system handling, format conversion, or local variables.
2173 Emacs can only visit a file in one way at a time.
2175 Do you want to save the file, and visit it literally instead? "
2176 "The file %s is already visited literally,
2177 meaning no coding system handling, format conversion, or local variables.
2178 You have edited the buffer. Now you have asked to visit the file normally,
2179 but Emacs can only visit a file in one way at a time.
2181 Do you want to save the file, and visit it normally instead? ")
2182 (file-name-nondirectory filename
)))
2185 (find-file-noselect-1 buf filename nowarn
2186 rawfile truename number
))
2191 Do you want to discard your changes, and visit the file literally now? "
2193 Do you want to discard your changes, and visit the file normally now? ")))
2194 (find-file-noselect-1 buf filename nowarn
2195 rawfile truename number
)
2196 (error (if rawfile
"File already visited non-literally"
2197 "File already visited literally"))))
2201 "The file %s is already visited normally.
2202 You have asked to visit it literally,
2203 meaning no coding system decoding, format conversion, or local variables.
2204 But Emacs can only visit a file in one way at a time.
2206 Do you want to revisit the file literally now? "
2207 "The file %s is already visited literally,
2208 meaning no coding system decoding, format conversion, or local variables.
2209 You have asked to visit it normally,
2210 but Emacs can only visit a file in one way at a time.
2212 Do you want to revisit the file normally now? ")
2213 (file-name-nondirectory filename
)))
2214 (find-file-noselect-1 buf filename nowarn
2215 rawfile truename number
)
2216 (error (if rawfile
"File already visited non-literally"
2217 "File already visited literally"))))))
2218 ;; Return the buffer we are using.
2220 ;; Create a new buffer.
2221 (setq buf
(create-file-buffer filename
))
2222 ;; find-file-noselect-1 may use a different buffer.
2223 (find-file-noselect-1 buf filename nowarn
2224 rawfile truename number
))))))
2226 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number
)
2228 (with-current-buffer buf
2229 (kill-local-variable 'find-file-literally
)
2230 ;; Needed in case we are re-visiting the file with a different
2231 ;; text representation.
2232 (kill-local-variable 'buffer-file-coding-system
)
2233 (kill-local-variable 'cursor-type
)
2234 (let ((inhibit-read-only t
))
2237 (set-buffer-multibyte t
))
2240 (let ((inhibit-read-only t
))
2241 (insert-file-contents-literally filename t
))
2243 (when (and (file-exists-p filename
)
2244 (not (file-readable-p filename
)))
2246 (signal 'file-error
(list "File is not readable"
2248 ;; Unconditionally set error
2251 (let ((inhibit-read-only t
))
2252 (insert-file-contents filename t
))
2254 (when (and (file-exists-p filename
)
2255 (not (file-readable-p filename
)))
2257 (signal 'file-error
(list "File is not readable"
2259 ;; Run find-file-not-found-functions until one returns non-nil.
2260 (or (run-hook-with-args-until-success 'find-file-not-found-functions
)
2261 ;; If they fail too, set error.
2263 ;; Record the file's truename, and maybe use that as visited name.
2264 (if (equal filename buffer-file-name
)
2265 (setq buffer-file-truename truename
)
2266 (setq buffer-file-truename
2267 (abbreviate-file-name (file-truename buffer-file-name
))))
2268 (setq buffer-file-number number
)
2269 (if find-file-visit-truename
2270 (setq buffer-file-name
(expand-file-name buffer-file-truename
)))
2271 ;; Set buffer's default directory to that of the file.
2272 (setq default-directory
(file-name-directory buffer-file-name
))
2273 ;; Turn off backup files for certain file names. Since
2274 ;; this is a permanent local, the major mode won't eliminate it.
2275 (and backup-enable-predicate
2276 (not (funcall backup-enable-predicate buffer-file-name
))
2278 (make-local-variable 'backup-inhibited
)
2279 (setq backup-inhibited t
)))
2282 (set-buffer-multibyte nil
)
2283 (setq buffer-file-coding-system
'no-conversion
)
2284 (set-buffer-major-mode buf
)
2285 (setq-local find-file-literally t
))
2286 (after-find-file error
(not nowarn
)))
2289 (defun insert-file-contents-literally (filename &optional visit beg end replace
)
2290 "Like `insert-file-contents', but only reads in the file literally.
2291 See `insert-file-contents' for an explanation of the parameters.
2292 A buffer may be modified in several ways after reading into the buffer,
2293 due to Emacs features such as format decoding, character code
2294 conversion, `find-file-hook', automatic uncompression, etc.
2296 This function ensures that none of these modifications will take place."
2297 (let ((format-alist nil
)
2298 (after-insert-file-functions nil
)
2299 (coding-system-for-read 'no-conversion
)
2300 (coding-system-for-write 'no-conversion
)
2301 (inhibit-file-name-handlers
2302 ;; FIXME: Yuck!! We should turn insert-file-contents-literally
2303 ;; into a file operation instead!
2304 (append '(jka-compr-handler image-file-handler epa-file-handler
)
2305 inhibit-file-name-handlers
))
2306 (inhibit-file-name-operation 'insert-file-contents
))
2307 (insert-file-contents filename visit beg end replace
)))
2309 (defun insert-file-1 (filename insert-func
)
2310 (if (file-directory-p filename
)
2311 (signal 'file-error
(list "Opening input file" "Is a directory"
2313 ;; Check whether the file is uncommonly large
2314 (abort-if-file-too-large (nth 7 (file-attributes filename
)) "insert" filename
)
2315 (let* ((buffer (find-buffer-visiting (abbreviate-file-name (file-truename filename
))
2316 #'buffer-modified-p
))
2317 (tem (funcall insert-func filename
)))
2318 (push-mark (+ (point) (car (cdr tem
))))
2320 (message "File %s already visited and modified in buffer %s"
2321 filename
(buffer-name buffer
)))))
2323 (defun insert-file-literally (filename)
2324 "Insert contents of file FILENAME into buffer after point with no conversion.
2326 This function is meant for the user to run interactively.
2327 Don't call it from programs! Use `insert-file-contents-literally' instead.
2328 \(Its calling sequence is different; see its documentation)."
2329 (declare (interactive-only insert-file-contents-literally
))
2330 (interactive "*fInsert file literally: ")
2331 (insert-file-1 filename
#'insert-file-contents-literally
))
2333 (defvar find-file-literally nil
2334 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
2335 This has the `permanent-local' property, which takes effect if you
2336 make the variable buffer-local.")
2337 (put 'find-file-literally
'permanent-local t
)
2339 (defun find-file-literally (filename)
2340 "Visit file FILENAME with no conversion of any kind.
2341 Format conversion and character code conversion are both disabled,
2342 and multibyte characters are disabled in the resulting buffer.
2343 The major mode used is Fundamental mode regardless of the file name,
2344 and local variable specifications in the file are ignored.
2345 Automatic uncompression and adding a newline at the end of the
2346 file due to `require-final-newline' is also disabled.
2348 You cannot absolutely rely on this function to result in
2349 visiting the file literally. If Emacs already has a buffer
2350 which is visiting the file, you get the existing buffer,
2351 regardless of whether it was created literally or not.
2353 In a Lisp program, if you want to be sure of accessing a file's
2354 contents literally, you should create a temporary buffer and then read
2355 the file contents into it using `insert-file-contents-literally'."
2357 (list (read-file-name
2358 "Find file literally: " nil default-directory
2359 (confirm-nonexistent-file-or-buffer))))
2360 (switch-to-buffer (find-file-noselect filename nil t
)))
2362 (defun after-find-file (&optional error warn noauto
2363 _after-find-file-from-revert-buffer
2365 "Called after finding a file and by the default revert function.
2366 Sets buffer mode, parses local variables.
2367 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
2368 error in reading the file. WARN non-nil means warn if there
2369 exists an auto-save file more recent than the visited file.
2370 NOAUTO means don't mess with auto-save mode.
2371 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER is ignored
2372 \(see `revert-buffer-in-progress-p' for similar functionality).
2373 Fifth arg NOMODES non-nil means don't alter the file's modes.
2374 Finishes by calling the functions in `find-file-hook'
2375 unless NOMODES is non-nil."
2376 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
2383 ((and error
(file-attributes buffer-file-name
))
2384 (setq buffer-read-only t
)
2385 (if (and (file-symlink-p buffer-file-name
)
2387 (file-chase-links buffer-file-name
))))
2388 "Symbolic link that points to nonexistent file"
2389 "File exists, but cannot be read"))
2390 ((not buffer-read-only
)
2392 ;; No need to warn if buffer is auto-saved
2393 ;; under the name of the visited file.
2394 (not (and buffer-file-name
2395 auto-save-visited-file-name
))
2396 (file-newer-than-file-p (or buffer-auto-save-file-name
2397 (make-auto-save-file-name))
2399 (format "%s has auto save data; consider M-x recover-this-file"
2400 (file-name-nondirectory buffer-file-name
))
2401 (setq not-serious t
)
2402 (if error
"(New file)" nil
)))
2404 (setq not-serious t
)
2405 "Note: file is write protected")
2406 ((file-attributes (directory-file-name default-directory
))
2407 "File not found and directory write-protected")
2408 ((file-exists-p (file-name-directory buffer-file-name
))
2409 (setq buffer-read-only nil
))
2411 (setq buffer-read-only nil
)
2412 "Use M-x make-directory RET RET to create the directory and its parents"))))
2415 (or not-serious
(sit-for 1 t
))))
2416 (when (and auto-save-default
(not noauto
))
2417 (auto-save-mode 1)))
2418 ;; Make people do a little extra work (C-x C-q)
2419 ;; before altering a backup file.
2420 (when (backup-file-name-p buffer-file-name
)
2421 (setq buffer-read-only t
))
2422 ;; When a file is marked read-only,
2423 ;; make the buffer read-only even if root is looking at it.
2424 (when (and (file-modes (buffer-file-name))
2425 (zerop (logand (file-modes (buffer-file-name)) #o222
)))
2426 (setq buffer-read-only t
))
2428 (when (and view-read-only view-mode
)
2431 ;; If requested, add a newline at the end of the file.
2432 (and (memq require-final-newline
'(visit visit-save
))
2433 (> (point-max) (point-min))
2434 (/= (char-after (1- (point-max))) ?
\n)
2435 (not (and (eq selective-display t
)
2436 (= (char-after (1- (point-max))) ?
\r)))
2437 (not buffer-read-only
)
2439 (goto-char (point-max))
2440 (ignore-errors (insert "\n"))))
2441 (when (and buffer-read-only
2443 (not (eq (get major-mode
'mode-class
) 'special
)))
2445 (run-hooks 'find-file-hook
)))
2447 (define-obsolete-function-alias 'report-errors
'with-demoted-errors
"25.1")
2449 (defun normal-mode (&optional find-file
)
2450 "Choose the major mode for this buffer automatically.
2451 Also sets up any specified local variables of the file.
2452 Uses the visited file name, the -*- line, and the local variables spec.
2454 This function is called automatically from `find-file'. In that case,
2455 we may set up the file-specified mode and local variables,
2456 depending on the value of `enable-local-variables'.
2457 In addition, if `local-enable-local-variables' is nil, we do
2458 not set local variables (though we do notice a mode specified with -*-.)
2460 `enable-local-variables' is ignored if you run `normal-mode' interactively,
2461 or from Lisp without specifying the optional argument FIND-FILE;
2462 in that case, this function acts as if `enable-local-variables' were t."
2464 (kill-all-local-variables)
2465 (unless delay-mode-hooks
2466 (run-hooks 'change-major-mode-after-body-hook
2467 'after-change-major-mode-hook
))
2468 (let ((enable-local-variables (or (not find-file
) enable-local-variables
)))
2469 ;; FIXME this is less efficient than it could be, since both
2470 ;; s-a-m and h-l-v may parse the same regions, looking for "mode:".
2471 (with-demoted-errors "File mode specification error: %s"
2473 ;; `delay-mode-hooks' being non-nil will have prevented the major
2474 ;; mode's call to `run-mode-hooks' from calling
2475 ;; `hack-local-variables'. In that case, call it now.
2476 (when delay-mode-hooks
2477 (with-demoted-errors "File local-variables error: %s"
2478 (hack-local-variables 'no-mode
))))
2479 ;; Turn font lock off and on, to make sure it takes account of
2480 ;; whatever file local variables are relevant to it.
2481 (when (and font-lock-mode
2482 ;; Font-lock-mode (now in font-core.el) can be ON when
2483 ;; font-lock.el still hasn't been loaded.
2484 (boundp 'font-lock-keywords
)
2485 (eq (car font-lock-keywords
) t
))
2486 (setq font-lock-keywords
(cadr font-lock-keywords
))
2487 (font-lock-mode 1)))
2489 (defcustom auto-mode-case-fold t
2490 "Non-nil means to try second pass through `auto-mode-alist'.
2491 This means that if the first case-sensitive search through the alist fails
2492 to find a matching major mode, a second case-insensitive search is made.
2493 On systems with case-insensitive file names, this variable is ignored,
2494 since only a single case-insensitive search through the alist is made."
2499 (defvar auto-mode-alist
2500 ;; Note: The entries for the modes defined in cc-mode.el (c-mode,
2501 ;; c++-mode, java-mode and more) are added through autoload
2502 ;; directives in that file. That way is discouraged since it
2503 ;; spreads out the definition of the initial value.
2506 (cons (purecopy (car elt
)) (cdr elt
)))
2507 `(;; do this first, so that .html.pl is Polish html, not Perl
2508 ("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . mhtml-mode
)
2509 ("\\.svgz?\\'" . image-mode
)
2510 ("\\.svgz?\\'" . xml-mode
)
2511 ("\\.x[bp]m\\'" . image-mode
)
2512 ("\\.x[bp]m\\'" . c-mode
)
2513 ("\\.p[bpgn]m\\'" . image-mode
)
2514 ("\\.tiff?\\'" . image-mode
)
2515 ("\\.gif\\'" . image-mode
)
2516 ("\\.png\\'" . image-mode
)
2517 ("\\.jpe?g\\'" . image-mode
)
2518 ("\\.te?xt\\'" . text-mode
)
2519 ("\\.[tT]e[xX]\\'" . tex-mode
)
2520 ("\\.ins\\'" . tex-mode
) ;Installation files for TeX packages.
2521 ("\\.ltx\\'" . latex-mode
)
2522 ("\\.dtx\\'" . doctex-mode
)
2523 ("\\.org\\'" . org-mode
)
2524 ("\\.el\\'" . emacs-lisp-mode
)
2525 ("Project\\.ede\\'" . emacs-lisp-mode
)
2526 ("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . scheme-mode
)
2527 ("\\.l\\'" . lisp-mode
)
2528 ("\\.li?sp\\'" . lisp-mode
)
2529 ("\\.[fF]\\'" . fortran-mode
)
2530 ("\\.for\\'" . fortran-mode
)
2531 ("\\.p\\'" . pascal-mode
)
2532 ("\\.pas\\'" . pascal-mode
)
2533 ("\\.\\(dpr\\|DPR\\)\\'" . delphi-mode
)
2534 ("\\.ad[abs]\\'" . ada-mode
)
2535 ("\\.ad[bs].dg\\'" . ada-mode
)
2536 ("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . perl-mode
)
2537 ("Imakefile\\'" . makefile-imake-mode
)
2538 ("Makeppfile\\(?:\\.mk\\)?\\'" . makefile-makepp-mode
) ; Put this before .mk
2539 ("\\.makepp\\'" . makefile-makepp-mode
)
2540 ,@(if (memq system-type
'(berkeley-unix darwin
))
2541 '(("\\.mk\\'" . makefile-bsdmake-mode
)
2542 ("\\.make\\'" . makefile-bsdmake-mode
)
2543 ("GNUmakefile\\'" . makefile-gmake-mode
)
2544 ("[Mm]akefile\\'" . makefile-bsdmake-mode
))
2545 '(("\\.mk\\'" . makefile-gmake-mode
) ; Might be any make, give Gnu the host advantage
2546 ("\\.make\\'" . makefile-gmake-mode
)
2547 ("[Mm]akefile\\'" . makefile-gmake-mode
)))
2548 ("\\.am\\'" . makefile-automake-mode
)
2549 ;; Less common extensions come here
2550 ;; so more common ones above are found faster.
2551 ("\\.texinfo\\'" . texinfo-mode
)
2552 ("\\.te?xi\\'" . texinfo-mode
)
2553 ("\\.[sS]\\'" . asm-mode
)
2554 ("\\.asm\\'" . asm-mode
)
2555 ("\\.css\\'" . css-mode
)
2556 ("\\.mixal\\'" . mixal-mode
)
2557 ("\\.gcov\\'" . compilation-mode
)
2558 ;; Besides .gdbinit, gdb documents other names to be usable for init
2559 ;; files, cross-debuggers can use something like
2560 ;; .PROCESSORNAME-gdbinit so that the host and target gdbinit files
2561 ;; don't interfere with each other.
2562 ("/\\.[a-z0-9-]*gdbinit" . gdb-script-mode
)
2563 ;; GDB 7.5 introduced OBJFILE-gdb.gdb script files; e.g. a file
2564 ;; named 'emacs-gdb.gdb', if it exists, will be automatically
2565 ;; loaded when GDB reads an objfile called 'emacs'.
2566 ("-gdb\\.gdb" . gdb-script-mode
)
2567 ("[cC]hange\\.?[lL]og?\\'" . change-log-mode
)
2568 ("[cC]hange[lL]og[-.][0-9]+\\'" . change-log-mode
)
2569 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
2570 ("\\.scm\\.[0-9]*\\'" . scheme-mode
)
2571 ("\\.[ckz]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode
)
2572 ("\\.bash\\'" . sh-mode
)
2573 ("\\(/\\|\\`\\)\\.\\(bash_\\(profile\\|history\\|log\\(in\\|out\\)\\)\\|z?log\\(in\\|out\\)\\)\\'" . sh-mode
)
2574 ("\\(/\\|\\`\\)\\.\\(shrc\\|zshrc\\|m?kshrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode
)
2575 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode
)
2576 ("\\.m?spec\\'" . sh-mode
)
2577 ("\\.m[mes]\\'" . nroff-mode
)
2578 ("\\.man\\'" . nroff-mode
)
2579 ("\\.sty\\'" . latex-mode
)
2580 ("\\.cl[so]\\'" . latex-mode
) ;LaTeX 2e class option
2581 ("\\.bbl\\'" . latex-mode
)
2582 ("\\.bib\\'" . bibtex-mode
)
2583 ("\\.bst\\'" . bibtex-style-mode
)
2584 ("\\.sql\\'" . sql-mode
)
2585 ("\\.m[4c]\\'" . m4-mode
)
2586 ("\\.mf\\'" . metafont-mode
)
2587 ("\\.mp\\'" . metapost-mode
)
2588 ("\\.vhdl?\\'" . vhdl-mode
)
2589 ("\\.article\\'" . text-mode
)
2590 ("\\.letter\\'" . text-mode
)
2591 ("\\.i?tcl\\'" . tcl-mode
)
2592 ("\\.exp\\'" . tcl-mode
)
2593 ("\\.itk\\'" . tcl-mode
)
2594 ("\\.icn\\'" . icon-mode
)
2595 ("\\.sim\\'" . simula-mode
)
2596 ("\\.mss\\'" . scribe-mode
)
2597 ;; The Fortran standard does not say anything about file extensions.
2598 ;; .f90 was widely used for F90, now we seem to be trapped into
2599 ;; using a different extension for each language revision.
2600 ;; Anyway, the following extensions are supported by gfortran.
2601 ("\\.f9[05]\\'" . f90-mode
)
2602 ("\\.f0[38]\\'" . f90-mode
)
2603 ("\\.indent\\.pro\\'" . fundamental-mode
) ; to avoid idlwave-mode
2604 ("\\.\\(pro\\|PRO\\)\\'" . idlwave-mode
)
2605 ("\\.srt\\'" . srecode-template-mode
)
2606 ("\\.prolog\\'" . prolog-mode
)
2607 ("\\.tar\\'" . tar-mode
)
2608 ;; The list of archive file extensions should be in sync with
2609 ;; `auto-coding-alist' with `no-conversion' coding system.
2611 arc\\|zip\\|lzh\\|lha\\|zoo\\|[jew]ar\\|xpi\\|rar\\|cbr\\|7z\\|\
2612 ARC\\|ZIP\\|LZH\\|LHA\\|ZOO\\|[JEW]AR\\|XPI\\|RAR\\|CBR\\|7Z\\)\\'" . archive-mode
)
2613 ("\\.oxt\\'" . archive-mode
) ;(Open|Libre)Office extensions.
2614 ("\\.\\(deb\\|[oi]pk\\)\\'" . archive-mode
) ; Debian/Opkg packages.
2615 ;; Mailer puts message to be edited in
2616 ;; /tmp/Re.... or Message
2617 ("\\`/tmp/Re" . text-mode
)
2618 ("/Message[0-9]*\\'" . text-mode
)
2619 ;; some news reader is reported to use this
2620 ("\\`/tmp/fol/" . text-mode
)
2621 ("\\.oak\\'" . scheme-mode
)
2622 ("\\.sgml?\\'" . sgml-mode
)
2623 ("\\.x[ms]l\\'" . xml-mode
)
2624 ("\\.dbk\\'" . xml-mode
)
2625 ("\\.dtd\\'" . sgml-mode
)
2626 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode
)
2627 ("\\.jsm?\\'" . javascript-mode
)
2628 ("\\.json\\'" . javascript-mode
)
2629 ("\\.jsx\\'" . js-jsx-mode
)
2630 ("\\.[ds]?vh?\\'" . verilog-mode
)
2631 ("\\.by\\'" . bovine-grammar-mode
)
2632 ("\\.wy\\'" . wisent-grammar-mode
)
2633 ;; .emacs or .gnus or .viper following a directory delimiter in
2634 ;; Unix or MS-DOS syntax.
2635 ("[:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode
)
2636 ("\\`\\..*emacs\\'" . emacs-lisp-mode
)
2637 ;; _emacs following a directory delimiter in MS-DOS syntax
2638 ("[:/]_emacs\\'" . emacs-lisp-mode
)
2639 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode
)
2640 ("\\.ml\\'" . lisp-mode
)
2641 ;; Linux-2.6.9 uses some different suffix for linker scripts:
2642 ;; "ld", "lds", "lds.S", "lds.in", "ld.script", and "ld.script.balo".
2643 ;; eCos uses "ld" and "ldi". Netbsd uses "ldscript.*".
2644 ("\\.ld[si]?\\'" . ld-script-mode
)
2645 ("ld\\.?script\\'" . ld-script-mode
)
2646 ;; .xs is also used for ld scripts, but seems to be more commonly
2647 ;; associated with Perl .xs files (C with Perl bindings). (Bug#7071)
2648 ("\\.xs\\'" . c-mode
)
2649 ;; Explained in binutils ld/genscripts.sh. Eg:
2650 ;; A .x script file is the default script.
2651 ;; A .xr script is for linking without relocation (-r flag). Etc.
2652 ("\\.x[abdsru]?[cnw]?\\'" . ld-script-mode
)
2653 ("\\.zone\\'" . dns-mode
)
2654 ("\\.soa\\'" . dns-mode
)
2655 ;; Common Lisp ASDF package system.
2656 ("\\.asd\\'" . lisp-mode
)
2657 ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode
)
2658 ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode
)
2659 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode
)
2660 ("\\.\\(dif\\|pat\\)\\'" . diff-mode
) ; for MS-DOS
2661 ("\\.[eE]?[pP][sS]\\'" . ps-mode
)
2662 ("\\.\\(?:PDF\\|DVI\\|OD[FGPST]\\|DOCX?\\|XLSX?\\|PPTX?\\|pdf\\|djvu\\|dvi\\|od[fgpst]\\|docx?\\|xlsx?\\|pptx?\\)\\'" . doc-view-mode-maybe
)
2663 ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode
)
2664 ("\\.s\\(v\\|iv\\|ieve\\)\\'" . sieve-mode
)
2665 ("BROWSE\\'" . ebrowse-tree-mode
)
2666 ("\\.ebrowse\\'" . ebrowse-tree-mode
)
2667 ("#\\*mail\\*" . mail-mode
)
2668 ("\\.g\\'" . antlr-mode
)
2669 ("\\.mod\\'" . m2-mode
)
2670 ("\\.ses\\'" . ses-mode
)
2671 ("\\.docbook\\'" . sgml-mode
)
2672 ("\\.com\\'" . dcl-mode
)
2673 ("/config\\.\\(?:bat\\|log\\)\\'" . fundamental-mode
)
2674 ;; Windows candidates may be opened case sensitively on Unix
2675 ("\\.\\(?:[iI][nN][iI]\\|[lL][sS][tT]\\|[rR][eE][gG]\\|[sS][yY][sS]\\)\\'" . conf-mode
)
2676 ("\\.la\\'" . conf-unix-mode
)
2677 ("\\.ppd\\'" . conf-ppd-mode
)
2678 ("java.+\\.conf\\'" . conf-javaprop-mode
)
2679 ("\\.properties\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-javaprop-mode
)
2680 ("\\.toml\\'" . conf-toml-mode
)
2681 ("\\.desktop\\'" . conf-desktop-mode
)
2682 ("\\`/etc/\\(?:DIR_COLORS\\|ethers\\|.?fstab\\|.*hosts\\|lesskey\\|login\\.?de\\(?:fs\\|vperm\\)\\|magic\\|mtab\\|pam\\.d/.*\\|permissions\\(?:\\.d/.+\\)?\\|protocols\\|rpc\\|services\\)\\'" . conf-space-mode
)
2683 ("\\`/etc/\\(?:acpid?/.+\\|aliases\\(?:\\.d/.+\\)?\\|default/.+\\|group-?\\|hosts\\..+\\|inittab\\|ksysguarddrc\\|opera6rc\\|passwd-?\\|shadow-?\\|sysconfig/.+\\)\\'" . conf-mode
)
2684 ;; ChangeLog.old etc. Other change-log-mode entries are above;
2685 ;; this has lower priority to avoid matching changelog.sgml etc.
2686 ("[cC]hange[lL]og[-.][-0-9a-z]+\\'" . change-log-mode
)
2687 ;; either user's dot-files or under /etc or some such
2688 ("/\\.?\\(?:gitconfig\\|gnokiirc\\|hgrc\\|kde.*rc\\|mime\\.types\\|wgetrc\\)\\'" . conf-mode
)
2689 ;; alas not all ~/.*rc files are like this
2690 ("/\\.\\(?:enigma\\|gltron\\|gtk\\|hxplayer\\|net\\|neverball\\|qt/.+\\|realplayer\\|scummvm\\|sversion\\|sylpheed/.+\\|xmp\\)rc\\'" . conf-mode
)
2691 ("/\\.\\(?:gdbtkinit\\|grip\\|orbital/.+txt\\|rhosts\\|tuxracer/options\\)\\'" . conf-mode
)
2692 ("/\\.?X\\(?:default\\|resource\\|re\\)s\\>" . conf-xdefaults-mode
)
2693 ("/X11.+app-defaults/\\|\\.ad\\'" . conf-xdefaults-mode
)
2694 ("/X11.+locale/.+/Compose\\'" . conf-colon-mode
)
2695 ;; this contains everything twice, with space and with colon :-(
2696 ("/X11.+locale/compose\\.dir\\'" . conf-javaprop-mode
)
2697 ;; Get rid of any trailing .n.m and try again.
2698 ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
2699 ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
2700 ;; Using mode nil rather than `ignore' would let the search continue
2701 ;; through this list (with the shortened name) rather than start over.
2702 ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" nil t
)
2703 ("\\.\\(?:orig\\|in\\|[bB][aA][kK]\\)\\'" nil t
)
2704 ;; This should come after "in" stripping (e.g. config.h.in).
2705 ;; *.cf, *.cfg, *.conf, *.config[.local|.de_DE.UTF8|...], */config
2706 ("[/.]c\\(?:on\\)?f\\(?:i?g\\)?\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-mode-maybe
)
2707 ;; The following should come after the ChangeLog pattern
2708 ;; for the sake of ChangeLog.1, etc.
2709 ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
2710 ("\\.[1-9]\\'" . nroff-mode
)))
2711 "Alist of filename patterns vs corresponding major mode functions.
2712 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
2713 \(NON-NIL stands for anything that is not nil; the value does not matter.)
2714 Visiting a file whose name matches REGEXP specifies FUNCTION as the
2715 mode function to use. FUNCTION will be called, unless it is nil.
2717 If the element has the form (REGEXP FUNCTION NON-NIL), then after
2718 calling FUNCTION (if it's not nil), we delete the suffix that matched
2719 REGEXP and search the list again for another match.
2721 The extensions whose FUNCTION is `archive-mode' should also
2722 appear in `auto-coding-alist' with `no-conversion' coding system.
2724 See also `interpreter-mode-alist', which detects executable script modes
2725 based on the interpreters they specify to run,
2726 and `magic-mode-alist', which determines modes based on file contents.")
2727 (put 'auto-mode-alist
'risky-local-variable t
)
2729 (defun conf-mode-maybe ()
2730 "Select Conf mode or XML mode according to start of file."
2734 (goto-char (point-min))
2735 (looking-at "<\\?xml \\|<!-- \\|<!DOCTYPE ")))
2739 (defvar interpreter-mode-alist
2740 ;; Note: The entries for the modes defined in cc-mode.el (awk-mode
2741 ;; and pike-mode) are added through autoload directives in that
2742 ;; file. That way is discouraged since it spreads out the
2743 ;; definition of the initial value.
2746 (cons (purecopy (car l
)) (cdr l
)))
2747 '(("\\(mini\\)?perl5?" . perl-mode
)
2748 ("wishx?" . tcl-mode
)
2749 ("tcl\\(sh\\)?" . tcl-mode
)
2750 ("expect" . tcl-mode
)
2751 ("octave" . octave-mode
)
2752 ("scm" . scheme-mode
)
2753 ("[acjkwz]sh" . sh-mode
)
2754 ("r?bash2?" . sh-mode
)
2757 ("\\(dt\\|pd\\|w\\)ksh" . sh-mode
)
2759 ("i?tcsh" . sh-mode
)
2764 ("tail" . text-mode
)
2765 ("more" . text-mode
)
2766 ("less" . text-mode
)
2768 ("make" . makefile-gmake-mode
) ; Debian uses this
2769 ("guile" . scheme-mode
)
2770 ("clisp" . lisp-mode
)
2771 ("emacs" . emacs-lisp-mode
)))
2772 "Alist mapping interpreter names to major modes.
2773 This is used for files whose first lines match `auto-mode-interpreter-regexp'.
2774 Each element looks like (REGEXP . MODE).
2775 If REGEXP matches the entire name (minus any directory part) of
2776 the interpreter specified in the first line of a script, enable
2779 See also `auto-mode-alist'.")
2781 (define-obsolete-variable-alias 'inhibit-first-line-modes-regexps
2782 'inhibit-file-local-variables-regexps
"24.1")
2784 ;; TODO really this should be a list of modes (eg tar-mode), not regexps,
2785 ;; because we are duplicating info from auto-mode-alist.
2786 ;; TODO many elements of this list are also in auto-coding-alist.
2787 (defvar inhibit-local-variables-regexps
2788 (mapcar 'purecopy
'("\\.tar\\'" "\\.t[bg]z\\'"
2789 "\\.arc\\'" "\\.zip\\'" "\\.lzh\\'" "\\.lha\\'"
2790 "\\.zoo\\'" "\\.[jew]ar\\'" "\\.xpi\\'" "\\.rar\\'"
2792 "\\.sx[dmicw]\\'" "\\.odt\\'"
2793 "\\.diff\\'" "\\.patch\\'"
2794 "\\.tiff?\\'" "\\.gif\\'" "\\.png\\'" "\\.jpe?g\\'"))
2795 "List of regexps matching file names in which to ignore local variables.
2796 This includes `-*-' lines as well as trailing \"Local Variables\" sections.
2797 Files matching this list are typically binary file formats.
2798 They may happen to contain sequences that look like local variable
2799 specifications, but are not really, or they may be containers for
2800 member files with their own local variable sections, which are
2801 not appropriate for the containing file.
2802 The function `inhibit-local-variables-p' uses this.")
2804 (define-obsolete-variable-alias 'inhibit-first-line-modes-suffixes
2805 'inhibit-local-variables-suffixes
"24.1")
2807 (defvar inhibit-local-variables-suffixes nil
2808 "List of regexps matching suffixes to remove from file names.
2809 The function `inhibit-local-variables-p' uses this: when checking
2810 a file name, it first discards from the end of the name anything that
2811 matches one of these regexps.")
2813 ;; Can't think of any situation in which you'd want this to be nil...
2814 (defvar inhibit-local-variables-ignore-case t
2815 "Non-nil means `inhibit-local-variables-p' ignores case.")
2817 (defun inhibit-local-variables-p ()
2818 "Return non-nil if file local variables should be ignored.
2819 This checks the file (or buffer) name against `inhibit-local-variables-regexps'
2820 and `inhibit-local-variables-suffixes'. If
2821 `inhibit-local-variables-ignore-case' is non-nil, this ignores case."
2822 (let ((temp inhibit-local-variables-regexps
)
2823 (name (if buffer-file-name
2824 (file-name-sans-versions buffer-file-name
)
2826 (case-fold-search inhibit-local-variables-ignore-case
))
2827 (while (let ((sufs inhibit-local-variables-suffixes
))
2828 (while (and sufs
(not (string-match (car sufs
) name
)))
2829 (setq sufs
(cdr sufs
)))
2831 (setq name
(substring name
0 (match-beginning 0))))
2833 (not (string-match (car temp
) name
)))
2834 (setq temp
(cdr temp
)))
2837 (defvar auto-mode-interpreter-regexp
2838 (purecopy "#![ \t]?\\([^ \t\n]*\
2839 /bin/env[ \t]\\)?\\([^ \t\n]+\\)")
2840 "Regexp matching interpreters, for file mode determination.
2841 This regular expression is matched against the first line of a file
2842 to determine the file's mode in `set-auto-mode'. If it matches, the file
2843 is assumed to be interpreted by the interpreter matched by the second group
2844 of the regular expression. The mode is then determined as the mode
2845 associated with that interpreter in `interpreter-mode-alist'.")
2847 (defvar magic-mode-alist nil
2848 "Alist of buffer beginnings vs. corresponding major mode functions.
2849 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2850 After visiting a file, if REGEXP matches the text at the beginning of the
2851 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2852 call FUNCTION rather than allowing `auto-mode-alist' to decide the buffer's
2855 If FUNCTION is nil, then it is not called. (That is a way of saying
2856 \"allow `auto-mode-alist' to decide for these files.\")")
2857 (put 'magic-mode-alist
'risky-local-variable t
)
2859 (defvar magic-fallback-mode-alist
2861 `((image-type-auto-detected-p . image-mode
)
2862 ("\\(PK00\\)?[P]K\003\004" . archive-mode
) ; zip
2863 ;; The < comes before the groups (but the first) to reduce backtracking.
2864 ;; TODO: UTF-16 <?xml may be preceded by a BOM 0xff 0xfe or 0xfe 0xff.
2865 ;; We use [ \t\r\n] instead of `\\s ' to make regex overflow less likely.
2866 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2867 (comment-re (concat "\\(?:!--" incomment-re
"*-->[ \t\r\n]*<\\)")))
2868 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
2870 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re
"*\\)?"
2871 "[Hh][Tt][Mm][Ll]"))
2873 ("<!DOCTYPE[ \t\r\n]+[Hh][Tt][Mm][Ll]" . mhtml-mode
)
2874 ;; These two must come after html, because they are more general:
2875 ("<\\?xml " . xml-mode
)
2876 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2877 (comment-re (concat "\\(?:!--" incomment-re
"*-->[ \t\r\n]*<\\)")))
2878 (concat "[ \t\r\n]*<" comment-re
"*!DOCTYPE "))
2881 ("# xmcd " . conf-unix-mode
)))
2882 "Like `magic-mode-alist' but has lower priority than `auto-mode-alist'.
2883 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2884 After visiting a file, if REGEXP matches the text at the beginning of the
2885 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2886 call FUNCTION, provided that `magic-mode-alist' and `auto-mode-alist'
2887 have not specified a mode for this file.
2889 If FUNCTION is nil, then it is not called.")
2890 (put 'magic-fallback-mode-alist
'risky-local-variable t
)
2892 (defvar magic-mode-regexp-match-limit
4000
2893 "Upper limit on `magic-mode-alist' regexp matches.
2894 Also applies to `magic-fallback-mode-alist'.")
2896 (defun set-auto-mode (&optional keep-mode-if-same
)
2897 "Select major mode appropriate for current buffer.
2899 To find the right major mode, this function checks for a -*- mode tag
2900 checks for a `mode:' entry in the Local Variables section of the file,
2901 checks if it uses an interpreter listed in `interpreter-mode-alist',
2902 matches the buffer beginning against `magic-mode-alist',
2903 compares the filename against the entries in `auto-mode-alist',
2904 then matches the buffer beginning against `magic-fallback-mode-alist'.
2906 If `enable-local-variables' is nil, or if the file name matches
2907 `inhibit-local-variables-regexps', this function does not check
2908 for any mode: tag anywhere in the file. If `local-enable-local-variables'
2909 is nil, then the only mode: tag that can be relevant is a -*- one.
2911 If the optional argument KEEP-MODE-IF-SAME is non-nil, then we
2912 set the major mode only if that would change it. In other words
2913 we don't actually set it to the same mode the buffer already has."
2914 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
2915 (let ((try-locals (not (inhibit-local-variables-p)))
2916 end done mode modes
)
2917 ;; Once we drop the deprecated feature where mode: is also allowed to
2918 ;; specify minor-modes (ie, there can be more than one "mode:"), we can
2919 ;; remove this section and just let (hack-local-variables t) handle it.
2920 ;; Find a -*- mode tag.
2922 (goto-char (point-min))
2923 (skip-chars-forward " \t\n")
2924 ;; Note by design local-enable-local-variables does not matter here.
2925 (and enable-local-variables
2927 (setq end
(set-auto-mode-1))
2928 (if (save-excursion (search-forward ":" end t
))
2929 ;; Find all specifications for the `mode:' variable
2930 ;; and execute them left to right.
2931 (while (let ((case-fold-search t
))
2932 (or (and (looking-at "mode:")
2933 (goto-char (match-end 0)))
2934 (re-search-forward "[ \t;]mode:" end t
)))
2935 (skip-chars-forward " \t")
2936 (let ((beg (point)))
2937 (if (search-forward ";" end t
)
2940 (skip-chars-backward " \t")
2941 (push (intern (concat (downcase (buffer-substring beg
(point))) "-mode"))
2943 ;; Simple -*-MODE-*- case.
2944 (push (intern (concat (downcase (buffer-substring (point) end
))
2947 ;; If we found modes to use, invoke them now, outside the save-excursion.
2950 (dolist (mode (nreverse modes
))
2951 (if (not (functionp mode
))
2952 (message "Ignoring unknown mode `%s'" mode
)
2954 (or (set-auto-mode-0 mode keep-mode-if-same
)
2955 ;; continuing would call minor modes again, toggling them off
2956 (throw 'nop nil
))))))
2957 ;; hack-local-variables checks local-enable-local-variables etc, but
2958 ;; we might as well be explicit here for the sake of clarity.
2960 enable-local-variables
2961 local-enable-local-variables
2963 (setq mode
(hack-local-variables t
))
2964 (not (memq mode modes
)) ; already tried and failed
2965 (if (not (functionp mode
))
2966 (message "Ignoring unknown mode `%s'" mode
)
2968 (set-auto-mode-0 mode keep-mode-if-same
)))
2969 ;; If we didn't, look for an interpreter specified in the first line.
2970 ;; As a special case, allow for things like "#!/bin/env perl", which
2971 ;; finds the interpreter anywhere in $PATH.
2973 (setq mode
(save-excursion
2974 (goto-char (point-min))
2975 (if (looking-at auto-mode-interpreter-regexp
)
2977 ;; Map interpreter name to a mode, signaling we're done at the
2979 (setq done
(assoc-default
2980 (file-name-nondirectory mode
)
2983 (format "\\`%s\\'" (car e
))
2985 interpreter-mode-alist
)
2987 ;; If we found an interpreter mode to use, invoke it now.
2988 (set-auto-mode-0 done keep-mode-if-same
))
2989 ;; Next try matching the buffer beginning against magic-mode-alist.
2991 (if (setq done
(save-excursion
2992 (goto-char (point-min))
2994 (narrow-to-region (point-min)
2996 (+ (point-min) magic-mode-regexp-match-limit
)))
2998 nil magic-mode-alist
3007 "Problem in magic-mode-alist with element %s"
3009 (set-auto-mode-0 done keep-mode-if-same
)))
3010 ;; Next compare the filename against the entries in auto-mode-alist.
3012 (if buffer-file-name
3013 (let ((name buffer-file-name
)
3014 (remote-id (file-remote-p buffer-file-name
))
3015 (case-insensitive-p (file-name-case-insensitive-p
3017 ;; Remove backup-suffixes from file name.
3018 (setq name
(file-name-sans-versions name
))
3019 ;; Remove remote file name identification.
3020 (when (and (stringp remote-id
)
3021 (string-match (regexp-quote remote-id
) name
))
3022 (setq name
(substring name
(match-end 0))))
3024 ;; Find first matching alist entry.
3026 (if case-insensitive-p
3027 ;; Filesystem is case-insensitive.
3028 (let ((case-fold-search t
))
3029 (assoc-default name auto-mode-alist
3031 ;; Filesystem is case-sensitive.
3033 ;; First match case-sensitively.
3034 (let ((case-fold-search nil
))
3035 (assoc-default name auto-mode-alist
3037 ;; Fallback to case-insensitive match.
3038 (and auto-mode-case-fold
3039 (let ((case-fold-search t
))
3040 (assoc-default name auto-mode-alist
3045 (setq mode
(car mode
)
3046 name
(substring name
0 (match-beginning 0)))
3049 (set-auto-mode-0 mode keep-mode-if-same
)
3051 ;; Next try matching the buffer beginning against magic-fallback-mode-alist.
3053 (if (setq done
(save-excursion
3054 (goto-char (point-min))
3056 (narrow-to-region (point-min)
3058 (+ (point-min) magic-mode-regexp-match-limit
)))
3059 (assoc-default nil magic-fallback-mode-alist
3068 "Problem with magic-fallback-mode-alist element: %s"
3070 (set-auto-mode-0 done keep-mode-if-same
)))
3072 (set-buffer-major-mode (current-buffer)))))
3074 ;; When `keep-mode-if-same' is set, we are working on behalf of
3075 ;; set-visited-file-name. In that case, if the major mode specified is the
3076 ;; same one we already have, don't actually reset it. We don't want to lose
3077 ;; minor modes such as Font Lock.
3078 (defun set-auto-mode-0 (mode &optional keep-mode-if-same
)
3079 "Apply MODE and return it.
3080 If optional arg KEEP-MODE-IF-SAME is non-nil, MODE is chased of
3081 any aliases and compared to current major mode. If they are the
3082 same, do nothing and return nil."
3083 (unless (and keep-mode-if-same
3084 (eq (indirect-function mode
)
3085 (indirect-function major-mode
)))
3090 (defvar file-auto-mode-skip
"^\\(#!\\|'\\\\\"\\)"
3091 "Regexp of lines to skip when looking for file-local settings.
3092 If the first line matches this regular expression, then the -*-...-*- file-
3093 local settings will be consulted on the second line instead of the first.")
3095 (defun set-auto-mode-1 ()
3096 "Find the -*- spec in the buffer.
3097 Call with point at the place to start searching from.
3098 If one is found, set point to the beginning and return the position
3099 of the end. Otherwise, return nil; may change point.
3100 The variable `inhibit-local-variables-regexps' can cause a -*- spec to
3101 be ignored; but `enable-local-variables' and `local-enable-local-variables'
3105 ;; Don't look for -*- if this file name matches any
3106 ;; of the regexps in inhibit-local-variables-regexps.
3107 (not (inhibit-local-variables-p))
3108 (search-forward "-*-" (line-end-position
3109 ;; If the file begins with "#!" (exec
3110 ;; interpreter magic), look for mode frobs
3111 ;; in the first two lines. You cannot
3112 ;; necessarily put them in the first line
3113 ;; of such a file without screwing up the
3114 ;; interpreter invocation. The same holds
3115 ;; for '\" in man pages (preprocessor
3116 ;; magic for the `man' program).
3117 (and (looking-at file-auto-mode-skip
) 2)) t
)
3119 (skip-chars-forward " \t")
3121 (search-forward "-*-" (line-end-position) t
))
3124 (skip-chars-backward " \t")
3129 ;;; Handling file local variables
3131 (defvar ignored-local-variables
3132 '(ignored-local-variables safe-local-variable-values
3133 file-local-variables-alist dir-local-variables-alist
)
3134 "Variables to be ignored in a file's local variable spec.")
3135 (put 'ignored-local-variables
'risky-local-variable t
)
3137 (defvar hack-local-variables-hook nil
3138 "Normal hook run after processing a file's local variables specs.
3139 Major modes can use this to examine user-specified local variables
3140 in order to initialize other data structure based on them.")
3142 (defcustom safe-local-variable-values nil
3143 "List variable-value pairs that are considered safe.
3144 Each element is a cons cell (VAR . VAL), where VAR is a variable
3145 symbol and VAL is a value that is considered safe."
3150 (defcustom safe-local-eval-forms
3151 ;; This should be here at least as long as Emacs supports write-file-hooks.
3152 '((add-hook 'write-file-hooks
'time-stamp
)
3153 (add-hook 'write-file-functions
'time-stamp
)
3154 (add-hook 'before-save-hook
'time-stamp nil t
)
3155 (add-hook 'before-save-hook
'delete-trailing-whitespace nil t
))
3156 "Expressions that are considered safe in an `eval:' local variable.
3157 Add expressions to this list if you want Emacs to evaluate them, when
3158 they appear in an `eval' local variable specification, without first
3159 asking you for confirmation."
3162 :version
"24.1" ; added write-file-hooks
3163 :type
'(repeat sexp
))
3165 ;; Risky local variables:
3166 (mapc (lambda (var) (put var
'risky-local-variable t
))
3168 buffer-auto-save-file-name
3170 buffer-file-truename
3173 default-text-properties
3177 file-name-handler-alist
3186 minor-mode-map-alist
3187 minor-mode-overriding-map-alist
3190 overriding-local-map
3191 overriding-terminal-local-map
3195 unread-command-events
))
3197 ;; Safe local variables:
3199 ;; For variables defined by major modes, the safety declarations can go into
3200 ;; the major mode's file, since that will be loaded before file variables are
3203 ;; For variables defined by minor modes, put the safety declarations in the
3204 ;; file defining the minor mode after the defcustom/defvar using an autoload
3207 ;; ;;;###autoload(put 'variable 'safe-local-variable 'stringp)
3209 ;; Otherwise, when Emacs visits a file specifying that local variable, the
3210 ;; minor mode file may not be loaded yet.
3212 ;; For variables defined in the C source code the declaration should go here:
3215 '((buffer-read-only . booleanp
) ;; C source code
3216 (default-directory . stringp
) ;; C source code
3217 (fill-column . integerp
) ;; C source code
3218 (indent-tabs-mode . booleanp
) ;; C source code
3219 (left-margin . integerp
) ;; C source code
3220 (no-update-autoloads . booleanp
)
3221 (lexical-binding . booleanp
) ;; C source code
3222 (tab-width . integerp
) ;; C source code
3223 (truncate-lines . booleanp
) ;; C source code
3224 (word-wrap . booleanp
) ;; C source code
3225 (bidi-display-reordering . booleanp
))) ;; C source code
3226 (put (car pair
) 'safe-local-variable
(cdr pair
)))
3228 (put 'bidi-paragraph-direction
'safe-local-variable
3229 (lambda (v) (memq v
'(nil right-to-left left-to-right
))))
3231 (put 'c-set-style
'safe-local-eval-function t
)
3233 (defvar file-local-variables-alist nil
3234 "Alist of file-local variable settings in the current buffer.
3235 Each element in this list has the form (VAR . VALUE), where VAR
3236 is a file-local variable (a symbol) and VALUE is the value
3237 specified. The actual value in the buffer may differ from VALUE,
3238 if it is changed by the major or minor modes, or by the user.")
3239 (make-variable-buffer-local 'file-local-variables-alist
)
3240 (put 'file-local-variables-alist
'permanent-local t
)
3242 (defvar dir-local-variables-alist nil
3243 "Alist of directory-local variable settings in the current buffer.
3244 Each element in this list has the form (VAR . VALUE), where VAR
3245 is a directory-local variable (a symbol) and VALUE is the value
3246 specified in .dir-locals.el. The actual value in the buffer
3247 may differ from VALUE, if it is changed by the major or minor modes,
3249 (make-variable-buffer-local 'dir-local-variables-alist
)
3251 (defvar before-hack-local-variables-hook nil
3252 "Normal hook run before setting file-local variables.
3253 It is called after checking for unsafe/risky variables and
3254 setting `file-local-variables-alist', and before applying the
3255 variables stored in `file-local-variables-alist'. A hook
3256 function is allowed to change the contents of this alist.
3258 This hook is called only if there is at least one file-local
3261 (defun hack-local-variables-confirm (all-vars unsafe-vars risky-vars dir-name
)
3262 "Get confirmation before setting up local variable values.
3263 ALL-VARS is the list of all variables to be set up.
3264 UNSAFE-VARS is the list of those that aren't marked as safe or risky.
3265 RISKY-VARS is the list of those that are marked as risky.
3266 If these settings come from directory-local variables, then
3267 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3268 (unless noninteractive
3269 (let ((name (cond (dir-name)
3271 (file-name-nondirectory buffer-file-name
))
3272 ((concat "buffer " (buffer-name)))))
3273 (offer-save (and (eq enable-local-variables t
)
3275 (buf (get-buffer-create "*Local Variables*")))
3276 ;; Set up the contents of the *Local Variables* buffer.
3277 (with-current-buffer buf
3281 (insert "The local variables list in " name
3282 "\ncontains values that may not be safe (*)"
3284 ", and variables that are risky (**)."
3287 (insert "The local variables list in " name
3288 "\ncontains variables that are risky (**)."))
3290 (insert "A local variables list is specified in " name
".")))
3291 (insert "\n\nDo you want to apply it? You can type
3292 y -- to apply the local variables list.
3293 n -- to ignore the local variables list.")
3296 ! -- to apply the local variables list, and permanently mark these
3297 values (*) as safe (in the future, they will be set automatically.)\n\n")
3299 (dolist (elt all-vars
)
3300 (cond ((member elt unsafe-vars
)
3302 ((member elt risky-vars
)
3306 (princ (car elt
) buf
)
3308 ;; Make strings with embedded whitespace easier to read.
3309 (let ((print-escape-newlines t
))
3310 (prin1 (cdr elt
) buf
))
3312 (set (make-local-variable 'cursor-type
) nil
)
3313 (set-buffer-modified-p nil
)
3314 (goto-char (point-min)))
3316 ;; Display the buffer and read a choice.
3317 (save-window-excursion
3318 (pop-to-buffer buf
'(display-buffer--maybe-at-bottom))
3319 (let* ((exit-chars '(?y ?n ?\s ?\C-g ?\C-v
))
3320 (prompt (format "Please type %s%s: "
3321 (if offer-save
"y, n, or !" "y or n")
3322 (if (< (line-number-at-pos (point-max))
3323 (window-body-height))
3325 (push ?\C-v exit-chars
)
3326 ", or C-v to scroll")))
3328 (if offer-save
(push ?
! exit-chars
))
3330 (setq char
(read-char-choice prompt exit-chars t
))
3331 (when (eq char ?\C-v
)
3334 (error (goto-char (point-min))
3337 (when (and offer-save
(= char ?
!) unsafe-vars
)
3338 (customize-push-and-save 'safe-local-variable-values unsafe-vars
))
3339 (prog1 (memq char
'(?
! ?\s ?y
))
3340 (quit-window t
)))))))
3342 (defconst hack-local-variable-regexp
3343 "[ \t]*\\([^][;\"'?()\\ \t\n]+\\)[ \t]*:[ \t]*")
3345 (defun hack-local-variables-prop-line (&optional handle-mode
)
3346 "Return local variables specified in the -*- line.
3347 Usually returns an alist of elements (VAR . VAL), where VAR is a
3348 variable and VAL is the specified value. Ignores any
3349 specification for `coding:', and sometimes for `mode' (which
3350 should have already been handled by `set-auto-coding' and
3351 `set-auto-mode', respectively). Return nil if the -*- line is
3354 If HANDLE-MODE is nil, we return the alist of all the local
3355 variables in the line except `coding' as described above. If it
3356 is neither nil nor t, we do the same, except that any settings of
3357 `mode' and `coding' are ignored. If HANDLE-MODE is t, we ignore
3358 all settings in the line except for `mode', which \(if present) we
3359 return as the symbol specifying the mode."
3360 (catch 'malformed-line
3362 (goto-char (point-min))
3363 (let ((end (set-auto-mode-1))
3367 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
3368 ;; Simple form: "-*- MODENAME -*-".
3369 (if (eq handle-mode t
)
3370 (intern (concat (match-string 1) "-mode"))))
3372 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
3373 ;; (last ";" is optional).
3374 ;; If HANDLE-MODE is t, just check for `mode'.
3375 ;; Otherwise, parse the -*- line into the RESULT alist.
3376 (while (not (or (and (eq handle-mode t
) result
)
3378 (unless (looking-at hack-local-variable-regexp
)
3379 (message "Malformed mode-line: %S"
3380 (buffer-substring-no-properties (point) end
))
3381 (throw 'malformed-line nil
))
3382 (goto-char (match-end 0))
3383 ;; There used to be a downcase here,
3384 ;; but the manual didn't say so,
3385 ;; and people want to set var names that aren't all lc.
3386 (let* ((key (intern (match-string 1)))
3387 (val (save-restriction
3388 (narrow-to-region (point) end
)
3389 (let ((read-circle nil
))
3390 (read (current-buffer)))))
3391 ;; It is traditional to ignore
3392 ;; case when checking for `mode' in set-auto-mode,
3393 ;; so we must do that here as well.
3394 ;; That is inconsistent, but we're stuck with it.
3395 ;; The same can be said for `coding' in set-auto-coding.
3396 (keyname (downcase (symbol-name key
))))
3399 (and (equal keyname
"mode")
3401 (intern (concat (downcase (symbol-name val
))
3403 ((equal keyname
"coding"))
3405 (when (or (not handle-mode
)
3406 (not (equal keyname
"mode")))
3408 (push (cons (cond ((eq key
'eval
) 'eval
)
3409 ;; Downcase "Mode:".
3410 ((equal keyname
"mode") 'mode
)
3411 (t (indirect-variable key
)))
3415 (skip-chars-forward " \t;")))
3418 (defun hack-local-variables-filter (variables dir-name
)
3419 "Filter local variable settings, querying the user if necessary.
3420 VARIABLES is the alist of variable-value settings. This alist is
3421 filtered based on the values of `ignored-local-variables',
3422 `enable-local-eval', `enable-local-variables', and (if necessary)
3423 user interaction. The results are added to
3424 `file-local-variables-alist', without applying them.
3425 If these settings come from directory-local variables, then
3426 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3427 ;; Find those variables that we may want to save to
3428 ;; `safe-local-variable-values'.
3429 (let (all-vars risky-vars unsafe-vars
)
3430 (dolist (elt variables
)
3431 (let ((var (car elt
))
3433 (cond ((memq var ignored-local-variables
)
3434 ;; Ignore any variable in `ignored-local-variables'.
3436 ;; Obey `enable-local-eval'.
3438 (when enable-local-eval
3439 (let ((safe (or (hack-one-local-variable-eval-safep val
)
3440 ;; In case previously marked safe (bug#5636).
3441 (safe-local-variable-p var val
))))
3442 ;; If not safe and e-l-v = :safe, ignore totally.
3443 (when (or safe
(not (eq enable-local-variables
:safe
)))
3445 (or (eq enable-local-eval t
)
3447 (push elt unsafe-vars
))))))
3448 ;; Ignore duplicates (except `mode') in the present list.
3449 ((and (assq var all-vars
) (not (eq var
'mode
))) nil
)
3450 ;; Accept known-safe variables.
3451 ((or (memq var
'(mode unibyte coding
))
3452 (safe-local-variable-p var val
))
3453 (push elt all-vars
))
3454 ;; The variable is either risky or unsafe:
3455 ((not (eq enable-local-variables
:safe
))
3457 (if (risky-local-variable-p var val
)
3458 (push elt risky-vars
)
3459 (push elt unsafe-vars
))))))
3461 ;; Query, unless all vars are safe or user wants no querying.
3462 (or (and (eq enable-local-variables t
)
3465 (memq enable-local-variables
'(:all
:safe
))
3466 (hack-local-variables-confirm all-vars unsafe-vars
3467 risky-vars dir-name
))
3468 (dolist (elt all-vars
)
3469 (unless (memq (car elt
) '(eval mode
))
3471 (setq dir-local-variables-alist
3472 (assq-delete-all (car elt
) dir-local-variables-alist
)))
3473 (setq file-local-variables-alist
3474 (assq-delete-all (car elt
) file-local-variables-alist
)))
3475 (push elt file-local-variables-alist
)))))
3477 ;; TODO? Warn once per file rather than once per session?
3478 (defvar hack-local-variables--warned-lexical nil
)
3480 (defun hack-local-variables (&optional handle-mode
)
3481 "Parse and put into effect this buffer's local variables spec.
3482 Uses `hack-local-variables-apply' to apply the variables.
3484 If HANDLE-MODE is nil, we apply all the specified local
3485 variables. If HANDLE-MODE is neither nil nor t, we do the same,
3486 except that any settings of `mode' are ignored.
3488 If HANDLE-MODE is t, all we do is check whether a \"mode:\"
3489 is specified, and return the corresponding mode symbol, or nil.
3490 In this case, we try to ignore minor-modes, and only return a
3493 If `enable-local-variables' or `local-enable-local-variables' is nil,
3494 this function does nothing. If `inhibit-local-variables-regexps'
3495 applies to the file in question, the file is not scanned for
3496 local variables, but directory-local variables may still be applied."
3497 ;; We don't let inhibit-local-variables-p influence the value of
3498 ;; enable-local-variables, because then it would affect dir-local
3499 ;; variables. We don't want to search eg tar files for file local
3500 ;; variable sections, but there is no reason dir-locals cannot apply
3501 ;; to them. The real meaning of inhibit-local-variables-p is "do
3502 ;; not scan this file for local variables".
3503 (let ((enable-local-variables
3504 (and local-enable-local-variables enable-local-variables
))
3506 (unless (eq handle-mode t
)
3507 (setq file-local-variables-alist nil
)
3508 (with-demoted-errors "Directory-local variables error: %s"
3509 ;; Note this is a no-op if enable-local-variables is nil.
3510 (hack-dir-local-variables)))
3511 ;; This entire function is basically a no-op if enable-local-variables
3512 ;; is nil. All it does is set file-local-variables-alist to nil.
3513 (when enable-local-variables
3514 ;; This part used to ignore enable-local-variables when handle-mode
3515 ;; was t. That was inappropriate, eg consider the
3516 ;; (artificial) example of:
3517 ;; (setq local-enable-local-variables nil)
3518 ;; Open a file foo.txt that contains "mode: sh".
3519 ;; It correctly opens in text-mode.
3520 ;; M-x set-visited-file name foo.c, and it incorrectly stays in text-mode.
3521 (unless (or (inhibit-local-variables-p)
3522 ;; If HANDLE-MODE is t, and the prop line specifies a
3523 ;; mode, then we're done, and have no need to scan further.
3524 (and (setq result
(hack-local-variables-prop-line
3526 (eq handle-mode t
)))
3527 ;; Look for "Local variables:" line in last page.
3529 (goto-char (point-max))
3530 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min))
3532 (when (let ((case-fold-search t
))
3533 (search-forward "Local Variables:" nil t
))
3534 (skip-chars-forward " \t")
3535 ;; suffix is what comes after "local variables:" in its line.
3536 ;; prefix is what comes before "local variables:" in its line.
3539 (regexp-quote (buffer-substring (point)
3540 (line-end-position)))
3543 (concat "^" (regexp-quote
3544 (buffer-substring (line-beginning-position)
3545 (match-beginning 0))))))
3548 (let ((startpos (point))
3550 (thisbuf (current-buffer)))
3552 (unless (let ((case-fold-search t
))
3554 (concat prefix
"[ \t]*End:[ \t]*" suffix
)
3556 ;; This used to be an error, but really all it means is
3557 ;; that this may simply not be a local-variables section,
3558 ;; so just ignore it.
3559 (message "Local variables list is not properly terminated"))
3561 (setq endpos
(point)))
3564 (insert-buffer-substring thisbuf startpos endpos
)
3565 (goto-char (point-min))
3566 (subst-char-in-region (point) (point-max) ?\^m ?
\n)
3568 ;; Discard the prefix.
3569 (if (looking-at prefix
)
3570 (delete-region (point) (match-end 0))
3571 (error "Local variables entry is missing the prefix"))
3573 ;; Discard the suffix.
3574 (if (looking-back suffix
(line-beginning-position))
3575 (delete-region (match-beginning 0) (point))
3576 (error "Local variables entry is missing the suffix"))
3578 (goto-char (point-min))
3580 (while (not (or (eobp)
3581 (and (eq handle-mode t
) result
)))
3582 ;; Find the variable name;
3583 (unless (looking-at hack-local-variable-regexp
)
3584 (error "Malformed local variable line: %S"
3585 (buffer-substring-no-properties
3586 (point) (line-end-position))))
3587 (goto-char (match-end 1))
3588 (let* ((str (match-string 1))
3591 (and (equal (downcase (symbol-name var
)) "mode")
3593 ;; Read the variable value.
3594 (skip-chars-forward "^:")
3596 (let ((read-circle nil
))
3597 (setq val
(read (current-buffer))))
3598 (if (eq handle-mode t
)
3600 ;; Specifying minor-modes via mode: is
3601 ;; deprecated, but try to reject them anyway.
3604 (setq val2
(downcase (symbol-name val
)))))
3605 (setq result
(intern (concat val2
"-mode"))))
3606 (cond ((eq var
'coding
))
3607 ((eq var
'lexical-binding
)
3608 (unless hack-local-variables--warned-lexical
3609 (setq hack-local-variables--warned-lexical t
)
3613 "%s: `lexical-binding' at end of file unreliable"
3614 (file-name-nondirectory
3615 ;; We are called from
3616 ;; 'with-temp-buffer', so we need
3617 ;; to use 'thisbuf's name in the
3619 (or (buffer-file-name thisbuf
) ""))))))
3620 ((and (eq var
'mode
) handle-mode
))
3623 (push (cons (if (eq var
'eval
)
3625 (indirect-variable var
))
3627 (forward-line 1))))))))
3628 ;; Now we've read all the local variables.
3629 ;; If HANDLE-MODE is t, return whether the mode was specified.
3630 (if (eq handle-mode t
) result
3631 ;; Otherwise, set the variables.
3632 (hack-local-variables-filter result nil
)
3633 (hack-local-variables-apply)))))
3635 (defun hack-local-variables-apply ()
3636 "Apply the elements of `file-local-variables-alist'.
3637 If there are any elements, runs `before-hack-local-variables-hook',
3638 then calls `hack-one-local-variable' to apply the alist elements one by one.
3639 Finishes by running `hack-local-variables-hook', regardless of whether
3640 the alist is empty or not.
3642 Note that this function ignores a `mode' entry if it specifies the same
3643 major mode as the buffer already has."
3644 (when file-local-variables-alist
3645 ;; Any 'evals must run in the Right sequence.
3646 (setq file-local-variables-alist
3647 (nreverse file-local-variables-alist
))
3648 (run-hooks 'before-hack-local-variables-hook
)
3649 (dolist (elt file-local-variables-alist
)
3650 (hack-one-local-variable (car elt
) (cdr elt
))))
3651 (run-hooks 'hack-local-variables-hook
))
3653 (defun safe-local-variable-p (sym val
)
3654 "Non-nil if SYM is safe as a file-local variable with value VAL.
3655 It is safe if any of these conditions are met:
3657 * There is a matching entry (SYM . VAL) in the
3658 `safe-local-variable-values' user option.
3660 * The `safe-local-variable' property of SYM is a function that
3661 evaluates to a non-nil value with VAL as an argument."
3662 (or (member (cons sym val
) safe-local-variable-values
)
3663 (let ((safep (get sym
'safe-local-variable
)))
3664 (and (functionp safep
)
3665 ;; If the function signals an error, that means it
3666 ;; can't assure us that the value is safe.
3667 (with-demoted-errors (funcall safep val
))))))
3669 (defun risky-local-variable-p (sym &optional _ignored
)
3670 "Non-nil if SYM could be dangerous as a file-local variable.
3671 It is dangerous if either of these conditions are met:
3673 * Its `risky-local-variable' property is non-nil.
3675 * Its name ends with \"hook(s)\", \"function(s)\", \"form(s)\", \"map\",
3676 \"program\", \"command(s)\", \"predicate(s)\", \"frame-alist\",
3677 \"mode-alist\", \"font-lock-(syntactic-)keyword*\",
3678 \"map-alist\", or \"bindat-spec\"."
3679 ;; If this is an alias, check the base name.
3681 (setq sym
(indirect-variable sym
))
3683 (or (get sym
'risky-local-variable
)
3684 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|\
3685 -commands?$\\|-predicates?$\\|font-lock-keywords$\\|font-lock-keywords\
3686 -[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|\
3687 -map$\\|-map-alist$\\|-bindat-spec$" (symbol-name sym
))))
3689 (defun hack-one-local-variable-quotep (exp)
3690 (and (consp exp
) (eq (car exp
) 'quote
) (consp (cdr exp
))))
3692 (defun hack-one-local-variable-constantp (exp)
3693 (or (and (not (symbolp exp
)) (not (consp exp
)))
3696 (hack-one-local-variable-quotep exp
)))
3698 (defun hack-one-local-variable-eval-safep (exp)
3699 "Return t if it is safe to eval EXP when it is found in a file."
3700 (or (not (consp exp
))
3701 ;; Detect certain `put' expressions.
3702 (and (eq (car exp
) 'put
)
3703 (hack-one-local-variable-quotep (nth 1 exp
))
3704 (hack-one-local-variable-quotep (nth 2 exp
))
3705 (let ((prop (nth 1 (nth 2 exp
)))
3707 (cond ((memq prop
'(lisp-indent-hook
3708 lisp-indent-function
3709 scheme-indent-function
))
3710 ;; Only allow safe values (not functions).
3712 (and (hack-one-local-variable-quotep val
)
3713 (eq (nth 1 val
) 'defun
))))
3714 ((eq prop
'edebug-form-spec
)
3715 ;; Only allow indirect form specs.
3716 ;; During bootstrapping, edebug-basic-spec might not be
3718 (and (fboundp 'edebug-basic-spec
)
3719 (hack-one-local-variable-quotep val
)
3720 (edebug-basic-spec (nth 1 val
)))))))
3721 ;; Allow expressions that the user requested.
3722 (member exp safe-local-eval-forms
)
3723 ;; Certain functions can be allowed with safe arguments
3724 ;; or can specify verification functions to try.
3725 (and (symbolp (car exp
))
3726 ;; Allow (minor)-modes calls with no arguments.
3727 ;; This obsoletes the use of "mode:" for such things. (Bug#8613)
3728 (or (and (member (cdr exp
) '(nil (1) (0) (-1)))
3729 (string-match "-mode\\'" (symbol-name (car exp
))))
3730 (let ((prop (get (car exp
) 'safe-local-eval-function
)))
3733 (dolist (arg (cdr exp
))
3734 (unless (hack-one-local-variable-constantp arg
)
3741 (dolist (function prop
)
3742 (if (funcall function exp
)
3746 (defun hack-one-local-variable--obsolete (var)
3747 (let ((o (get var
'byte-obsolete-variable
)))
3749 (let ((instead (nth 0 o
))
3751 (message "%s is obsolete%s; %s"
3752 var
(if since
(format " (since %s)" since
))
3753 (if (stringp instead
)
3754 (substitute-command-keys instead
)
3755 (format-message "use `%s' instead" instead
)))))))
3757 (defun hack-one-local-variable (var val
)
3758 "Set local variable VAR with value VAL.
3759 If VAR is `mode', call `VAL-mode' as a function unless it's
3760 already the major mode."
3763 (let ((mode (intern (concat (downcase (symbol-name val
))
3765 (unless (eq (indirect-function mode
)
3766 (indirect-function major-mode
))
3770 (`(add-hook ',hook .
,_
) (hack-one-local-variable--obsolete hook
)))
3771 (save-excursion (eval val
)))
3773 (hack-one-local-variable--obsolete var
)
3774 ;; Make sure the string has no text properties.
3775 ;; Some text properties can get evaluated in various ways,
3776 ;; so it is risky to put them on with a local variable list.
3778 (set-text-properties 0 (length val
) nil val
))
3779 (set (make-local-variable var
) val
))))
3781 ;;; Handling directory-local variables, aka project settings.
3783 (defvar dir-locals-class-alist
'()
3784 "Alist mapping directory-local variable classes (symbols) to variable lists.")
3786 (defvar dir-locals-directory-cache
'()
3787 "List of cached directory roots for directory-local variable classes.
3788 Each element in this list has the form (DIR CLASS MTIME).
3789 DIR is the name of the directory.
3790 CLASS is the name of a variable class (a symbol).
3791 MTIME is the recorded modification time of the directory-local
3792 variables file associated with this entry. This time is a list
3793 of integers (the same format as `file-attributes'), and is
3794 used to test whether the cache entry is still valid.
3795 Alternatively, MTIME can be nil, which means the entry is always
3798 (defsubst dir-locals-get-class-variables
(class)
3799 "Return the variable list for CLASS."
3800 (cdr (assq class dir-locals-class-alist
)))
3802 (defun dir-locals-collect-mode-variables (mode-variables variables
)
3803 "Collect directory-local variables from MODE-VARIABLES.
3804 VARIABLES is the initial list of variables.
3805 Returns the new list."
3806 (dolist (pair mode-variables variables
)
3807 (let* ((variable (car pair
))
3809 (slot (assq variable variables
)))
3810 ;; If variables are specified more than once, only use the last. (Why?)
3811 ;; The pseudo-variables mode and eval are different (bug#3430).
3812 (if (and slot
(not (memq variable
'(mode eval
))))
3814 ;; Need a new cons in case we setcdr later.
3815 (push (cons variable value
) variables
)))))
3817 (defun dir-locals-collect-variables (class-variables root variables
)
3818 "Collect entries from CLASS-VARIABLES into VARIABLES.
3819 ROOT is the root directory of the project.
3820 Return the new variables list."
3821 (let* ((file-name (or (buffer-file-name)
3822 ;; Handle non-file buffers, too.
3823 (expand-file-name default-directory
)))
3824 (sub-file-name (if (and file-name
3825 (file-name-absolute-p file-name
))
3826 ;; FIXME: Why not use file-relative-name?
3827 (substring file-name
(length root
)))))
3829 (dolist (entry class-variables variables
)
3830 (let ((key (car entry
)))
3833 ;; Don't include this in the previous condition, because we
3834 ;; want to filter all strings before the next condition.
3835 (when (and sub-file-name
3836 (>= (length sub-file-name
) (length key
))
3837 (string-prefix-p key sub-file-name
))
3838 (setq variables
(dir-locals-collect-variables
3839 (cdr entry
) root variables
))))
3841 (derived-mode-p key
))
3842 (let* ((alist (cdr entry
))
3843 (subdirs (assq 'subdirs alist
)))
3844 (if (or (not subdirs
)
3846 (setq alist
(delq subdirs alist
))
3848 ;; TODO someone might want to extend this to allow
3849 ;; integer values for subdir, where N means
3850 ;; variables apply to this directory and N levels
3851 ;; below it (0 == nil).
3852 (equal root default-directory
))
3853 (setq variables
(dir-locals-collect-mode-variables
3854 alist variables
))))))))
3856 ;; The file's content might be invalid (e.g. have a merge conflict), but
3857 ;; that shouldn't prevent the user from opening the file.
3858 (message "%s error: %s" dir-locals-file
(error-message-string err
))
3861 (defun dir-locals-set-directory-class (directory class
&optional mtime
)
3862 "Declare that the DIRECTORY root is an instance of CLASS.
3863 DIRECTORY is the name of a directory, a string.
3864 CLASS is the name of a project class, a symbol.
3865 MTIME is either the modification time of the directory-local
3866 variables file that defined this class, or nil.
3868 When a file beneath DIRECTORY is visited, the mode-specific
3869 variables from CLASS are applied to the buffer. The variables
3870 for a class are defined using `dir-locals-set-class-variables'."
3871 (setq directory
(file-name-as-directory (expand-file-name directory
)))
3872 (unless (assq class dir-locals-class-alist
)
3873 (error "No such class `%s'" (symbol-name class
)))
3874 (push (list directory class mtime
) dir-locals-directory-cache
))
3876 (defun dir-locals-set-class-variables (class variables
)
3877 "Map the type CLASS to a list of variable settings.
3878 CLASS is the project class, a symbol. VARIABLES is a list
3879 that declares directory-local variables for the class.
3880 An element in VARIABLES is either of the form:
3881 (MAJOR-MODE . ALIST)
3885 In the first form, MAJOR-MODE is a symbol, and ALIST is an alist
3886 whose elements are of the form (VARIABLE . VALUE).
3888 In the second form, DIRECTORY is a directory name (a string), and
3889 LIST is a list of the form accepted by the function.
3891 When a file is visited, the file's class is found. A directory
3892 may be assigned a class using `dir-locals-set-directory-class'.
3893 Then variables are set in the file's buffer according to the
3894 VARIABLES list of the class. The list is processed in order.
3896 * If the element is of the form (MAJOR-MODE . ALIST), and the
3897 buffer's major mode is derived from MAJOR-MODE (as determined
3898 by `derived-mode-p'), then all the variables in ALIST are
3899 applied. A MAJOR-MODE of nil may be used to match any buffer.
3900 `make-local-variable' is called for each variable before it is
3903 * If the element is of the form (DIRECTORY . LIST), and DIRECTORY
3904 is an initial substring of the file's directory, then LIST is
3905 applied by recursively following these rules."
3906 (setf (alist-get class dir-locals-class-alist
) variables
))
3908 (defconst dir-locals-file
".dir-locals.el"
3909 "File that contains directory-local variables.
3910 It has to be constant to enforce uniform values across different
3911 environments and users.
3913 A second dir-locals file can be used by a user to specify their
3914 personal dir-local variables even if the current directory
3915 already has a `dir-locals-file' that is shared with other
3916 users (such as in a git repository). The name of this second
3917 file is derived by appending \"-2\" to the base name of
3918 `dir-locals-file'. With the default value of `dir-locals-file',
3919 a \".dir-locals-2.el\" file in the same directory will override
3920 the \".dir-locals.el\".
3922 See Info node `(elisp)Directory Local Variables' for details.")
3924 (defun dir-locals--all-files (directory)
3925 "Return a list of all readable dir-locals files in DIRECTORY.
3926 The returned list is sorted by increasing priority. That is,
3927 values specified in the last file should take precedence over
3928 those in the first."
3929 (when (file-readable-p directory
)
3930 (let* ((file-1 (expand-file-name (if (eq system-type
'ms-dos
)
3931 (dosified-file-name dir-locals-file
)
3934 (file-2 (when (string-match "\\.el\\'" file-1
)
3935 (replace-match "-2.el" t nil file-1
)))
3937 ;; The order here is important.
3938 (dolist (f (list file-2 file-1
))
3942 (not (file-directory-p f
)))
3946 (defun dir-locals-find-file (file)
3947 "Find the directory-local variables for FILE.
3948 This searches upward in the directory tree from FILE.
3949 It stops at the first directory that has been registered in
3950 `dir-locals-directory-cache' or contains a `dir-locals-file'.
3951 If it finds an entry in the cache, it checks that it is valid.
3952 A cache entry with no modification time element (normally, one that
3953 has been assigned directly using `dir-locals-set-directory-class', not
3954 set from a file) is always valid.
3955 A cache entry based on a `dir-locals-file' is valid if the modification
3956 time stored in the cache matches the current file modification time.
3957 If not, the cache entry is cleared so that the file will be re-read.
3959 This function returns either:
3960 - nil (no directory local variables found),
3961 - the matching entry from `dir-locals-directory-cache' (a list),
3962 - or the full path to the directory (a string) containing at
3963 least one `dir-locals-file' in the case of no valid cache
3965 (setq file
(expand-file-name file
))
3966 (let* ((locals-dir (locate-dominating-file (file-name-directory file
)
3967 #'dir-locals--all-files
))
3969 ;; `locate-dominating-file' may have abbreviated the name.
3971 (setq locals-dir
(expand-file-name locals-dir
)))
3972 ;; Find the best cached value in `dir-locals-directory-cache'.
3973 (dolist (elt dir-locals-directory-cache
)
3974 (when (and (string-prefix-p (car elt
) file
3976 '(windows-nt cygwin ms-dos
)))
3977 (> (length (car elt
)) (length (car dir-elt
))))
3978 (setq dir-elt elt
)))
3980 (or (null locals-dir
)
3981 (<= (length locals-dir
)
3982 (length (car dir-elt
)))))
3983 ;; Found a potential cache entry. Check validity.
3984 ;; A cache entry with no MTIME is assumed to always be valid
3985 ;; (ie, set directly, not from a dir-locals file).
3986 ;; Note, we don't bother to check that there is a matching class
3987 ;; element in dir-locals-class-alist, since that's done by
3988 ;; dir-locals-set-directory-class.
3989 (if (or (null (nth 2 dir-elt
))
3990 (let ((cached-files (dir-locals--all-files (car dir-elt
))))
3991 ;; The entry MTIME should match the most recent
3992 ;; MTIME among matching files.
3994 (equal (nth 2 dir-elt
)
3996 (dolist (f cached-files latest
)
3997 (let ((f-time (nth 5 (file-attributes f
))))
3998 (if (time-less-p latest f-time
)
3999 (setq latest f-time
)))))))))
4000 ;; This cache entry is OK.
4002 ;; This cache entry is invalid; clear it.
4003 (setq dir-locals-directory-cache
4004 (delq dir-elt dir-locals-directory-cache
))
4005 ;; Return the first existing dir-locals file. Might be the same
4006 ;; as dir-elt's, might not (eg latter might have been deleted).
4011 (defun dir-locals-read-from-dir (dir)
4012 "Load all variables files in DIR and register a new class and instance.
4013 DIR is the absolute name of a directory which must contain at
4014 least one dir-local file (which is a file holding variables to
4016 Return the new class name, which is a symbol named DIR."
4018 (let* ((class-name (intern dir
))
4019 (files (dir-locals--all-files dir
))
4021 ;; If there was a problem, use the values we could get but
4022 ;; don't let the cache prevent future reads.
4023 (latest 0) (success 0)
4025 (with-demoted-errors "Error reading dir-locals: %S"
4026 (dolist (file files
)
4027 (let ((file-time (nth 5 (file-attributes file
))))
4028 (if (time-less-p latest file-time
)
4029 (setq latest file-time
)))
4031 (insert-file-contents file
)
4032 (condition-case-unless-debug nil
4034 (map-merge-with 'list
(lambda (a b
) (map-merge 'list a b
))
4036 (read (current-buffer))))
4037 (end-of-file nil
))))
4038 (setq success latest
))
4039 (dir-locals-set-class-variables class-name variables
)
4040 (dir-locals-set-directory-class dir class-name success
)
4043 (define-obsolete-function-alias 'dir-locals-read-from-file
4044 'dir-locals-read-from-dir
"25.1")
4046 (defcustom enable-remote-dir-locals nil
4047 "Non-nil means dir-local variables will be applied to remote files."
4052 (defvar hack-dir-local-variables--warned-coding nil
)
4054 (defun hack-dir-local-variables ()
4055 "Read per-directory local variables for the current buffer.
4056 Store the directory-local variables in `dir-local-variables-alist'
4057 and `file-local-variables-alist', without applying them.
4059 This does nothing if either `enable-local-variables' or
4060 `enable-dir-local-variables' are nil."
4061 (when (and enable-local-variables
4062 enable-dir-local-variables
4063 (or enable-remote-dir-locals
4064 (not (file-remote-p (or (buffer-file-name)
4065 default-directory
)))))
4066 ;; Find the variables file.
4067 (let ((dir-or-cache (dir-locals-find-file
4068 (or (buffer-file-name) default-directory
)))
4072 ((stringp dir-or-cache
)
4073 (setq dir-name dir-or-cache
4074 class
(dir-locals-read-from-dir dir-or-cache
)))
4075 ((consp dir-or-cache
)
4076 (setq dir-name
(nth 0 dir-or-cache
))
4077 (setq class
(nth 1 dir-or-cache
))))
4080 (dir-locals-collect-variables
4081 (dir-locals-get-class-variables class
) dir-name nil
)))
4083 (dolist (elt variables
)
4084 (if (eq (car elt
) 'coding
)
4085 (unless hack-dir-local-variables--warned-coding
4086 (setq hack-dir-local-variables--warned-coding t
)
4087 (display-warning 'files
4088 "Coding cannot be specified by dir-locals"))
4089 (unless (memq (car elt
) '(eval mode
))
4090 (setq dir-local-variables-alist
4091 (assq-delete-all (car elt
) dir-local-variables-alist
)))
4092 (push elt dir-local-variables-alist
)))
4093 (hack-local-variables-filter variables dir-name
)))))))
4095 (defun hack-dir-local-variables-non-file-buffer ()
4096 "Apply directory-local variables to a non-file buffer.
4097 For non-file buffers, such as Dired buffers, directory-local
4098 variables are looked for in `default-directory' and its parent
4100 (hack-dir-local-variables)
4101 (hack-local-variables-apply))
4104 (defcustom change-major-mode-with-file-name t
4105 "Non-nil means \\[write-file] should set the major mode from the file name.
4106 However, the mode will not be changed if
4107 \(1) a local variables list or the `-*-' line specifies a major mode, or
4108 \(2) the current major mode is a \"special\" mode,
4109 not suitable for ordinary files, or
4110 \(3) the new file name does not particularly specify any mode."
4112 :group
'editing-basics
)
4114 (defun set-visited-file-name (filename &optional no-query along-with-file
)
4115 "Change name of file visited in current buffer to FILENAME.
4116 This also renames the buffer to correspond to the new file.
4117 The next time the buffer is saved it will go in the newly specified file.
4118 FILENAME nil or an empty string means mark buffer as not visiting any file.
4119 Remember to delete the initial contents of the minibuffer
4120 if you wish to pass an empty string as the argument.
4122 The optional second argument NO-QUERY, if non-nil, inhibits asking for
4123 confirmation in the case where another buffer is already visiting FILENAME.
4125 The optional third argument ALONG-WITH-FILE, if non-nil, means that
4126 the old visited file has been renamed to the new name FILENAME."
4127 (interactive "FSet visited file name: ")
4128 (if (buffer-base-buffer)
4129 (error "An indirect buffer cannot visit a file"))
4130 (let (truename old-try-locals
)
4133 (if (string-equal filename
"")
4135 (expand-file-name filename
))))
4138 (setq truename
(file-truename filename
))
4139 (if find-file-visit-truename
4140 (setq filename truename
))))
4142 (let ((new-name (file-name-nondirectory filename
)))
4143 (if (string= new-name
"")
4144 (error "Empty file name"))))
4145 (let ((buffer (and filename
(find-buffer-visiting filename
))))
4146 (and buffer
(not (eq buffer
(current-buffer)))
4148 (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
4150 (user-error "Aborted")))
4151 (or (equal filename buffer-file-name
)
4153 (and filename
(lock-buffer filename
))
4155 (setq old-try-locals
(not (inhibit-local-variables-p))
4156 buffer-file-name filename
)
4157 (if filename
; make buffer name reflect filename.
4158 (let ((new-name (file-name-nondirectory buffer-file-name
)))
4159 (setq default-directory
(file-name-directory buffer-file-name
))
4160 ;; If new-name == old-name, renaming would add a spurious <2>
4161 ;; and it's considered as a feature in rename-buffer.
4162 (or (string= new-name
(buffer-name))
4163 (rename-buffer new-name t
))))
4164 (setq buffer-backed-up nil
)
4166 (clear-visited-file-modtime))
4167 ;; Abbreviate the file names of the buffer.
4170 (setq buffer-file-truename
(abbreviate-file-name truename
))
4171 (if find-file-visit-truename
4172 (setq buffer-file-name truename
))))
4173 (setq buffer-file-number
4175 (nthcdr 10 (file-attributes buffer-file-name
))
4177 ;; write-file-functions is normally used for things like ftp-find-file
4178 ;; that visit things that are not local files as if they were files.
4179 ;; Changing to visit an ordinary local file instead should flush the hook.
4180 (kill-local-variable 'write-file-functions
)
4181 (kill-local-variable 'local-write-file-hooks
)
4182 (kill-local-variable 'revert-buffer-function
)
4183 (kill-local-variable 'backup-inhibited
)
4184 ;; If buffer was read-only because of version control,
4185 ;; that reason is gone now, so make it writable.
4187 (setq buffer-read-only nil
))
4188 (kill-local-variable 'vc-mode
)
4189 ;; Turn off backup files for certain file names.
4190 ;; Since this is a permanent local, the major mode won't eliminate it.
4191 (and buffer-file-name
4192 backup-enable-predicate
4193 (not (funcall backup-enable-predicate buffer-file-name
))
4195 (make-local-variable 'backup-inhibited
)
4196 (setq backup-inhibited t
)))
4197 (let ((oauto buffer-auto-save-file-name
))
4198 (cond ((null filename
)
4199 (setq buffer-auto-save-file-name nil
))
4200 ((not buffer-auto-save-file-name
)
4201 ;; If auto-save was not already on, turn it on if appropriate.
4202 (and buffer-file-name auto-save-default
(auto-save-mode t
)))
4204 ;; If auto save is on, start using a new name. We
4205 ;; deliberately don't rename or delete the old auto save
4206 ;; for the old visited file name. This is because
4207 ;; perhaps the user wants to save the new state and then
4208 ;; compare with the previous state from the auto save
4210 (setq buffer-auto-save-file-name
(make-auto-save-file-name))))
4211 ;; Rename the old auto save file if any.
4212 (and oauto buffer-auto-save-file-name
4213 (file-exists-p oauto
)
4214 (rename-file oauto buffer-auto-save-file-name t
)))
4215 (and buffer-file-name
4216 (not along-with-file
)
4217 (set-buffer-modified-p t
))
4218 ;; Update the major mode, if the file name determines it.
4220 ;; Don't change the mode if it is special.
4221 (or (not change-major-mode-with-file-name
)
4222 (get major-mode
'mode-class
)
4223 ;; Don't change the mode if the local variable list specifies it.
4224 ;; The file name can influence whether the local variables apply.
4226 ;; h-l-v also checks it, but might as well be explicit.
4227 (not (inhibit-local-variables-p))
4228 (hack-local-variables t
))
4229 ;; TODO consider making normal-mode handle this case.
4230 (let ((old major-mode
))
4232 (or (eq old major-mode
)
4233 (hack-local-variables))))
4236 (defun write-file (filename &optional confirm
)
4237 "Write current buffer into file FILENAME.
4238 This makes the buffer visit that file, and marks it as not modified.
4240 If you specify just a directory name as FILENAME, that means to use
4241 the default file name but in that directory. You can also yank
4242 the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
4244 If the buffer is not already visiting a file, the default file name
4245 for the output file is the buffer name.
4247 If optional second arg CONFIRM is non-nil, this function
4248 asks for confirmation before overwriting an existing file.
4249 Interactively, confirmation is required unless you supply a prefix argument."
4250 ;; (interactive "FWrite file: ")
4252 (list (if buffer-file-name
4253 (read-file-name "Write file: "
4255 (read-file-name "Write file: " default-directory
4257 (file-name-nondirectory (buffer-name))
4260 (not current-prefix-arg
)))
4261 (or (null filename
) (string-equal filename
"")
4263 ;; If arg is a directory name,
4264 ;; use the default file name, but in that directory.
4265 (if (directory-name-p filename
)
4266 (setq filename
(concat filename
4267 (file-name-nondirectory
4268 (or buffer-file-name
(buffer-name))))))
4270 (file-exists-p filename
)
4271 ;; NS does its own confirm dialog.
4272 (not (and (eq (framep-on-display) 'ns
)
4273 (listp last-nonmenu-event
)
4275 (or (y-or-n-p (format-message
4276 "File `%s' exists; overwrite? " filename
))
4277 (user-error "Canceled")))
4278 (set-visited-file-name filename
(not confirm
))))
4279 (set-buffer-modified-p t
)
4280 ;; Make buffer writable if file is writable.
4281 (and buffer-file-name
4282 (file-writable-p buffer-file-name
)
4283 (setq buffer-read-only nil
))
4285 ;; It's likely that the VC status at the new location is different from
4286 ;; the one at the old location.
4289 (defun file-extended-attributes (filename)
4290 "Return an alist of extended attributes of file FILENAME.
4292 Extended attributes are platform-specific metadata about the file,
4293 such as SELinux context, list of ACL entries, etc."
4294 `((acl .
,(file-acl filename
))
4295 (selinux-context .
,(file-selinux-context filename
))))
4297 (defun set-file-extended-attributes (filename attributes
)
4298 "Set extended attributes of file FILENAME to ATTRIBUTES.
4300 ATTRIBUTES must be an alist of file attributes as returned by
4301 `file-extended-attributes'.
4302 Value is t if the function succeeds in setting the attributes."
4304 (dolist (elt attributes
)
4305 (let ((attr (car elt
))
4307 (cond ((eq attr
'acl
)
4308 (setq rv
(set-file-acl filename val
)))
4309 ((eq attr
'selinux-context
)
4310 (setq rv
(set-file-selinux-context filename val
))))
4311 (setq result
(or result rv
))))
4315 (defun backup-buffer ()
4316 "Make a backup of the disk file visited by the current buffer, if appropriate.
4317 This is normally done before saving the buffer the first time.
4319 A backup may be done by renaming or by copying; see documentation of
4320 variable `make-backup-files'. If it's done by renaming, then the file is
4321 no longer accessible under its old name.
4323 The value is non-nil after a backup was made by renaming.
4324 It has the form (MODES EXTENDED-ATTRIBUTES BACKUPNAME).
4325 MODES is the result of `file-modes' on the original
4326 file; this means that the caller, after saving the buffer, should change
4327 the modes of the new file to agree with the old modes.
4328 EXTENDED-ATTRIBUTES is the result of `file-extended-attributes'
4329 on the original file; this means that the caller, after saving
4330 the buffer, should change the extended attributes of the new file
4331 to agree with the old attributes.
4332 BACKUPNAME is the backup file name, which is the old file renamed."
4333 (when (and make-backup-files
(not backup-inhibited
) (not buffer-backed-up
))
4334 (let ((attributes (file-attributes buffer-file-name
)))
4335 (when (and attributes
(memq (aref (elt attributes
8) 0) '(?- ?l
)))
4336 ;; If specified name is a symbolic link, chase it to the target.
4337 ;; This makes backups in the directory where the real file is.
4338 (let* ((real-file-name (file-chase-links buffer-file-name
))
4339 (backup-info (find-backup-file-name real-file-name
)))
4341 (let* ((backupname (car backup-info
))
4342 (targets (cdr backup-info
))
4344 ;; If have old versions to maybe delete,
4345 ;; ask the user to confirm now, before doing anything.
4346 ;; But don't actually delete til later.
4348 (booleanp delete-old-versions
)
4349 (or delete-old-versions
4351 (format "Delete excess backup versions of %s? "
4354 (modes (file-modes buffer-file-name
))
4355 (extended-attributes
4356 (file-extended-attributes buffer-file-name
))
4357 (copy-when-priv-mismatch
4358 backup-by-copying-when-privileged-mismatch
)
4360 (or file-precious-flag backup-by-copying
4361 ;; Don't rename a suid or sgid file.
4362 (and modes
(< 0 (logand modes
#o6000
)))
4363 (not (file-writable-p
4364 (file-name-directory real-file-name
)))
4365 (and backup-by-copying-when-linked
4366 (< 1 (file-nlinks real-file-name
)))
4367 (and (or backup-by-copying-when-mismatch
4368 (and (integerp copy-when-priv-mismatch
)
4369 (let ((attr (file-attributes
4373 copy-when-priv-mismatch
))))
4374 (not (file-ownership-preserved-p real-file-name
4379 ;; Actually make the backup file.
4381 (backup-buffer-copy real-file-name backupname
4382 modes extended-attributes
)
4383 ;; rename-file should delete old backup.
4384 (rename-file real-file-name backupname t
)
4385 (setq setmodes
(list modes extended-attributes
4387 (setq buffer-backed-up t
)
4388 ;; Now delete the old versions, if desired.
4389 (dolist (old-version old-versions
)
4390 (delete-file old-version
)))
4392 ;; If trouble writing the backup, write it in .emacs.d/%backup%.
4393 (when (not buffer-backed-up
)
4394 (setq backupname
(locate-user-emacs-file "%backup%~"))
4395 (message "Cannot write backup file; backing up in %s"
4398 (backup-buffer-copy real-file-name backupname
4399 modes extended-attributes
)
4400 (setq buffer-backed-up t
))
4403 (defun backup-buffer-copy (from-name to-name modes extended-attributes
)
4404 ;; Create temp files with strict access rights. It's easy to
4405 ;; loosen them later, whereas it's impossible to close the
4406 ;; time-window of loose permissions otherwise.
4407 (with-file-modes ?
\700
4408 (when (condition-case nil
4409 ;; Try to overwrite old backup first.
4410 (copy-file from-name to-name t t t
)
4412 (while (condition-case nil
4414 (when (file-exists-p to-name
)
4415 (delete-file to-name
))
4416 (copy-file from-name to-name nil t t
)
4418 (file-already-exists t
))
4419 ;; The file was somehow created by someone else between
4420 ;; `delete-file' and `copy-file', so let's try again.
4421 ;; rms says "I think there is also a possible race
4422 ;; condition for making backup files" (emacs-devel 20070821).
4424 ;; If set-file-extended-attributes fails, fall back on set-file-modes.
4425 (unless (and extended-attributes
4426 (with-demoted-errors
4427 (set-file-extended-attributes to-name extended-attributes
)))
4429 (set-file-modes to-name
(logand modes
#o1777
)))))
4431 (defvar file-name-version-regexp
4432 "\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)"
4433 ;; The last ~[[:digit]]+ matches relative versions in git,
4434 ;; e.g. `foo.js.~HEAD~1~'.
4435 "Regular expression matching the backup/version part of a file name.
4436 Used by `file-name-sans-versions'.")
4438 (defun file-name-sans-versions (name &optional keep-backup-version
)
4439 "Return file NAME sans backup versions or strings.
4440 This is a separate procedure so your site-init or startup file can
4442 If the optional argument KEEP-BACKUP-VERSION is non-nil,
4443 we do not remove backup version numbers, only true file version numbers.
4444 See also `file-name-version-regexp'."
4445 (let ((handler (find-file-name-handler name
'file-name-sans-versions
)))
4447 (funcall handler
'file-name-sans-versions name keep-backup-version
)
4449 (unless keep-backup-version
4450 (string-match (concat file-name-version-regexp
"\\'")
4453 (defun file-ownership-preserved-p (file &optional group
)
4454 "Return t if deleting FILE and rewriting it would preserve the owner.
4455 Return also t if FILE does not exist. If GROUP is non-nil, check whether
4456 the group would be preserved too."
4457 (let ((handler (find-file-name-handler file
'file-ownership-preserved-p
)))
4459 (funcall handler
'file-ownership-preserved-p file group
)
4460 (let ((attributes (file-attributes file
'integer
)))
4461 ;; Return t if the file doesn't exist, since it's true that no
4462 ;; information would be lost by an (attempted) delete and create.
4463 (or (null attributes
)
4464 (and (or (= (nth 2 attributes
) (user-uid))
4465 ;; Files created on Windows by Administrator (RID=500)
4466 ;; have the Administrators group (RID=544) recorded as
4467 ;; their owner. Rewriting them will still preserve the
4469 (and (eq system-type
'windows-nt
)
4470 (= (user-uid) 500) (= (nth 2 attributes
) 544)))
4472 ;; On BSD-derived systems files always inherit the parent
4473 ;; directory's group, so skip the group-gid test.
4474 (memq system-type
'(berkeley-unix darwin gnu
/kfreebsd
))
4475 (= (nth 3 attributes
) (group-gid)))
4476 (let* ((parent (or (file-name-directory file
) "."))
4477 (parent-attributes (file-attributes parent
'integer
)))
4478 (and parent-attributes
4479 ;; On some systems, a file created in a setuid directory
4480 ;; inherits that directory's owner.
4482 (= (nth 2 parent-attributes
) (user-uid))
4483 (string-match "^...[^sS]" (nth 8 parent-attributes
)))
4484 ;; On many systems, a file created in a setgid directory
4485 ;; inherits that directory's group. On some systems
4486 ;; this happens even if the setgid bit is not set.
4488 (= (nth 3 parent-attributes
)
4489 (nth 3 attributes
)))))))))))
4491 (defun file-name-sans-extension (filename)
4492 "Return FILENAME sans final \"extension\".
4493 The extension, in a file name, is the part that begins with the last `.',
4494 except that a leading `.' of the file name, if there is one, doesn't count."
4496 (let ((file (file-name-sans-versions (file-name-nondirectory filename
)))
4498 (if (and (string-match "\\.[^.]*\\'" file
)
4499 (not (eq 0 (match-beginning 0))))
4500 (if (setq directory
(file-name-directory filename
))
4501 ;; Don't use expand-file-name here; if DIRECTORY is relative,
4502 ;; we don't want to expand it.
4503 (concat directory
(substring file
0 (match-beginning 0)))
4504 (substring file
0 (match-beginning 0)))
4507 (defun file-name-extension (filename &optional period
)
4508 "Return FILENAME's final \"extension\".
4509 The extension, in a file name, is the part that begins with the last `.',
4510 excluding version numbers and backup suffixes, except that a leading `.'
4511 of the file name, if there is one, doesn't count.
4512 Return nil for extensionless file names such as `foo'.
4513 Return the empty string for file names such as `foo.'.
4515 By default, the returned value excludes the period that starts the
4516 extension, but if the optional argument PERIOD is non-nil, the period
4517 is included in the value, and in that case, if FILENAME has no
4518 extension, the value is \"\"."
4520 (let ((file (file-name-sans-versions (file-name-nondirectory filename
))))
4521 (if (and (string-match "\\.[^.]*\\'" file
)
4522 (not (eq 0 (match-beginning 0))))
4523 (substring file
(+ (match-beginning 0) (if period
0 1)))
4527 (defun file-name-base (&optional filename
)
4528 "Return the base name of the FILENAME: no directory, no extension."
4529 (declare (advertised-calling-convention (filename) "27.1"))
4530 (file-name-sans-extension
4531 (file-name-nondirectory (or filename
(buffer-file-name)))))
4533 (defcustom make-backup-file-name-function
4534 #'make-backup-file-name--default-function
4535 "A function that `make-backup-file-name' uses to create backup file names.
4536 The function receives a single argument, the original file name.
4538 If you change this, you may need to change `backup-file-name-p' and
4539 `file-name-sans-versions' too.
4541 You could make this buffer-local to do something special for specific files.
4543 For historical reasons, a value of nil means to use the default function.
4544 This should not be relied upon.
4546 See also `backup-directory-alist'."
4547 :version
"24.4" ; nil -> make-backup-file-name--default-function
4549 :type
'(choice (const :tag
"Deprecated way to get the default function" nil
)
4550 (function :tag
"Function")))
4552 (defcustom backup-directory-alist nil
4553 "Alist of filename patterns and backup directory names.
4554 Each element looks like (REGEXP . DIRECTORY). Backups of files with
4555 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
4556 relative or absolute. If it is absolute, so that all matching files
4557 are backed up into the same directory, the file names in this
4558 directory will be the full name of the file backed up with all
4559 directory separators changed to `!' to prevent clashes. This will not
4560 work correctly if your filesystem truncates the resulting name.
4562 For the common case of all backups going into one directory, the alist
4563 should contain a single element pairing \".\" with the appropriate
4566 If this variable is nil, or it fails to match a filename, the backup
4567 is made in the original file's directory.
4569 On MS-DOS filesystems without long names this variable is always
4572 :type
'(repeat (cons (regexp :tag
"Regexp matching filename")
4573 (directory :tag
"Backup directory name"))))
4575 (defun normal-backup-enable-predicate (name)
4576 "Default `backup-enable-predicate' function.
4577 Checks for files in `temporary-file-directory',
4578 `small-temporary-file-directory', and \"/tmp\"."
4579 (let ((temporary-file-directory temporary-file-directory
)
4581 ;; On MS-Windows, file-truename will convert short 8+3 aliases to
4582 ;; their long file-name equivalents, so compare-strings does TRT.
4583 (if (memq system-type
'(ms-dos windows-nt
))
4584 (setq temporary-file-directory
(file-truename temporary-file-directory
)
4585 name
(file-truename name
)
4587 (not (or (let ((comp (compare-strings temporary-file-directory
0 nil
4588 name
0 nil caseless
)))
4589 ;; Directory is under temporary-file-directory.
4590 (and (not (eq comp t
))
4591 (< comp
(- (length temporary-file-directory
)))))
4592 (let ((comp (compare-strings "/tmp" 0 nil
4594 ;; Directory is under /tmp.
4595 (and (not (eq comp t
))
4596 (< comp
(- (length "/tmp")))))
4597 (if small-temporary-file-directory
4598 (let ((comp (compare-strings small-temporary-file-directory
4600 name
0 nil caseless
)))
4601 ;; Directory is under small-temporary-file-directory.
4602 (and (not (eq comp t
))
4603 (< comp
(- (length small-temporary-file-directory
))))))))))
4605 (defun make-backup-file-name (file)
4606 "Create the non-numeric backup file name for FILE.
4607 This calls the function that `make-backup-file-name-function' specifies,
4608 with a single argument FILE."
4609 (funcall (or make-backup-file-name-function
4610 #'make-backup-file-name--default-function
)
4613 (defun make-backup-file-name--default-function (file)
4614 "Default function for `make-backup-file-name'.
4615 Normally this just returns FILE's name with `~' appended.
4616 It searches for a match for FILE in `backup-directory-alist'.
4617 If the directory for the backup doesn't exist, it is created."
4618 (if (and (eq system-type
'ms-dos
)
4619 (not (msdos-long-file-names)))
4620 (let ((fn (file-name-nondirectory file
)))
4621 (concat (file-name-directory file
)
4622 (or (and (string-match "\\`[^.]+\\'" fn
)
4623 (concat (match-string 0 fn
) ".~"))
4624 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn
)
4625 (concat (match-string 0 fn
) "~")))))
4626 (concat (make-backup-file-name-1 file
) "~")))
4628 (defun make-backup-file-name-1 (file)
4629 "Subroutine of `make-backup-file-name--default-function'.
4630 The function `find-backup-file-name' also uses this."
4631 (let ((alist backup-directory-alist
)
4632 elt backup-directory abs-backup-directory
)
4634 (setq elt
(pop alist
))
4635 (if (string-match (car elt
) file
)
4636 (setq backup-directory
(cdr elt
)
4638 ;; If backup-directory is relative, it should be relative to the
4639 ;; file's directory. By expanding explicitly here, we avoid
4640 ;; depending on default-directory.
4641 (if backup-directory
4642 (setq abs-backup-directory
4643 (expand-file-name backup-directory
4644 (file-name-directory file
))))
4645 (if (and abs-backup-directory
(not (file-exists-p abs-backup-directory
)))
4647 (make-directory abs-backup-directory
'parents
)
4648 (file-error (setq backup-directory nil
4649 abs-backup-directory nil
))))
4650 (if (null backup-directory
)
4652 (if (file-name-absolute-p backup-directory
)
4654 (when (memq system-type
'(windows-nt ms-dos cygwin
))
4655 ;; Normalize DOSish file names: downcase the drive
4656 ;; letter, if any, and replace the leading "x:" with
4658 (or (file-name-absolute-p file
)
4659 (setq file
(expand-file-name file
))) ; make defaults explicit
4661 ((file-remote-p file
)
4662 ;; Remove the leading slash, if any, to prevent
4663 ;; convert-standard-filename from converting that to a
4665 (and (memq (aref file
0) '(?
/ ?
\\))
4666 (setq file
(substring file
1)))
4667 ;; Replace any invalid file-name characters, then
4668 ;; prepend the leading slash back.
4669 (setq file
(concat "/" (convert-standard-filename file
))))
4671 ;; Replace any invalid file-name characters.
4672 (setq file
(expand-file-name (convert-standard-filename file
)))
4673 (if (eq (aref file
1) ?
:)
4674 (setq file
(concat "/"
4676 (char-to-string (downcase (aref file
0)))
4677 (if (eq (aref file
2) ?
/)
4680 (substring file
2)))))))
4681 ;; Make the name unique by substituting directory
4682 ;; separators. It may not really be worth bothering about
4683 ;; doubling `!'s in the original name...
4685 (subst-char-in-string
4687 (replace-regexp-in-string "!" "!!" file
))
4689 (expand-file-name (file-name-nondirectory file
)
4690 (file-name-as-directory abs-backup-directory
))))))
4692 (defun backup-file-name-p (file)
4693 "Return non-nil if FILE is a backup file name (numeric or not).
4694 This is a separate function so you can redefine it for customization.
4695 You may need to redefine `file-name-sans-versions' as well."
4696 (string-match "~\\'" file
))
4698 (defvar backup-extract-version-start
)
4700 ;; This is used in various files.
4701 ;; The usage of backup-extract-version-start is not very clean,
4702 ;; but I can't see a good alternative, so as of now I am leaving it alone.
4703 (defun backup-extract-version (fn)
4704 "Given the name of a numeric backup file, FN, return the backup number.
4705 Uses the free variable `backup-extract-version-start', whose value should be
4706 the index in the name where the version number begins."
4707 (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start
)
4708 (= (match-beginning 0) backup-extract-version-start
))
4709 (string-to-number (substring fn backup-extract-version-start -
1))
4712 (defun find-backup-file-name (fn)
4713 "Find a file name for a backup file FN, and suggestions for deletions.
4714 Value is a list whose car is the name for the backup file
4715 and whose cdr is a list of old versions to consider deleting now.
4716 If the value is nil, don't make a backup.
4717 Uses `backup-directory-alist' in the same way as
4718 `make-backup-file-name--default-function' does."
4719 (let ((handler (find-file-name-handler fn
'find-backup-file-name
)))
4720 ;; Run a handler for this function so that ange-ftp can refuse to do it.
4722 (funcall handler
'find-backup-file-name fn
)
4723 (if (or (eq version-control
'never
)
4724 ;; We don't support numbered backups on plain MS-DOS
4725 ;; when long file names are unavailable.
4726 (and (eq system-type
'ms-dos
)
4727 (not (msdos-long-file-names))))
4728 (list (make-backup-file-name fn
))
4729 (let* ((basic-name (make-backup-file-name-1 fn
))
4730 (base-versions (concat (file-name-nondirectory basic-name
)
4732 (backup-extract-version-start (length base-versions
))
4734 (number-to-delete 0)
4735 possibilities deserve-versions-p versions
)
4737 (setq possibilities
(file-name-all-completions
4739 (file-name-directory basic-name
))
4740 versions
(sort (mapcar #'backup-extract-version
4743 high-water-mark
(apply 'max
0 versions
)
4744 deserve-versions-p
(or version-control
4745 (> high-water-mark
0))
4746 number-to-delete
(- (length versions
)
4750 (file-error (setq possibilities nil
)))
4751 (if (not deserve-versions-p
)
4752 (list (make-backup-file-name fn
))
4753 (cons (format "%s.~%d~" basic-name
(1+ high-water-mark
))
4754 (if (and (> number-to-delete
0)
4755 ;; Delete nothing if there is overflow
4756 ;; in the number of versions to keep.
4757 (>= (+ kept-new-versions kept-old-versions -
1) 0))
4759 (format "%s.~%d~" basic-name n
))
4760 (let ((v (nthcdr kept-old-versions versions
)))
4761 (rplacd (nthcdr (1- number-to-delete
) v
) ())
4764 (defun file-nlinks (filename)
4765 "Return number of names file FILENAME has."
4766 (car (cdr (file-attributes filename
))))
4768 (defun file-relative-name (filename &optional directory
)
4769 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4770 This function returns a relative file name which is equivalent to FILENAME
4771 when used with that default directory as the default.
4772 If FILENAME is a relative file name, it will be interpreted as existing in
4773 `default-directory'.
4774 If FILENAME and DIRECTORY lie on different machines or on different drives
4775 on a DOS/Windows machine, it returns FILENAME in expanded form."
4778 (file-name-as-directory (expand-file-name (or directory
4779 default-directory
))))
4780 (setq filename
(expand-file-name filename
))
4781 (let ((fremote (file-remote-p filename
))
4782 (dremote (file-remote-p directory
))
4783 (fold-case (or (file-name-case-insensitive-p filename
)
4784 read-file-name-completion-ignore-case
)))
4785 (if ;; Conditions for separate trees
4787 ;; Test for different filesystems on DOS/Windows
4789 ;; Should `cygwin' really be included here? --stef
4790 (memq system-type
'(ms-dos cygwin windows-nt
))
4792 ;; Test for different drive letters
4793 (not (eq t
(compare-strings filename
0 2 directory
0 2 fold-case
)))
4794 ;; Test for UNCs on different servers
4795 (not (eq t
(compare-strings
4797 (if (string-match "\\`//\\([^:/]+\\)/" filename
)
4798 (match-string 1 filename
)
4799 ;; Windows file names cannot have ? in
4800 ;; them, so use that to detect when
4801 ;; neither FILENAME nor DIRECTORY is a
4806 (if (string-match "\\`//\\([^:/]+\\)/" directory
)
4807 (match-string 1 directory
)
4810 ;; Test for different remote file system identification
4811 (not (equal fremote dremote
)))
4813 (let ((ancestor ".")
4814 (filename-dir (file-name-as-directory filename
)))
4816 (or (string-prefix-p directory filename-dir fold-case
)
4817 (string-prefix-p directory filename fold-case
)))
4818 (setq directory
(file-name-directory (substring directory
0 -
1))
4819 ancestor
(if (equal ancestor
".")
4821 (concat "../" ancestor
))))
4822 ;; Now ancestor is empty, or .., or ../.., etc.
4823 (if (string-prefix-p directory filename fold-case
)
4824 ;; We matched within FILENAME's directory part.
4825 ;; Add the rest of FILENAME onto ANCESTOR.
4826 (let ((rest (substring filename
(length directory
))))
4827 (if (and (equal ancestor
".") (not (equal rest
"")))
4828 ;; But don't bother with ANCESTOR if it would give us `./'.
4830 (concat (file-name-as-directory ancestor
) rest
)))
4831 ;; We matched FILENAME's directory equivalent.
4834 (defun save-buffer (&optional arg
)
4835 "Save current buffer in visited file if modified.
4836 Variations are described below.
4838 By default, makes the previous version into a backup file
4839 if previously requested or if this is the first save.
4840 Prefixed with one \\[universal-argument], marks this version
4841 to become a backup when the next save is done.
4842 Prefixed with two \\[universal-argument]'s,
4843 makes the previous version into a backup file.
4844 Prefixed with three \\[universal-argument]'s, marks this version
4845 to become a backup when the next save is done,
4846 and makes the previous version into a backup file.
4848 With a numeric prefix argument of 0, never make the previous version
4851 Note that the various variables that control backups, such
4852 as `version-control', `backup-enable-predicate', `vc-make-backup-files',
4853 and `backup-inhibited', to name just the more popular ones, still
4854 control whether a backup will actually be produced, even when you
4855 invoke this command prefixed with two or three \\[universal-argument]'s.
4857 If a file's name is FOO, the names of its numbered backup versions are
4858 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
4859 Numeric backups (rather than FOO~) will be made if value of
4860 `version-control' is not the atom `never' and either there are already
4861 numeric versions of the file being backed up, or `version-control' is
4863 We don't want excessive versions piling up, so there are variables
4864 `kept-old-versions', which tells Emacs how many oldest versions to keep,
4865 and `kept-new-versions', which tells how many newest versions to keep.
4866 Defaults are 2 old versions and 2 new.
4867 `dired-kept-versions' controls dired's clean-directory (.) command.
4868 If `delete-old-versions' is nil, system will query user
4869 before trimming versions. Otherwise it does it silently.
4871 If `vc-make-backup-files' is nil, which is the default,
4872 no backup files are made for files managed by version control.
4873 (This is because the version control system itself records previous versions.)
4875 See the subroutine `basic-save-buffer' for more information."
4877 (let ((modp (buffer-modified-p))
4878 (make-backup-files (or (and make-backup-files
(not (eq arg
0)))
4879 (memq arg
'(16 64)))))
4880 (and modp
(memq arg
'(16 64)) (setq buffer-backed-up nil
))
4881 ;; We used to display the message below only for files > 50KB, but
4882 ;; then Rmail-mbox never displays it due to buffer swapping. If
4883 ;; the test is ever re-introduced, be sure to handle saving of
4887 (not noninteractive
)
4888 (not save-silently
))
4889 (message "Saving file %s..." (buffer-file-name)))
4890 (basic-save-buffer (called-interactively-p 'any
))
4891 (and modp
(memq arg
'(4 64)) (setq buffer-backed-up nil
))))
4893 (defun delete-auto-save-file-if-necessary (&optional force
)
4894 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
4895 Normally delete only if the file was written by this Emacs since
4896 the last real save, but optional arg FORCE non-nil means delete anyway."
4897 (and buffer-auto-save-file-name delete-auto-save-files
4898 (not (string= buffer-file-name buffer-auto-save-file-name
))
4899 (or force
(recent-auto-save-p))
4902 (delete-file buffer-auto-save-file-name
)
4904 (set-buffer-auto-saved))))
4906 (defvar auto-save-hook nil
4907 "Normal hook run just before auto-saving.")
4909 (defcustom before-save-hook nil
4910 "Normal hook that is run before a buffer is saved to its file.
4911 Only used by `save-buffer'."
4912 :options
'(copyright-update time-stamp
)
4916 (defcustom after-save-hook nil
4917 "Normal hook that is run after a buffer is saved to its file.
4918 Only used by `save-buffer'."
4919 :options
'(executable-make-buffer-file-executable-if-script-p)
4923 (defvar save-buffer-coding-system nil
4924 "If non-nil, use this coding system for saving the buffer.
4925 More precisely, use this coding system in place of the
4926 value of `buffer-file-coding-system', when saving the buffer.
4927 Calling `write-region' for any purpose other than saving the buffer
4928 will still use `buffer-file-coding-system'; this variable has no effect
4931 (make-variable-buffer-local 'save-buffer-coding-system
)
4932 (put 'save-buffer-coding-system
'permanent-local t
)
4934 (defun basic-save-buffer (&optional called-interactively
)
4935 "Save the current buffer in its visited file, if it has been modified.
4937 The hooks `write-contents-functions', `local-write-file-hooks'
4938 and `write-file-functions' get a chance to do the job of saving;
4939 if they do not, then the buffer is saved in the visited file in
4942 Before and after saving the buffer, this function runs
4943 `before-save-hook' and `after-save-hook', respectively."
4944 (interactive '(called-interactively))
4945 (save-current-buffer
4946 ;; In an indirect buffer, save its base buffer instead.
4947 (if (buffer-base-buffer)
4948 (set-buffer (buffer-base-buffer)))
4949 (if (or (buffer-modified-p)
4950 ;; Handle the case when no modification has been made but
4951 ;; the file disappeared since visited.
4952 (and buffer-file-name
4953 (not (file-exists-p buffer-file-name
))))
4954 (let ((recent-save (recent-auto-save-p))
4956 (or (null buffer-file-name
)
4957 (verify-visited-file-modtime (current-buffer))
4958 (not (file-exists-p buffer-file-name
))
4961 "%s has changed since visited or saved. Save anyway? "
4962 (file-name-nondirectory buffer-file-name
)))
4963 (user-error "Save not confirmed"))
4967 (and (> (point-max) (point-min))
4968 (not find-file-literally
)
4969 (null buffer-read-only
)
4970 (/= (char-after (1- (point-max))) ?
\n)
4971 (not (and (eq selective-display t
)
4972 (= (char-after (1- (point-max))) ?
\r)))
4973 (or (eq require-final-newline t
)
4974 (eq require-final-newline
'visit-save
)
4975 (and require-final-newline
4977 (format "Buffer %s does not end in newline. Add one? "
4980 (goto-char (point-max))
4982 ;; Don't let errors prevent saving the buffer.
4983 (with-demoted-errors (run-hooks 'before-save-hook
))
4984 ;; Give `write-contents-functions' a chance to
4985 ;; short-circuit the whole process.
4986 (unless (run-hook-with-args-until-success 'write-contents-functions
)
4987 ;; If buffer has no file name, ask user for one.
4988 (or buffer-file-name
4991 (read-file-name "File to save in: "
4992 nil
(expand-file-name (buffer-name))))))
4993 (if (file-exists-p filename
)
4994 (if (file-directory-p filename
)
4995 ;; Signal an error if the user specified the name of an
4996 ;; existing directory.
4997 (error "%s is a directory" filename
)
4998 (unless (y-or-n-p (format-message
4999 "File `%s' exists; overwrite? "
5001 (error "Canceled"))))
5002 (set-visited-file-name filename
)))
5003 ;; Support VC version backups.
5005 (or (run-hook-with-args-until-success 'local-write-file-hooks
)
5006 (run-hook-with-args-until-success 'write-file-functions
)
5007 ;; If a hook returned t, file is already "written".
5008 ;; Otherwise, write it the usual way now.
5009 (let ((dir (file-name-directory
5010 (expand-file-name buffer-file-name
))))
5011 (unless (file-exists-p dir
)
5014 "Directory `%s' does not exist; create? " dir
))
5015 (make-directory dir t
)
5016 (error "Canceled")))
5017 (setq setmodes
(basic-save-buffer-1)))))
5018 ;; Now we have saved the current buffer. Let's make sure
5019 ;; that buffer-file-coding-system is fixed to what
5020 ;; actually used for saving by binding it locally.
5021 (when buffer-file-name
5022 (if save-buffer-coding-system
5023 (setq save-buffer-coding-system last-coding-system-used
)
5024 (setq buffer-file-coding-system last-coding-system-used
))
5025 (setq buffer-file-number
5026 (nthcdr 10 (file-attributes buffer-file-name
)))
5031 (with-demoted-errors
5032 (set-file-modes buffer-file-name
(car setmodes
)))
5033 (set-file-extended-attributes buffer-file-name
5036 ;; Support VC `implicit' locking.
5038 ;; If the auto-save file was recent before this command,
5040 (delete-auto-save-file-if-necessary recent-save
))
5041 (run-hooks 'after-save-hook
))
5043 (not called-interactively
)
5044 (files--message "(No changes need to be saved)")))))
5046 ;; This does the "real job" of writing a buffer into its visited file
5047 ;; and making a backup file. This is what is normally done
5048 ;; but inhibited if one of write-file-functions returns non-nil.
5049 ;; It returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
5051 (defun basic-save-buffer-1 ()
5053 (if save-buffer-coding-system
5054 (let ((coding-system-for-write save-buffer-coding-system
))
5055 (basic-save-buffer-2))
5056 (basic-save-buffer-2))
5057 (if buffer-file-coding-system-explicit
5058 (setcar buffer-file-coding-system-explicit last-coding-system-used
))))
5060 ;; This returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
5062 (defun basic-save-buffer-2 ()
5063 (let (tempsetmodes setmodes
)
5064 (if (not (file-writable-p buffer-file-name
))
5065 (let ((dir (file-name-directory buffer-file-name
)))
5066 (if (not (file-directory-p dir
))
5067 (if (file-exists-p dir
)
5068 (error "%s is not a directory" dir
)
5069 (error "%s: no such directory" dir
))
5070 (if (not (file-exists-p buffer-file-name
))
5071 (error "Directory %s write-protected" dir
)
5074 "File %s is write-protected; try to save anyway? "
5075 (file-name-nondirectory
5077 (setq tempsetmodes t
)
5078 (error "Attempt to save to a file which you aren't allowed to write"))))))
5079 (or buffer-backed-up
5080 (setq setmodes
(backup-buffer)))
5081 (let* ((dir (file-name-directory buffer-file-name
))
5082 (dir-writable (file-writable-p dir
)))
5083 (if (or (and file-precious-flag dir-writable
)
5084 (and break-hardlink-on-save
5085 (file-exists-p buffer-file-name
)
5086 (> (file-nlinks buffer-file-name
) 1)
5088 (error (concat "Directory %s write-protected; "
5089 "cannot break hardlink when saving")
5091 ;; Write temp name, then rename it.
5092 ;; This requires write access to the containing dir,
5093 ;; which is why we don't try it if we don't have that access.
5094 (let ((realname buffer-file-name
)
5096 (old-modtime (visited-file-modtime)))
5097 ;; Create temp files with strict access rights. It's easy to
5098 ;; loosen them later, whereas it's impossible to close the
5099 ;; time-window of loose permissions otherwise.
5102 (clear-visited-file-modtime)
5103 ;; Call write-region in the appropriate way
5104 ;; for saving the buffer.
5107 (expand-file-name "tmp" dir
)))
5108 ;; Pass in nil&nil rather than point-min&max
5109 ;; cause we're saving the whole buffer.
5110 ;; write-region-annotate-functions may use it.
5111 (write-region nil nil tempname nil realname
5112 buffer-file-truename
)
5113 (when save-silently
(message nil
)))
5114 ;; If we failed, restore the buffer's modtime.
5115 (error (set-visited-file-modtime old-modtime
)
5116 (signal (car err
) (cdr err
))))
5117 ;; Since we have created an entirely new file,
5118 ;; make sure it gets the right permission bits set.
5119 (setq setmodes
(or setmodes
5120 (list (or (file-modes buffer-file-name
)
5121 (logand ?
\666 (default-file-modes)))
5122 (file-extended-attributes buffer-file-name
)
5124 ;; We succeeded in writing the temp file,
5126 (rename-file tempname buffer-file-name t
))
5127 ;; If file not writable, see if we can make it writable
5128 ;; temporarily while we write it.
5129 ;; But no need to do so if we have just backed it up
5130 ;; (setmodes is set) because that says we're superseding.
5131 (cond ((and tempsetmodes
(not setmodes
))
5132 ;; Change the mode back, after writing.
5133 (setq setmodes
(list (file-modes buffer-file-name
)
5134 (file-extended-attributes buffer-file-name
)
5136 ;; If set-file-extended-attributes fails, fall back on
5139 (with-demoted-errors
5140 (set-file-extended-attributes buffer-file-name
5142 (set-file-modes buffer-file-name
5143 (logior (car setmodes
) 128))))))
5147 ;; Pass in nil&nil rather than point-min&max to indicate
5148 ;; we're saving the buffer rather than just a region.
5149 ;; write-region-annotate-functions may make use of it.
5150 (write-region nil nil
5151 buffer-file-name nil t buffer-file-truename
)
5152 (when save-silently
(message nil
))
5154 ;; If we get an error writing the new file, and we made
5155 ;; the backup by renaming, undo the backing-up.
5156 (and setmodes
(not success
)
5158 (rename-file (nth 2 setmodes
) buffer-file-name t
)
5159 (setq buffer-backed-up nil
))))))
5162 (declare-function diff-no-select
"diff"
5163 (old new
&optional switches no-async buf
))
5165 (defvar save-some-buffers-action-alist
5168 (if (not enable-recursive-minibuffers
)
5169 (progn (display-buffer buf
)
5170 (setq other-window-scroll-buffer buf
))
5171 (view-buffer buf
(lambda (_) (exit-recursive-edit)))
5173 ;; Return nil to ask about BUF again.
5175 ,(purecopy "view this buffer"))
5177 (if (null (buffer-file-name buf
))
5178 (message "Not applicable: no file")
5179 (require 'diff
) ;for diff-no-select.
5180 (let ((diffbuf (diff-no-select (buffer-file-name buf
) buf
5182 (if (not enable-recursive-minibuffers
)
5183 (progn (display-buffer diffbuf
)
5184 (setq other-window-scroll-buffer diffbuf
))
5185 (view-buffer diffbuf
(lambda (_) (exit-recursive-edit)))
5187 ;; Return nil to ask about BUF again.
5189 ,(purecopy "view changes in this buffer")))
5190 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
5191 (put 'save-some-buffers-action-alist
'risky-local-variable t
)
5193 (defvar buffer-save-without-query nil
5194 "Non-nil means `save-some-buffers' should save this buffer without asking.")
5195 (make-variable-buffer-local 'buffer-save-without-query
)
5197 (defcustom save-some-buffers-default-predicate nil
5198 "Default predicate for `save-some-buffers'.
5199 This allows you to stop `save-some-buffers' from asking
5200 about certain files that you'd usually rather not save."
5202 ;; FIXME nil should not be a valid option, let alone the default,
5203 ;; eg so that add-function can be used.
5204 :type
'(choice (const :tag
"Default" nil
) function
)
5207 (defun save-some-buffers (&optional arg pred
)
5208 "Save some modified file-visiting buffers. Asks user about each one.
5209 You can answer `y' to save, `n' not to save, `C-r' to look at the
5210 buffer in question with `view-buffer' before deciding or `d' to
5211 view the differences using `diff-buffer-with-file'.
5213 This command first saves any buffers where `buffer-save-without-query' is
5214 non-nil, without asking.
5216 Optional argument ARG (interactively, prefix argument) non-nil means save
5217 all with no questions.
5218 Optional second argument PRED determines which buffers are considered:
5219 If PRED is nil, all the file-visiting buffers are considered.
5220 If PRED is t, then certain non-file buffers will also be considered.
5221 If PRED is a zero-argument function, it indicates for each buffer whether
5222 to consider it or not when called with that buffer current.
5223 PRED defaults to the value of `save-some-buffers-default-predicate'.
5225 See `save-some-buffers-action-alist' if you want to
5226 change the additional actions you can take on files."
5229 (setq pred save-some-buffers-default-predicate
))
5230 (save-window-excursion
5231 (let* (queried autosaved-buffers
5232 files-done abbrevs-done
)
5233 (dolist (buffer (buffer-list))
5234 ;; First save any buffers that we're supposed to save unconditionally.
5235 ;; That way the following code won't ask about them.
5236 (with-current-buffer buffer
5237 (when (and buffer-save-without-query
(buffer-modified-p))
5238 (push (buffer-name) autosaved-buffers
)
5240 ;; Ask about those buffers that merit it,
5241 ;; and record the number thus saved.
5245 ;; Note that killing some buffers may kill others via
5246 ;; hooks (e.g. Rmail and its viewing buffer).
5247 (and (buffer-live-p buffer
)
5248 (buffer-modified-p buffer
)
5249 (not (buffer-base-buffer buffer
))
5251 (buffer-file-name buffer
)
5252 (with-current-buffer buffer
5253 (or (eq buffer-offer-save
'always
)
5254 (and pred buffer-offer-save
(> (buffer-size) 0)))))
5255 (or (not (functionp pred
))
5256 (with-current-buffer buffer
(funcall pred
)))
5260 (if (buffer-file-name buffer
)
5261 (format "Save file %s? "
5262 (buffer-file-name buffer
))
5263 (format "Save buffer %s? "
5264 (buffer-name buffer
))))))
5266 (with-current-buffer buffer
5269 '("buffer" "buffers" "save")
5270 save-some-buffers-action-alist
))
5271 ;; Maybe to save abbrevs, and record whether
5272 ;; we either saved them or asked to.
5273 (and save-abbrevs abbrevs-changed
5276 (eq save-abbrevs
'silently
)
5277 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name
)))
5278 (write-abbrev-file nil
))
5279 ;; Don't keep bothering user if he says no.
5280 (setq abbrevs-changed nil
)
5281 (setq abbrevs-done t
)))
5282 (or queried
(> files-done
0) abbrevs-done
5284 ((null autosaved-buffers
)
5285 (when (called-interactively-p 'any
)
5286 (files--message "(No files need saving)")))
5287 ((= (length autosaved-buffers
) 1)
5288 (files--message "(Saved %s)" (car autosaved-buffers
)))
5290 (files--message "(Saved %d files: %s)"
5291 (length autosaved-buffers
)
5292 (mapconcat 'identity autosaved-buffers
", "))))))))
5294 (defun clear-visited-file-modtime ()
5295 "Clear out records of last mod time of visited file.
5296 Next attempt to save will not complain of a discrepancy."
5297 (set-visited-file-modtime 0))
5299 (defun not-modified (&optional arg
)
5300 "Mark current buffer as unmodified, not needing to be saved.
5301 With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
5303 It is not a good idea to use this function in Lisp programs, because it
5304 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
5305 (declare (interactive-only set-buffer-modified-p
))
5307 (files--message (if arg
"Modification-flag set"
5308 "Modification-flag cleared"))
5309 (set-buffer-modified-p arg
))
5311 (defun toggle-read-only (&optional arg interactive
)
5312 "Change whether this buffer is read-only."
5313 (declare (obsolete read-only-mode
"24.3"))
5314 (interactive (list current-prefix-arg t
))
5316 (call-interactively 'read-only-mode
)
5317 (read-only-mode (or arg
'toggle
))))
5319 (defun insert-file (filename)
5320 "Insert contents of file FILENAME into buffer after point.
5321 Set mark after the inserted text.
5323 This function is meant for the user to run interactively.
5324 Don't call it from programs! Use `insert-file-contents' instead.
5325 \(Its calling sequence is different; see its documentation)."
5326 (declare (interactive-only insert-file-contents
))
5327 (interactive "*fInsert file: ")
5328 (insert-file-1 filename
#'insert-file-contents
))
5330 (defun append-to-file (start end filename
)
5331 "Append the contents of the region to the end of file FILENAME.
5332 When called from a function, expects three arguments,
5333 START, END and FILENAME. START and END are normally buffer positions
5334 specifying the part of the buffer to write.
5335 If START is nil, that means to use the entire buffer contents.
5336 If START is a string, then output that string to the file
5337 instead of any buffer contents; END is ignored.
5339 This does character code conversion and applies annotations
5340 like `write-region' does."
5341 (interactive "r\nFAppend to file: ")
5342 (prog1 (write-region start end filename t
)
5343 (when save-silently
(message nil
))))
5345 (defun file-newest-backup (filename)
5346 "Return most recent backup file for FILENAME or nil if no backups exist."
5347 ;; `make-backup-file-name' will get us the right directory for
5348 ;; ordinary or numeric backups. It might create a directory for
5349 ;; backups as a side-effect, according to `backup-directory-alist'.
5350 (let* ((filename (file-name-sans-versions
5351 (make-backup-file-name (expand-file-name filename
))))
5352 (file (file-name-nondirectory filename
))
5353 (dir (file-name-directory filename
))
5354 (comp (file-name-all-completions file dir
))
5358 (setq tem
(pop comp
))
5359 (cond ((and (backup-file-name-p tem
)
5360 (string= (file-name-sans-versions tem
) file
))
5361 (setq tem
(concat dir tem
))
5362 (if (or (null newest
)
5363 (file-newer-than-file-p tem newest
))
5364 (setq newest tem
)))))
5367 (defun rename-uniquely ()
5368 "Rename current buffer to a similar name not already taken.
5369 This function is useful for creating multiple shell process buffers
5370 or multiple mail buffers, etc.
5372 Note that some commands, in particular those based on `compilation-mode'
5373 \(`compile', `grep', etc.) will reuse the current buffer if it has the
5374 appropriate mode even if it has been renamed. So as well as renaming
5375 the buffer, you also need to switch buffers before running another
5376 instance of such commands."
5379 (let ((base-name (buffer-name)))
5380 (and (string-match "<[0-9]+>\\'" base-name
)
5381 (not (and buffer-file-name
5383 (file-name-nondirectory buffer-file-name
))))
5384 ;; If the existing buffer name has a <NNN>,
5385 ;; which isn't part of the file name (if any),
5386 ;; then get rid of that.
5387 (setq base-name
(substring base-name
0 (match-beginning 0))))
5388 (rename-buffer (generate-new-buffer-name base-name
))
5389 (force-mode-line-update))))
5391 (defun files--ensure-directory (dir)
5392 "Make directory DIR if it is not already a directory. Return nil."
5394 (make-directory-internal dir
)
5396 (unless (file-directory-p dir
)
5397 (signal (car err
) (cdr err
))))))
5399 (defun make-directory (dir &optional parents
)
5400 "Create the directory DIR and optionally any nonexistent parent dirs.
5401 If DIR already exists as a directory, signal an error, unless
5404 Interactively, the default choice of directory to create is the
5405 current buffer's default directory. That is useful when you have
5406 visited a file in a nonexistent directory.
5408 Noninteractively, the second (optional) argument PARENTS, if
5409 non-nil, says whether to create parent directories that don't
5410 exist. Interactively, this happens by default.
5412 If creating the directory or directories fail, an error will be
5415 (list (read-file-name "Make directory: " default-directory default-directory
5418 ;; If default-directory is a remote directory,
5419 ;; make sure we find its make-directory handler.
5420 (setq dir
(expand-file-name dir
))
5421 (let ((handler (find-file-name-handler dir
'make-directory
)))
5423 (funcall handler
'make-directory dir parents
)
5425 (make-directory-internal dir
)
5426 (let ((dir (directory-file-name (expand-file-name dir
)))
5429 (setq parent
(directory-file-name
5430 (file-name-directory dir
)))
5432 (files--ensure-directory dir
)
5434 ;; Do not loop if root does not exist (Bug#2309).
5435 (not (string= dir parent
)))))
5436 (setq create-list
(cons dir create-list
)
5438 (dolist (dir create-list
)
5439 (files--ensure-directory dir
)))))))
5441 (defconst directory-files-no-dot-files-regexp
5442 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"
5443 "Regexp matching any file name except \".\" and \"..\".")
5445 (defun files--force (no-such fn
&rest args
)
5446 "Use NO-SUCH to affect behavior of function FN applied to list ARGS.
5447 This acts like (apply FN ARGS) except it returns NO-SUCH if it is
5448 non-nil and if FN fails due to a missing file or directory."
5451 (file-missing (or no-such
(signal (car err
) (cdr err
))))))
5453 (defun delete-directory (directory &optional recursive trash
)
5454 "Delete the directory named DIRECTORY. Does not follow symlinks.
5455 If RECURSIVE is non-nil, delete files in DIRECTORY as well, with
5456 no error if something else is simultaneously deleting them.
5457 TRASH non-nil means to trash the directory instead, provided
5458 `delete-by-moving-to-trash' is non-nil.
5460 When called interactively, TRASH is nil if and only if a prefix
5461 argument is given, and a further prompt asks the user for
5462 RECURSIVE if DIRECTORY is nonempty."
5464 (let* ((trashing (and delete-by-moving-to-trash
5465 (null current-prefix-arg
)))
5466 (dir (expand-file-name
5467 (read-directory-name
5469 "Move directory to trash: "
5470 "Delete directory: ")
5471 default-directory default-directory nil nil
))))
5473 (if (directory-files dir nil directory-files-no-dot-files-regexp
)
5475 (format-message "Directory `%s' is not empty, really %s? "
5476 dir
(if trashing
"trash" "delete")))
5478 (null current-prefix-arg
))))
5479 ;; If default-directory is a remote directory, make sure we find its
5480 ;; delete-directory handler.
5481 (setq directory
(directory-file-name (expand-file-name directory
)))
5482 (let ((handler (find-file-name-handler directory
'delete-directory
)))
5485 (funcall handler
'delete-directory directory recursive trash
))
5486 ((and delete-by-moving-to-trash trash
)
5487 ;; Only move non-empty dir to trash if recursive deletion was
5488 ;; requested. This mimics the non-`delete-by-moving-to-trash'
5489 ;; case, where the operation fails in delete-directory-internal.
5490 ;; As `move-file-to-trash' trashes directories (empty or
5491 ;; otherwise) as a unit, we do not need to recurse here.
5492 (if (and (not recursive
)
5493 ;; Check if directory is empty apart from "." and "..".
5495 directory
'full directory-files-no-dot-files-regexp
))
5496 (error "Directory is not empty, not moving to trash")
5497 (move-file-to-trash directory
)))
5498 ;; Otherwise, call ourselves recursively if needed.
5500 (when (or (not recursive
) (file-symlink-p directory
)
5502 (files--force t
#'directory-files directory
'full
5503 directory-files-no-dot-files-regexp
))
5504 (directory-exists (listp files
)))
5505 (when directory-exists
5506 (mapc (lambda (file)
5507 ;; This test is equivalent to but more efficient
5508 ;; than (and (file-directory-p fn)
5509 ;; (not (file-symlink-p fn))).
5510 (if (eq t
(car (file-attributes file
)))
5511 (delete-directory file recursive
)
5512 (files--force t
#'delete-file file
)))
5515 (files--force recursive
#'delete-directory-internal directory
))))))
5517 (defun file-equal-p (file1 file2
)
5518 "Return non-nil if files FILE1 and FILE2 name the same file.
5519 If FILE1 or FILE2 does not exist, the return value is unspecified."
5520 (let ((handler (or (find-file-name-handler file1
'file-equal-p
)
5521 (find-file-name-handler file2
'file-equal-p
))))
5523 (funcall handler
'file-equal-p file1 file2
)
5524 (let (f1-attr f2-attr
)
5525 (and (setq f1-attr
(file-attributes (file-truename file1
)))
5526 (setq f2-attr
(file-attributes (file-truename file2
)))
5527 (equal f1-attr f2-attr
))))))
5529 (defun file-in-directory-p (file dir
)
5530 "Return non-nil if FILE is in DIR or a subdirectory of DIR.
5531 A directory is considered to be \"in\" itself.
5532 Return nil if DIR is not an existing directory."
5533 (let ((handler (or (find-file-name-handler file
'file-in-directory-p
)
5534 (find-file-name-handler dir
'file-in-directory-p
))))
5536 (funcall handler
'file-in-directory-p file dir
)
5537 (when (file-directory-p dir
) ; DIR must exist.
5538 (setq file
(file-truename file
)
5539 dir
(file-truename dir
))
5540 (let ((ls1 (split-string file
"/" t
))
5541 (ls2 (split-string dir
"/" t
))
5544 ;; A UNC on Windows systems, or a "super-root" on Apollo.
5545 ((string-match "\\`//" file
) "//")
5546 ((string-match "\\`/" file
) "/")
5549 (while (and ls1 ls2
(not mismatch
))
5550 (if (string-equal (car ls1
) (car ls2
))
5551 (setq root
(concat root
(car ls1
) "/"))
5556 (file-equal-p root dir
)))))))
5558 (defun copy-directory (directory newname
&optional keep-time parents copy-contents
)
5559 "Copy DIRECTORY to NEWNAME. Both args must be strings.
5560 This function always sets the file modes of the output files to match
5561 the corresponding input file.
5563 The third arg KEEP-TIME non-nil means give the output files the same
5564 last-modified time as the old ones. (This works on only some systems.)
5566 A prefix arg makes KEEP-TIME non-nil.
5568 Noninteractively, the last argument PARENTS says whether to
5569 create parent directories if they don't exist. Interactively,
5570 this happens by default.
5572 If NEWNAME is a directory name, copy DIRECTORY as a subdirectory
5573 there. However, if called from Lisp with a non-nil optional
5574 argument COPY-CONTENTS, copy the contents of DIRECTORY directly
5575 into NEWNAME instead."
5577 (let ((dir (read-directory-name
5578 "Copy directory: " default-directory default-directory t nil
)))
5580 (read-directory-name
5581 (format "Copy directory %s to: " dir
)
5582 default-directory default-directory nil nil
)
5583 current-prefix-arg t nil
)))
5584 (when (file-in-directory-p newname directory
)
5585 (error "Cannot copy `%s' into its subdirectory `%s'"
5587 ;; If default-directory is a remote directory, make sure we find its
5588 ;; copy-directory handler.
5589 (let ((handler (or (find-file-name-handler directory
'copy-directory
)
5590 (find-file-name-handler newname
'copy-directory
))))
5592 (funcall handler
'copy-directory directory
5593 newname keep-time parents copy-contents
)
5595 ;; Compute target name.
5596 (setq directory
(directory-file-name (expand-file-name directory
))
5597 newname
(expand-file-name newname
))
5599 (cond ((not (directory-name-p newname
))
5600 ;; If NEWNAME is not a directory name, create it;
5601 ;; that is where we will copy the files of DIRECTORY.
5602 (make-directory newname parents
))
5603 ;; NEWNAME is a directory name. If COPY-CONTENTS is non-nil,
5604 ;; create NEWNAME if it is not already a directory;
5605 ;; otherwise, create NEWNAME/[DIRECTORY-BASENAME].
5607 (or parents
(not (file-directory-p newname
)))
5608 (setq newname
(concat newname
5609 (file-name-nondirectory directory
))))
5610 (make-directory (directory-file-name newname
) parents
)))
5612 ;; Copy recursively.
5614 ;; We do not want to copy "." and "..".
5615 (directory-files directory
'full
5616 directory-files-no-dot-files-regexp
))
5617 (let ((target (concat (file-name-as-directory newname
)
5618 (file-name-nondirectory file
)))
5619 (filetype (car (file-attributes file
))))
5621 ((eq filetype t
) ; Directory but not a symlink.
5622 (copy-directory file target keep-time parents t
))
5623 ((stringp filetype
) ; Symbolic link
5624 (make-symbolic-link filetype target t
))
5625 ((copy-file file target t keep-time
)))))
5627 ;; Set directory attributes.
5628 (let ((modes (file-modes directory
))
5629 (times (and keep-time
(nth 5 (file-attributes directory
)))))
5630 (if modes
(set-file-modes newname modes
))
5631 (if times
(set-file-times newname times
))))))
5634 ;; At time of writing, only info uses this.
5635 (defun prune-directory-list (dirs &optional keep reject
)
5636 "Return a copy of DIRS with all non-existent directories removed.
5637 The optional argument KEEP is a list of directories to retain even if
5638 they don't exist, and REJECT is a list of directories to remove from
5639 DIRS, even if they exist; REJECT takes precedence over KEEP.
5641 Note that membership in REJECT and KEEP is checked using simple string
5644 (mapcar (lambda (dir)
5645 (and (not (member dir reject
))
5646 (or (member dir keep
) (file-directory-p dir
))
5651 (put 'revert-buffer-function
'permanent-local t
)
5652 (defvar revert-buffer-function
#'revert-buffer--default
5653 "Function to use to revert this buffer.
5654 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
5655 which are the arguments that `revert-buffer' received.
5656 It also has access to the `preserve-modes' argument of `revert-buffer'
5657 via the `revert-buffer-preserve-modes' dynamic variable.
5659 For historical reasons, a value of nil means to use the default function.
5660 This should not be relied upon.")
5662 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
5663 (defvar revert-buffer-insert-file-contents-function
5664 #'revert-buffer-insert-file-contents--default-function
5665 "Function to use to insert contents when reverting this buffer.
5666 The function receives two arguments: the first the nominal file name to use;
5667 the second is t if reading the auto-save file.
5669 The function is responsible for updating (or preserving) point.
5671 For historical reasons, a value of nil means to use the default function.
5672 This should not be relied upon.")
5674 (defun buffer-stale--default-function (&optional _noconfirm
)
5675 "Default function to use for `buffer-stale-function'.
5676 This function ignores its argument.
5677 This returns non-nil if the current buffer is visiting a readable file
5678 whose modification time does not match that of the buffer.
5680 This function only handles buffers that are visiting files.
5681 Non-file buffers need a custom function"
5682 (and buffer-file-name
5683 (file-readable-p buffer-file-name
)
5684 (not (buffer-modified-p (current-buffer)))
5685 (not (verify-visited-file-modtime (current-buffer)))))
5687 (defvar buffer-stale-function
#'buffer-stale--default-function
5688 "Function to check whether a buffer needs reverting.
5689 This should be a function with one optional argument NOCONFIRM.
5690 Auto Revert Mode passes t for NOCONFIRM. The function should return
5691 non-nil if the buffer should be reverted. A return value of
5692 `fast' means that the need for reverting was not checked, but
5693 that reverting the buffer is fast. The buffer is current when
5694 this function is called.
5696 The idea behind the NOCONFIRM argument is that it should be
5697 non-nil if the buffer is going to be reverted without asking the
5698 user. In such situations, one has to be careful with potentially
5699 time consuming operations.
5701 For historical reasons, a value of nil means to use the default function.
5702 This should not be relied upon.
5704 For more information on how this variable is used by Auto Revert mode,
5705 see Info node `(emacs)Supporting additional buffers'.")
5707 (defvar before-revert-hook nil
5708 "Normal hook for `revert-buffer' to run before reverting.
5709 The function `revert-buffer--default' runs this.
5710 A customized `revert-buffer-function' need not run this hook.")
5712 (defvar after-revert-hook nil
5713 "Normal hook for `revert-buffer' to run after reverting.
5714 Note that the hook value that it runs is the value that was in effect
5715 before reverting; that makes a difference if you have buffer-local
5718 The function `revert-buffer--default' runs this.
5719 A customized `revert-buffer-function' need not run this hook.")
5721 (defvar revert-buffer-in-progress-p nil
5722 "Non-nil if a `revert-buffer' operation is in progress, nil otherwise.")
5724 (defvar revert-buffer-internal-hook
)
5726 ;; `revert-buffer-function' was defined long ago to be a function of only
5727 ;; 2 arguments, so we have to use a dynbind variable to pass the
5728 ;; `preserve-modes' argument of `revert-buffer'.
5729 (defvar revert-buffer-preserve-modes
)
5731 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes
)
5732 "Replace current buffer text with the text of the visited file on disk.
5733 This undoes all changes since the file was visited or saved.
5734 With a prefix argument, offer to revert from latest auto-save file, if
5735 that is more recent than the visited file.
5737 This command also implements an interface for special buffers
5738 that contain text which doesn't come from a file, but reflects
5739 some other data instead (e.g. Dired buffers, `buffer-list'
5740 buffers). This is done via the variable `revert-buffer-function'.
5741 In these cases, it should reconstruct the buffer contents from the
5744 When called from Lisp, the first argument is IGNORE-AUTO; only offer
5745 to revert from the auto-save file when this is nil. Note that the
5746 sense of this argument is the reverse of the prefix argument, for the
5747 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
5750 Optional second argument NOCONFIRM means don't ask for confirmation
5751 at all. (The variable `revert-without-query' offers another way to
5752 revert buffers without querying for confirmation.)
5754 Optional third argument PRESERVE-MODES non-nil means don't alter
5755 the files modes. Normally we reinitialize them using `normal-mode'.
5757 This function binds `revert-buffer-in-progress-p' non-nil while it operates.
5759 This function calls the function that `revert-buffer-function' specifies
5760 to do the work, with arguments IGNORE-AUTO and NOCONFIRM.
5761 The default function runs the hooks `before-revert-hook' and
5762 `after-revert-hook'."
5763 ;; I admit it's odd to reverse the sense of the prefix argument, but
5764 ;; there is a lot of code out there which assumes that the first
5765 ;; argument should be t to avoid consulting the auto-save file, and
5766 ;; there's no straightforward way to encourage authors to notice a
5767 ;; reversal of the argument sense. So I'm just changing the user
5768 ;; interface, but leaving the programmatic interface the same.
5769 (interactive (list (not current-prefix-arg
)))
5770 (let ((revert-buffer-in-progress-p t
)
5771 (revert-buffer-preserve-modes preserve-modes
))
5772 (funcall (or revert-buffer-function
#'revert-buffer--default
)
5773 ignore-auto noconfirm
)))
5775 (defun revert-buffer--default (ignore-auto noconfirm
)
5776 "Default function for `revert-buffer'.
5777 The arguments IGNORE-AUTO and NOCONFIRM are as described for `revert-buffer'.
5778 Runs the hooks `before-revert-hook' and `after-revert-hook' at the
5781 Calls `revert-buffer-insert-file-contents-function' to reread the
5782 contents of the visited file, with two arguments: the first is the file
5783 name, the second is non-nil if reading an auto-save file.
5785 This function only handles buffers that are visiting files.
5786 Non-file buffers need a custom function."
5787 (with-current-buffer (or (buffer-base-buffer (current-buffer))
5789 (let* ((auto-save-p (and (not ignore-auto
)
5790 (recent-auto-save-p)
5791 buffer-auto-save-file-name
5792 (file-readable-p buffer-auto-save-file-name
)
5794 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
5795 (file-name (if auto-save-p
5796 buffer-auto-save-file-name
5798 (cond ((null file-name
)
5799 (error "Buffer does not seem to be associated with any file"))
5801 (and (not (buffer-modified-p))
5803 (dolist (regexp revert-without-query
)
5804 (when (string-match regexp file-name
)
5805 (throw 'found t
)))))
5806 (yes-or-no-p (format "Revert buffer from file %s? "
5808 (run-hooks 'before-revert-hook
)
5809 ;; If file was backed up but has changed since,
5810 ;; we should make another backup.
5811 (and (not auto-save-p
)
5812 (not (verify-visited-file-modtime (current-buffer)))
5813 (setq buffer-backed-up nil
))
5814 ;; Effectively copy the after-revert-hook status,
5815 ;; since after-find-file will clobber it.
5816 (let ((global-hook (default-value 'after-revert-hook
))
5817 (local-hook (when (local-variable-p 'after-revert-hook
)
5819 (inhibit-read-only t
))
5820 ;; FIXME: Throw away undo-log when preserve-modes is nil?
5822 (or revert-buffer-insert-file-contents-function
5823 #'revert-buffer-insert-file-contents--default-function
)
5824 file-name auto-save-p
)
5825 ;; Recompute the truename in case changes in symlinks
5826 ;; have changed the truename.
5827 (setq buffer-file-truename
5828 (abbreviate-file-name (file-truename buffer-file-name
)))
5829 (after-find-file nil nil t nil revert-buffer-preserve-modes
)
5830 ;; Run after-revert-hook as it was before we reverted.
5831 (setq-default revert-buffer-internal-hook global-hook
)
5833 (set (make-local-variable 'revert-buffer-internal-hook
)
5835 (kill-local-variable 'revert-buffer-internal-hook
))
5836 (run-hooks 'revert-buffer-internal-hook
))
5839 (defun revert-buffer-insert-file-contents--default-function (file-name auto-save-p
)
5840 "Default function for `revert-buffer-insert-file-contents-function'.
5841 The function `revert-buffer--default' calls this.
5842 FILE-NAME is the name of the file. AUTO-SAVE-P is non-nil if this is
5845 ((not (file-exists-p file-name
))
5846 (error (if buffer-file-number
5847 "File %s no longer exists!"
5848 "Cannot revert nonexistent file %s")
5850 ((not (file-readable-p file-name
))
5851 (error (if buffer-file-number
5852 "File %s no longer readable!"
5853 "Cannot revert unreadable file %s")
5856 ;; Bind buffer-file-name to nil
5857 ;; so that we don't try to lock the file.
5858 (let ((buffer-file-name nil
))
5862 (let ((coding-system-for-read
5863 ;; Auto-saved file should be read by Emacs's
5865 (if auto-save-p
'auto-save-coding
5866 (or coding-system-for-read
5868 buffer-file-coding-system-explicit
5869 (car buffer-file-coding-system-explicit
))))))
5870 (if (and (not enable-multibyte-characters
)
5871 coding-system-for-read
5872 (not (memq (coding-system-base
5873 coding-system-for-read
)
5874 '(no-conversion raw-text
))))
5875 ;; As a coding system suitable for multibyte
5876 ;; buffer is specified, make the current
5877 ;; buffer multibyte.
5878 (set-buffer-multibyte t
))
5880 ;; This force after-insert-file-set-coding
5881 ;; (called from insert-file-contents) to set
5882 ;; buffer-file-coding-system to a proper value.
5883 (kill-local-variable 'buffer-file-coding-system
)
5885 ;; Note that this preserves point in an intelligent way.
5886 (if revert-buffer-preserve-modes
5887 (let ((buffer-file-format buffer-file-format
))
5888 (insert-file-contents file-name
(not auto-save-p
)
5890 (insert-file-contents file-name
(not auto-save-p
)
5893 (defun recover-this-file ()
5894 "Recover the visited file--get contents from its last auto-save file."
5896 (or buffer-file-name
5897 (user-error "This buffer is not visiting a file"))
5898 (recover-file buffer-file-name
))
5900 (defun recover-file (file)
5901 "Visit file FILE, but get contents from its last auto-save file."
5902 ;; Actually putting the file name in the minibuffer should be used
5904 ;; Not just because users often use the default.
5905 (interactive "FRecover file: ")
5906 (setq file
(expand-file-name file
))
5907 (if (auto-save-file-name-p (file-name-nondirectory file
))
5908 (error "%s is an auto-save file" (abbreviate-file-name file
)))
5909 (let ((file-name (let ((buffer-file-name file
))
5910 (make-auto-save-file-name))))
5911 (cond ((and (file-exists-p file
)
5912 (not (file-exists-p file-name
)))
5913 (error "Auto save file %s does not exist"
5914 (abbreviate-file-name file-name
)))
5915 ((if (file-exists-p file
)
5916 (not (file-newer-than-file-p file-name file
))
5917 (not (file-exists-p file-name
)))
5918 (error "Auto-save file %s not current"
5919 (abbreviate-file-name file-name
)))
5920 ((with-temp-buffer-window
5922 #'(lambda (window _value
)
5923 (with-selected-window window
5925 (yes-or-no-p (format "Recover auto save file %s? " file-name
))
5926 (when (window-live-p window
)
5927 (quit-restore-window window
'kill
)))))
5928 (with-current-buffer standard-output
5929 (let ((switches dired-listing-switches
))
5930 (if (file-symlink-p file
)
5931 (setq switches
(concat switches
" -L")))
5932 ;; Use insert-directory-safely, not insert-directory,
5933 ;; because these files might not exist. In particular,
5934 ;; FILE might not exist if the auto-save file was for
5935 ;; a buffer that didn't visit a file, such as "*mail*".
5936 ;; The code in v20.x called `ls' directly, so we need
5937 ;; to emulate what `ls' did in that case.
5938 (insert-directory-safely file switches
)
5939 (insert-directory-safely file-name switches
))))
5940 (switch-to-buffer (find-file-noselect file t
))
5941 (let ((inhibit-read-only t
)
5942 ;; Keep the current buffer-file-coding-system.
5943 (coding-system buffer-file-coding-system
)
5944 ;; Auto-saved file should be read with special coding.
5945 (coding-system-for-read 'auto-save-coding
))
5947 (insert-file-contents file-name nil
)
5948 (set-buffer-file-coding-system coding-system
))
5949 (after-find-file nil nil t
))
5950 (t (user-error "Recover-file canceled")))))
5952 (defun recover-session ()
5953 "Recover auto save files from a previous Emacs session.
5954 This command first displays a Dired buffer showing you the
5955 previous sessions that you could recover from.
5956 To choose one, move point to the proper line and then type C-c C-c.
5957 Then you'll be asked about a number of files to recover."
5959 (if (null auto-save-list-file-prefix
)
5960 (error "You set `auto-save-list-file-prefix' to disable making session files"))
5961 (let ((dir (file-name-directory auto-save-list-file-prefix
))
5962 (nd (file-name-nondirectory auto-save-list-file-prefix
)))
5963 (unless (file-directory-p dir
)
5964 (make-directory dir t
))
5965 (unless (directory-files dir nil
5967 directory-files-no-dot-files-regexp
5968 (concat "\\`" (regexp-quote nd
)))
5970 (error "No previous sessions to recover")))
5971 (let ((ls-lisp-support-shell-wildcards t
))
5972 (dired (concat auto-save-list-file-prefix
"*")
5973 (concat dired-listing-switches
" -t")))
5974 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
5975 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish
)
5977 (goto-char (point-min))
5978 (or (looking-at " Move to the session you want to recover,")
5979 (let ((inhibit-read-only t
))
5980 ;; Each line starts with a space
5981 ;; so that Font Lock mode won't highlight the first character.
5982 (insert " To recover a session, move to it and type C-c C-c.\n"
5983 (substitute-command-keys
5984 " To delete a session file, type \
5985 \\[dired-flag-file-deletion] on its line to flag
5986 the file for deletion, then \\[dired-do-flagged-delete] to \
5987 delete flagged files.\n\n"))))))
5989 (defun recover-session-finish ()
5990 "Choose one saved session to recover auto-save files from.
5991 This command is used in the special Dired buffer created by
5992 \\[recover-session]."
5994 ;; Get the name of the session file to recover from.
5995 (let ((file (dired-get-filename))
5997 (buffer (get-buffer-create " *recover*")))
5999 (dired-do-flagged-delete t
)
6001 (with-current-buffer buffer
6002 ;; Read in the auto-save-list file.
6004 (insert-file-contents file
)
6005 ;; Loop thru the text of that file
6006 ;; and get out the names of the files to recover.
6008 (let (thisfile autofile
)
6010 ;; This is a pair of lines for a non-file-visiting buffer.
6011 ;; Get the auto-save file name and manufacture
6012 ;; a "visited file name" from that.
6015 ;; If there is no auto-save file name, the
6016 ;; auto-save-list file is probably corrupted.
6019 (buffer-substring-no-properties
6021 (line-end-position)))
6025 (file-name-nondirectory autofile
)
6027 (file-name-directory autofile
))))
6029 ;; This pair of lines is a file-visiting
6030 ;; buffer. Use the visited file name.
6033 (buffer-substring-no-properties
6034 (point) (progn (end-of-line) (point))))
6037 (buffer-substring-no-properties
6038 (point) (progn (end-of-line) (point))))
6040 ;; Ignore a file if its auto-save file does not exist now.
6041 (if (and autofile
(file-exists-p autofile
))
6042 (setq files
(cons thisfile files
)))))
6043 (setq files
(nreverse files
))
6044 ;; The file contains a pair of line for each auto-saved buffer.
6045 ;; The first line of the pair contains the visited file name
6046 ;; or is empty if the buffer was not visiting a file.
6047 ;; The second line is the auto-save file name.
6049 (map-y-or-n-p "Recover %s? "
6052 (save-excursion (recover-file file
))
6054 "Failed to recover `%s'" file
)))
6056 '("file" "files" "recover"))
6057 (message "No files can be recovered from this session now")))
6058 (kill-buffer buffer
))))
6060 (defun kill-buffer-ask (buffer)
6061 "Kill BUFFER if confirmed."
6062 (when (yes-or-no-p (format "Buffer %s %s. Kill? "
6063 (buffer-name buffer
)
6064 (if (buffer-modified-p buffer
)
6065 "HAS BEEN EDITED" "is unmodified")))
6066 (kill-buffer buffer
)))
6068 (defun kill-some-buffers (&optional list
)
6069 "Kill some buffers. Asks the user whether to kill each one of them.
6070 Non-interactively, if optional argument LIST is non-nil, it
6071 specifies the list of buffers to kill, asking for approval for each one."
6074 (setq list
(buffer-list)))
6076 (let* ((buffer (car list
))
6077 (name (buffer-name buffer
)))
6078 (and name
; Can be nil for an indirect buffer
6079 ; if we killed the base buffer.
6080 (not (string-equal name
""))
6081 (/= (aref name
0) ?\s
)
6082 (kill-buffer-ask buffer
)))
6083 (setq list
(cdr list
))))
6085 (defun kill-matching-buffers (regexp &optional internal-too no-ask
)
6086 "Kill buffers whose name matches the specified REGEXP.
6087 Ignores buffers whose name starts with a space, unless optional
6088 prefix argument INTERNAL-TOO is non-nil. Asks before killing
6089 each buffer, unless NO-ASK is non-nil."
6090 (interactive "sKill buffers matching this regular expression: \nP")
6091 (dolist (buffer (buffer-list))
6092 (let ((name (buffer-name buffer
)))
6093 (when (and name
(not (string-equal name
""))
6094 (or internal-too
(/= (aref name
0) ?\s
))
6095 (string-match regexp name
))
6096 (funcall (if no-ask
'kill-buffer
'kill-buffer-ask
) buffer
)))))
6099 (defun rename-auto-save-file ()
6100 "Adjust current buffer's auto save file name for current conditions.
6101 Also rename any existing auto save file, if it was made in this session."
6102 (let ((osave buffer-auto-save-file-name
))
6103 (setq buffer-auto-save-file-name
6104 (make-auto-save-file-name))
6105 (if (and osave buffer-auto-save-file-name
6106 (not (string= buffer-auto-save-file-name buffer-file-name
))
6107 (not (string= buffer-auto-save-file-name osave
))
6108 (file-exists-p osave
)
6109 (recent-auto-save-p))
6110 (rename-file osave buffer-auto-save-file-name t
))))
6112 (defun make-auto-save-file-name ()
6113 "Return file name to use for auto-saves of current buffer.
6114 Does not consider `auto-save-visited-file-name' as that variable is checked
6115 before calling this function. You can redefine this for customization.
6116 See also `auto-save-file-name-p'."
6117 (if buffer-file-name
6118 (let ((handler (find-file-name-handler buffer-file-name
6119 'make-auto-save-file-name
)))
6121 (funcall handler
'make-auto-save-file-name
)
6122 (let ((list auto-save-file-name-transforms
)
6123 (filename buffer-file-name
)
6125 ;; Apply user-specified translations
6126 ;; to the file name.
6127 (while (and list
(not result
))
6128 (if (string-match (car (car list
)) filename
)
6129 (setq result
(replace-match (cadr (car list
)) t nil
6131 uniq
(car (cddr (car list
)))))
6132 (setq list
(cdr list
)))
6135 (setq filename
(concat
6136 (file-name-directory result
)
6137 (subst-char-in-string
6139 (replace-regexp-in-string "!" "!!"
6141 (setq filename result
)))
6143 (if (and (eq system-type
'ms-dos
)
6144 (not (msdos-long-file-names)))
6145 ;; We truncate the file name to DOS 8+3 limits
6146 ;; before doing anything else, because the regexp
6147 ;; passed to string-match below cannot handle
6148 ;; extensions longer than 3 characters, multiple
6149 ;; dots, and other atrocities.
6150 (let ((fn (dos-8+3-filename
6151 (file-name-nondirectory buffer-file-name
))))
6153 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
6155 (concat (file-name-directory buffer-file-name
)
6156 "#" (match-string 1 fn
)
6157 "." (match-string 3 fn
) "#"))
6158 (concat (file-name-directory filename
)
6160 (file-name-nondirectory filename
)
6162 ;; Make sure auto-save file names don't contain characters
6163 ;; invalid for the underlying filesystem.
6164 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
6165 ;; Don't modify remote filenames
6166 (not (file-remote-p result
)))
6167 (convert-standard-filename result
)
6170 ;; Deal with buffers that don't have any associated files. (Mail
6171 ;; mode tends to create a good number of these.)
6173 (let ((buffer-name (buffer-name))
6176 ;; Restrict the characters used in the file name to those which
6177 ;; are known to be safe on all filesystems, url-encoding the
6179 ;; We do this on all platforms, because even if we are not
6180 ;; running on DOS/Windows, the current directory may be on a
6181 ;; mounted VFAT filesystem, such as a USB memory stick.
6182 (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit
)
6183 (let* ((character (aref buffer-name
(match-beginning 0)))
6185 ;; For multibyte characters, this will produce more than
6186 ;; 2 hex digits, so is not true URL encoding.
6187 (format "%%%02X" character
)))
6188 (setq buffer-name
(replace-match replacement t t buffer-name
))
6189 (setq limit
(1+ (match-end 0)))))
6190 ;; Generate the file name.
6195 (format "#%s#" buffer-name
)
6196 ;; Try a few alternative directories, to get one we can
6199 ((file-writable-p default-directory
) default-directory
)
6200 ((file-writable-p "/var/tmp/") "/var/tmp/")
6202 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
6203 ;; Don't modify remote filenames
6204 (not (file-remote-p fname
)))
6205 ;; The call to convert-standard-filename is in case
6206 ;; buffer-name includes characters not allowed by the
6207 ;; DOS/Windows filesystems. make-temp-file writes to the
6208 ;; file it creates, so we must fix the file name _before_
6209 ;; make-temp-file is called.
6210 (convert-standard-filename fname
)
6213 ;; make-temp-file creates the file,
6214 ;; but we don't want it to exist until we do an auto-save.
6216 (delete-file file-name
)
6220 (defun auto-save-file-name-p (filename)
6221 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
6222 FILENAME should lack slashes. You can redefine this for customization."
6223 (string-match "\\`#.*#\\'" filename
))
6225 (defun wildcard-to-regexp (wildcard)
6226 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
6227 The generated regexp will match a filename only if the filename
6228 matches that wildcard according to shell rules. Only wildcards known
6229 by `sh' are supported."
6230 (let* ((i (string-match "[[.*+\\^$?]" wildcard
))
6231 ;; Copy the initial run of non-special characters.
6232 (result (substring wildcard
0 i
))
6233 (len (length wildcard
)))
6234 ;; If no special characters, we're almost done.
6237 (let ((ch (aref wildcard i
))
6245 (eq (aref wildcard
(1+ i
)) ?\
]))
6247 ((eq ch ?\
[) ; [...] maps to regexp char class
6252 ((eq (aref wildcard i
) ?
!) ; [!...] -> [^...]
6255 (if (eq (aref wildcard i
) ?\
])
6260 ((eq (aref wildcard i
) ?^
)
6261 ;; Found "[^". Insert a `\0' character
6262 ;; (which cannot happen in a filename)
6263 ;; into the character class, so that `^'
6264 ;; is not the first character after `[',
6265 ;; and thus non-special in a regexp.
6269 ((eq (aref wildcard i
) ?\
])
6270 ;; I don't think `]' can appear in a
6271 ;; character class in a wildcard, but
6272 ;; let's be general here.
6277 (prog1 ; copy everything upto next `]'.
6280 (setq j
(string-match
6282 (setq i
(if j
(1- j
) (1- len
)))))))
6284 ((eq ch ?
*) "[^\000]*")
6288 ((eq ch ?
\\) "\\\\") ; probably cannot happen...
6289 ((eq ch ??
) "[^\000]")
6290 (t (char-to-string ch
)))))
6292 ;; Shell wildcards should match the entire filename,
6293 ;; not its part. Make the regexp say so.
6294 (concat "\\`" result
"\\'")))
6296 (defcustom list-directory-brief-switches
6298 "Switches for `list-directory' to pass to `ls' for brief listing."
6302 (defcustom list-directory-verbose-switches
6304 "Switches for `list-directory' to pass to `ls' for verbose listing."
6308 (defun file-expand-wildcards (pattern &optional full
)
6309 "Expand wildcard pattern PATTERN.
6310 This returns a list of file names which match the pattern.
6311 Files are sorted in `string<' order.
6313 If PATTERN is written as an absolute file name,
6314 the values are absolute also.
6316 If PATTERN is written as a relative file name, it is interpreted
6317 relative to the current default directory, `default-directory'.
6318 The file names returned are normally also relative to the current
6319 default directory. However, if FULL is non-nil, they are absolute."
6321 (let* ((nondir (file-name-nondirectory pattern
))
6322 (dirpart (file-name-directory pattern
))
6323 ;; A list of all dirs that DIRPART specifies.
6324 ;; This can be more than one dir
6325 ;; if DIRPART contains wildcards.
6326 (dirs (if (and dirpart
6327 (string-match "[[*?]" (file-local-name dirpart
)))
6328 (mapcar 'file-name-as-directory
6329 (file-expand-wildcards (directory-file-name dirpart
)))
6333 (when (or (null dir
) ; Possible if DIRPART is not wild.
6334 (file-accessible-directory-p dir
))
6335 (let ((this-dir-contents
6336 ;; Filter out "." and ".."
6338 (mapcar #'(lambda (name)
6339 (unless (string-match "\\`\\.\\.?\\'"
6340 (file-name-nondirectory name
))
6342 (directory-files (or dir
".") full
6343 (wildcard-to-regexp nondir
))))))
6346 (if (and dir
(not full
))
6347 (mapcar #'(lambda (name) (concat dir name
))
6353 ;; Let Tramp know that `file-expand-wildcards' does not need an advice.
6354 (provide 'files
'(remote-wildcards))
6356 (defun list-directory (dirname &optional verbose
)
6357 "Display a list of files in or matching DIRNAME, a la `ls'.
6358 DIRNAME is globbed by the shell if necessary.
6359 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
6360 Actions controlled by variables `list-directory-brief-switches'
6361 and `list-directory-verbose-switches'."
6362 (interactive (let ((pfx current-prefix-arg
))
6363 (list (read-directory-name (if pfx
"List directory (verbose): "
6364 "List directory (brief): ")
6365 nil default-directory nil
)
6367 (let ((switches (if verbose list-directory-verbose-switches
6368 list-directory-brief-switches
))
6370 (or dirname
(setq dirname default-directory
))
6371 (setq dirname
(expand-file-name dirname
))
6372 (with-output-to-temp-buffer "*Directory*"
6373 (setq buffer standard-output
)
6374 (buffer-disable-undo standard-output
)
6375 (princ "Directory ")
6378 (with-current-buffer "*Directory*"
6379 (let ((wildcard (not (file-directory-p dirname
))))
6380 (insert-directory dirname switches wildcard
(not wildcard
)))))
6381 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
6382 (with-current-buffer buffer
6383 (setq default-directory
6384 (if (file-directory-p dirname
)
6385 (file-name-as-directory dirname
)
6386 (file-name-directory dirname
))))))
6388 (defun shell-quote-wildcard-pattern (pattern)
6389 "Quote characters special to the shell in PATTERN, leave wildcards alone.
6391 PATTERN is assumed to represent a file-name wildcard suitable for the
6392 underlying filesystem. For Unix and GNU/Linux, each character from the
6393 set [ \\t\\n;<>&|()\\=`\\='\"#$] is quoted with a backslash; for DOS/Windows, all
6394 the parts of the pattern which don't include wildcard characters are
6395 quoted with double quotes.
6397 This function leaves alone existing quote characters (\\ on Unix and \"
6398 on Windows), so PATTERN can use them to quote wildcard characters that
6399 need to be passed verbatim to shell commands."
6402 ((memq system-type
'(ms-dos windows-nt cygwin
))
6403 ;; DOS/Windows don't allow `"' in file names. So if the
6404 ;; argument has quotes, we can safely assume it is already
6405 ;; quoted by the caller.
6406 (if (or (string-match "[\"]" pattern
)
6407 ;; We quote [&()#$`'] in case their shell is a port of a
6408 ;; Unixy shell. We quote [,=+] because stock DOS and
6409 ;; Windows shells require that in some cases, such as
6410 ;; passing arguments to batch files that use positional
6411 ;; arguments like %1.
6412 (not (string-match "[ \t;&()#$`',=+]" pattern
)))
6417 (while (string-match "[*?]+" pattern beg
)
6418 (setq end
(match-beginning 0)
6419 result
(concat result
(substring pattern beg end
)
6421 (substring pattern end
(match-end 0))
6424 (concat result
(substring pattern beg
) "\""))))
6427 (while (string-match "[ \t\n;<>&|()`'\"#$]" pattern beg
)
6429 (concat (substring pattern
0 (match-beginning 0))
6431 (substring pattern
(match-beginning 0)))
6432 beg
(1+ (match-end 0)))))
6436 (defvar insert-directory-program
(purecopy "ls")
6437 "Absolute or relative name of the `ls' program used by `insert-directory'.")
6439 (defcustom directory-free-space-program
(purecopy "df")
6440 "Program to get the amount of free space on a file system.
6441 We assume the output has the format of `df'.
6442 The value of this variable must be just a command name or file name;
6443 if you want to specify options, use `directory-free-space-args'.
6445 A value of nil disables this feature.
6447 This variable is obsolete; Emacs no longer uses it."
6448 :type
'(choice (string :tag
"Program") (const :tag
"None" nil
))
6450 (make-obsolete-variable 'directory-free-space-program
6451 "ignored, as Emacs uses `file-system-info' instead"
6454 (defcustom directory-free-space-args
6455 (purecopy (if (eq system-type
'darwin
) "-k" "-Pk"))
6456 "Options to use when running `directory-free-space-program'."
6459 (make-obsolete-variable 'directory-free-space-args
6460 "ignored, as Emacs uses `file-system-info' instead"
6463 (defun get-free-disk-space (dir)
6464 "Return the amount of free space on directory DIR's file system.
6465 The return value is a string describing the amount of free
6466 space (normally, the number of free 1KB blocks).
6468 If DIR's free space cannot be obtained, this function returns nil."
6470 (let ((avail (nth 2 (file-system-info dir
))))
6472 (format "%.0f" (/ avail
1024))))))
6474 ;; The following expression replaces `dired-move-to-filename-regexp'.
6475 (defvar directory-listing-before-filename-regexp
6476 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
6477 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
6478 ;; In some locales, month abbreviations are as short as 2 letters,
6479 ;; and they can be followed by ".".
6480 ;; In Breton, a month name can include a quote character.
6481 (month (concat l-or-quote l-or-quote
"+\\.?"))
6483 (yyyy "[0-9][0-9][0-9][0-9]")
6485 (HH:MM
"[ 0-2][0-9][:.][0-5][0-9]")
6486 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
6487 (zone "[-+][0-2][0-9][0-5][0-9]")
6488 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
6489 (iso-time (concat HH
:MM
"\\(:" seconds
"\\( ?" zone
"\\)?\\)?"))
6490 (iso (concat "\\(\\(" yyyy
"-\\)?" iso-mm-dd
"[ T]" iso-time
6491 "\\|" yyyy
"-" iso-mm-dd
"\\)"))
6492 (western (concat "\\(" month s
"+" dd
"\\|" dd
"\\.?" s month
"\\)"
6494 "\\(" HH
:MM
"\\|" yyyy
"\\)"))
6495 (western-comma (concat month s
"+" dd
"," s
"+" yyyy
))
6496 ;; Japanese MS-Windows ls-lisp has one-digit months, and
6497 ;; omits the Kanji characters after month and day-of-month.
6498 ;; On Mac OS X 10.3, the date format in East Asian locales is
6499 ;; day-of-month digits followed by month digits.
6502 (concat "\\(" mm l
"?" s dd l
"?" s
"+"
6503 "\\|" dd s mm s
"+" "\\)"
6504 "\\(" HH
:MM
"\\|" yyyy l
"?" "\\)")))
6505 ;; The "[0-9]" below requires the previous column to end in a digit.
6506 ;; This avoids recognizing `1 may 1997' as a date in the line:
6507 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
6509 ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
6511 ;; For non-iso date formats, we add the ".*" in order to find
6512 ;; the last possible match. This avoids recognizing
6513 ;; `jservice 10 1024' as a date in the line:
6514 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
6516 ;; vc dired listings provide the state or blanks between file
6517 ;; permissions and date. The state is always surrounded by
6519 ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
6520 ;; This is not supported yet.
6521 (purecopy (concat "\\([0-9][BkKMGTPEZY]? " iso
6522 "\\|.*[0-9][BkKMGTPEZY]? "
6523 "\\(" western
"\\|" western-comma
"\\|" east-asian
"\\)"
6525 "Regular expression to match up to the file name in a directory listing.
6526 The default value is designed to recognize dates and times
6527 regardless of the language.")
6529 (defvar insert-directory-ls-version
'unknown
)
6531 (defun insert-directory-wildcard-in-dir-p (dir)
6532 "Return non-nil if DIR contents a shell wildcard in the directory part.
6533 The return value is a cons (DIR . WILDCARDS); DIR is the
6534 `default-directory' in the Dired buffer, and WILDCARDS are the wildcards.
6536 Valid wildcards are '*', '?', '[abc]' and '[a-z]'."
6537 (let ((wildcards "[?*"))
6538 (when (and (or (not (featurep 'ls-lisp
))
6539 ls-lisp-support-shell-wildcards
)
6540 (string-match (concat "[" wildcards
"]") (file-name-directory dir
))
6541 (not (file-exists-p dir
))) ; Prefer an existing file to wildcards.
6542 (let ((regexp (format "\\`\\([^%s]*/\\)\\([^%s]*[%s].*\\)"
6543 wildcards wildcards wildcards
)))
6544 (string-match regexp dir
)
6545 (cons (match-string 1 dir
) (match-string 2 dir
))))))
6547 (defun insert-directory-clean (beg switches
)
6548 (when (if (stringp switches
)
6549 (string-match "--dired\\>" switches
)
6550 (member "--dired" switches
))
6551 ;; The following overshoots by one line for an empty
6552 ;; directory listed with "--dired", but without "-a"
6553 ;; switch, where the ls output contains a
6554 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
6555 ;; We take care of that case later.
6557 (when (looking-at "//SUBDIRED//")
6558 (delete-region (point) (progn (forward-line 1) (point)))
6560 (if (looking-at "//DIRED//")
6561 (let ((end (line-end-position))
6564 ;; Find all the lines that are error messages,
6565 ;; and record the bounds of each one.
6567 (while (< (point) linebeg
)
6568 (or (eql (following-char) ?\s
)
6569 (push (list (point) (line-end-position)) error-lines
))
6571 (setq error-lines
(nreverse error-lines
))
6572 ;; Now read the numeric positions of file names.
6574 (forward-word-strictly 1)
6576 (while (< (point) end
)
6577 (let ((start (insert-directory-adj-pos
6578 (+ beg
(read (current-buffer)))
6580 (end (insert-directory-adj-pos
6581 (+ beg
(read (current-buffer)))
6583 (if (memq (char-after end
) '(?
\n ?\s
))
6584 ;; End is followed by \n or by " -> ".
6585 (put-text-property start end
'dired-filename t
)
6586 ;; It seems that we can't trust ls's output as to
6587 ;; byte positions of filenames.
6588 (put-text-property beg
(point) 'dired-filename nil
)
6592 (delete-region (point) (progn (forward-line 1) (point))))
6593 ;; Take care of the case where the ls output contains a
6594 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
6595 ;; and we went one line too far back (see above).
6597 (if (looking-at "//DIRED-OPTIONS//")
6598 (delete-region (point) (progn (forward-line 1) (point))))))
6601 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
6602 ;; FULL-DIRECTORY-P is nil.
6603 ;; The single line of output must display FILE's name as it was
6604 ;; given, namely, an absolute path name.
6605 ;; - must insert exactly one line for each file if WILDCARD or
6606 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
6607 ;; before the file lines, plus optional text after the file lines.
6608 ;; Lines are delimited by "\n", so filenames containing "\n" are not
6610 ;; File lines should display the basename.
6611 ;; - must be consistent with
6612 ;; - functions dired-move-to-filename, (these two define what a file line is)
6613 ;; dired-move-to-end-of-filename,
6614 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
6615 ;; dired-insert-headerline
6616 ;; dired-after-subdir-garbage (defines what a "total" line is)
6617 ;; - variable dired-subdir-regexp
6618 ;; - may be passed "--dired" as the first argument in SWITCHES.
6619 ;; Filename handlers might have to remove this switch if their
6620 ;; "ls" command does not support it.
6621 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
6622 "Insert directory listing for FILE, formatted according to SWITCHES.
6623 Leaves point after the inserted text.
6624 SWITCHES may be a string of options, or a list of strings
6625 representing individual options.
6626 Optional third arg WILDCARD means treat FILE as shell wildcard.
6627 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
6628 switches do not contain `d', so that a full listing is expected.
6630 This works by running a directory listing program
6631 whose name is in the variable `insert-directory-program'.
6632 If WILDCARD, it also runs the shell specified by `shell-file-name'.
6634 When SWITCHES contains the long `--dired' option, this function
6635 treats it specially, for the sake of dired. However, the
6636 normally equivalent short `-D' option is just passed on to
6637 `insert-directory-program', as any other option."
6638 ;; We need the directory in order to find the right handler.
6639 (let ((handler (find-file-name-handler (expand-file-name file
)
6640 'insert-directory
)))
6642 (funcall handler
'insert-directory file switches
6643 wildcard full-directory-p
)
6644 (let (result (beg (point)))
6646 ;; Read the actual directory using `insert-directory-program'.
6647 ;; RESULT gets the status code.
6648 (let* (;; We at first read by no-conversion, then after
6649 ;; putting text property `dired-filename, decode one
6650 ;; bunch by one to preserve that property.
6651 (coding-system-for-read 'no-conversion
)
6652 ;; This is to control encoding the arguments in call-process.
6653 (coding-system-for-write
6654 (and enable-multibyte-characters
6655 (or file-name-coding-system
6656 default-file-name-coding-system
))))
6659 ;; If the wildcard is just in the file part, then run ls in
6660 ;; the directory part of the file pattern using the last
6661 ;; component as argument. Otherwise, run ls in the longest
6662 ;; subdirectory of the directory part free of wildcards; use
6663 ;; the remaining of the file pattern as argument.
6664 (let* ((dir-wildcard (insert-directory-wildcard-in-dir-p file
))
6666 (cond (dir-wildcard (car dir-wildcard
))
6668 (if (file-name-absolute-p file
)
6669 (file-name-directory file
)
6670 (file-name-directory (expand-file-name file
))))))
6671 (pattern (if dir-wildcard
(cdr dir-wildcard
) (file-name-nondirectory file
))))
6672 ;; NB since switches is passed to the shell, be
6673 ;; careful of malicious values, eg "-l;reboot".
6674 ;; See eg dired-safe-switches-p.
6676 shell-file-name nil t nil
6677 shell-command-switch
6678 (concat (if (memq system-type
'(ms-dos windows-nt
))
6680 "\\") ; Disregard Unix shell aliases!
6681 insert-directory-program
6683 (if (stringp switches
)
6685 (mapconcat 'identity switches
" "))
6687 ;; Quote some characters that have
6688 ;; special meanings in shells; but
6689 ;; don't quote the wildcards--we want
6690 ;; them to be special. We also
6691 ;; currently don't quote the quoting
6692 ;; characters in case people want to
6693 ;; use them explicitly to quote
6694 ;; wildcard characters.
6695 (shell-quote-wildcard-pattern pattern
))))
6696 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
6697 ;; directory if FILE is a symbolic link.
6698 (unless full-directory-p
6701 ((stringp switches
) (concat switches
" -d"))
6702 ((member "-d" switches
) switches
)
6703 (t (append switches
'("-d"))))))
6704 (apply 'call-process
6705 insert-directory-program nil t nil
6707 (if (listp switches
) switches
6708 (unless (equal switches
"")
6709 ;; Split the switches at any spaces so we can
6710 ;; pass separate options as separate args.
6711 (split-string-and-unquote switches
)))
6712 ;; Avoid lossage if FILE starts with `-'.
6715 (if (string-match "\\`~" file
)
6716 (setq file
(expand-file-name file
)))
6718 (if full-directory-p
6719 ;; (concat (file-name-as-directory file) ".")
6723 ;; If we got "//DIRED//" in the output, it means we got a real
6724 ;; directory listing, even if `ls' returned nonzero.
6725 ;; So ignore any errors.
6726 (when (if (stringp switches
)
6727 (string-match "--dired\\>" switches
)
6728 (member "--dired" switches
))
6731 (when (looking-at "//SUBDIRED//")
6733 (if (looking-at "//DIRED//")
6736 (when (and (not (eq 0 result
))
6737 (eq insert-directory-ls-version
'unknown
))
6738 ;; The first time ls returns an error,
6739 ;; find the version numbers of ls,
6740 ;; and set insert-directory-ls-version
6741 ;; to > if it is more than 5.2.1, < if it is less, nil if it
6742 ;; is equal or if the info cannot be obtained.
6743 ;; (That can mean it isn't GNU ls.)
6746 (call-process "ls" nil t nil
"--version")
6748 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out
)
6749 (let* ((version (match-string 1 version-out
))
6750 (split (split-string version
"[.]"))
6751 (numbers (mapcar 'string-to-number split
))
6754 (while (and (not comparison
) (or numbers min
))
6756 (setq comparison
'>))
6758 (setq comparison
'<))
6759 ((> (car numbers
) (car min
))
6760 (setq comparison
'>))
6761 ((< (car numbers
) (car min
))
6762 (setq comparison
'<))
6764 (setq numbers
(cdr numbers
)
6766 (setq insert-directory-ls-version
(or comparison
'=)))
6767 (setq insert-directory-ls-version nil
))))
6769 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
6770 (when (and (eq 1 result
) (eq insert-directory-ls-version
'>))
6773 ;; If `insert-directory-program' failed, signal an error.
6774 (unless (eq 0 result
)
6775 ;; Delete the error message it may have output.
6776 (delete-region beg
(point))
6777 ;; On non-Posix systems, we cannot open a directory, so
6778 ;; don't even try, because that will always result in
6779 ;; the ubiquitous "Access denied". Instead, show the
6780 ;; command line so the user can try to guess what went wrong.
6781 (if (and (file-directory-p file
)
6782 (memq system-type
'(ms-dos windows-nt
)))
6784 "Reading directory: \"%s %s -- %s\" exited with status %s"
6785 insert-directory-program
6786 (if (listp switches
) (concat switches
) switches
)
6788 ;; Unix. Access the file to get a suitable error.
6789 (access-file file
"Reading directory")
6790 (error "Listing directory failed but `access-file' worked")))
6791 (insert-directory-clean beg switches
)
6792 ;; Now decode what read if necessary.
6793 (let ((coding (or coding-system-for-read
6794 file-name-coding-system
6795 default-file-name-coding-system
6799 (when (and enable-multibyte-characters
6800 (not (memq (coding-system-base coding
)
6801 '(raw-text no-conversion
))))
6802 ;; If no coding system is specified or detection is
6803 ;; requested, detect the coding.
6804 (if (eq (coding-system-base coding
) 'undecided
)
6805 (setq coding
(detect-coding-region beg
(point) t
)))
6806 (if (not (eq (coding-system-base coding
) 'undecided
))
6809 (coding-system-change-eol-conversion coding
'unix
))
6810 (narrow-to-region beg
(point))
6811 (goto-char (point-min))
6814 val
(get-text-property (point) 'dired-filename
))
6815 (goto-char (next-single-property-change
6816 (point) 'dired-filename nil
(point-max)))
6817 ;; Force no eol conversion on a file name, so
6818 ;; that CR is preserved.
6819 (decode-coding-region pos
(point)
6820 (if val coding-no-eol coding
))
6822 (put-text-property pos
(point)
6823 'dired-filename t
)))))))
6825 (if full-directory-p
6826 ;; Try to insert the amount of free space.
6829 ;; First find the line to put it on.
6830 (when (re-search-forward "^ *\\(total\\)" nil t
)
6831 (let ((available (get-free-disk-space ".")))
6833 ;; Replace "total" with "used", to avoid confusion.
6834 (replace-match "total used in directory" nil nil nil
1)
6836 (insert " available " available
))))))))))
6838 (defun insert-directory-adj-pos (pos error-lines
)
6839 "Convert `ls --dired' file name position value POS to a buffer position.
6840 File name position values returned in ls --dired output
6841 count only stdout; they don't count the error messages sent to stderr.
6842 So this function converts to them to real buffer positions.
6843 ERROR-LINES is a list of buffer positions of error message lines,
6844 of the form (START END)."
6845 (while (and error-lines
(< (caar error-lines
) pos
))
6846 (setq pos
(+ pos
(- (nth 1 (car error-lines
)) (nth 0 (car error-lines
)))))
6850 (defun insert-directory-safely (file switches
6851 &optional wildcard full-directory-p
)
6852 "Insert directory listing for FILE, formatted according to SWITCHES.
6854 Like `insert-directory', but if FILE does not exist, it inserts a
6855 message to that effect instead of signaling an error."
6856 (if (file-exists-p file
)
6857 (insert-directory file switches wildcard full-directory-p
)
6858 ;; Simulate the message printed by `ls'.
6859 (insert (format "%s: No such file or directory\n" file
))))
6861 (defcustom kill-emacs-query-functions nil
6862 "Functions to call with no arguments to query about killing Emacs.
6863 If any of these functions returns nil, killing Emacs is canceled.
6864 `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
6865 the low level primitive, does not. See also `kill-emacs-hook'."
6868 :group
'convenience
)
6870 (defcustom confirm-kill-emacs nil
6871 "How to ask for confirmation when leaving Emacs.
6872 If nil, the default, don't ask at all. If the value is non-nil, it should
6873 be a predicate function; for example `yes-or-no-p'."
6874 :type
'(choice (const :tag
"Ask with yes-or-no-p" yes-or-no-p
)
6875 (const :tag
"Ask with y-or-n-p" y-or-n-p
)
6876 (const :tag
"Don't confirm" nil
)
6877 (function :tag
"Predicate function"))
6881 (defcustom confirm-kill-processes t
6882 "Non-nil if Emacs should confirm killing processes on exit.
6883 If this variable is nil, the value of
6884 `process-query-on-exit-flag' is ignored. Otherwise, if there are
6885 processes with a non-nil `process-query-on-exit-flag', Emacs will
6886 prompt the user before killing them."
6891 (defun save-buffers-kill-emacs (&optional arg
)
6892 "Offer to save each buffer, then kill this Emacs process.
6893 With prefix ARG, silently save all file-visiting buffers without asking.
6894 If there are active processes where `process-query-on-exit-flag'
6895 returns non-nil and `confirm-kill-processes' is non-nil,
6896 asks whether processes should be killed.
6897 Runs the members of `kill-emacs-query-functions' in turn and stops
6898 if any returns nil. If `confirm-kill-emacs' is non-nil, calls it."
6900 ;; Don't use save-some-buffers-default-predicate, because we want
6901 ;; to ask about all the buffers before killing Emacs.
6902 (save-some-buffers arg t
)
6903 (let ((confirm confirm-kill-emacs
))
6905 (or (not (memq t
(mapcar (function
6906 (lambda (buf) (and (buffer-file-name buf
)
6907 (buffer-modified-p buf
))))
6909 (progn (setq confirm nil
)
6910 (yes-or-no-p "Modified buffers exist; exit anyway? ")))
6911 (or (not (fboundp 'process-list
))
6912 ;; process-list is not defined on MSDOS.
6913 (not confirm-kill-processes
)
6914 (let ((processes (process-list))
6917 (and (memq (process-status (car processes
)) '(run stop open listen
))
6918 (process-query-on-exit-flag (car processes
))
6920 (setq processes
(cdr processes
)))
6922 (with-displayed-buffer-window
6923 (get-buffer-create "*Process List*")
6924 '(display-buffer--maybe-at-bottom)
6925 #'(lambda (window _value
)
6926 (with-selected-window window
6930 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))
6931 (when (window-live-p window
)
6932 (quit-restore-window window
'kill
)))))
6933 (list-processes t
)))))
6934 ;; Query the user for other things, perhaps.
6935 (run-hook-with-args-until-failure 'kill-emacs-query-functions
)
6937 (funcall confirm
"Really exit Emacs? "))
6940 (defun save-buffers-kill-terminal (&optional arg
)
6941 "Offer to save each buffer, then kill the current connection.
6942 If the current frame has no client, kill Emacs itself using
6943 `save-buffers-kill-emacs'.
6945 With prefix ARG, silently save all file-visiting buffers, then kill.
6947 If emacsclient was started with a list of filenames to edit, then
6948 only these files will be asked to be saved."
6950 (if (frame-parameter nil
'client
)
6951 (server-save-buffers-kill-terminal arg
)
6952 (save-buffers-kill-emacs arg
)))
6954 ;; We use /: as a prefix to "quote" a file name
6955 ;; so that magic file name handlers will not apply to it.
6957 (setq file-name-handler-alist
6958 (cons (cons (purecopy "\\`/:") 'file-name-non-special
)
6959 file-name-handler-alist
))
6961 ;; We depend on being the last handler on the list,
6962 ;; so that anything else which does need handling
6963 ;; has been handled already.
6964 ;; So it is safe for us to inhibit *all* magic file name handlers for
6965 ;; operations, which return a file name. See Bug#29579.
6967 (defun file-name-non-special (operation &rest arguments
)
6968 (let* ((op-returns-file-name-list
6969 '(expand-file-name file-name-directory file-name-as-directory
6970 directory-file-name file-name-sans-versions
6971 find-backup-file-name file-remote-p
))
6972 (file-name-handler-alist
6974 (not (memq operation op-returns-file-name-list
))
6975 file-name-handler-alist
))
6977 ;; Some operations respect file name handlers in
6978 ;; `default-directory'. Because core function like
6979 ;; `call-process' don't care about file name handlers in
6980 ;; `default-directory', we here have to resolve the
6981 ;; directory into a local one. For `process-file',
6982 ;; `start-file-process', and `shell-command', this fixes
6985 '(insert-directory process-file start-file-process
6986 shell-command temporary-file-directory
))
6987 (directory-file-name
6989 (unhandled-file-name-directory default-directory
)))
6991 ;; Get a list of the indices of the args which are file names.
6993 (cdr (or (assq operation
6994 ;; The first seven are special because they
6995 ;; return a file name. We want to include the /:
6996 ;; in the return value.
6997 ;; So just avoid stripping it in the first place.
6999 (mapcar 'list op-returns-file-name-list
)
7000 '(;; `identity' means just return the first arg
7001 ;; not stripped of its quoting.
7002 (substitute-in-file-name identity
)
7003 ;; `add' means add "/:" to the result.
7004 (file-truename add
0)
7005 (insert-file-contents insert-file-contents
0)
7006 ;; `unquote-then-quote' means set buffer-file-name
7007 ;; temporarily to unquoted filename.
7008 (verify-visited-file-modtime unquote-then-quote
)
7009 ;; List the arguments which are filenames.
7010 (file-name-completion 0 1)
7011 (file-name-all-completions 0 1)
7013 (file-newer-than-file-p 0 1)
7017 (copy-directory 0 1)
7018 (file-in-directory-p 0 1)
7019 (make-symbolic-link 0 1)
7020 (add-name-to-file 0 1)
7021 (make-auto-save-file-name buffer-file-name
)
7022 (set-visited-file-modtime buffer-file-name
)
7023 ;; These file-notify-* operations take a
7025 (file-notify-rm-watch . nil
)
7026 (file-notify-valid-p . nil
))))
7027 ;; For all other operations, treat the first argument only
7028 ;; as the file name.
7031 ;; Copy ARGUMENTS so we can replace elements in it.
7032 (arguments (copy-sequence arguments
)))
7033 (if (symbolp (car file-arg-indices
))
7034 (setq method
(pop file-arg-indices
)))
7035 ;; Strip off the /: from the file names that have it.
7037 (while (consp file-arg-indices
)
7038 (let ((pair (nthcdr (car file-arg-indices
) arguments
)))
7040 (string-match "\\`/:" (car pair
))
7042 (if (= (length (car pair
)) 2)
7044 (substring (car pair
) 2)))))
7045 (setq file-arg-indices
(cdr file-arg-indices
))))
7047 (`identity
(car arguments
))
7048 (`add
(file-name-quote (apply operation arguments
)))
7050 (let ((buffer-file-name
7051 (if (string-match "\\`/:" buffer-file-name
)
7052 (substring buffer-file-name
(match-end 0))
7054 (apply operation arguments
)))
7055 (`insert-file-contents
7056 (let ((visit (nth 1 arguments
)))
7058 (apply operation arguments
)
7059 (when (and visit buffer-file-name
)
7060 (setq buffer-file-name
(concat "/:" buffer-file-name
))))))
7061 (`unquote-then-quote
7062 ;; We can't use `cl-letf' with `(buffer-local-value)' here
7063 ;; because it wouldn't work during bootstrapping.
7064 (let ((buffer (current-buffer)))
7065 ;; `unquote-then-quote' is only used for the
7066 ;; `verify-visited-file-modtime' action, which takes a buffer
7067 ;; as only optional argument.
7068 (with-current-buffer (or (car arguments
) buffer
)
7069 (let ((buffer-file-name (substring buffer-file-name
2)))
7070 ;; Make sure to hide the temporary buffer change from the
7071 ;; underlying operation.
7072 (with-current-buffer buffer
7073 (apply operation arguments
))))))
7075 (apply operation arguments
)))))
7077 (defsubst file-name-quoted-p
(name)
7078 "Whether NAME is quoted with prefix \"/:\".
7079 If NAME is a remote file name, check the local part of NAME."
7080 (string-prefix-p "/:" (file-local-name name
)))
7082 (defsubst file-name-quote
(name)
7083 "Add the quotation prefix \"/:\" to file NAME.
7084 If NAME is a remote file name, the local part of NAME is quoted.
7085 If NAME is already a quoted file name, NAME is returned unchanged."
7086 (if (file-name-quoted-p name
)
7088 (concat (file-remote-p name
) "/:" (file-local-name name
))))
7090 (defsubst file-name-unquote
(name)
7091 "Remove quotation prefix \"/:\" from file NAME, if any.
7092 If NAME is a remote file name, the local part of NAME is unquoted."
7093 (let ((localname (file-local-name name
)))
7094 (when (file-name-quoted-p localname
)
7096 localname
(if (= (length localname
) 2) "/" (substring localname
2))))
7097 (concat (file-remote-p name
) localname
)))
7099 ;; Symbolic modes and read-file-modes.
7101 (defun file-modes-char-to-who (char)
7102 "Convert CHAR to a numeric bit-mask for extracting mode bits.
7103 CHAR is in [ugoa] and represents the category of users (Owner, Group,
7104 Others, or All) for whom to produce the mask.
7105 The bit-mask that is returned extracts from mode bits the access rights
7106 for the specified category of users."
7107 (cond ((= char ?u
) #o4700
)
7108 ((= char ?g
) #o2070
)
7109 ((= char ?o
) #o1007
)
7110 ((= char ?a
) #o7777
)
7111 (t (error "%c: bad `who' character" char
))))
7113 (defun file-modes-char-to-right (char &optional from
)
7114 "Convert CHAR to a numeric value of mode bits.
7115 CHAR is in [rwxXstugo] and represents symbolic access permissions.
7116 If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
7117 (or from
(setq from
0))
7118 (cond ((= char ?r
) #o0444
)
7119 ((= char ?w
) #o0222
)
7120 ((= char ?x
) #o0111
)
7121 ((= char ?s
) #o6000
)
7122 ((= char ?t
) #o1000
)
7123 ;; Rights relative to the previous file modes.
7124 ((= char ?X
) (if (= (logand from
#o111
) 0) 0 #o0111
))
7125 ((= char ?u
) (let ((uright (logand #o4700 from
)))
7126 (+ uright
(/ uright
#o10
) (/ uright
#o100
))))
7127 ((= char ?g
) (let ((gright (logand #o2070 from
)))
7128 (+ gright
(/ gright
#o10
) (* gright
#o10
))))
7129 ((= char ?o
) (let ((oright (logand #o1007 from
)))
7130 (+ oright
(* oright
#o10
) (* oright
#o100
))))
7131 (t (error "%c: bad right character" char
))))
7133 (defun file-modes-rights-to-number (rights who-mask
&optional from
)
7134 "Convert a symbolic mode string specification to an equivalent number.
7135 RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]*)+\".
7136 WHO-MASK is the bit-mask specifying the category of users to which to
7137 apply the access permissions. See `file-modes-char-to-who'.
7138 FROM (or 0 if nil) gives the mode bits on which to base permissions if
7139 RIGHTS request to add, remove, or set permissions based on existing ones,
7141 (let* ((num-rights (or from
0))
7142 (list-rights (string-to-list rights
))
7143 (op (pop list-rights
)))
7144 (while (memq op
'(?
+ ?- ?
=))
7147 (while (memq (setq char-right
(pop list-rights
))
7148 '(?r ?w ?x ?X ?s ?t ?u ?g ?o
))
7151 (file-modes-char-to-right char-right num-rights
))))
7152 (setq num-right
(logand who-mask num-right
)
7154 (cond ((= op ?
+) (logior num-rights num-right
))
7155 ((= op ?-
) (logand num-rights
(lognot num-right
)))
7156 (t (logior (logand num-rights
(lognot who-mask
)) num-right
)))
7160 (defun file-modes-symbolic-to-number (modes &optional from
)
7161 "Convert symbolic file modes to numeric file modes.
7162 MODES is the string to convert, it should match
7163 \"[ugoa]*([+-=][rwxXstugo]*)+,...\".
7164 See Info node `(coreutils)File permissions' for more information on this
7166 FROM (or 0 if nil) gives the mode bits on which to base permissions if
7167 MODES request to add, remove, or set permissions based on existing ones,
7170 (let ((case-fold-search nil
)
7171 (num-modes (or from
0)))
7172 (while (/= (string-to-char modes
) 0)
7173 (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]*\\)+\\(,\\|\\)" modes
)
7174 (let ((num-who (apply 'logior
0
7175 (mapcar 'file-modes-char-to-who
7176 (match-string 1 modes
)))))
7178 (setq num-who
(logior #o7000
(default-file-modes))))
7180 (file-modes-rights-to-number (substring modes
(match-end 1))
7182 modes
(substring modes
(match-end 3))))
7183 (error "Parse error in modes near `%s'" (substring modes
0))))
7186 (defun read-file-modes (&optional prompt orig-file
)
7187 "Read file modes in octal or symbolic notation and return its numeric value.
7188 PROMPT is used as the prompt, default to \"File modes (octal or symbolic): \".
7189 ORIG-FILE is the name of a file on whose mode bits to base returned
7190 permissions if what user types requests to add, remove, or set permissions
7191 based on existing mode bits, as in \"og+rX-w\"."
7192 (let* ((modes (or (if orig-file
(file-modes orig-file
) 0)
7193 (error "File not found")))
7194 (modestr (and (stringp orig-file
)
7195 (nth 8 (file-attributes orig-file
))))
7197 (and (stringp modestr
)
7198 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr
)
7199 (replace-regexp-in-string
7201 (format "u=%s,g=%s,o=%s"
7202 (match-string 1 modestr
)
7203 (match-string 2 modestr
)
7204 (match-string 3 modestr
)))))
7205 (value (read-string (or prompt
"File modes (octal or symbolic): ")
7208 (if (string-match "^[0-7]+" value
)
7209 (string-to-number value
8)
7210 (file-modes-symbolic-to-number value modes
)))))
7212 (define-obsolete-variable-alias 'cache-long-line-scans
7213 'cache-long-scans
"24.4")
7215 ;; Trashcan handling.
7216 (defcustom trash-directory nil
7217 "Directory for `move-file-to-trash' to move files and directories to.
7218 This directory is only used when the function `system-move-file-to-trash'
7220 Relative paths are interpreted relative to `default-directory'.
7221 If the value is nil, Emacs uses a freedesktop.org-style trashcan."
7222 :type
'(choice (const nil
) directory
)
7226 (defvar trash--hexify-table
)
7228 (declare-function system-move-file-to-trash
"w32fns.c" (filename))
7230 (defun move-file-to-trash (filename)
7231 "Move the file (or directory) named FILENAME to the trash.
7232 When `delete-by-moving-to-trash' is non-nil, this function is
7233 called by `delete-file' and `delete-directory' instead of
7234 deleting files outright.
7236 If the function `system-move-file-to-trash' is defined, call it
7237 with FILENAME as an argument.
7238 Otherwise, if `trash-directory' is non-nil, move FILENAME to that
7240 Otherwise, trash FILENAME using the freedesktop.org conventions,
7241 like the GNOME, KDE and XFCE desktop environments. Emacs only
7242 moves files to \"home trash\", ignoring per-volume trashcans."
7243 (interactive "fMove file to trash: ")
7244 (cond (trash-directory
7245 ;; If `trash-directory' is non-nil, move the file there.
7246 (let* ((trash-dir (expand-file-name trash-directory
))
7247 (fn (directory-file-name (expand-file-name filename
)))
7248 (new-fn (concat (file-name-as-directory trash-dir
)
7249 (file-name-nondirectory fn
))))
7250 ;; We can't trash a parent directory of trash-directory.
7251 (if (string-prefix-p fn trash-dir
)
7252 (error "Trash directory `%s' is a subdirectory of `%s'"
7253 trash-dir filename
))
7254 (unless (file-directory-p trash-dir
)
7255 (make-directory trash-dir t
))
7256 ;; Ensure that the trashed file-name is unique.
7257 (if (file-exists-p new-fn
)
7258 (let ((version-control t
)
7259 (backup-directory-alist nil
))
7260 (setq new-fn
(car (find-backup-file-name new-fn
)))))
7261 (let (delete-by-moving-to-trash)
7262 (rename-file fn new-fn
))))
7263 ;; If `system-move-file-to-trash' is defined, use it.
7264 ((fboundp 'system-move-file-to-trash
)
7265 (system-move-file-to-trash filename
))
7266 ;; Otherwise, use the freedesktop.org method, as specified at
7267 ;; http://freedesktop.org/wiki/Specifications/trash-spec
7269 (let* ((xdg-data-dir
7270 (directory-file-name
7271 (expand-file-name "Trash"
7272 (or (getenv "XDG_DATA_HOME")
7273 "~/.local/share"))))
7274 (trash-files-dir (expand-file-name "files" xdg-data-dir
))
7275 (trash-info-dir (expand-file-name "info" xdg-data-dir
))
7276 (fn (directory-file-name (expand-file-name filename
))))
7278 ;; Check if we have permissions to delete.
7279 (unless (file-writable-p (directory-file-name
7280 (file-name-directory fn
)))
7281 (error "Cannot move %s to trash: Permission denied" filename
))
7282 ;; The trashed file cannot be the trash dir or its parent.
7283 (if (string-prefix-p fn trash-files-dir
)
7284 (error "The trash directory %s is a subdirectory of %s"
7285 trash-files-dir filename
))
7286 (if (string-prefix-p fn trash-info-dir
)
7287 (error "The trash directory %s is a subdirectory of %s"
7288 trash-info-dir filename
))
7290 ;; Ensure that the trash directory exists; otherwise, create it.
7291 (with-file-modes #o700
7292 (unless (file-exists-p trash-files-dir
)
7293 (make-directory trash-files-dir t
))
7294 (unless (file-exists-p trash-info-dir
)
7295 (make-directory trash-info-dir t
)))
7297 ;; Try to move to trash with .trashinfo undo information
7300 (set-buffer-file-coding-system 'utf-8-unix
)
7301 (insert "[Trash Info]\nPath=")
7302 ;; Perform url-encoding on FN. For compatibility with
7303 ;; other programs (e.g. XFCE Thunar), allow literal "/"
7304 ;; for path separators.
7305 (unless (boundp 'trash--hexify-table
)
7306 (setq trash--hexify-table
(make-vector 256 nil
))
7307 (let ((unreserved-chars
7308 (list ?
/ ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m
7309 ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A
7310 ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O
7311 ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?
0 ?
1 ?
2
7312 ?
3 ?
4 ?
5 ?
6 ?
7 ?
8 ?
9 ?- ?_ ?. ?
! ?~ ?
* ?
'
7315 (aset trash--hexify-table byte
7316 (if (memq byte unreserved-chars
)
7317 (char-to-string byte
)
7318 (format "%%%02x" byte
))))))
7319 (mapc (lambda (byte)
7320 (insert (aref trash--hexify-table byte
)))
7321 (if (multibyte-string-p fn
)
7322 (encode-coding-string fn
'utf-8
)
7324 (insert "\nDeletionDate="
7325 (format-time-string "%Y-%m-%dT%T")
7328 ;; Make a .trashinfo file. Use O_EXCL, as per trash-spec 1.0.
7329 (let* ((files-base (file-name-nondirectory fn
))
7330 (info-fn (expand-file-name
7331 (concat files-base
".trashinfo")
7334 (write-region nil nil info-fn nil
'quiet info-fn
'excl
)
7335 (file-already-exists
7336 ;; Uniquify new-fn. Some file managers do not
7337 ;; like Emacs-style backup file names. E.g.:
7338 ;; https://bugs.kde.org/170956
7339 (setq info-fn
(make-temp-file
7340 (expand-file-name files-base trash-info-dir
)
7342 (setq files-base
(file-name-nondirectory info-fn
))
7343 (write-region nil nil info-fn nil
'quiet info-fn
)))
7344 ;; Finally, try to move the file to the trashcan.
7345 (let ((delete-by-moving-to-trash nil
)
7346 (new-fn (expand-file-name files-base trash-files-dir
)))
7347 (rename-file fn new-fn
)))))))))
7349 (defsubst file-attribute-type
(attributes)
7350 "The type field in ATTRIBUTES returned by `file-attributes'.
7351 The value is either t for directory, string (name linked to) for
7352 symbolic link, or nil."
7355 (defsubst file-attribute-link-number
(attributes)
7356 "Return the number of links in ATTRIBUTES returned by `file-attributes'."
7359 (defsubst file-attribute-user-id
(attributes)
7360 "The UID field in ATTRIBUTES returned by `file-attributes'.
7361 This is either a string or a number. If a string value cannot be
7362 looked up, a numeric value, either an integer or a float, is
7366 (defsubst file-attribute-group-id
(attributes)
7367 "The GID field in ATTRIBUTES returned by `file-attributes'.
7368 This is either a string or a number. If a string value cannot be
7369 looked up, a numeric value, either an integer or a float, is
7373 (defsubst file-attribute-access-time
(attributes)
7374 "The last access time in ATTRIBUTES returned by `file-attributes'.
7375 This a list of integers (HIGH LOW USEC PSEC) in the same style
7379 (defsubst file-attribute-modification-time
(attributes)
7380 "The modification time in ATTRIBUTES returned by `file-attributes'.
7381 This is the time of the last change to the file's contents, and
7382 is a list of integers (HIGH LOW USEC PSEC) in the same style
7386 (defsubst file-attribute-status-change-time
(attributes)
7387 "The status modification time in ATTRIBUTES returned by `file-attributes'.
7388 This is the time of last change to the file's attributes: owner
7389 and group, access mode bits, etc, and is a list of integers (HIGH
7390 LOW USEC PSEC) in the same style as (current-time)."
7393 (defsubst file-attribute-size
(attributes)
7394 "The size (in bytes) in ATTRIBUTES returned by `file-attributes'.
7395 This is a floating point number if the size is too large for an integer."
7398 (defsubst file-attribute-modes
(attributes)
7399 "The file modes in ATTRIBUTES returned by `file-attributes'.
7400 This is a string of ten letters or dashes as in ls -l."
7403 (defsubst file-attribute-inode-number
(attributes)
7404 "The inode number in ATTRIBUTES returned by `file-attributes'.
7405 If it is larger than what an Emacs integer can hold, this is of
7406 the form (HIGH . LOW): first the high bits, then the low 16 bits.
7407 If even HIGH is too large for an Emacs integer, this is instead
7408 of the form (HIGH MIDDLE . LOW): first the high bits, then the
7409 middle 24 bits, and finally the low 16 bits."
7410 (nth 10 attributes
))
7412 (defsubst file-attribute-device-number
(attributes)
7413 "The file system device number in ATTRIBUTES returned by `file-attributes'.
7414 If it is larger than what an Emacs integer can hold, this is of
7415 the form (HIGH . LOW): first the high bits, then the low 16 bits.
7416 If even HIGH is too large for an Emacs integer, this is instead
7417 of the form (HIGH MIDDLE . LOW): first the high bits, then the
7418 middle 24 bits, and finally the low 16 bits."
7419 (nth 11 attributes
))
7421 (defun file-attribute-collect (attributes &rest attr-names
)
7422 "Return a sublist of ATTRIBUTES returned by `file-attributes'.
7423 ATTR-NAMES are symbols with the selected attribute names.
7425 Valid attribute names are: type, link-number, user-id, group-id,
7426 access-time, modification-time, status-change-time, size, modes,
7427 inode-number and device-number."
7428 (let ((all '(type link-number user-id group-id access-time
7429 modification-time status-change-time
7430 size modes inode-number device-number
))
7433 (let ((attr (pop attr-names
)))
7436 (intern (format "file-attribute-%s" (symbol-name attr
)))
7439 (error "Wrong attribute name '%S'" attr
))))
7442 (define-key ctl-x-map
"\C-f" 'find-file
)
7443 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
7444 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
7445 (define-key ctl-x-map
"\C-s" 'save-buffer
)
7446 (define-key ctl-x-map
"s" 'save-some-buffers
)
7447 (define-key ctl-x-map
"\C-w" 'write-file
)
7448 (define-key ctl-x-map
"i" 'insert-file
)
7449 (define-key esc-map
"~" 'not-modified
)
7450 (define-key ctl-x-map
"\C-d" 'list-directory
)
7451 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-terminal
)
7452 (define-key ctl-x-map
"\C-q" 'read-only-mode
)
7454 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
7455 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
7456 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
7457 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
7458 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
7460 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
7461 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
7462 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
7463 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
7464 (define-key ctl-x-5-map
"\C-o" 'display-buffer-other-frame
)
7466 ;;; files.el ends here