* lisp/dired.el (dired-get-filename): Don't string-to-multibyte
[emacs.git] / lisp / dired.el
blob1c283c5de3f83bf00979427fd480f874689141a9
1 ;;; dired.el --- directory-browsing commands -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1986, 1992-1997, 2000-2018 Free Software
4 ;; Foundation, Inc.
6 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: files
9 ;; Package: emacs
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; This is a major mode for directory browsing and editing.
29 ;; It is documented in the Emacs manual.
31 ;; Rewritten in 1990/1991 to add tree features, file marking and
32 ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
33 ;; Finished up by rms in 1992.
35 ;;; Code:
37 (eval-when-compile (require 'subr-x))
38 ;; When bootstrapping dired-loaddefs has not been generated.
39 (require 'dired-loaddefs nil t)
41 (declare-function dired-buffer-more-recently-used-p
42 "dired-x" (buffer1 buffer2))
44 ;;; Customizable variables
46 (defgroup dired nil
47 "Directory editing."
48 :link '(custom-manual "(emacs)Dired")
49 :group 'files)
51 (defgroup dired-mark nil
52 "Handling marks in Dired."
53 :prefix "dired-"
54 :group 'dired)
57 ;;;###autoload
58 (defcustom dired-listing-switches (purecopy "-al")
59 "Switches passed to `ls' for Dired. MUST contain the `l' option.
60 May contain all other options that don't contradict `-l';
61 may contain even `F', `b', `i' and `s'. See also the variable
62 `dired-ls-F-marks-symlinks' concerning the `F' switch.
63 Options that include embedded whitespace must be quoted
64 like this: \"--option=value with spaces\"; you can use
65 `combine-and-quote-strings' to produce the correct quoting of
66 each option.
67 On systems such as MS-DOS and MS-Windows, which use `ls' emulation in Lisp,
68 some of the `ls' switches are not supported; see the doc string of
69 `insert-directory' in `ls-lisp.el' for more details."
70 :type 'string
71 :group 'dired)
73 (defcustom dired-subdir-switches nil
74 "If non-nil, switches passed to `ls' for inserting subdirectories.
75 If nil, `dired-listing-switches' is used."
76 :group 'dired
77 :type '(choice (const :tag "Use dired-listing-switches" nil)
78 (string :tag "Switches")))
80 (defcustom dired-chown-program
81 (purecopy (cond ((executable-find "chown") "chown")
82 ((file-executable-p "/usr/sbin/chown") "/usr/sbin/chown")
83 ((file-executable-p "/etc/chown") "/etc/chown")
84 (t "chown")))
85 "Name of chown command (usually `chown')."
86 :group 'dired
87 :type 'file)
89 (defcustom dired-use-ls-dired 'unspecified
90 "Non-nil means Dired should pass the \"--dired\" option to \"ls\".
91 The special value of `unspecified' means to check explicitly, and
92 save the result in this variable. This is performed the first
93 time `dired-insert-directory' is called.
95 Note that if you set this option to nil, either through choice or
96 because your \"ls\" program does not support \"--dired\", Dired
97 will fail to parse some \"unusual\" file names, e.g. those with leading
98 spaces. You might want to install ls from GNU Coreutils, which does
99 support this option. Alternatively, you might want to use Emacs's
100 own emulation of \"ls\", by using:
101 (setq ls-lisp-use-insert-directory-program nil)
102 (require \\='ls-lisp)
103 This is used by default on MS Windows, which does not have an \"ls\" program.
104 Note that `ls-lisp' does not support as many options as GNU ls, though.
105 For more details, see Info node `(emacs)ls in Lisp'."
106 :group 'dired
107 :type '(choice (const :tag "Check for --dired support" unspecified)
108 (const :tag "Do not use --dired" nil)
109 (other :tag "Use --dired" t)))
111 (defcustom dired-chmod-program "chmod"
112 "Name of chmod command (usually `chmod')."
113 :group 'dired
114 :type 'file)
116 (defcustom dired-touch-program "touch"
117 "Name of touch command (usually `touch')."
118 :group 'dired
119 :type 'file)
121 (defcustom dired-ls-F-marks-symlinks nil
122 "Informs Dired about how `ls -lF' marks symbolic links.
123 Set this to t if `ls' (or whatever program is specified by
124 `insert-directory-program') with `-lF' marks the symbolic link
125 itself with a trailing @ (usually the case under Ultrix).
127 Example: if `ln -s foo bar; ls -F bar' gives `bar -> foo', set it to
128 nil (the default), if it gives `bar@ -> foo', set it to t.
130 Dired checks if there is really a @ appended. Thus, if you have a
131 marking `ls' program on one host and a non-marking on another host, and
132 don't care about symbolic links which really end in a @, you can
133 always set this variable to t."
134 :type 'boolean
135 :group 'dired-mark)
137 (defcustom dired-trivial-filenames (purecopy "\\`\\.\\.?\\'\\|\\`#")
138 "Regexp of files to skip when finding first file of a directory.
139 A value of nil means move to the subdir line.
140 A value of t means move to first file."
141 :type '(choice (const :tag "Move to subdir" nil)
142 (const :tag "Move to first" t)
143 regexp)
144 :group 'dired)
146 (defcustom dired-keep-marker-rename t
147 ;; Use t as default so that moved files "take their markers with them".
148 "Controls marking of renamed files.
149 If t, files keep their previous marks when they are renamed.
150 If a character, renamed files (whether previously marked or not)
151 are afterward marked with that character.
152 This option affects only files renamed by `dired-do-rename' and
153 `dired-do-rename-regexp'. See `wdired-keep-marker-rename'
154 if you want to do the same for files renamed in WDired mode."
155 :type '(choice (const :tag "Keep" t)
156 (character :tag "Mark" :value ?R))
157 :group 'dired-mark)
159 (defcustom dired-keep-marker-copy ?C
160 "Controls marking of copied files.
161 If t, copied files are marked if and as the corresponding original files were.
162 If a character, copied files are unconditionally marked with that character."
163 :type '(choice (const :tag "Keep" t)
164 (character :tag "Mark"))
165 :group 'dired-mark)
167 (defcustom dired-keep-marker-hardlink ?H
168 "Controls marking of newly made hard links.
169 If t, they are marked if and as the files linked to were marked.
170 If a character, new links are unconditionally marked with that character."
171 :type '(choice (const :tag "Keep" t)
172 (character :tag "Mark"))
173 :group 'dired-mark)
175 (defcustom dired-keep-marker-symlink ?Y
176 "Controls marking of newly made symbolic links.
177 If t, they are marked if and as the files linked to were marked.
178 If a character, new links are unconditionally marked with that character."
179 :type '(choice (const :tag "Keep" t)
180 (character :tag "Mark"))
181 :group 'dired-mark)
183 (defcustom dired-dwim-target nil
184 "If non-nil, Dired tries to guess a default target directory.
185 This means: if there is a Dired buffer displayed in the next
186 window, use its current directory, instead of this Dired buffer's
187 current directory.
189 The target is used in the prompt for file copy, rename etc."
190 :type 'boolean
191 :group 'dired)
193 (defcustom dired-copy-preserve-time t
194 "If non-nil, Dired preserves the last-modified time in a file copy.
195 \(This works on only some systems.)"
196 :type 'boolean
197 :group 'dired)
199 ; These variables were deleted and the replacements are on files.el.
200 ; We leave aliases behind for back-compatibility.
201 (define-obsolete-variable-alias 'dired-free-space-program
202 'directory-free-space-program "27.1")
203 (define-obsolete-variable-alias 'dired-free-space-args
204 'directory-free-space-args "27.1")
206 ;;; Hook variables
208 (defcustom dired-load-hook nil
209 "Run after loading Dired.
210 You can customize key bindings or load extensions with this."
211 :group 'dired
212 :type 'hook)
214 (defcustom dired-mode-hook nil
215 "Run at the very end of `dired-mode'."
216 :group 'dired
217 :type 'hook)
219 (defcustom dired-before-readin-hook nil
220 "This hook is run before a Dired buffer is read in (created or reverted)."
221 :group 'dired
222 :type 'hook)
224 (defcustom dired-after-readin-hook nil
225 "Hook run after each time a file or directory is read by Dired.
226 After each listing of a file or directory, this hook is run
227 with the buffer narrowed to the listing."
228 :group 'dired
229 :type 'hook)
230 ;; Note this can't simply be run inside function `dired-ls' as the hook
231 ;; functions probably depend on the dired-subdir-alist to be OK.
233 (defcustom dired-initial-position-hook nil
234 "This hook is used to position the point.
235 It is run by the function `dired-initial-position'."
236 :group 'dired
237 :type 'hook
238 :version "24.4")
240 (defcustom dired-dnd-protocol-alist
241 '(("^file:///" . dired-dnd-handle-local-file)
242 ("^file://" . dired-dnd-handle-file)
243 ("^file:" . dired-dnd-handle-local-file))
244 "The functions to call when a drop in `dired-mode' is made.
245 See `dnd-protocol-alist' for more information. When nil, behave
246 as in other buffers. Changing this option is effective only for
247 new Dired buffers."
248 :type '(choice (repeat (cons (regexp) (function)))
249 (const :tag "Behave as in other buffers" nil))
250 :version "22.1"
251 :group 'dired)
253 (defcustom dired-hide-details-hide-symlink-targets t
254 "Non-nil means `dired-hide-details-mode' hides symbolic link targets."
255 :type 'boolean
256 :version "24.4"
257 :group 'dired)
259 (defcustom dired-hide-details-hide-information-lines t
260 "Non-nil means `dired-hide-details-mode' hides all but header and file lines."
261 :type 'boolean
262 :version "24.4"
263 :group 'dired)
265 (defcustom dired-always-read-filesystem nil
266 "Non-nil means revert buffers visiting files before searching them.
267 By default, commands like `dired-mark-files-containing-regexp' will
268 search any buffers visiting the marked files without reverting them,
269 even if they were changed on disk. When this option is non-nil, such
270 buffers are always reverted in a temporary buffer before searching
271 them: the search is performed on the temporary buffer, the original
272 buffer visiting the file is not modified."
273 :type 'boolean
274 :version "26.1"
275 :group 'dired)
277 ;; Internal variables
279 (defvar dired-marker-char ?* ; the answer is 42
280 ;; so that you can write things like
281 ;; (let ((dired-marker-char ?X))
282 ;; ;; great code using X markers ...
283 ;; )
284 ;; For example, commands operating on two sets of files, A and B.
285 ;; Or marking files with digits 0-9. This could implicate
286 ;; concentric sets or an order for the marked files.
287 ;; The code depends on dynamic scoping on the marker char.
288 "In Dired, the current mark character.
289 This is what the do-commands look for, and what the mark-commands store.")
291 (defvar dired-del-marker ?D
292 "Character used to flag files for deletion.")
294 (defvar dired-shrink-to-fit t
295 ;; I see no reason ever to make this nil -- rms.
296 ;; (> baud-rate search-slow-speed)
297 "Non-nil means Dired shrinks the display buffer to fit the marked files.")
298 (make-obsolete-variable 'dired-shrink-to-fit
299 "use the Customization interface to add a new rule
300 to `display-buffer-alist' where condition regexp is \"^ \\*Marked Files\\*$\",
301 action argument symbol is `window-height' and its value is nil." "24.3")
303 (defvar dired-file-version-alist)
305 ;;;###autoload
306 (defvar dired-directory nil
307 "The directory name or wildcard spec that this Dired directory lists.
308 Local to each Dired buffer. May be a list, in which case the car is the
309 directory name and the cdr is the list of files to mention.
310 The directory name must be absolute, but need not be fully expanded.")
312 ;; Beware of "-l;reboot" etc. See bug#3230.
313 (defun dired-safe-switches-p (switches)
314 "Return non-nil if string SWITCHES does not look risky for Dired."
315 (or (not switches)
316 (and (stringp switches)
317 (< (length switches) 100) ; arbitrary
318 (string-match-p "\\` *-[- [:alnum:]]+\\'" switches))))
320 (defvar dired-actual-switches nil
321 "The value of `dired-listing-switches' used to make this buffer's text.")
323 (put 'dired-actual-switches 'safe-local-variable 'dired-safe-switches-p)
325 (defvar dired-re-inode-size "[0-9 \t]*[.,0-9]*[BkKMGTPEZY]?[ \t]*"
326 "Regexp for optional initial inode and file size as made by `ls -i -s'.")
328 ;; These regexps must be tested at beginning-of-line, but are also
329 ;; used to search for next matches, so neither omitting "^" nor
330 ;; replacing "^" by "\n" (to make it slightly faster) will work.
332 (defvar dired-re-mark "^[^ \n]")
333 ;; "Regexp matching a marked line.
334 ;; Important: the match ends just after the marker."
335 (defvar dired-re-maybe-mark "^. ")
336 ;; The [^:] part after "d" and "l" is to avoid confusion with the
337 ;; DOS/Windows-style drive letters in directory names, like in "d:/foo".
338 (defvar dired-re-dir (concat dired-re-maybe-mark dired-re-inode-size "d[^:]"))
339 (defvar dired-re-sym (concat dired-re-maybe-mark dired-re-inode-size "l[^:]"))
340 (defvar dired-re-exe;; match ls permission string of an executable file
341 (mapconcat (lambda (x)
342 (concat dired-re-maybe-mark dired-re-inode-size x))
343 '("-[-r][-w][xs][-r][-w].[-r][-w]."
344 "-[-r][-w].[-r][-w][xs][-r][-w]."
345 "-[-r][-w].[-r][-w].[-r][-w][xst]")
346 "\\|"))
347 (defvar dired-re-perms "[-bcdlps][-r][-w].[-r][-w].[-r][-w].")
348 (defvar dired-re-dot "^.* \\.\\.?/?$")
350 ;; The subdirectory names in the next two lists are expanded.
351 (defvar dired-subdir-alist nil
352 "Association list of subdirectories and their buffer positions.
353 Each subdirectory has an element: (DIRNAME . STARTMARKER).
354 The order of elements is the reverse of the order in the buffer.
355 In simple cases, this list contains one element.")
357 (defvar-local dired-switches-alist nil
358 "Keeps track of which switches to use for inserted subdirectories.
359 This is an alist of the form (SUBDIR . SWITCHES).")
361 (defvaralias 'dired-move-to-filename-regexp
362 'directory-listing-before-filename-regexp)
364 (defvar dired-subdir-regexp "^. \\([^\n\r]+\\)\\(:\\)[\n\r]"
365 "Regexp matching a maybe hidden subdirectory line in `ls -lR' output.
366 Subexpression 1 is the subdirectory proper, no trailing colon.
367 The match starts at the beginning of the line and ends after the end
368 of the line (\\n or \\r).
369 Subexpression 2 must end right before the \\n or \\r.")
371 (defgroup dired-faces nil
372 "Faces used by Dired."
373 :group 'dired
374 :group 'faces)
376 (defface dired-header
377 '((t (:inherit font-lock-type-face)))
378 "Face used for directory headers."
379 :group 'dired-faces
380 :version "22.1")
381 (defvar dired-header-face 'dired-header
382 "Face name used for directory headers.")
384 (defface dired-mark
385 '((t (:inherit font-lock-constant-face)))
386 "Face used for Dired marks."
387 :group 'dired-faces
388 :version "22.1")
389 (defvar dired-mark-face 'dired-mark
390 "Face name used for Dired marks.")
392 (defface dired-marked
393 '((t (:inherit warning)))
394 "Face used for marked files."
395 :group 'dired-faces
396 :version "22.1")
397 (defvar dired-marked-face 'dired-marked
398 "Face name used for marked files.")
400 (defface dired-flagged
401 '((t (:inherit error)))
402 "Face used for files flagged for deletion."
403 :group 'dired-faces
404 :version "22.1")
405 (defvar dired-flagged-face 'dired-flagged
406 "Face name used for files flagged for deletion.")
408 (defface dired-warning
409 ;; Inherit from font-lock-warning-face since with min-colors 8
410 ;; font-lock-comment-face is not colored any more.
411 '((t (:inherit font-lock-warning-face)))
412 "Face used to highlight a part of a buffer that needs user attention."
413 :group 'dired-faces
414 :version "22.1")
415 (defvar dired-warning-face 'dired-warning
416 "Face name used for a part of a buffer that needs user attention.")
418 (defface dired-perm-write
419 '((((type w32 pc)) :inherit default) ;; These default to rw-rw-rw.
420 ;; Inherit from font-lock-comment-delimiter-face since with min-colors 8
421 ;; font-lock-comment-face is not colored any more.
422 (t (:inherit font-lock-comment-delimiter-face)))
423 "Face used to highlight permissions of group- and world-writable files."
424 :group 'dired-faces
425 :version "22.2")
426 (defvar dired-perm-write-face 'dired-perm-write
427 "Face name used for permissions of group- and world-writable files.")
429 (defface dired-directory
430 '((t (:inherit font-lock-function-name-face)))
431 "Face used for subdirectories."
432 :group 'dired-faces
433 :version "22.1")
434 (defvar dired-directory-face 'dired-directory
435 "Face name used for subdirectories.")
437 (defface dired-symlink
438 '((t (:inherit font-lock-keyword-face)))
439 "Face used for symbolic links."
440 :group 'dired-faces
441 :version "22.1")
442 (defvar dired-symlink-face 'dired-symlink
443 "Face name used for symbolic links.")
445 (defface dired-ignored
446 '((t (:inherit shadow)))
447 "Face used for files suffixed with `completion-ignored-extensions'."
448 :group 'dired-faces
449 :version "22.1")
450 (defvar dired-ignored-face 'dired-ignored
451 "Face name used for files suffixed with `completion-ignored-extensions'.")
453 (defvar dired-font-lock-keywords
454 (list
456 ;; Dired marks.
457 (list dired-re-mark '(0 dired-mark-face))
459 ;; We make heavy use of MATCH-ANCHORED, since the regexps don't identify the
460 ;; file name itself. We search for Dired defined regexps, and then use the
461 ;; Dired defined function `dired-move-to-filename' before searching for the
462 ;; simple regexp ".+". It is that regexp which matches the file name.
464 ;; Marked files.
465 (list (concat "^[" (char-to-string dired-marker-char) "]")
466 '(".+" (dired-move-to-filename) nil (0 dired-marked-face)))
468 ;; Flagged files.
469 (list (concat "^[" (char-to-string dired-del-marker) "]")
470 '(".+" (dired-move-to-filename) nil (0 dired-flagged-face)))
471 ;; People who are paranoid about security would consider this more
472 ;; important than other things such as whether it is a directory.
473 ;; But we don't want to encourage paranoia, so our default
474 ;; should be what's most useful for non-paranoids. -- rms.
475 ;;; ;;
476 ;;; ;; Files that are group or world writable.
477 ;;; (list (concat dired-re-maybe-mark dired-re-inode-size
478 ;;; "\\([-d]\\(....w....\\|.......w.\\)\\)")
479 ;;; '(1 dired-warning-face)
480 ;;; '(".+" (dired-move-to-filename) nil (0 dired-warning-face)))
481 ;; However, we don't need to highlight the file name, only the
482 ;; permissions, to win generally. -- fx.
483 ;; Fixme: we could also put text properties on the permission
484 ;; fields with keymaps to frob the permissions, somewhat a la XEmacs.
485 (list (concat dired-re-maybe-mark dired-re-inode-size
486 "[-d]....\\(w\\)....") ; group writable
487 '(1 dired-perm-write-face))
488 (list (concat dired-re-maybe-mark dired-re-inode-size
489 "[-d].......\\(w\\).") ; world writable
490 '(1 dired-perm-write-face))
492 ;; Subdirectories.
493 (list dired-re-dir
494 '(".+" (dired-move-to-filename) nil (0 dired-directory-face)))
496 ;; Symbolic links.
497 (list dired-re-sym
498 '(".+" (dired-move-to-filename) nil (0 dired-symlink-face)))
500 ;; Files suffixed with `completion-ignored-extensions'.
501 '(eval .
502 ;; It is quicker to first find just an extension, then go back to the
503 ;; start of that file name. So we do this complex MATCH-ANCHORED form.
504 (list (concat "\\(" (regexp-opt completion-ignored-extensions) "\\|#\\)$")
505 '(".+" (dired-move-to-filename) nil (0 dired-ignored-face))))
507 ;; Files suffixed with `completion-ignored-extensions'
508 ;; plus a character put in by -F.
509 '(eval .
510 (list (concat "\\(" (regexp-opt completion-ignored-extensions)
511 "\\|#\\)[*=|]$")
512 '(".+" (progn
513 (end-of-line)
514 ;; If the last character is not part of the filename,
515 ;; move back to the start of the filename
516 ;; so it can be fontified.
517 ;; Otherwise, leave point at the end of the line;
518 ;; that way, nothing is fontified.
519 (unless (get-text-property (1- (point)) 'mouse-face)
520 (dired-move-to-filename)))
521 nil (0 dired-ignored-face))))
523 ;; Explicitly put the default face on file names ending in a colon to
524 ;; avoid fontifying them as directory header.
525 (list (concat dired-re-maybe-mark dired-re-inode-size dired-re-perms ".*:$")
526 '(".+" (dired-move-to-filename) nil (0 'default)))
528 ;; Directory headers.
529 (list dired-subdir-regexp '(1 dired-header-face))
531 "Additional expressions to highlight in Dired mode.")
533 (defvar dnd-protocol-alist)
535 ;;; Macros must be defined before they are used, for the byte compiler.
537 (defmacro dired-mark-if (predicate msg)
538 "Mark all files for which PREDICATE evals to non-nil.
539 PREDICATE is evaluated on each line, with point at beginning of line.
540 MSG is a noun phrase for the type of files being marked.
541 It should end with a noun that can be pluralized by adding `s'.
542 Return value is the number of files marked, or nil if none were marked."
543 `(let ((inhibit-read-only t) count)
544 (save-excursion
545 (setq count 0)
546 (when ,msg
547 (message "%s %ss%s..."
548 (cond ((eq dired-marker-char ?\040) "Unmarking")
549 ((eq dired-del-marker dired-marker-char)
550 "Flagging")
551 (t "Marking"))
552 ,msg
553 (if (eq dired-del-marker dired-marker-char)
554 " for deletion"
555 "")))
556 (goto-char (point-min))
557 (while (not (eobp))
558 (if ,predicate
559 (progn
560 (delete-char 1)
561 (insert dired-marker-char)
562 (setq count (1+ count))))
563 (forward-line 1))
564 (if ,msg (message "%s %s%s %s%s."
565 count
566 ,msg
567 (dired-plural-s count)
568 (if (eq dired-marker-char ?\040) "un" "")
569 (if (eq dired-marker-char dired-del-marker)
570 "flagged" "marked"))))
571 (and (> count 0) count)))
573 (defmacro dired-map-over-marks (body arg &optional show-progress
574 distinguish-one-marked)
575 "Eval BODY with point on each marked line. Return a list of BODY's results.
576 If no marked file could be found, execute BODY on the current
577 line. ARG, if non-nil, specifies the files to use instead of the
578 marked files.
580 If ARG is an integer, use the next ARG (or previous -ARG, if
581 ARG<0) files. In that case, point is dragged along. This is so
582 that commands on the next ARG (instead of the marked) files can
583 be chained easily.
584 For any other non-nil value of ARG, use the current file.
586 If optional third arg SHOW-PROGRESS evaluates to non-nil,
587 redisplay the dired buffer after each file is processed.
589 No guarantee is made about the position on the marked line.
590 BODY must ensure this itself if it depends on this.
592 Search starts at the beginning of the buffer, thus the car of the
593 list corresponds to the line nearest to the buffer's bottom.
594 This is also true for (positive and negative) integer values of
595 ARG.
597 BODY should not be too long as it is expanded four times.
599 If DISTINGUISH-ONE-MARKED is non-nil, then if we find just one
600 marked file, return (t FILENAME) instead of (FILENAME)."
602 ;;Warning: BODY must not add new lines before point - this may cause an
603 ;;endless loop.
604 ;;This warning should not apply any longer, sk 2-Sep-1991 14:10.
605 `(prog1
606 (let ((inhibit-read-only t) case-fold-search found results)
607 (if ,arg
608 (if (integerp ,arg)
609 (progn ;; no save-excursion, want to move point.
610 (dired-repeat-over-lines
611 ,arg
612 (lambda ()
613 (if ,show-progress (sit-for 0))
614 (setq results (cons ,body results))))
615 (if (< ,arg 0)
616 (nreverse results)
617 results))
618 ;; non-nil, non-integer ARG means use current file:
619 (list ,body))
620 (let ((regexp (dired-marker-regexp)) next-position)
621 (save-excursion
622 (goto-char (point-min))
623 ;; remember position of next marked file before BODY
624 ;; can insert lines before the just found file,
625 ;; confusing us by finding the same marked file again
626 ;; and again and...
627 (setq next-position (and (re-search-forward regexp nil t)
628 (point-marker))
629 found (not (null next-position)))
630 (while next-position
631 (goto-char next-position)
632 (if ,show-progress (sit-for 0))
633 (setq results (cons ,body results))
634 ;; move after last match
635 (goto-char next-position)
636 (forward-line 1)
637 (set-marker next-position nil)
638 (setq next-position (and (re-search-forward regexp nil t)
639 (point-marker)))))
640 (if (and ,distinguish-one-marked (= (length results) 1))
641 (setq results (cons t results)))
642 (if found
643 results
644 (list ,body)))))
645 ;; save-excursion loses, again
646 (dired-move-to-filename)))
648 (defun dired-get-marked-files (&optional localp arg filter distinguish-one-marked error)
649 "Return the marked files' names as list of strings.
650 The list is in the same order as the buffer, that is, the car is the
651 first marked file.
652 Values returned are normally absolute file names.
653 Optional arg LOCALP as in `dired-get-filename'.
654 Optional second argument ARG, if non-nil, specifies files near
655 point instead of marked files. It usually comes from the prefix
656 argument.
657 If ARG is an integer, use the next ARG files.
658 If ARG is any other non-nil value, return the current file name.
659 If no files are marked, and ARG is nil, also return the current file name.
660 Optional third argument FILTER, if non-nil, is a function to select
661 some of the files--those for which (funcall FILTER FILENAME) is non-nil.
663 If DISTINGUISH-ONE-MARKED is non-nil, then if we find just one marked file,
664 return (t FILENAME) instead of (FILENAME).
665 Don't use that together with FILTER.
667 If ERROR is non-nil, signal an error when the list of found files is empty.
668 ERROR can be a string with the error message."
669 (let ((all-of-them
670 (save-excursion
671 (delq nil (dired-map-over-marks
672 (dired-get-filename localp 'no-error-if-not-filep)
673 arg nil distinguish-one-marked))))
674 result)
675 (when (equal all-of-them '(t))
676 (setq all-of-them nil))
677 (if (not filter)
678 (setq result
679 (if (and distinguish-one-marked (eq (car all-of-them) t))
680 all-of-them
681 (nreverse all-of-them)))
682 (dolist (file all-of-them)
683 (if (funcall filter file)
684 (push file result))))
685 (when (and (null result) error)
686 (user-error (if (stringp error) error "No files specified")))
687 result))
690 ;; The dired command
692 (defun dired-read-dir-and-switches (str)
693 ;; For use in interactive.
694 (reverse (list
695 (if current-prefix-arg
696 (read-string "Dired listing switches: "
697 dired-listing-switches))
698 ;; If a dialog is used, call `read-directory-name' so the
699 ;; dialog code knows we want directories. Some dialogs
700 ;; can only select directories or files when popped up,
701 ;; not both. If no dialog is used, call `read-file-name'
702 ;; because the user may want completion of file names for
703 ;; use in a wildcard pattern.
704 (if (next-read-file-uses-dialog-p)
705 (read-directory-name (format "Dired %s(directory): " str)
706 nil default-directory nil)
707 (read-file-name (format "Dired %s(directory): " str)
708 nil default-directory nil)))))
710 ;; We want to switch to a more sophisticated version of
711 ;; dired-read-dir-and-switches like the following, if there is a way
712 ;; to make it more intuitive. See bug#1285.
714 ;; (defun dired-read-dir-and-switches (str)
715 ;; ;; For use in interactive.
716 ;; (reverse
717 ;; (list
718 ;; (if current-prefix-arg
719 ;; (read-string "Dired listing switches: "
720 ;; dired-listing-switches))
721 ;; ;; If a dialog is about to be used, call read-directory-name so
722 ;; ;; the dialog code knows we want directories. Some dialogs can
723 ;; ;; only select directories or files when popped up, not both.
724 ;; (if (next-read-file-uses-dialog-p)
725 ;; (read-directory-name (format "Dired %s(directory): " str)
726 ;; nil default-directory nil)
727 ;; (let ((cie ()))
728 ;; (dolist (ext completion-ignored-extensions)
729 ;; (if (eq ?/ (aref ext (1- (length ext)))) (push ext cie)))
730 ;; (setq cie (concat (regexp-opt cie "\\(?:") "\\'"))
731 ;; (let* ((default (and buffer-file-name
732 ;; (abbreviate-file-name buffer-file-name)))
733 ;; (cie cie)
734 ;; (completion-table
735 ;; ;; We need a mix of read-file-name and
736 ;; ;; read-directory-name so that completion to directories
737 ;; ;; is preferred, but if the user wants to enter a global
738 ;; ;; pattern, he can still use completion on filenames to
739 ;; ;; help him write the pattern.
740 ;; ;; Essentially, we want to use
741 ;; ;; (completion-table-with-predicate
742 ;; ;; 'read-file-name-internal 'file-directory-p nil)
743 ;; ;; but that doesn't work because read-file-name-internal
744 ;; ;; does not obey its `predicate' argument.
745 ;; (completion-table-in-turn
746 ;; (lambda (str pred action)
747 ;; (let ((read-file-name-predicate
748 ;; (lambda (f)
749 ;; (and (not (member f '("./" "../")))
750 ;; ;; Hack! Faster than file-directory-p!
751 ;; (eq (aref f (1- (length f))) ?/)
752 ;; (not (string-match cie f))))))
753 ;; (complete-with-action
754 ;; action 'read-file-name-internal str nil)))
755 ;; 'read-file-name-internal)))
756 ;; (minibuffer-with-setup-hook
757 ;; (lambda ()
758 ;; (setq minibuffer-default default)
759 ;; (setq minibuffer-completion-table completion-table))
760 ;; (read-file-name (format "Dired %s(directory): " str)
761 ;; nil default-directory nil))))))))
763 (defun dired-file-name-at-point ()
764 "Try to get a file name at point in the current dired buffer.
765 This hook is intended to be put in `file-name-at-point-functions'.
766 Note that it returns an abbreviated name that can't be used
767 as an argument to `dired-goto-file'."
768 (let ((filename (dired-get-filename nil t)))
769 (when filename
770 (if (file-directory-p filename)
771 (file-name-as-directory (abbreviate-file-name filename))
772 (abbreviate-file-name filename)))))
774 ;;;###autoload (define-key ctl-x-map "d" 'dired)
775 ;;;###autoload
776 (defun dired (dirname &optional switches)
777 "\"Edit\" directory DIRNAME--delete, rename, print, etc. some files in it.
778 Optional second argument SWITCHES specifies the `ls' options used.
779 \(Interactively, use a prefix argument to be able to specify SWITCHES.)
781 If DIRNAME is a string, Dired displays a list of files in DIRNAME (which
782 may also have shell wildcards appended to select certain files).
784 If DIRNAME is a cons, its first element is taken as the directory name
785 and the rest as an explicit list of files to make directory entries for.
786 In this case, SWITCHES are applied to each of the files separately, and
787 therefore switches that control the order of the files in the produced
788 listing have no effect.
790 \\<dired-mode-map>\
791 You can flag files for deletion with \\[dired-flag-file-deletion] and then
792 delete them by typing \\[dired-do-flagged-delete].
793 Type \\[describe-mode] after entering Dired for more info.
795 If DIRNAME is already in a Dired buffer, that buffer is used without refresh."
796 ;; Cannot use (interactive "D") because of wildcards.
797 (interactive (dired-read-dir-and-switches ""))
798 (pop-to-buffer-same-window (dired-noselect dirname switches)))
800 ;;;###autoload (define-key ctl-x-4-map "d" 'dired-other-window)
801 ;;;###autoload
802 (defun dired-other-window (dirname &optional switches)
803 "\"Edit\" directory DIRNAME. Like `dired' but selects in another window."
804 (interactive (dired-read-dir-and-switches "in other window "))
805 (switch-to-buffer-other-window (dired-noselect dirname switches)))
807 ;;;###autoload (define-key ctl-x-5-map "d" 'dired-other-frame)
808 ;;;###autoload
809 (defun dired-other-frame (dirname &optional switches)
810 "\"Edit\" directory DIRNAME. Like `dired' but makes a new frame."
811 (interactive (dired-read-dir-and-switches "in other frame "))
812 (switch-to-buffer-other-frame (dired-noselect dirname switches)))
814 ;;;###autoload
815 (defun dired-noselect (dir-or-list &optional switches)
816 "Like `dired' but returns the Dired buffer as value, does not select it."
817 (or dir-or-list (setq dir-or-list default-directory))
818 ;; This loses the distinction between "/foo/*/" and "/foo/*" that
819 ;; some shells make:
820 (let (dirname initially-was-dirname)
821 (if (consp dir-or-list)
822 (setq dirname (car dir-or-list))
823 (setq dirname dir-or-list))
824 (setq initially-was-dirname
825 (string= (file-name-as-directory dirname) dirname))
826 (setq dirname (abbreviate-file-name
827 (expand-file-name (directory-file-name dirname))))
828 (if find-file-visit-truename
829 (setq dirname (file-truename dirname)))
830 ;; If the argument was syntactically a directory name not a file name,
831 ;; or if it happens to name a file that is a directory,
832 ;; convert it syntactically to a directory name.
833 ;; The reason for checking initially-was-dirname
834 ;; and not just file-directory-p
835 ;; is that file-directory-p is slow over ftp.
836 (if (or initially-was-dirname (file-directory-p dirname))
837 (setq dirname (file-name-as-directory dirname)))
838 (if (consp dir-or-list)
839 (setq dir-or-list (cons dirname (cdr dir-or-list)))
840 (setq dir-or-list dirname))
841 (dired-internal-noselect dir-or-list switches)))
843 ;; The following is an internal dired function. It returns non-nil if
844 ;; the directory visited by the current dired buffer has changed on
845 ;; disk. DIRNAME should be the directory name of that directory.
846 (defun dired-directory-changed-p (dirname)
847 (not (let ((attributes (file-attributes dirname))
848 (modtime (visited-file-modtime)))
849 (or (eq modtime 0)
850 (not (eq (car attributes) t))
851 (equal (nth 5 attributes) modtime)))))
853 (defun dired-buffer-stale-p (&optional noconfirm)
854 "Return non-nil if current Dired buffer needs updating.
855 If NOCONFIRM is non-nil, then this function always returns nil
856 for a remote directory. This feature is used by Auto Revert mode."
857 (let ((dirname
858 (if (consp dired-directory) (car dired-directory) dired-directory)))
859 (and (stringp dirname)
860 (not (when noconfirm (file-remote-p dirname)))
861 (file-readable-p dirname)
862 ;; Do not auto-revert when the dired buffer can be currently
863 ;; written by the user as in `wdired-mode'.
864 buffer-read-only
865 (dired-directory-changed-p dirname))))
867 (defcustom dired-auto-revert-buffer nil
868 "Automatically revert Dired buffer on revisiting.
869 If t, revisiting an existing Dired buffer automatically reverts it.
870 If its value is a function, call this function with the directory
871 name as single argument and revert the buffer if it returns non-nil.
872 Otherwise, a message offering to revert the changed dired buffer
873 is displayed.
874 Note that this is not the same as `auto-revert-mode' that
875 periodically reverts at specified time intervals."
876 :type '(choice
877 (const :tag "Don't revert" nil)
878 (const :tag "Always revert visited Dired buffer" t)
879 (const :tag "Revert changed Dired buffer" dired-directory-changed-p)
880 (function :tag "Predicate function"))
881 :group 'dired
882 :version "23.2")
884 (defun dired--need-align-p ()
885 "Return non-nil if some file names are misaligned.
886 The return value is the target column for the file names."
887 (save-excursion
888 (goto-char (point-min))
889 (dired-goto-next-file)
890 ;; Use point difference instead of `current-column', because
891 ;; the former works when `dired-hide-details-mode' is enabled.
892 (let* ((first (- (point) (point-at-bol)))
893 (target first))
894 (while (and (not (eobp))
895 (progn
896 (forward-line)
897 (dired-move-to-filename)))
898 (when-let* ((distance (- (point) (point-at-bol)))
899 (higher (> distance target)))
900 (setq target distance)))
901 (and (/= first target) target))))
903 (defun dired--align-all-files ()
904 "Align all files adding spaces in front of the size column."
905 (let ((target (dired--need-align-p))
906 (regexp directory-listing-before-filename-regexp))
907 (when target
908 (save-excursion
909 (goto-char (point-min))
910 (dired-goto-next-file)
911 (while (dired-move-to-filename)
912 ;; Use point difference instead of `current-column', because
913 ;; the former works when `dired-hide-details-mode' is enabled.
914 (let ((distance (- target (- (point) (point-at-bol))))
915 (inhibit-read-only t))
916 (unless (zerop distance)
917 (re-search-backward regexp nil t)
918 (goto-char (match-beginning 0))
919 (search-backward-regexp "[[:space:]]" nil t)
920 (skip-chars-forward "[:space:]")
921 (insert-char ?\s distance 'inherit))
922 (forward-line)))))))
924 (defun dired-internal-noselect (dir-or-list &optional switches mode)
925 ;; If DIR-OR-LIST is a string and there is an existing dired buffer
926 ;; for it, just leave buffer as it is (don't even call dired-revert).
927 ;; This saves time especially for deep trees or with ange-ftp.
928 ;; The user can type `g' easily, and it is more consistent with find-file.
929 ;; But if SWITCHES are given they are probably different from the
930 ;; buffer's old value, so call dired-sort-other, which does
931 ;; revert the buffer.
932 ;; Revert the buffer if DIR-OR-LIST is a cons or `dired-directory'
933 ;; is a cons and DIR-OR-LIST is a string.
934 ;; A pity we can't possibly do "Directory has changed - refresh? "
935 ;; like find-file does.
936 ;; Optional argument MODE is passed to dired-find-buffer-nocreate,
937 ;; see there.
938 (let* ((old-buf (current-buffer))
939 (dirname (if (consp dir-or-list) (car dir-or-list) dir-or-list))
940 ;; Look for an existing buffer.
941 (buffer (dired-find-buffer-nocreate dirname mode))
942 ;; Note that buffer already is in dired-mode, if found.
943 (new-buffer-p (null buffer)))
944 (or buffer
945 (setq buffer (create-file-buffer (directory-file-name dirname))))
946 (set-buffer buffer)
947 (if (not new-buffer-p) ; existing buffer ...
948 (cond (switches ; ... but new switches
949 ;; file list may have changed
950 (setq dired-directory dir-or-list)
951 ;; this calls dired-revert
952 (dired-sort-other switches))
953 ;; Always revert when `dir-or-list' is a cons. Also revert
954 ;; if `dired-directory' is a cons but `dir-or-list' is not.
955 ((or (consp dir-or-list) (consp dired-directory))
956 (setq dired-directory dir-or-list)
957 (revert-buffer))
958 ;; Always revert regardless of whether it has changed or not.
959 ((eq dired-auto-revert-buffer t)
960 (revert-buffer))
961 ;; Revert when predicate function returns non-nil.
962 ((functionp dired-auto-revert-buffer)
963 (when (funcall dired-auto-revert-buffer dirname)
964 (revert-buffer)
965 (message "Changed directory automatically updated")))
966 ;; If directory has changed on disk, offer to revert.
967 ((when (dired-directory-changed-p dirname)
968 (message "%s"
969 (substitute-command-keys
970 "Directory has changed on disk; type \\[revert-buffer] to update Dired")))))
971 ;; Else a new buffer
972 (setq default-directory
973 (or (car-safe (insert-directory-wildcard-in-dir-p dirname))
974 ;; We can do this unconditionally
975 ;; because dired-noselect ensures that the name
976 ;; is passed in directory name syntax
977 ;; if it was the name of a directory at all.
978 (file-name-directory dirname)))
979 (or switches (setq switches dired-listing-switches))
980 (if mode (funcall mode)
981 (dired-mode dir-or-list switches))
982 ;; default-directory and dired-actual-switches are set now
983 ;; (buffer-local), so we can call dired-readin:
984 (let ((failed t))
985 (unwind-protect
986 (progn (dired-readin)
987 (setq failed nil))
988 ;; dired-readin can fail if parent directories are inaccessible.
989 ;; Don't leave an empty buffer around in that case.
990 (if failed (kill-buffer buffer))))
991 (goto-char (point-min))
992 (dired-initial-position dirname))
993 (when (consp dired-directory)
994 (dired--align-all-files))
995 (set-buffer old-buf)
996 buffer))
998 (defvar dired-buffers nil
999 ;; Enlarged by dired-advertise
1000 ;; Queried by function dired-buffers-for-dir. When this detects a
1001 ;; killed buffer, it is removed from this list.
1002 "Alist of expanded directories and their associated Dired buffers.")
1004 (defvar dired-find-subdir)
1006 ;; FIXME add a doc-string, and document dired-x extensions.
1007 (defun dired-find-buffer-nocreate (dirname &optional mode)
1008 ;; This differs from dired-buffers-for-dir in that it does not consider
1009 ;; subdirs of default-directory and searches for the first match only.
1010 ;; Also, the major mode must be MODE.
1011 (if (and (featurep 'dired-x)
1012 dired-find-subdir
1013 ;; Don't try to find a wildcard as a subdirectory.
1014 (string-equal dirname (file-name-directory dirname)))
1015 (let* ((cur-buf (current-buffer))
1016 (buffers (nreverse
1017 (dired-buffers-for-dir (expand-file-name dirname))))
1018 (cur-buf-matches (and (memq cur-buf buffers)
1019 ;; Wildcards must match, too:
1020 (equal dired-directory dirname))))
1021 ;; We don't want to switch to the same buffer---
1022 (setq buffers (delq cur-buf buffers))
1023 (or (car (sort buffers #'dired-buffer-more-recently-used-p))
1024 ;; ---unless it's the only possibility:
1025 (and cur-buf-matches cur-buf)))
1026 ;; No dired-x, or dired-find-subdir nil.
1027 (setq dirname (expand-file-name dirname))
1028 (let (found (blist dired-buffers)) ; was (buffer-list)
1029 (or mode (setq mode 'dired-mode))
1030 (while blist
1031 (if (null (buffer-name (cdr (car blist))))
1032 (setq blist (cdr blist))
1033 (with-current-buffer (cdr (car blist))
1034 (if (and (eq major-mode mode)
1035 dired-directory ;; nil during find-alternate-file
1036 (equal dirname
1037 (expand-file-name
1038 (if (consp dired-directory)
1039 (car dired-directory)
1040 dired-directory))))
1041 (setq found (cdr (car blist))
1042 blist nil)
1043 (setq blist (cdr blist))))))
1044 found)))
1047 ;; Read in a new dired buffer
1049 (defun dired-readin ()
1050 "Read in a new Dired buffer.
1051 Differs from `dired-insert-subdir' in that it accepts
1052 wildcards, erases the buffer, and builds the subdir-alist anew
1053 \(including making it buffer-local and clearing it first)."
1055 ;; default-directory and dired-actual-switches must be buffer-local
1056 ;; and initialized by now.
1057 (let (dirname
1058 ;; This makes read-in much faster.
1059 ;; In particular, it prevents the font lock hook from running
1060 ;; until the directory is all read in.
1061 (inhibit-modification-hooks t))
1062 (if (consp dired-directory)
1063 (setq dirname (car dired-directory))
1064 (setq dirname dired-directory))
1065 (setq dirname (expand-file-name dirname))
1066 (save-excursion
1067 ;; This hook which may want to modify dired-actual-switches
1068 ;; based on dired-directory, e.g. with ange-ftp to a SysV host
1069 ;; where ls won't understand -Al switches.
1070 (run-hooks 'dired-before-readin-hook)
1071 (if (consp buffer-undo-list)
1072 (setq buffer-undo-list nil))
1073 (setq-local file-name-coding-system
1074 (or coding-system-for-read file-name-coding-system))
1075 (let ((inhibit-read-only t)
1076 ;; Don't make undo entries for readin.
1077 (buffer-undo-list t))
1078 (widen)
1079 (erase-buffer)
1080 (dired-readin-insert))
1081 (goto-char (point-min))
1082 ;; Must first make alist buffer local and set it to nil because
1083 ;; dired-build-subdir-alist will call dired-clear-alist first
1084 (setq-local dired-subdir-alist nil)
1085 (dired-build-subdir-alist)
1086 (let ((attributes (file-attributes dirname)))
1087 (if (eq (car attributes) t)
1088 (set-visited-file-modtime (nth 5 attributes))))
1089 (set-buffer-modified-p nil)
1090 ;; No need to narrow since the whole buffer contains just
1091 ;; dired-readin's output, nothing else. The hook can
1092 ;; successfully use dired functions (e.g. dired-get-filename)
1093 ;; as the subdir-alist has been built in dired-readin.
1094 (run-hooks 'dired-after-readin-hook))))
1096 ;; Subroutines of dired-readin
1098 (defun dired-readin-insert ()
1099 ;; Insert listing for the specified dir (and maybe file list)
1100 ;; already in dired-directory, assuming a clean buffer.
1101 (let (dir file-list)
1102 (if (consp dired-directory)
1103 (setq dir (car dired-directory)
1104 file-list (cdr dired-directory))
1105 (setq dir dired-directory
1106 file-list nil))
1107 (setq dir (expand-file-name dir))
1108 (if (and (equal "" (file-name-nondirectory dir))
1109 (not file-list))
1110 ;; If we are reading a whole single directory...
1111 (dired-insert-directory dir dired-actual-switches nil nil t)
1112 (if (and (not (insert-directory-wildcard-in-dir-p dir))
1113 (not (file-readable-p
1114 (directory-file-name (file-name-directory dir)))))
1115 (error "Directory %s inaccessible or nonexistent" dir))
1116 ;; Else treat it as a wildcard spec
1117 ;; unless we have an explicit list of files.
1118 (dired-insert-directory dir dired-actual-switches
1119 file-list (not file-list) t))))
1121 (defun dired-align-file (beg end)
1122 "Align the fields of a file to the ones of surrounding lines.
1123 BEG..END is the line where the file info is located."
1124 ;; Some versions of ls try to adjust the size of each field so as to just
1125 ;; hold the largest element ("largest" in the current invocation, of
1126 ;; course). So when a single line is output, the size of each field is
1127 ;; just big enough for that one output. Thus when dired refreshes one
1128 ;; line, the alignment if this line w.r.t the rest is messed up because
1129 ;; the fields of that one line will generally be smaller.
1131 ;; To work around this problem, we here add spaces to try and
1132 ;; re-align the fields as needed. Since this is purely aesthetic,
1133 ;; it is of utmost importance that it doesn't mess up anything like
1134 ;; `dired-move-to-filename'. To this end, we limit ourselves to
1135 ;; adding spaces only, and to only add them at places where there
1136 ;; was already at least one space. This way, as long as
1137 ;; `directory-listing-before-filename-regexp' always matches spaces
1138 ;; with "*" or "+", we know we haven't made anything worse. There
1139 ;; is one spot where the exact number of spaces is important, which
1140 ;; is just before the actual filename, so we refrain from adding
1141 ;; spaces there (and within the filename as well, of course).
1142 (save-excursion
1143 (let (file file-col other other-col)
1144 ;; Check that there is indeed a file, and that there is another adjacent
1145 ;; file with which to align, and that additional spaces are needed to
1146 ;; align the filenames.
1147 (when (and (setq file (progn (goto-char beg)
1148 (dired-move-to-filename nil end)))
1149 (setq file-col (current-column))
1150 (setq other
1151 (or (and (goto-char beg)
1152 (zerop (forward-line -1))
1153 (dired-move-to-filename))
1154 (and (goto-char beg)
1155 (zerop (forward-line 1))
1156 (dired-move-to-filename))))
1157 (setq other-col (current-column))
1158 (/= file other)
1159 ;; Make sure there is some work left to do.
1160 (> other-col file-col))
1161 ;; If we've only looked at the line above, check to see if the line
1162 ;; below exists as well and if so, align with the shorter one.
1163 (when (and (< other file)
1164 (goto-char beg)
1165 (zerop (forward-line 1))
1166 (dired-move-to-filename))
1167 (let ((alt-col (current-column)))
1168 (when (< alt-col other-col)
1169 (setq other-col alt-col)
1170 (setq other (point)))))
1171 ;; Keep positions uptodate when we insert stuff.
1172 (if (> other file) (setq other (copy-marker other)))
1173 (setq file (copy-marker file))
1174 ;; Main loop.
1175 (goto-char beg)
1176 (skip-chars-forward " ") ;Skip to the first field.
1177 (while (and (> other-col file-col)
1178 ;; Don't touch anything just before (and after) the
1179 ;; beginning of the filename.
1180 (> file (point)))
1181 ;; We're now just in front of a field, with a space behind us.
1182 (let* ((curcol (current-column))
1183 ;; Nums are right-aligned.
1184 (num-align (looking-at-p "[0-9]"))
1185 ;; Let's look at the other line, in the same column: we
1186 ;; should be either near the end of the previous field, or
1187 ;; in the space between that field and the next.
1188 ;; [ Of course, it's also possible that we're already within
1189 ;; the next field or even past it, but that's unlikely since
1190 ;; other-col > file-col. ]
1191 ;; Let's find the distance to the alignment-point (either
1192 ;; the beginning or the end of the next field, depending on
1193 ;; whether this field is left or right aligned).
1194 (align-pt-offset
1195 (save-excursion
1196 (goto-char other)
1197 (move-to-column curcol)
1198 (when (looking-at
1199 (concat
1200 (if (eq (char-before) ?\s) " *" "[^ ]* *")
1201 (if num-align "[0-9][^ ]*")))
1202 (- (match-end 0) (match-beginning 0)))))
1203 ;; Now, the number of spaces to insert is align-pt-offset
1204 ;; minus the distance to the equivalent point on the
1205 ;; current line.
1206 (spaces
1207 (if (not num-align)
1208 align-pt-offset
1209 (and align-pt-offset
1210 (save-excursion
1211 (skip-chars-forward "^ ")
1212 (- align-pt-offset (- (current-column) curcol)))))))
1213 (when (and spaces (> spaces 0))
1214 (setq file-col (+ spaces file-col))
1215 (if (> file-col other-col)
1216 (setq spaces (- spaces (- file-col other-col))))
1217 (insert-char ?\s spaces 'inherit)
1218 ;; Let's just make really sure we did not mess up.
1219 (unless (save-excursion
1220 (eq (dired-move-to-filename) (marker-position file)))
1221 ;; Damn! We messed up: let's revert the change.
1222 (delete-char (- spaces)))))
1223 ;; Now skip to next field.
1224 (skip-chars-forward "^ ") (skip-chars-forward " "))
1225 (set-marker file nil)))))
1228 (defvar ls-lisp-use-insert-directory-program)
1230 (defun dired-check-switches (switches short &optional long)
1231 "Return non-nil if the string SWITCHES matches LONG or SHORT format."
1232 (let (case-fold-search)
1233 (and (stringp switches)
1234 (string-match-p (concat "\\(\\`\\| \\)-[[:alnum:]]*" short
1235 (if long (concat "\\|--" long "\\>") ""))
1236 switches))))
1238 (defun dired-switches-escape-p (switches)
1239 "Return non-nil if the string SWITCHES contains -b or --escape."
1240 ;; Do not match things like "--block-size" that happen to contain "b".
1241 (dired-check-switches switches "b" "escape"))
1243 (defun dired-switches-recursive-p (switches)
1244 "Return non-nil if the string SWITCHES contains -R or --recursive."
1245 (dired-check-switches switches "R" "recursive"))
1247 (defun dired-insert-directory (dir switches &optional file-list wildcard hdr)
1248 "Insert a directory listing of DIR, Dired style.
1249 Use SWITCHES to make the listings.
1250 If FILE-LIST is non-nil, list only those files.
1251 Otherwise, if WILDCARD is non-nil, expand wildcards;
1252 in that case, DIR should be a file name that uses wildcards.
1253 In other cases, DIR should be a directory name or a directory filename.
1254 If HDR is non-nil, insert a header line with the directory name."
1255 (let ((opoint (point))
1256 (process-environment (copy-sequence process-environment))
1257 end)
1258 (if (and
1259 ;; Don't try to invoke `ls' if we are on DOS/Windows where
1260 ;; ls-lisp emulation is used, except if they want to use `ls'
1261 ;; as indicated by `ls-lisp-use-insert-directory-program'.
1262 (not (and (featurep 'ls-lisp)
1263 (null ls-lisp-use-insert-directory-program)))
1264 (not (and (featurep 'eshell)
1265 (bound-and-true-p eshell-ls-use-in-dired)))
1266 (or (file-remote-p dir)
1267 (if (eq dired-use-ls-dired 'unspecified)
1268 ;; Check whether "ls --dired" gives exit code 0, and
1269 ;; save the answer in `dired-use-ls-dired'.
1270 (or (setq dired-use-ls-dired
1271 (eq 0 (call-process insert-directory-program
1272 nil nil nil "--dired")))
1273 (progn
1274 (message "ls does not support --dired; \
1275 see `dired-use-ls-dired' for more details.")
1276 nil))
1277 dired-use-ls-dired)))
1278 (setq switches (concat "--dired " switches)))
1279 ;; Expand directory wildcards and fill file-list.
1280 (let ((dir-wildcard (insert-directory-wildcard-in-dir-p dir)))
1281 (cond (dir-wildcard
1282 (setq switches (concat "-d " switches))
1283 ;; We don't know whether the remote ls supports
1284 ;; "--dired", so we cannot add it to the `process-file'
1285 ;; call for wildcards.
1286 (when (file-remote-p dir)
1287 (setq switches (dired-replace-in-string "--dired" "" switches)))
1288 (let* ((default-directory (car dir-wildcard))
1289 (script (format "ls %s %s" switches (cdr dir-wildcard)))
1290 (remotep (file-remote-p dir))
1291 (sh (or (and remotep "/bin/sh")
1292 (and (bound-and-true-p explicit-shell-file-name)
1293 (executable-find explicit-shell-file-name))
1294 (executable-find "sh")))
1295 (switch (if remotep "-c" shell-command-switch)))
1296 (unless
1297 (zerop
1298 (process-file sh nil (current-buffer) nil switch script))
1299 (user-error
1300 "%s: No files matching wildcard" (cdr dir-wildcard)))
1301 (insert-directory-clean (point) switches)))
1303 ;; We used to specify the C locale here, to force English
1304 ;; month names; but this should not be necessary any
1305 ;; more, with the new value of
1306 ;; `directory-listing-before-filename-regexp'.
1307 (if file-list
1308 (dolist (f file-list)
1309 (let ((beg (point)))
1310 (insert-directory f switches nil nil)
1311 ;; Re-align fields, if necessary.
1312 (dired-align-file beg (point))))
1313 (insert-directory dir switches wildcard (not wildcard))))))
1314 ;; Quote certain characters, unless ls quoted them for us.
1315 (if (not (dired-switches-escape-p dired-actual-switches))
1316 (save-excursion
1317 (setq end (point-marker))
1318 (goto-char opoint)
1319 (while (search-forward "\\" end t)
1320 (replace-match (apply #'propertize
1321 "\\\\"
1322 (text-properties-at (match-beginning 0)))
1323 nil t))
1324 (goto-char opoint)
1325 (while (search-forward "\^m" end t)
1326 (replace-match (apply #'propertize
1327 "\\015"
1328 (text-properties-at (match-beginning 0)))
1329 nil t))
1330 (set-marker end nil))
1331 ;; Replace any newlines in DIR with literal "\n"s, for the sake
1332 ;; of the header line. To disambiguate a literal "\n" in the
1333 ;; actual dirname, we also replace "\" with "\\".
1334 ;; Personally, I think this should always be done, irrespective
1335 ;; of the value of dired-actual-switches, because:
1336 ;; i) Dired simply does not work with an unescaped newline in
1337 ;; the directory name used in the header (bug=10469#28), and
1338 ;; ii) "\" is always replaced with "\\" in the listing, so doing
1339 ;; it in the header as well makes things consistent.
1340 ;; But at present it is only done if "-b" is in ls-switches,
1341 ;; because newlines in dirnames are uncommon, and people may
1342 ;; have gotten used to seeing unescaped "\" in the headers.
1343 ;; Note: adjust dired-build-subdir-alist if you change this.
1344 (setq dir (replace-regexp-in-string "\\\\" "\\\\" dir nil t)
1345 dir (replace-regexp-in-string "\n" "\\n" dir nil t)))
1346 ;; If we used --dired and it worked, the lines are already indented.
1347 ;; Otherwise, indent them.
1348 (unless (save-excursion
1349 (goto-char opoint)
1350 (looking-at-p " "))
1351 (let ((indent-tabs-mode nil))
1352 (indent-rigidly opoint (point) 2)))
1353 ;; Insert text at the beginning to standardize things.
1354 (let ((content-point opoint))
1355 (save-excursion
1356 (goto-char opoint)
1357 (when (and (or hdr wildcard)
1358 (not (and (looking-at "^ \\(.*\\):$")
1359 (file-name-absolute-p (match-string 1)))))
1360 ;; Note that dired-build-subdir-alist will replace the name
1361 ;; by its expansion, so it does not matter whether what we insert
1362 ;; here is fully expanded, but it should be absolute.
1363 (insert " " (or (car-safe (insert-directory-wildcard-in-dir-p dir))
1364 (directory-file-name (file-name-directory dir))) ":\n")
1365 (setq content-point (point)))
1366 (when wildcard
1367 ;; Insert "wildcard" line where "total" line would be for a full dir.
1368 (insert " wildcard " (or (cdr-safe (insert-directory-wildcard-in-dir-p dir))
1369 (file-name-nondirectory dir))
1370 "\n")))
1371 (dired-insert-set-properties content-point (point)))))
1373 (defun dired-insert-set-properties (beg end)
1374 "Add various text properties to the lines in the region."
1375 (save-excursion
1376 (goto-char beg)
1377 (while (< (point) end)
1378 (ignore-errors
1379 (if (not (dired-move-to-filename))
1380 (unless (or (looking-at-p "^$")
1381 (looking-at-p dired-subdir-regexp))
1382 (put-text-property (line-beginning-position)
1383 (1+ (line-end-position))
1384 'invisible 'dired-hide-details-information))
1385 (put-text-property (+ (line-beginning-position) 1) (1- (point))
1386 'invisible 'dired-hide-details-detail)
1387 (add-text-properties
1388 (point)
1389 (progn
1390 (dired-move-to-end-of-filename)
1391 (point))
1392 '(mouse-face
1393 highlight
1394 dired-filename t
1395 help-echo "mouse-2: visit this file in other window"))
1396 (when (< (+ (point) 4) (line-end-position))
1397 (put-text-property (+ (point) 4) (line-end-position)
1398 'invisible 'dired-hide-details-link))))
1399 (forward-line 1))))
1401 ;; Reverting a dired buffer
1403 (defun dired-revert (&optional _arg _noconfirm)
1404 "Reread the Dired buffer.
1405 Must also be called after `dired-actual-switches' have changed.
1406 Should not fail even on completely garbaged buffers.
1407 Preserves old cursor, marks/flags, hidden-p.
1409 Dired sets `revert-buffer-function' to this function. The args
1410 ARG and NOCONFIRM, passed from `revert-buffer', are ignored."
1411 (widen) ; just in case user narrowed
1412 (let ((modflag (buffer-modified-p))
1413 (positions (dired-save-positions))
1414 (mark-alist nil) ; save marked files
1415 (hidden-subdirs (dired-remember-hidden))
1416 (old-subdir-alist (cdr (reverse dired-subdir-alist))) ; except pwd
1417 (case-fold-search nil) ; we check for upper case ls flags
1418 (inhibit-read-only t))
1419 (goto-char (point-min))
1420 (setq mark-alist;; only after dired-remember-hidden since this unhides:
1421 (dired-remember-marks (point-min) (point-max)))
1422 ;; treat top level dir extra (it may contain wildcards)
1423 (if (not (consp dired-directory))
1424 (dired-uncache dired-directory)
1425 (dired-uncache (car dired-directory))
1426 (dolist (dir (cdr dired-directory))
1427 (if (file-name-absolute-p dir)
1428 (dired-uncache dir))))
1429 ;; Run dired-after-readin-hook just once, below.
1430 (let ((dired-after-readin-hook nil))
1431 (dired-readin)
1432 (dired-insert-old-subdirs old-subdir-alist))
1433 (dired-mark-remembered mark-alist) ; mark files that were marked
1434 ;; ... run the hook for the whole buffer, and only after markers
1435 ;; have been reinserted (else omitting in dired-x would omit marked files)
1436 (run-hooks 'dired-after-readin-hook) ; no need to narrow
1437 (dired-restore-positions positions)
1438 (save-excursion ; hide subdirs that were hidden
1439 (dolist (dir hidden-subdirs)
1440 (if (dired-goto-subdir dir)
1441 (dired-hide-subdir 1))))
1442 (unless modflag (restore-buffer-modified-p nil)))
1443 ;; outside of the let scope
1444 ;;; Might as well not override the user if the user changed this.
1445 ;;; (setq buffer-read-only t)
1448 ;; Subroutines of dired-revert
1449 ;; Some of these are also used when inserting subdirs.
1451 (defun dired-save-positions ()
1452 "Return current positions in the buffer and all windows with this directory.
1453 The positions have the form (BUFFER-POSITION WINDOW-POSITIONS).
1455 BUFFER-POSITION is the point position in the current Dired buffer.
1456 It has the form (BUFFER DIRED-FILENAME BUFFER-LINE-NUMBER).
1458 WINDOW-POSITIONS are current positions in all windows displaying
1459 this dired buffer. The window positions have the form (WINDOW
1460 DIRED-FILENAME WINDOW-LINE-NUMBER).
1462 We store line numbers instead of point positions because the header
1463 lines might change as well: when this happen the line number doesn't
1464 change; the point does."
1465 (list
1466 (list (current-buffer) (dired-get-filename nil t) (line-number-at-pos))
1467 (mapcar (lambda (w)
1468 (with-selected-window w
1469 (list w
1470 (dired-get-filename nil t)
1471 (line-number-at-pos (window-point w)))))
1472 (get-buffer-window-list nil 0 t))))
1474 (defun dired-restore-positions (positions)
1475 "Restore POSITIONS saved with `dired-save-positions'."
1476 (let* ((buf-file-pos (nth 0 positions))
1477 (buffer (nth 0 buf-file-pos)))
1478 (unless (and (nth 1 buf-file-pos)
1479 (dired-goto-file (nth 1 buf-file-pos)))
1480 (goto-char (point-min))
1481 (forward-line (1- (nth 2 buf-file-pos)))
1482 (dired-move-to-filename))
1483 (dolist (win-file-pos (nth 1 positions))
1484 ;; Ensure that window still displays the original buffer.
1485 (when (eq (window-buffer (nth 0 win-file-pos)) buffer)
1486 (with-selected-window (nth 0 win-file-pos)
1487 (unless (and (nth 1 win-file-pos)
1488 (dired-goto-file (nth 1 win-file-pos)))
1489 (goto-char (point-min))
1490 (forward-line (1- (nth 2 win-file-pos)))
1491 (dired-move-to-filename)))))))
1493 (defun dired-remember-marks (beg end)
1494 "Return alist of files and their marks, from BEG to END."
1495 (if selective-display ; must unhide to make this work.
1496 (let ((inhibit-read-only t))
1497 (subst-char-in-region beg end ?\r ?\n)))
1498 (let (fil chr alist)
1499 (save-excursion
1500 (goto-char beg)
1501 (while (re-search-forward dired-re-mark end t)
1502 (if (setq fil (dired-get-filename nil t))
1503 (setq chr (preceding-char)
1504 alist (cons (cons fil chr) alist)))))
1505 alist))
1507 (defun dired-mark-remembered (alist)
1508 "Mark all files remembered in ALIST.
1509 Each element of ALIST looks like (FILE . MARKERCHAR)."
1510 (let (elt fil chr)
1511 (save-excursion
1512 (while alist
1513 (setq elt (car alist)
1514 alist (cdr alist)
1515 fil (car elt)
1516 chr (cdr elt))
1517 (when (dired-goto-file fil)
1518 (beginning-of-line)
1519 (delete-char 1)
1520 (insert chr))))))
1522 (defun dired-remember-hidden ()
1523 "Return a list of names of subdirs currently hidden."
1524 (let ((l dired-subdir-alist) dir pos result)
1525 (while l
1526 (setq dir (car (car l))
1527 pos (cdr (car l))
1528 l (cdr l))
1529 (goto-char pos)
1530 (skip-chars-forward "^\r\n")
1531 (if (eq (following-char) ?\r)
1532 (setq result (cons dir result))))
1533 result))
1535 (defun dired-insert-old-subdirs (old-subdir-alist)
1536 "Try to insert all subdirs that were displayed before.
1537 Do so according to the former subdir alist OLD-SUBDIR-ALIST."
1538 (or (dired-switches-recursive-p dired-actual-switches)
1539 (let (elt dir)
1540 (while old-subdir-alist
1541 (setq elt (car old-subdir-alist)
1542 old-subdir-alist (cdr old-subdir-alist)
1543 dir (car elt))
1544 (ignore-errors
1545 (dired-uncache dir)
1546 (dired-insert-subdir dir))))))
1548 (defun dired-uncache (dir)
1549 "Remove directory DIR from any directory cache."
1550 (let ((handler (find-file-name-handler dir 'dired-uncache)))
1551 (if handler
1552 (funcall handler 'dired-uncache dir))))
1554 ;; dired mode key bindings and initialization
1556 (defvar dired-mode-map
1557 ;; This looks ugly when substitute-command-keys uses C-d instead d:
1558 ;; (define-key dired-mode-map "\C-d" 'dired-flag-file-deletion)
1559 (let ((map (make-keymap)))
1560 (set-keymap-parent map special-mode-map)
1561 (define-key map [mouse-2] 'dired-mouse-find-file-other-window)
1562 (define-key map [follow-link] 'mouse-face)
1563 ;; Commands to mark or flag certain categories of files
1564 (define-key map "#" 'dired-flag-auto-save-files)
1565 (define-key map "." 'dired-clean-directory)
1566 (define-key map "~" 'dired-flag-backup-files)
1567 ;; Upper case keys (except !) for operating on the marked files
1568 (define-key map "A" 'dired-do-find-regexp)
1569 (define-key map "C" 'dired-do-copy)
1570 (define-key map "B" 'dired-do-byte-compile)
1571 (define-key map "D" 'dired-do-delete)
1572 (define-key map "G" 'dired-do-chgrp)
1573 (define-key map "H" 'dired-do-hardlink)
1574 (define-key map "L" 'dired-do-load)
1575 (define-key map "M" 'dired-do-chmod)
1576 (define-key map "O" 'dired-do-chown)
1577 (define-key map "P" 'dired-do-print)
1578 (define-key map "Q" 'dired-do-find-regexp-and-replace)
1579 (define-key map "R" 'dired-do-rename)
1580 (define-key map "S" 'dired-do-symlink)
1581 (define-key map "T" 'dired-do-touch)
1582 (define-key map "X" 'dired-do-shell-command)
1583 (define-key map "Z" 'dired-do-compress)
1584 (define-key map "c" 'dired-do-compress-to)
1585 (define-key map "!" 'dired-do-shell-command)
1586 (define-key map "&" 'dired-do-async-shell-command)
1587 ;; Comparison commands
1588 (define-key map "=" 'dired-diff)
1589 ;; Tree Dired commands
1590 (define-key map "\M-\C-?" 'dired-unmark-all-files)
1591 (define-key map "\M-\C-d" 'dired-tree-down)
1592 (define-key map "\M-\C-u" 'dired-tree-up)
1593 (define-key map "\M-\C-n" 'dired-next-subdir)
1594 (define-key map "\M-\C-p" 'dired-prev-subdir)
1595 ;; move to marked files
1596 (define-key map "\M-{" 'dired-prev-marked-file)
1597 (define-key map "\M-}" 'dired-next-marked-file)
1598 ;; Make all regexp commands share a `%' prefix:
1599 ;; We used to get to the submap via a symbol dired-regexp-prefix,
1600 ;; but that seems to serve little purpose, and copy-keymap
1601 ;; does a better job without it.
1602 (define-key map "%" nil)
1603 (define-key map "%u" 'dired-upcase)
1604 (define-key map "%l" 'dired-downcase)
1605 (define-key map "%d" 'dired-flag-files-regexp)
1606 (define-key map "%g" 'dired-mark-files-containing-regexp)
1607 (define-key map "%m" 'dired-mark-files-regexp)
1608 (define-key map "%r" 'dired-do-rename-regexp)
1609 (define-key map "%C" 'dired-do-copy-regexp)
1610 (define-key map "%H" 'dired-do-hardlink-regexp)
1611 (define-key map "%R" 'dired-do-rename-regexp)
1612 (define-key map "%S" 'dired-do-symlink-regexp)
1613 (define-key map "%&" 'dired-flag-garbage-files)
1614 ;; Commands for marking and unmarking.
1615 (define-key map "*" nil)
1616 (define-key map "**" 'dired-mark-executables)
1617 (define-key map "*/" 'dired-mark-directories)
1618 (define-key map "*@" 'dired-mark-symlinks)
1619 (define-key map "*%" 'dired-mark-files-regexp)
1620 (define-key map "*c" 'dired-change-marks)
1621 (define-key map "*s" 'dired-mark-subdir-files)
1622 (define-key map "*m" 'dired-mark)
1623 (define-key map "*u" 'dired-unmark)
1624 (define-key map "*?" 'dired-unmark-all-files)
1625 (define-key map "*!" 'dired-unmark-all-marks)
1626 (define-key map "U" 'dired-unmark-all-marks)
1627 (define-key map "*\177" 'dired-unmark-backward)
1628 (define-key map "*\C-n" 'dired-next-marked-file)
1629 (define-key map "*\C-p" 'dired-prev-marked-file)
1630 (define-key map "*t" 'dired-toggle-marks)
1631 ;; Lower keys for commands not operating on all the marked files
1632 (define-key map "a" 'dired-find-alternate-file)
1633 (define-key map "d" 'dired-flag-file-deletion)
1634 (define-key map "e" 'dired-find-file)
1635 (define-key map "f" 'dired-find-file)
1636 (define-key map "\C-m" 'dired-find-file)
1637 (put 'dired-find-file :advertised-binding "\C-m")
1638 (define-key map "g" 'revert-buffer)
1639 (define-key map "i" 'dired-maybe-insert-subdir)
1640 (define-key map "j" 'dired-goto-file)
1641 (define-key map "k" 'dired-do-kill-lines)
1642 (define-key map "l" 'dired-do-redisplay)
1643 (define-key map "m" 'dired-mark)
1644 (define-key map "n" 'dired-next-line)
1645 (define-key map "o" 'dired-find-file-other-window)
1646 (define-key map "\C-o" 'dired-display-file)
1647 (define-key map "p" 'dired-previous-line)
1648 (define-key map "s" 'dired-sort-toggle-or-edit)
1649 (define-key map "t" 'dired-toggle-marks)
1650 (define-key map "u" 'dired-unmark)
1651 (define-key map "v" 'dired-view-file)
1652 (define-key map "w" 'dired-copy-filename-as-kill)
1653 (define-key map "W" 'browse-url-of-dired-file)
1654 (define-key map "x" 'dired-do-flagged-delete)
1655 (define-key map "y" 'dired-show-file-type)
1656 (define-key map "+" 'dired-create-directory)
1657 ;; moving
1658 (define-key map "<" 'dired-prev-dirline)
1659 (define-key map ">" 'dired-next-dirline)
1660 (define-key map "^" 'dired-up-directory)
1661 (define-key map " " 'dired-next-line)
1662 (define-key map [?\S-\ ] 'dired-previous-line)
1663 (define-key map [remap next-line] 'dired-next-line)
1664 (define-key map [remap previous-line] 'dired-previous-line)
1665 ;; hiding
1666 (define-key map "$" 'dired-hide-subdir)
1667 (define-key map "\M-$" 'dired-hide-all)
1668 (define-key map "(" 'dired-hide-details-mode)
1669 ;; isearch
1670 (define-key map (kbd "M-s a C-s") 'dired-do-isearch)
1671 (define-key map (kbd "M-s a M-C-s") 'dired-do-isearch-regexp)
1672 (define-key map (kbd "M-s f C-s") 'dired-isearch-filenames)
1673 (define-key map (kbd "M-s f M-C-s") 'dired-isearch-filenames-regexp)
1674 ;; misc
1675 (define-key map [remap read-only-mode] 'dired-toggle-read-only)
1676 ;; `toggle-read-only' is an obsolete alias for `read-only-mode'
1677 (define-key map [remap toggle-read-only] 'dired-toggle-read-only)
1678 (define-key map "?" 'dired-summary)
1679 (define-key map "\177" 'dired-unmark-backward)
1680 (define-key map [remap undo] 'dired-undo)
1681 (define-key map [remap advertised-undo] 'dired-undo)
1682 ;; thumbnail manipulation (image-dired)
1683 (define-key map "\C-td" 'image-dired-display-thumbs)
1684 (define-key map "\C-tt" 'image-dired-tag-files)
1685 (define-key map "\C-tr" 'image-dired-delete-tag)
1686 (define-key map "\C-tj" 'image-dired-jump-thumbnail-buffer)
1687 (define-key map "\C-ti" 'image-dired-dired-display-image)
1688 (define-key map "\C-tx" 'image-dired-dired-display-external)
1689 (define-key map "\C-ta" 'image-dired-display-thumbs-append)
1690 (define-key map "\C-t." 'image-dired-display-thumb)
1691 (define-key map "\C-tc" 'image-dired-dired-comment-files)
1692 (define-key map "\C-tf" 'image-dired-mark-tagged-files)
1693 (define-key map "\C-t\C-t" 'image-dired-dired-toggle-marked-thumbs)
1694 (define-key map "\C-te" 'image-dired-dired-edit-comment-and-tags)
1695 ;; encryption and decryption (epa-dired)
1696 (define-key map ":d" 'epa-dired-do-decrypt)
1697 (define-key map ":v" 'epa-dired-do-verify)
1698 (define-key map ":s" 'epa-dired-do-sign)
1699 (define-key map ":e" 'epa-dired-do-encrypt)
1701 ;; Make menu bar items.
1703 ;; No need to fo this, now that top-level items are fewer.
1704 ;;;;
1705 ;; Get rid of the Edit menu bar item to save space.
1706 ;(define-key map [menu-bar edit] 'undefined)
1708 (define-key map [menu-bar subdir]
1709 (cons "Subdir" (make-sparse-keymap "Subdir")))
1711 (define-key map [menu-bar subdir hide-all]
1712 '(menu-item "Hide All" dired-hide-all
1713 :help "Hide all subdirectories, leave only header lines"))
1714 (define-key map [menu-bar subdir hide-subdir]
1715 '(menu-item "Hide/UnHide Subdir" dired-hide-subdir
1716 :help "Hide or unhide current directory listing"))
1717 (define-key map [menu-bar subdir tree-down]
1718 '(menu-item "Tree Down" dired-tree-down
1719 :help "Go to first subdirectory header down the tree"))
1720 (define-key map [menu-bar subdir tree-up]
1721 '(menu-item "Tree Up" dired-tree-up
1722 :help "Go to first subdirectory header up the tree"))
1723 (define-key map [menu-bar subdir up]
1724 '(menu-item "Up Directory" dired-up-directory
1725 :help "Edit the parent directory"))
1726 (define-key map [menu-bar subdir prev-subdir]
1727 '(menu-item "Prev Subdir" dired-prev-subdir
1728 :help "Go to previous subdirectory header line"))
1729 (define-key map [menu-bar subdir next-subdir]
1730 '(menu-item "Next Subdir" dired-next-subdir
1731 :help "Go to next subdirectory header line"))
1732 (define-key map [menu-bar subdir prev-dirline]
1733 '(menu-item "Prev Dirline" dired-prev-dirline
1734 :help "Move to next directory-file line"))
1735 (define-key map [menu-bar subdir next-dirline]
1736 '(menu-item "Next Dirline" dired-next-dirline
1737 :help "Move to previous directory-file line"))
1738 (define-key map [menu-bar subdir insert]
1739 '(menu-item "Insert This Subdir" dired-maybe-insert-subdir
1740 :help "Insert contents of subdirectory"
1741 :enable (let ((f (dired-get-filename nil t)))
1742 (and f (file-directory-p f)))))
1743 (define-key map [menu-bar immediate]
1744 (cons "Immediate" (make-sparse-keymap "Immediate")))
1746 (define-key map
1747 [menu-bar immediate image-dired-dired-display-external]
1748 '(menu-item "Display Image Externally" image-dired-dired-display-external
1749 :help "Display image in external viewer"))
1750 (define-key map
1751 [menu-bar immediate image-dired-dired-display-image]
1752 '(menu-item "Display Image" image-dired-dired-display-image
1753 :help "Display sized image in a separate window"))
1754 (define-key map
1755 [menu-bar immediate image-dired-dired-toggle-marked-thumbs]
1756 '(menu-item "Toggle Image Thumbnails in This Buffer" image-dired-dired-toggle-marked-thumbs
1757 :help "Add or remove image thumbnails in front of marked file names"))
1759 (define-key map [menu-bar immediate hide-details]
1760 '(menu-item "Hide Details" dired-hide-details-mode
1761 :help "Hide details in buffer"
1762 :button (:toggle . dired-hide-details-mode)))
1763 (define-key map [menu-bar immediate revert-buffer]
1764 '(menu-item "Refresh" revert-buffer
1765 :help "Update contents of shown directories"))
1767 (define-key map [menu-bar immediate dashes]
1768 '("--"))
1770 (define-key map [menu-bar immediate isearch-filenames-regexp]
1771 '(menu-item "Isearch Regexp in File Names..." dired-isearch-filenames-regexp
1772 :help "Incrementally search for regexp in file names only"))
1773 (define-key map [menu-bar immediate isearch-filenames]
1774 '(menu-item "Isearch in File Names..." dired-isearch-filenames
1775 :help "Incrementally search for string in file names only."))
1776 (define-key map [menu-bar immediate compare-directories]
1777 '(menu-item "Compare Directories..." dired-compare-directories
1778 :help "Mark files with different attributes in two Dired buffers"))
1779 (define-key map [menu-bar immediate backup-diff]
1780 '(menu-item "Compare with Backup" dired-backup-diff
1781 :help "Diff file at cursor with its latest backup"))
1782 (define-key map [menu-bar immediate diff]
1783 '(menu-item "Diff..." dired-diff
1784 :help "Compare file at cursor with another file"))
1785 (define-key map [menu-bar immediate view]
1786 '(menu-item "View This File" dired-view-file
1787 :help "Examine file at cursor in read-only mode"))
1788 (define-key map [menu-bar immediate display]
1789 '(menu-item "Display in Other Window" dired-display-file
1790 :help "Display file at cursor in other window"))
1791 (define-key map [menu-bar immediate find-file-other-window]
1792 '(menu-item "Find in Other Window" dired-find-file-other-window
1793 :help "Edit file at cursor in other window"))
1794 (define-key map [menu-bar immediate find-file]
1795 '(menu-item "Find This File" dired-find-file
1796 :help "Edit file at cursor"))
1797 (define-key map [menu-bar immediate create-directory]
1798 '(menu-item "Create Directory..." dired-create-directory
1799 :help "Create a directory"))
1800 (define-key map [menu-bar immediate wdired-mode]
1801 '(menu-item "Edit File Names" wdired-change-to-wdired-mode
1802 :help "Put a Dired buffer in a mode in which filenames are editable"
1803 :keys "C-x C-q"
1804 :filter (lambda (x) (if (eq major-mode 'dired-mode) x))))
1806 (define-key map [menu-bar regexp]
1807 (cons "Regexp" (make-sparse-keymap "Regexp")))
1809 (define-key map
1810 [menu-bar regexp image-dired-mark-tagged-files]
1811 '(menu-item "Mark From Image Tag..." image-dired-mark-tagged-files
1812 :help "Mark files whose image tags matches regexp"))
1814 (define-key map [menu-bar regexp dashes-1]
1815 '("--"))
1817 (define-key map [menu-bar regexp downcase]
1818 '(menu-item "Downcase" dired-downcase
1819 ;; When running on plain MS-DOS, there's only one
1820 ;; letter-case for file names.
1821 :enable (or (not (fboundp 'msdos-long-file-names))
1822 (msdos-long-file-names))
1823 :help "Rename marked files to lower-case name"))
1824 (define-key map [menu-bar regexp upcase]
1825 '(menu-item "Upcase" dired-upcase
1826 :enable (or (not (fboundp 'msdos-long-file-names))
1827 (msdos-long-file-names))
1828 :help "Rename marked files to upper-case name"))
1829 (define-key map [menu-bar regexp hardlink]
1830 '(menu-item "Hardlink..." dired-do-hardlink-regexp
1831 :help "Make hard links for files matching regexp"))
1832 (define-key map [menu-bar regexp symlink]
1833 '(menu-item "Symlink..." dired-do-symlink-regexp
1834 :visible (fboundp 'make-symbolic-link)
1835 :help "Make symbolic links for files matching regexp"))
1836 (define-key map [menu-bar regexp rename]
1837 '(menu-item "Rename..." dired-do-rename-regexp
1838 :help "Rename marked files matching regexp"))
1839 (define-key map [menu-bar regexp copy]
1840 '(menu-item "Copy..." dired-do-copy-regexp
1841 :help "Copy marked files matching regexp"))
1842 (define-key map [menu-bar regexp flag]
1843 '(menu-item "Flag..." dired-flag-files-regexp
1844 :help "Flag files matching regexp for deletion"))
1845 (define-key map [menu-bar regexp mark]
1846 '(menu-item "Mark..." dired-mark-files-regexp
1847 :help "Mark files matching regexp for future operations"))
1848 (define-key map [menu-bar regexp mark-cont]
1849 '(menu-item "Mark Containing..." dired-mark-files-containing-regexp
1850 :help "Mark files whose contents matches regexp"))
1852 (define-key map [menu-bar mark]
1853 (cons "Mark" (make-sparse-keymap "Mark")))
1855 (define-key map [menu-bar mark prev]
1856 '(menu-item "Previous Marked" dired-prev-marked-file
1857 :help "Move to previous marked file"))
1858 (define-key map [menu-bar mark next]
1859 '(menu-item "Next Marked" dired-next-marked-file
1860 :help "Move to next marked file"))
1861 (define-key map [menu-bar mark marks]
1862 '(menu-item "Change Marks..." dired-change-marks
1863 :help "Replace marker with another character"))
1864 (define-key map [menu-bar mark unmark-all]
1865 '(menu-item "Unmark All" dired-unmark-all-marks))
1866 (define-key map [menu-bar mark symlinks]
1867 '(menu-item "Mark Symlinks" dired-mark-symlinks
1868 :visible (fboundp 'make-symbolic-link)
1869 :help "Mark all symbolic links"))
1870 (define-key map [menu-bar mark directories]
1871 '(menu-item "Mark Directories" dired-mark-directories
1872 :help "Mark all directories except `.' and `..'"))
1873 (define-key map [menu-bar mark directory]
1874 '(menu-item "Mark Old Backups" dired-clean-directory
1875 :help "Flag old numbered backups for deletion"))
1876 (define-key map [menu-bar mark executables]
1877 '(menu-item "Mark Executables" dired-mark-executables
1878 :help "Mark all executable files"))
1879 (define-key map [menu-bar mark garbage-files]
1880 '(menu-item "Flag Garbage Files" dired-flag-garbage-files
1881 :help "Flag unneeded files for deletion"))
1882 (define-key map [menu-bar mark backup-files]
1883 '(menu-item "Flag Backup Files" dired-flag-backup-files
1884 :help "Flag all backup files for deletion"))
1885 (define-key map [menu-bar mark auto-save-files]
1886 '(menu-item "Flag Auto-save Files" dired-flag-auto-save-files
1887 :help "Flag auto-save files for deletion"))
1888 (define-key map [menu-bar mark deletion]
1889 '(menu-item "Flag" dired-flag-file-deletion
1890 :help "Flag current line's file for deletion"))
1891 (define-key map [menu-bar mark unmark]
1892 '(menu-item "Unmark" dired-unmark
1893 :help "Unmark or unflag current line's file"))
1894 (define-key map [menu-bar mark mark]
1895 '(menu-item "Mark" dired-mark
1896 :help "Mark current line's file for future operations"))
1897 (define-key map [menu-bar mark toggle-marks]
1898 '(menu-item "Toggle Marks" dired-toggle-marks
1899 :help "Mark unmarked files, unmark marked ones"))
1901 (define-key map [menu-bar operate]
1902 (cons "Operate" (make-sparse-keymap "Operate")))
1904 (define-key map
1905 [menu-bar operate image-dired-delete-tag]
1906 '(menu-item "Delete Image Tag..." image-dired-delete-tag
1907 :help "Delete image tag from current or marked files"))
1908 (define-key map
1909 [menu-bar operate image-dired-tag-files]
1910 '(menu-item "Add Image Tags..." image-dired-tag-files
1911 :help "Add image tags to current or marked files"))
1912 (define-key map
1913 [menu-bar operate image-dired-dired-comment-files]
1914 '(menu-item "Add Image Comment..." image-dired-dired-comment-files
1915 :help "Add image comment to current or marked files"))
1916 (define-key map
1917 [menu-bar operate image-dired-display-thumbs]
1918 '(menu-item "Display Image Thumbnails" image-dired-display-thumbs
1919 :help "Display image thumbnails for current or marked image files"))
1921 (define-key map [menu-bar operate dashes-4]
1922 '("--"))
1924 (define-key map
1925 [menu-bar operate epa-dired-do-decrypt]
1926 '(menu-item "Decrypt..." epa-dired-do-decrypt
1927 :help "Decrypt current or marked files"))
1929 (define-key map
1930 [menu-bar operate epa-dired-do-verify]
1931 '(menu-item "Verify" epa-dired-do-verify
1932 :help "Verify digital signature of current or marked files"))
1934 (define-key map
1935 [menu-bar operate epa-dired-do-sign]
1936 '(menu-item "Sign..." epa-dired-do-sign
1937 :help "Create digital signature of current or marked files"))
1939 (define-key map
1940 [menu-bar operate epa-dired-do-encrypt]
1941 '(menu-item "Encrypt..." epa-dired-do-encrypt
1942 :help "Encrypt current or marked files"))
1944 (define-key map [menu-bar operate dashes-3]
1945 '("--"))
1947 (define-key map [menu-bar operate query-replace]
1948 '(menu-item "Query Replace in Files..." dired-do-find-regexp-and-replace
1949 :help "Replace regexp matches in marked files"))
1950 (define-key map [menu-bar operate search]
1951 '(menu-item "Search Files..." dired-do-find-regexp
1952 :help "Search marked files for matches of regexp"))
1953 (define-key map [menu-bar operate isearch-regexp]
1954 '(menu-item "Isearch Regexp Files..." dired-do-isearch-regexp
1955 :help "Incrementally search marked files for regexp"))
1956 (define-key map [menu-bar operate isearch]
1957 '(menu-item "Isearch Files..." dired-do-isearch
1958 :help "Incrementally search marked files for string"))
1959 (define-key map [menu-bar operate chown]
1960 '(menu-item "Change Owner..." dired-do-chown
1961 :visible (not (memq system-type '(ms-dos windows-nt)))
1962 :help "Change the owner of marked files"))
1963 (define-key map [menu-bar operate chgrp]
1964 '(menu-item "Change Group..." dired-do-chgrp
1965 :visible (not (memq system-type '(ms-dos windows-nt)))
1966 :help "Change the group of marked files"))
1967 (define-key map [menu-bar operate chmod]
1968 '(menu-item "Change Mode..." dired-do-chmod
1969 :help "Change mode (attributes) of marked files"))
1970 (define-key map [menu-bar operate touch]
1971 '(menu-item "Change Timestamp..." dired-do-touch
1972 :help "Change timestamp of marked files"))
1973 (define-key map [menu-bar operate load]
1974 '(menu-item "Load" dired-do-load
1975 :help "Load marked Emacs Lisp files"))
1976 (define-key map [menu-bar operate compile]
1977 '(menu-item "Byte-compile" dired-do-byte-compile
1978 :help "Byte-compile marked Emacs Lisp files"))
1979 (define-key map [menu-bar operate compress]
1980 '(menu-item "Compress" dired-do-compress
1981 :help "Compress/uncompress marked files"))
1982 (define-key map [menu-bar operate print]
1983 '(menu-item "Print..." dired-do-print
1984 :help "Ask for print command and print marked files"))
1985 (define-key map [menu-bar operate hardlink]
1986 '(menu-item "Hardlink to..." dired-do-hardlink
1987 :help "Make hard links for current or marked files"))
1988 (define-key map [menu-bar operate symlink]
1989 '(menu-item "Symlink to..." dired-do-symlink
1990 :visible (fboundp 'make-symbolic-link)
1991 :help "Make symbolic links for current or marked files"))
1992 (define-key map [menu-bar operate async-command]
1993 '(menu-item "Asynchronous Shell Command..." dired-do-async-shell-command
1994 :help "Run a shell command asynchronously on current or marked files"))
1995 (define-key map [menu-bar operate command]
1996 '(menu-item "Shell Command..." dired-do-shell-command
1997 :help "Run a shell command on current or marked files"))
1998 (define-key map [menu-bar operate delete]
1999 '(menu-item "Delete" dired-do-delete
2000 :help "Delete current file or all marked files"))
2001 (define-key map [menu-bar operate rename]
2002 '(menu-item "Rename to..." dired-do-rename
2003 :help "Rename current file or move marked files"))
2004 (define-key map [menu-bar operate copy]
2005 '(menu-item "Copy to..." dired-do-copy
2006 :help "Copy current file or all marked files"))
2008 map)
2009 "Local keymap for Dired mode buffers.")
2011 ;; Dired mode is suitable only for specially formatted data.
2012 (put 'dired-mode 'mode-class 'special)
2014 ;; Autoload cookie needed by desktop.el
2015 ;;;###autoload
2016 (defun dired-mode (&optional dirname switches)
2018 Mode for \"editing\" directory listings.
2019 In Dired, you are \"editing\" a list of the files in a directory and
2020 (optionally) its subdirectories, in the format of `ls -lR'.
2021 Each directory is a page: use \\[backward-page] and \\[forward-page] to move pagewise.
2022 \"Editing\" means that you can run shell commands on files, visit,
2023 compress, load or byte-compile them, change their file attributes
2024 and insert subdirectories into the same buffer. You can \"mark\"
2025 files for later commands or \"flag\" them for deletion, either file
2026 by file or all files matching certain criteria.
2027 You can move using the usual cursor motion commands.\\<dired-mode-map>
2028 The buffer is read-only. Digits are prefix arguments.
2029 Type \\[dired-flag-file-deletion] to flag a file `D' for deletion.
2030 Type \\[dired-mark] to Mark a file or subdirectory for later commands.
2031 Most commands operate on the marked files and use the current file
2032 if no files are marked. Use a numeric prefix argument to operate on
2033 the next ARG (or previous -ARG if ARG<0) files, or just `1'
2034 to operate on the current file only. Prefix arguments override marks.
2035 Mark-using commands display a list of failures afterwards. Type \\[dired-summary]
2036 to see why something went wrong.
2037 Type \\[dired-unmark] to Unmark a file or all files of an inserted subdirectory.
2038 Type \\[dired-unmark-backward] to back up one line and unmark or unflag.
2039 Type \\[dired-do-flagged-delete] to delete (eXpunge) the files flagged `D'.
2040 Type \\[dired-find-file] to Find the current line's file
2041 (or dired it in another buffer, if it is a directory).
2042 Type \\[dired-find-file-other-window] to find file or Dired directory in Other window.
2043 Type \\[dired-maybe-insert-subdir] to Insert a subdirectory in this buffer.
2044 Type \\[dired-do-rename] to Rename a file or move the marked files to another directory.
2045 Type \\[dired-do-copy] to Copy files.
2046 Type \\[dired-sort-toggle-or-edit] to toggle Sorting by name/date or change the `ls' switches.
2047 Type \\[revert-buffer] to read all currently expanded directories aGain.
2048 This retains all marks and hides subdirs again that were hidden before.
2049 Use `SPC' and `DEL' to move down and up by lines.
2051 If Dired ever gets confused, you can either type \\[revert-buffer] \
2052 to read the
2053 directories again, type \\[dired-do-redisplay] \
2054 to relist the file at point or the marked files or a
2055 subdirectory, or type \\[dired-build-subdir-alist] to parse the buffer
2056 again for the directory tree.
2058 Customization variables (rename this buffer and type \\[describe-variable] on each line
2059 for more info):
2061 `dired-listing-switches'
2062 `dired-trivial-filenames'
2063 `dired-marker-char'
2064 `dired-del-marker'
2065 `dired-keep-marker-rename'
2066 `dired-keep-marker-copy'
2067 `dired-keep-marker-hardlink'
2068 `dired-keep-marker-symlink'
2070 Hooks (use \\[describe-variable] to see their documentation):
2072 `dired-before-readin-hook'
2073 `dired-after-readin-hook'
2074 `dired-mode-hook'
2075 `dired-load-hook'
2077 Keybindings:
2078 \\{dired-mode-map}"
2079 ;; Not to be called interactively (e.g. dired-directory will be set
2080 ;; to default-directory, which is wrong with wildcards).
2081 (kill-all-local-variables)
2082 (use-local-map dired-mode-map)
2083 (dired-advertise) ; default-directory is already set
2084 (setq major-mode 'dired-mode
2085 mode-name "Dired"
2086 ;; case-fold-search nil
2087 buffer-read-only t
2088 selective-display t ; for subdirectory hiding
2089 mode-line-buffer-identification
2090 (propertized-buffer-identification "%17b"))
2091 ;; Ignore dired-hide-details-* value of invisible text property by default.
2092 (when (eq buffer-invisibility-spec t)
2093 (setq buffer-invisibility-spec (list t)))
2094 (setq-local revert-buffer-function #'dired-revert)
2095 (setq-local buffer-stale-function #'dired-buffer-stale-p)
2096 (setq-local page-delimiter "\n\n")
2097 (setq-local dired-directory (or dirname default-directory))
2098 ;; list-buffers uses this to display the dir being edited in this buffer.
2099 (setq list-buffers-directory
2100 (expand-file-name (if (listp dired-directory)
2101 (car dired-directory)
2102 dired-directory)))
2103 (setq-local dired-actual-switches (or switches dired-listing-switches))
2104 (setq-local font-lock-defaults
2105 '(dired-font-lock-keywords t nil nil beginning-of-line))
2106 (setq-local desktop-save-buffer 'dired-desktop-buffer-misc-data)
2107 (setq dired-switches-alist nil)
2108 (hack-dir-local-variables-non-file-buffer) ; before sorting
2109 (dired-sort-other dired-actual-switches t)
2110 (when (featurep 'dnd)
2111 (setq-local dnd-protocol-alist
2112 (append dired-dnd-protocol-alist dnd-protocol-alist)))
2113 (add-hook 'file-name-at-point-functions 'dired-file-name-at-point nil t)
2114 (add-hook 'isearch-mode-hook 'dired-isearch-filenames-setup nil t)
2115 (run-mode-hooks 'dired-mode-hook))
2117 ;; Idiosyncratic dired commands that don't deal with marks.
2119 (defun dired-summary ()
2120 "Summarize basic Dired commands and show recent Dired errors."
2121 (interactive)
2122 (dired-why)
2123 ;>> this should check the key-bindings and use substitute-command-keys if non-standard
2124 (message
2125 "d-elete, u-ndelete, x-punge, f-ind, o-ther window, R-ename, C-opy, h-elp"))
2127 (defun dired-undo ()
2128 "Undo in a Dired buffer.
2129 This doesn't recover lost files, it just undoes changes in the buffer itself.
2130 You can use it to recover marks, killed lines or subdirs."
2131 (interactive)
2132 (let ((inhibit-read-only t))
2133 (undo))
2134 (dired-build-subdir-alist)
2135 (message "Change in Dired buffer undone.
2136 Actual changes in files cannot be undone by Emacs."))
2138 (defun dired-toggle-read-only ()
2139 "Edit Dired buffer with Wdired, or make it read-only.
2140 If the current buffer can be edited with Wdired, (i.e. the major
2141 mode is `dired-mode'), call `wdired-change-to-wdired-mode'.
2142 Otherwise, toggle `read-only-mode'."
2143 (interactive)
2144 (if (derived-mode-p 'dired-mode)
2145 (wdired-change-to-wdired-mode)
2146 (read-only-mode 'toggle)))
2148 (defun dired-next-line (arg)
2149 "Move down lines then position at filename.
2150 Optional prefix ARG says how many lines to move; default is one line."
2151 (interactive "^p")
2152 (let ((line-move-visual)
2153 (goal-column))
2154 (line-move arg t))
2155 ;; We never want to move point into an invisible line.
2156 (while (and (invisible-p (point))
2157 (not (if (and arg (< arg 0)) (bobp) (eobp))))
2158 (forward-char (if (and arg (< arg 0)) -1 1)))
2159 (dired-move-to-filename))
2161 (defun dired-previous-line (arg)
2162 "Move up lines then position at filename.
2163 Optional prefix ARG says how many lines to move; default is one line."
2164 (interactive "^p")
2165 (dired-next-line (- (or arg 1))))
2167 (defun dired-next-dirline (arg &optional opoint)
2168 "Goto ARGth next directory file line."
2169 (interactive "p")
2170 (or opoint (setq opoint (point)))
2171 (if (if (> arg 0)
2172 (re-search-forward dired-re-dir nil t arg)
2173 (beginning-of-line)
2174 (re-search-backward dired-re-dir nil t (- arg)))
2175 (dired-move-to-filename) ; user may type `i' or `f'
2176 (goto-char opoint)
2177 (error "No more subdirectories")))
2179 (defun dired-prev-dirline (arg)
2180 "Goto ARGth previous directory file line."
2181 (interactive "p")
2182 (dired-next-dirline (- arg)))
2184 (defun dired-up-directory (&optional other-window)
2185 "Run Dired on parent directory of current directory.
2186 Find the parent directory either in this buffer or another buffer.
2187 Creates a buffer if necessary.
2188 If OTHER-WINDOW (the optional prefix arg), display the parent
2189 directory in another window."
2190 (interactive "P")
2191 (let* ((dir (dired-current-directory))
2192 (up (file-name-directory (directory-file-name dir))))
2193 (or (dired-goto-file (directory-file-name dir))
2194 ;; Only try dired-goto-subdir if buffer has more than one dir.
2195 (and (cdr dired-subdir-alist)
2196 (dired-goto-subdir up))
2197 (progn
2198 (if other-window
2199 (dired-other-window up)
2200 (dired up))
2201 (dired-goto-file dir)))))
2203 (defun dired-get-file-for-visit ()
2204 "Get the current line's file name, with an error if file does not exist."
2205 (interactive)
2206 ;; We pass t for second arg so that we don't get error for `.' and `..'.
2207 (let ((raw (dired-get-filename nil t))
2208 file-name)
2209 (if (null raw)
2210 (error "No file on this line"))
2211 (setq file-name (file-name-sans-versions raw t))
2212 (if (file-exists-p file-name)
2213 file-name
2214 (if (file-symlink-p file-name)
2215 (error "File is a symlink to a nonexistent target")
2216 (error "File no longer exists; type `g' to update Dired buffer")))))
2218 ;; Force C-m keybinding rather than `f' or `e' in the mode doc:
2219 (define-obsolete-function-alias 'dired-advertised-find-file 'dired-find-file "23.2")
2220 (defun dired-find-file ()
2221 "In Dired, visit the file or directory named on this line."
2222 (interactive)
2223 ;; Bind `find-file-run-dired' so that the command works on directories
2224 ;; too, independent of the user's setting.
2225 (let ((find-file-run-dired t)
2226 ;; This binding prevents problems with preserving point in
2227 ;; windows displaying Dired buffers, because reverting a Dired
2228 ;; buffer empties it, which changes the places where the
2229 ;; markers used by switch-to-buffer-preserve-window-point
2230 ;; point.
2231 (switch-to-buffer-preserve-window-point
2232 (if dired-auto-revert-buffer
2234 switch-to-buffer-preserve-window-point)))
2235 (find-file (dired-get-file-for-visit))))
2237 (defun dired-find-alternate-file ()
2238 "In Dired, visit file or directory on current line via `find-alternate-file'.
2239 This kills the Dired buffer, then visits the current line's file or directory."
2240 (interactive)
2241 (set-buffer-modified-p nil)
2242 (find-alternate-file (dired-get-file-for-visit)))
2243 ;; Don't override the setting from .emacs.
2244 ;;;###autoload (put 'dired-find-alternate-file 'disabled t)
2246 (defun dired-mouse-find-file (event &optional find-file-func find-dir-func)
2247 "In Dired, visit the file or directory name you click on.
2248 The optional arguments FIND-FILE-FUNC and FIND-DIR-FUNC specify
2249 functions to visit the file and directory, respectively. If
2250 omitted or nil, these arguments default to `find-file' and `dired',
2251 respectively."
2252 (interactive "e")
2253 (or find-file-func (setq find-file-func 'find-file))
2254 (or find-dir-func (setq find-dir-func 'dired))
2255 (let (window pos file)
2256 (save-excursion
2257 (setq window (posn-window (event-end event))
2258 pos (posn-point (event-end event)))
2259 (if (not (windowp window))
2260 (error "No file chosen"))
2261 (set-buffer (window-buffer window))
2262 (goto-char pos)
2263 (setq file (dired-get-file-for-visit)))
2264 (if (file-directory-p file)
2265 (or (and (cdr dired-subdir-alist)
2266 (dired-goto-subdir file))
2267 (progn
2268 (select-window window)
2269 (funcall find-dir-func file)))
2270 (select-window window)
2271 (funcall find-file-func (file-name-sans-versions file t)))))
2273 (defun dired-mouse-find-file-other-window (event)
2274 "In Dired, visit the file or directory name you click on in another window."
2275 (interactive "e")
2276 (dired-mouse-find-file event 'find-file-other-window 'dired-other-window))
2278 (defun dired-mouse-find-file-other-frame (event)
2279 "In Dired, visit the file or directory name you click on in another frame."
2280 (interactive "e")
2281 (dired-mouse-find-file event 'find-file-other-frame 'dired-other-frame))
2283 (defun dired-view-file ()
2284 "In Dired, examine a file in view mode, returning to Dired when done.
2285 When file is a directory, show it in this buffer if it is inserted.
2286 Otherwise, display it in another buffer."
2287 (interactive)
2288 (let ((file (dired-get-file-for-visit)))
2289 (if (file-directory-p file)
2290 (or (and (cdr dired-subdir-alist)
2291 (dired-goto-subdir file))
2292 (dired file))
2293 (view-file file))))
2295 (defun dired-find-file-other-window ()
2296 "In Dired, visit this file or directory in another window."
2297 (interactive)
2298 (find-file-other-window (dired-get-file-for-visit)))
2300 (defun dired-display-file ()
2301 "In Dired, display this file or directory in another window."
2302 (interactive)
2303 (display-buffer (find-file-noselect (dired-get-file-for-visit))
2306 ;;; Functions for extracting and manipulating file names in Dired buffers.
2308 (defun dired-get-filename (&optional localp no-error-if-not-filep)
2309 "In Dired, return name of file mentioned on this line.
2310 Value returned normally includes the directory name.
2311 Optional arg LOCALP with value `no-dir' means don't include directory
2312 name in result. A value of `verbatim' means to return the name exactly as
2313 it occurs in the buffer, and a value of t means construct name relative to
2314 `default-directory', which still may contain slashes if in a subdirectory.
2315 Optional arg NO-ERROR-IF-NOT-FILEP means treat `.' and `..' as
2316 regular filenames and return nil if no filename on this line.
2317 Otherwise, an error occurs in these cases."
2318 (let (case-fold-search file p1 p2 already-absolute)
2319 (save-excursion
2320 (if (setq p1 (dired-move-to-filename (not no-error-if-not-filep)))
2321 (setq p2 (dired-move-to-end-of-filename no-error-if-not-filep))))
2322 ;; nil if no file on this line, but no-error-if-not-filep is t:
2323 (if (setq file (and p1 p2 (buffer-substring p1 p2)))
2324 (progn
2325 ;; Get rid of the mouse-face property that file names have.
2326 (set-text-properties 0 (length file) nil file)
2327 ;; Unquote names quoted by ls or by dired-insert-directory.
2328 ;; This code was written using `read' to unquote, because
2329 ;; it's faster than substituting \007 (4 chars) -> ^G (1
2330 ;; char) etc. in a lisp loop. Unfortunately, this decision
2331 ;; has necessitated hacks such as dealing with filenames
2332 ;; with quotation marks in their names.
2333 (while (string-match "\\(?:[^\\]\\|\\`\\)\\(\"\\)" file)
2334 (setq file (replace-match "\\\"" nil t file 1)))
2335 ;; Unescape any spaces escaped by ls -b (bug#10469).
2336 ;; Other -b quotes, eg \t, \n, work transparently.
2337 (if (dired-switches-escape-p dired-actual-switches)
2338 (let ((start 0)
2339 (rep "")
2340 (shift -1))
2341 (if (eq localp 'verbatim)
2342 (setq rep "\\\\"
2343 shift +1))
2344 (while (string-match "\\(\\\\\\) " file start)
2345 (setq file (replace-match rep nil t file 1)
2346 start (+ shift (match-end 0))))))
2347 (when (eq system-type 'windows-nt)
2348 (save-match-data
2349 (let ((start 0))
2350 (while (string-match "\\\\" file start)
2351 (aset file (match-beginning 0) ?/)
2352 (setq start (match-end 0))))))
2354 ;; Hence we don't need to worry about converting `\\' back to `\'.
2355 (setq file (read (concat "\"" file "\"")))))
2356 (and file (files--name-absolute-system-p file)
2357 (setq already-absolute t))
2358 (cond
2359 ((null file)
2360 nil)
2361 ((eq localp 'verbatim)
2362 file)
2363 ((and (not no-error-if-not-filep)
2364 (member file '("." "..")))
2365 (error "Cannot operate on `.' or `..'"))
2366 ((and (eq localp 'no-dir) already-absolute)
2367 (file-name-nondirectory file))
2368 (already-absolute
2369 (let ((handler (find-file-name-handler file nil)))
2370 ;; check for safe-magic property so that we won't
2371 ;; put /: for names that don't really need them.
2372 ;; For instance, .gz files when auto-compression-mode is on.
2373 (if (and handler (not (get handler 'safe-magic)))
2374 (concat "/:" file)
2375 file)))
2376 ((eq localp 'no-dir)
2377 file)
2378 ((equal (dired-current-directory) "/")
2379 (setq file (concat (dired-current-directory localp) file))
2380 (let ((handler (find-file-name-handler file nil)))
2381 ;; check for safe-magic property so that we won't
2382 ;; put /: for names that don't really need them.
2383 ;; For instance, .gz files when auto-compression-mode is on.
2384 (if (and handler (not (get handler 'safe-magic)))
2385 (concat "/:" file)
2386 file)))
2388 (concat (dired-current-directory localp) file)))))
2390 (defun dired-string-replace-match (regexp string newtext
2391 &optional literal global)
2392 "Replace first match of REGEXP in STRING with NEWTEXT.
2393 If it does not match, nil is returned instead of the new string.
2394 Optional arg LITERAL means to take NEWTEXT literally.
2395 Optional arg GLOBAL means to replace all matches."
2396 (if global
2397 (let ((start 0) ret)
2398 (while (string-match regexp string start)
2399 (let ((from-end (- (length string) (match-end 0))))
2400 (setq ret (setq string (replace-match newtext t literal string)))
2401 (setq start (- (length string) from-end))))
2402 ret)
2403 (if (not (string-match regexp string 0))
2405 (replace-match newtext t literal string))))
2407 (defun dired-make-absolute (file &optional dir)
2408 ;;"Convert FILE (a file name relative to DIR) to an absolute file name."
2409 ;; We can't always use expand-file-name as this would get rid of `.'
2410 ;; or expand in / instead default-directory if DIR=="".
2411 ;; This should be good enough for ange-ftp.
2412 ;; It should be reasonably fast, though, as it is called in
2413 ;; dired-get-filename.
2414 (concat (or dir default-directory) file))
2416 (defun dired-make-relative (file &optional dir)
2417 "Convert FILE (an absolute file name) to a name relative to DIR.
2418 If DIR is omitted or nil, it defaults to `default-directory'.
2419 If FILE is not in the directory tree of DIR, return FILE
2420 unchanged."
2421 (or dir (setq dir default-directory))
2422 ;; This case comes into play if default-directory is set to
2423 ;; use ~.
2424 (if (and (> (length dir) 0) (= (aref dir 0) ?~))
2425 (setq dir (expand-file-name dir)))
2426 (if (string-match (concat "^" (regexp-quote dir)) file)
2427 (substring file (match-end 0))
2428 file))
2430 (define-minor-mode dired-hide-details-mode
2431 "Toggle visibility of detailed information in current Dired buffer.
2432 When this minor mode is enabled, details such as file ownership and
2433 permissions are hidden from view.
2435 See options: `dired-hide-details-hide-symlink-targets' and
2436 `dired-hide-details-hide-information-lines'."
2437 :group 'dired
2438 (unless (derived-mode-p 'dired-mode)
2439 (error "Not a Dired buffer"))
2440 (dired-hide-details-update-invisibility-spec)
2441 (if dired-hide-details-mode
2442 (add-hook 'wdired-mode-hook
2443 'dired-hide-details-update-invisibility-spec
2446 (remove-hook 'wdired-mode-hook
2447 'dired-hide-details-update-invisibility-spec
2448 t)))
2450 (defun dired-hide-details-update-invisibility-spec ()
2451 (funcall (if dired-hide-details-mode
2452 'add-to-invisibility-spec
2453 'remove-from-invisibility-spec)
2454 'dired-hide-details-detail)
2455 (funcall (if (and dired-hide-details-mode
2456 dired-hide-details-hide-information-lines)
2457 'add-to-invisibility-spec
2458 'remove-from-invisibility-spec)
2459 'dired-hide-details-information)
2460 (funcall (if (and dired-hide-details-mode
2461 dired-hide-details-hide-symlink-targets
2462 (not (derived-mode-p 'wdired-mode)))
2463 'add-to-invisibility-spec
2464 'remove-from-invisibility-spec)
2465 'dired-hide-details-link))
2467 ;;; Functions for finding the file name in a dired buffer line.
2469 (defvar dired-permission-flags-regexp
2470 "\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)"
2471 "Regular expression to match the permission flags in `ls -l'.")
2473 ;; Move to first char of filename on this line.
2474 ;; Returns position (point) or nil if no filename on this line."
2475 (defun dired-move-to-filename (&optional raise-error eol)
2476 "Move to the beginning of the filename on the current line.
2477 Return the position of the beginning of the filename, or nil if none found."
2478 ;; This is the UNIX version.
2479 (or eol (setq eol (line-end-position)))
2480 (beginning-of-line)
2481 ;; First try assuming `ls --dired' was used.
2482 (let ((change (next-single-property-change (point) 'dired-filename nil eol)))
2483 (cond
2484 ((and change (< change eol))
2485 (goto-char change))
2486 ((re-search-forward directory-listing-before-filename-regexp eol t)
2487 (goto-char (match-end 0)))
2488 ((re-search-forward dired-permission-flags-regexp eol t)
2489 ;; Ha! There *is* a file. Our regexp-from-hell just failed to find it.
2490 (if raise-error
2491 (error "Unrecognized line! Check directory-listing-before-filename-regexp"))
2492 (beginning-of-line)
2493 nil)
2494 (raise-error
2495 (error "No file on this line")))))
2497 (defun dired-move-to-end-of-filename (&optional no-error)
2498 ;; Assumes point is at beginning of filename,
2499 ;; thus the rwx bit re-search-backward below will succeed in *this*
2500 ;; line if at all. So, it should be called only after
2501 ;; (dired-move-to-filename t).
2502 ;; On failure, signals an error (with non-nil NO-ERROR just returns nil).
2503 ;; This is the UNIX version.
2504 (if (get-text-property (point) 'dired-filename)
2505 (goto-char (next-single-property-change (point) 'dired-filename))
2506 (let (opoint file-type executable symlink hidden used-F eol)
2507 (setq used-F (dired-check-switches dired-actual-switches "F" "classify")
2508 opoint (point)
2509 eol (line-end-position)
2510 hidden (and selective-display
2511 (save-excursion (search-forward "\r" eol t))))
2512 (if hidden
2514 (save-excursion ;; Find out what kind of file this is:
2515 ;; Restrict perm bits to be non-blank,
2516 ;; otherwise this matches one char to early (looking backward):
2517 ;; "l---------" (some systems make symlinks that way)
2518 ;; "----------" (plain file with zero perms)
2519 (if (re-search-backward
2520 dired-permission-flags-regexp nil t)
2521 (setq file-type (char-after (match-beginning 1))
2522 symlink (eq file-type ?l)
2523 ;; Only with -F we need to know whether it's an executable
2524 executable (and
2525 used-F
2526 (string-match
2527 "[xst]" ;; execute bit set anywhere?
2528 (concat
2529 (match-string 2)
2530 (match-string 3)
2531 (match-string 4)))))
2532 (or no-error (error "No file on this line"))))
2533 ;; Move point to end of name:
2534 (if symlink
2535 (if (search-forward " -> " eol t)
2536 (progn
2537 (forward-char -4)
2538 (and used-F
2539 dired-ls-F-marks-symlinks
2540 (eq (preceding-char) ?@) ;; did ls really mark the link?
2541 (forward-char -1))))
2542 (goto-char eol) ;; else not a symbolic link
2543 ;; ls -lF marks dirs, sockets, fifos and executables with exactly
2544 ;; one trailing character. (Executable bits on symlinks ain't mean
2545 ;; a thing, even to ls, but we know it's not a symlink.)
2546 (and used-F
2547 (or (memq file-type '(?d ?s ?p))
2548 executable)
2549 (forward-char -1))))
2550 (or no-error
2551 (not (eq opoint (point)))
2552 (error "%s" (if hidden
2553 (substitute-command-keys
2554 "File line is hidden, type \\[dired-hide-subdir] to unhide")
2555 "No file on this line")))
2556 (if (eq opoint (point))
2558 (point)))))
2561 ;;; COPY NAMES OF MARKED FILES INTO KILL-RING.
2563 (defun dired-copy-filename-as-kill (&optional arg)
2564 "Copy names of marked (or next ARG) files into the kill ring.
2565 The names are separated by a space.
2566 With a zero prefix arg, use the absolute file name of each marked file.
2567 With \\[universal-argument], use the file name relative to the Dired buffer's
2568 `default-directory'. (This still may contain slashes if in a subdirectory.)
2570 If on a subdir headerline, use absolute subdirname instead;
2571 prefix arg and marked files are ignored in this case.
2573 You can then feed the file name(s) to other commands with \\[yank]."
2574 (interactive "P")
2575 (let ((string
2576 (or (dired-get-subdir)
2577 (mapconcat #'identity
2578 (if arg
2579 (cond ((zerop (prefix-numeric-value arg))
2580 (dired-get-marked-files))
2581 ((consp arg)
2582 (dired-get-marked-files t))
2584 (dired-get-marked-files
2585 'no-dir (prefix-numeric-value arg))))
2586 (dired-get-marked-files 'no-dir))
2587 " "))))
2588 (unless (string= string "")
2589 (if (eq last-command 'kill-region)
2590 (kill-append string nil)
2591 (kill-new string))
2592 (message "%s" string))))
2595 ;; Keeping Dired buffers in sync with the filesystem and with each other
2597 (defun dired-buffers-for-dir (dir &optional file)
2598 ;; Return a list of buffers for DIR (top level or in-situ subdir).
2599 ;; If FILE is non-nil, include only those whose wildcard pattern (if any)
2600 ;; matches FILE.
2601 ;; The list is in reverse order of buffer creation, most recent last.
2602 ;; As a side effect, killed dired buffers for DIR are removed from
2603 ;; dired-buffers.
2604 (setq dir (file-name-as-directory dir))
2605 (let (result buf)
2606 (dolist (elt dired-buffers)
2607 (setq buf (cdr elt))
2608 (cond
2609 ((null (buffer-name buf))
2610 ;; Buffer is killed - clean up:
2611 (setq dired-buffers (delq elt dired-buffers)))
2612 ((dired-in-this-tree dir (car elt))
2613 (with-current-buffer buf
2614 (and (assoc dir dired-subdir-alist)
2615 (or (null file)
2616 (if (stringp dired-directory)
2617 (let ((wildcards (file-name-nondirectory
2618 dired-directory)))
2619 (or (zerop (length wildcards))
2620 (string-match-p (dired-glob-regexp wildcards)
2621 file)))
2622 (member (expand-file-name file dir)
2623 (cdr dired-directory))))
2624 (setq result (cons buf result)))))))
2625 result))
2627 (defun dired-glob-regexp (pattern)
2628 "Convert glob-pattern PATTERN to a regular expression."
2629 (let ((matched-in-pattern 0) ;; How many chars of PATTERN we've handled.
2630 regexp)
2631 (while (string-match "[[?*]" pattern matched-in-pattern)
2632 (let ((op-end (match-end 0))
2633 (next-op (aref pattern (match-beginning 0))))
2634 (setq regexp (concat regexp
2635 (regexp-quote
2636 (substring pattern matched-in-pattern
2637 (match-beginning 0)))))
2638 (cond ((= next-op ??)
2639 (setq regexp (concat regexp "."))
2640 (setq matched-in-pattern op-end))
2641 ((= next-op ?\[)
2642 ;; Fails to handle ^ yet ????
2643 (let* ((set-start (match-beginning 0))
2644 (set-cont
2645 (if (= (aref pattern (1+ set-start)) ?^)
2646 (+ 3 set-start)
2647 (+ 2 set-start)))
2648 (set-end (string-match-p "]" pattern set-cont))
2649 (set (substring pattern set-start (1+ set-end))))
2650 (setq regexp (concat regexp set))
2651 (setq matched-in-pattern (1+ set-end))))
2652 ((= next-op ?*)
2653 (setq regexp (concat regexp ".*"))
2654 (setq matched-in-pattern op-end)))))
2655 (concat "\\`"
2656 regexp
2657 (regexp-quote
2658 (substring pattern matched-in-pattern))
2659 "\\'")))
2663 (defun dired-advertise ()
2664 ;;"Advertise in variable `dired-buffers' that we dired `default-directory'."
2665 ;; With wildcards we actually advertise too much.
2666 (let ((expanded-default (expand-file-name default-directory)))
2667 (if (memq (current-buffer) (dired-buffers-for-dir expanded-default))
2668 t ; we have already advertised ourselves
2669 (setq dired-buffers
2670 (cons (cons expanded-default (current-buffer))
2671 dired-buffers)))))
2673 (defun dired-unadvertise (dir)
2674 ;; Remove DIR from the buffer alist in variable dired-buffers.
2675 ;; This has the effect of removing any buffer whose main directory is DIR.
2676 ;; It does not affect buffers in which DIR is a subdir.
2677 ;; Removing is also done as a side-effect in dired-buffer-for-dir.
2678 (setq dired-buffers
2679 (delq (assoc (expand-file-name dir) dired-buffers) dired-buffers)))
2681 ;; Tree Dired
2683 ;;; utility functions
2685 (defun dired-in-this-tree (file dir)
2686 ;;"Is FILE part of the directory tree starting at DIR?"
2687 (let (case-fold-search)
2688 (string-match-p (concat "^" (regexp-quote dir)) file)))
2690 (defun dired-normalize-subdir (dir)
2691 ;; Prepend default-directory to DIR if relative file name.
2692 ;; dired-get-filename must be able to make a valid file name from a
2693 ;; file and its directory DIR.
2694 (file-name-as-directory
2695 (if (file-name-absolute-p dir)
2697 (expand-file-name dir default-directory))))
2699 (defun dired-get-subdir ()
2700 ;;"Return the subdir name on this line, or nil if not on a headerline."
2701 ;; Look up in the alist whether this is a headerline.
2702 (save-excursion
2703 (let ((cur-dir (dired-current-directory)))
2704 (beginning-of-line) ; alist stores b-o-l positions
2705 (and (zerop (- (point)
2706 (dired-get-subdir-min (assoc cur-dir
2707 dired-subdir-alist))))
2708 cur-dir))))
2710 ;; can't use macro, must be redefinable for other alist format in dired-nstd.
2711 (defalias 'dired-get-subdir-min 'cdr)
2713 (defun dired-get-subdir-max (elt)
2714 (save-excursion
2715 (goto-char (dired-get-subdir-min elt))
2716 (dired-subdir-max)))
2718 (defun dired-clear-alist ()
2719 (while dired-subdir-alist
2720 (set-marker (dired-get-subdir-min (car dired-subdir-alist)) nil)
2721 (setq dired-subdir-alist (cdr dired-subdir-alist))))
2723 (defun dired-subdir-index (dir)
2724 ;; Return an index into alist for use with nth
2725 ;; for the sake of subdir moving commands.
2726 (let (found (index 0) (alist dired-subdir-alist))
2727 (while alist
2728 (if (string= dir (car (car alist)))
2729 (setq alist nil found t)
2730 (setq alist (cdr alist) index (1+ index))))
2731 (if found index nil)))
2733 (defun dired-next-subdir (arg &optional no-error-if-not-found no-skip)
2734 "Go to next subdirectory, regardless of level."
2735 ;; Use 0 arg to go to this directory's header line.
2736 ;; NO-SKIP prevents moving to end of header line, returning whatever
2737 ;; position was found in dired-subdir-alist.
2738 (interactive "p")
2739 (let ((this-dir (dired-current-directory))
2740 pos index)
2741 ;; nth with negative arg does not return nil but the first element
2742 (setq index (- (dired-subdir-index this-dir) arg))
2743 (setq pos (if (>= index 0)
2744 (dired-get-subdir-min (nth index dired-subdir-alist))))
2745 (if pos
2746 (progn
2747 (goto-char pos)
2748 (or no-skip (skip-chars-forward "^\n\r"))
2749 (point))
2750 (if no-error-if-not-found
2751 nil ; return nil if not found
2752 (error "%s directory" (if (> arg 0) "Last" "First"))))))
2754 (defun dired-build-subdir-alist (&optional switches)
2755 "Build `dired-subdir-alist' by parsing the buffer.
2756 Returns the new value of the alist.
2757 If optional arg SWITCHES is non-nil, use its value
2758 instead of `dired-actual-switches'."
2759 (interactive)
2760 (dired-clear-alist)
2761 (save-excursion
2762 (let* ((count 0)
2763 (inhibit-read-only t)
2764 (buffer-undo-list t)
2765 (switches (or switches dired-actual-switches))
2766 new-dir-name
2767 (R-ftp-base-dir-regex
2768 ;; Used to expand subdirectory names correctly in recursive
2769 ;; ange-ftp listings.
2770 (and (dired-switches-recursive-p switches)
2771 (string-match "\\`/.*:\\(/.*\\)" default-directory)
2772 (concat "\\`" (match-string 1 default-directory)))))
2773 (goto-char (point-min))
2774 (setq dired-subdir-alist nil)
2775 (while (re-search-forward dired-subdir-regexp nil t)
2776 ;; Avoid taking a file name ending in a colon
2777 ;; as a subdir name.
2778 (unless (save-excursion
2779 (goto-char (match-beginning 0))
2780 (beginning-of-line)
2781 (forward-char 2)
2782 (looking-at-p dired-re-perms))
2783 (save-excursion
2784 (goto-char (match-beginning 1))
2785 (setq new-dir-name
2786 (buffer-substring-no-properties (point) (match-end 1))
2787 new-dir-name
2788 (save-match-data
2789 (if (and R-ftp-base-dir-regex
2790 (not (string= new-dir-name default-directory))
2791 (string-match R-ftp-base-dir-regex new-dir-name))
2792 (concat default-directory
2793 (substring new-dir-name (match-end 0)))
2794 (expand-file-name new-dir-name))))
2795 (delete-region (point) (match-end 1))
2796 (insert new-dir-name))
2797 (setq count (1+ count))
2798 ;; Undo any escaping of newlines and \ by dired-insert-directory.
2799 ;; Convert "n" preceded by odd number of \ to newline, and \\ to \.
2800 (when (and (dired-switches-escape-p switches)
2801 (string-match-p "\\\\" new-dir-name))
2802 (let (temp res)
2803 (mapc (lambda (char)
2804 (cond ((equal char ?\\)
2805 (if temp
2806 (setq res (concat res "\\")
2807 temp nil)
2808 (setq temp "\\")))
2809 ((and temp (equal char ?n))
2810 (setq res (concat res "\n")
2811 temp nil))
2813 (setq res (concat res temp (char-to-string char))
2814 temp nil))))
2815 new-dir-name)
2816 (setq new-dir-name res)))
2817 (dired-alist-add-1 new-dir-name
2818 ;; Place a sub directory boundary between lines.
2819 (save-excursion
2820 (goto-char (match-beginning 0))
2821 (beginning-of-line)
2822 (point-marker)))))
2823 (if (and (> count 1) (called-interactively-p 'interactive))
2824 (message "Buffer includes %d directories" count)))
2825 ;; We don't need to sort it because it is in buffer order per
2826 ;; constructionem. Return new alist:
2827 dired-subdir-alist))
2829 (defun dired-alist-add-1 (dir new-marker)
2830 ;; Add new DIR at NEW-MARKER. Don't sort.
2831 (setq dired-subdir-alist
2832 (cons (cons (dired-normalize-subdir dir) new-marker)
2833 dired-subdir-alist)))
2835 (defun dired-goto-next-nontrivial-file ()
2836 ;; Position point on first nontrivial file after point.
2837 (dired-goto-next-file);; so there is a file to compare with
2838 (if (stringp dired-trivial-filenames)
2839 (while (and (not (eobp))
2840 (string-match-p dired-trivial-filenames
2841 (file-name-nondirectory
2842 (or (dired-get-filename nil t) ""))))
2843 (forward-line 1)
2844 (dired-move-to-filename))))
2846 (defun dired-goto-next-file ()
2847 (let ((max (1- (dired-subdir-max))))
2848 (while (and (not (dired-move-to-filename)) (< (point) max))
2849 (forward-line 1))))
2851 (defun dired-goto-file (file)
2852 "Go to line describing file FILE in this Dired buffer."
2853 ;; Return value of point on success, else nil.
2854 ;; FILE must be an absolute file name.
2855 ;; Loses if FILE contains control chars like "\007" for which ls
2856 ;; either inserts "?" or "\\007" into the buffer, so we won't find
2857 ;; it in the buffer.
2858 (interactive
2859 (prog1 ; let push-mark display its message
2860 (list (expand-file-name
2861 (read-file-name "Goto file: "
2862 (dired-current-directory))))
2863 (push-mark)))
2864 (unless (file-name-absolute-p file)
2865 (error "File name `%s' is not absolute" file))
2866 (setq file (directory-file-name file)) ; does no harm if not a directory
2867 (let* ((case-fold-search nil)
2868 (dir (file-name-directory file))
2869 (found (or
2870 ;; First, look for a listing under the absolute name.
2871 (save-excursion
2872 (goto-char (point-min))
2873 (dired-goto-file-1 file file (point-max)))
2874 ;; Next, look for it as a relative name with leading
2875 ;; subdirectories. (This happens in Dired buffers
2876 ;; created by find-dired, for example.)
2877 (save-excursion
2878 (goto-char (point-min))
2879 (dired-goto-file-1 (file-relative-name file
2880 default-directory)
2881 file (point-max)))
2882 ;; Otherwise, look for it as a relative name, a base
2883 ;; name only. The hair is to get the result of
2884 ;; `dired-goto-subdir' without calling it if we don't
2885 ;; have any subdirs.
2886 (save-excursion
2887 (when (if (string= dir (expand-file-name default-directory))
2888 (goto-char (point-min))
2889 (and (cdr dired-subdir-alist)
2890 (dired-goto-subdir dir)))
2891 (dired-goto-file-1 (file-name-nondirectory file)
2892 file
2893 (dired-subdir-max)))))))
2894 ;; Return buffer position, if found.
2895 (if found
2896 (goto-char found))))
2898 (defun dired-goto-file-1 (file full-name limit)
2899 "Advance to the Dired listing labeled by FILE; return its position.
2900 Return nil if the listing is not found. If FILE contains
2901 characters that would not appear in a Dired buffer, search using
2902 the quoted forms of those characters.
2904 FULL-NAME specifies the actual file name the listing must have,
2905 as returned by `dired-get-filename'. LIMIT is the search limit."
2906 (let (str)
2907 (setq str (replace-regexp-in-string "\^m" "\\^m" file nil t))
2908 (setq str (replace-regexp-in-string "\\\\" "\\\\" str nil t))
2909 (and (dired-switches-escape-p dired-actual-switches)
2910 (string-match-p "[ \t\n]" str)
2911 ;; FIXME: to fix this for embedded control characters etc, we
2912 ;; should escape everything that `ls -b' does.
2913 (setq str (replace-regexp-in-string " " "\\ " str nil t)
2914 str (replace-regexp-in-string "\t" "\\t" str nil t)
2915 str (replace-regexp-in-string "\n" "\\n" str nil t)))
2916 (let ((found nil)
2917 ;; filenames are preceded by SPC, this makes the search faster
2918 ;; (e.g. for the filename "-").
2919 (search-string (concat " " str)))
2920 (while (and (not found)
2921 (search-forward search-string limit 'move))
2922 ;; Check that we are in the right place. Match could have
2923 ;; BASE just as initial substring or in permission bits etc.
2924 (if (equal full-name (dired-get-filename nil t))
2925 (setq found (dired-move-to-filename))
2926 (forward-line 1)))
2927 found)))
2929 (defvar dired-find-subdir)
2931 ;; FIXME document whatever dired-x is doing.
2932 (defun dired-initial-position (dirname)
2933 "Where point should go in a new listing of DIRNAME.
2934 Point is assumed to be at the beginning of new subdir line.
2935 It runs the hook `dired-initial-position-hook'."
2936 (end-of-line)
2937 (and (featurep 'dired-x) dired-find-subdir
2938 (dired-goto-subdir dirname))
2939 (if dired-trivial-filenames (dired-goto-next-nontrivial-file))
2940 (run-hooks 'dired-initial-position-hook))
2942 ;; These are hooks which make tree dired work.
2943 ;; They are in this file because other parts of dired need to call them.
2944 ;; But they don't call the rest of tree dired unless there are subdirs loaded.
2946 ;; This function is called for each retrieved filename.
2947 ;; It could stand to be faster, though it's mostly function call
2948 ;; overhead. Avoiding the function call seems to save about 10% in
2949 ;; dired-get-filename. Make it a defsubst?
2950 (defun dired-current-directory (&optional localp)
2951 "Return the name of the subdirectory to which this line belongs.
2952 This returns a string with trailing slash, like `default-directory'.
2953 Optional argument means return a file name relative to `default-directory',
2954 in which case the value could be an empty string if `default-directory'
2955 is the directory where the file on this line resides."
2956 (let ((here (point))
2957 (alist (or dired-subdir-alist
2958 ;; probably because called in a non-dired buffer
2959 (error "No subdir-alist in %s" (current-buffer))))
2960 elt dir)
2961 (while alist
2962 (setq elt (car alist)
2963 dir (car elt)
2964 ;; use `<=' (not `<') as subdir line is part of subdir
2965 alist (if (<= (dired-get-subdir-min elt) here)
2966 nil ; found
2967 (cdr alist))))
2968 (if localp
2969 (dired-make-relative dir default-directory)
2970 dir)))
2972 ;; Subdirs start at the beginning of their header lines and end just
2973 ;; before the beginning of the next header line (or end of buffer).
2975 (defun dired-subdir-max ()
2976 (save-excursion
2977 (if (or (null (cdr dired-subdir-alist)) (not (dired-next-subdir 1 t t)))
2978 (point-max)
2979 (point))))
2981 ;; Deleting files
2983 (defcustom dired-recursive-deletes 'top
2984 "Whether Dired deletes directories recursively.
2985 If nil, Dired will not delete non-empty directories.
2986 `always' means to delete non-empty directories recursively,
2987 without asking. This is dangerous!
2988 `top' means to ask for each top-level directory specified by the
2989 Dired deletion command, and delete its subdirectories without
2990 asking.
2991 Any other value means to ask for each directory."
2992 :type '(choice :tag "Delete non-empty directories"
2993 (const :tag "Yes" always)
2994 (const :tag "No--only delete empty directories" nil)
2995 (const :tag "Confirm for each directory" t)
2996 (const :tag "Confirm for each top directory only" top))
2997 :group 'dired)
2999 ;; Match anything but `.' and `..'.
3000 (defvar dired-re-no-dot "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*")
3002 ;; Delete file, possibly delete a directory and all its files.
3003 ;; This function is useful outside of dired. One could change its name
3004 ;; to e.g. recursive-delete-file and put it somewhere else.
3005 (defun dired-delete-file (file &optional recursive trash) "\
3006 Delete FILE or directory (possibly recursively if optional RECURSIVE is true.)
3007 RECURSIVE determines what to do with a non-empty directory. The effect of
3008 its possible values is:
3010 nil -- do not delete.
3011 `always' -- delete recursively without asking.
3012 `top' -- ask for each directory at top level.
3013 Anything else -- ask for each sub-directory.
3015 TRASH non-nil means to trash the file instead of deleting, provided
3016 `delete-by-moving-to-trash' (which see) is non-nil."
3017 ;; This test is equivalent to
3018 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3019 ;; but more efficient
3020 (if (not (eq t (car (file-attributes file))))
3021 (delete-file file trash)
3022 (let* ((empty-dir-p (null (directory-files file t dired-re-no-dot))))
3023 (if (and recursive (not empty-dir-p))
3024 (unless (eq recursive 'always)
3025 (let ((prompt
3026 (format "Recursively %s %s? "
3027 (if (and trash delete-by-moving-to-trash)
3028 "trash"
3029 "delete")
3030 (dired-make-relative file))))
3031 (pcase (read-answer
3032 prompt
3033 '(("yes" ?y "delete recursively the current directory")
3034 ("no" ?n "skip to next")
3035 ("all" ?! "delete all remaining directories with no more questions")
3036 ("quit" ?q "exit")))
3037 ('"all" (setq recursive 'always dired-recursive-deletes recursive))
3038 ('"yes" (if (eq recursive 'top) (setq recursive 'always)))
3039 ('"no" (setq recursive nil))
3040 ('"quit" (keyboard-quit))
3041 (_ (keyboard-quit))))) ; catch all unknown answers
3042 (setq recursive nil)) ; Empty dir or recursive is nil.
3043 (delete-directory file recursive trash))))
3045 (defun dired-do-flagged-delete (&optional nomessage)
3046 "In Dired, delete the files flagged for deletion.
3047 If NOMESSAGE is non-nil, we don't display any message
3048 if there are no flagged files.
3049 `dired-recursive-deletes' controls whether deletion of
3050 non-empty directories is allowed."
3051 (interactive)
3052 (let* ((dired-marker-char dired-del-marker)
3053 (regexp (dired-marker-regexp))
3054 case-fold-search)
3055 (if (save-excursion (goto-char (point-min))
3056 (re-search-forward regexp nil t))
3057 (dired-internal-do-deletions
3058 (nreverse
3059 ;; this can't move point since ARG is nil
3060 (dired-map-over-marks (cons (dired-get-filename) (point))
3061 nil))
3062 nil t)
3063 (or nomessage
3064 (message "(No deletions requested)")))))
3066 (defun dired-do-delete (&optional arg)
3067 "Delete all marked (or next ARG) files.
3068 `dired-recursive-deletes' controls whether deletion of
3069 non-empty directories is allowed."
3070 ;; This is more consistent with the file marking feature than
3071 ;; dired-do-flagged-delete.
3072 (interactive "P")
3073 (dired-internal-do-deletions
3074 (nreverse
3075 ;; this may move point if ARG is an integer
3076 (dired-map-over-marks (cons (dired-get-filename) (point))
3077 arg))
3078 arg t))
3080 (defvar dired-deletion-confirmer 'yes-or-no-p) ; or y-or-n-p?
3082 (defun dired-internal-do-deletions (l arg &optional trash)
3083 ;; L is an alist of files to delete, with their buffer positions.
3084 ;; ARG is the prefix arg.
3085 ;; Filenames are absolute.
3086 ;; (car L) *must* be the *last* (bottommost) file in the dired buffer.
3087 ;; That way as changes are made in the buffer they do not shift the
3088 ;; lines still to be changed, so the (point) values in L stay valid.
3089 ;; Also, for subdirs in natural order, a subdir's files are deleted
3090 ;; before the subdir itself - the other way around would not work.
3091 (let* ((files (mapcar #'car l))
3092 (count (length l))
3093 (succ 0)
3094 ;; Bind `dired-recursive-deletes' so that we can change it
3095 ;; locally according with the user answer within `dired-delete-file'.
3096 (dired-recursive-deletes dired-recursive-deletes)
3097 (trashing (and trash delete-by-moving-to-trash)))
3098 ;; canonicalize file list for pop up
3099 (setq files (mapcar #'dired-make-relative files))
3100 (if (dired-mark-pop-up
3101 " *Deletions*" 'delete files dired-deletion-confirmer
3102 (format "%s %s "
3103 (if trashing "Trash" "Delete")
3104 (dired-mark-prompt arg files)))
3105 (save-excursion
3106 (catch '--delete-cancel
3107 (let ((progress-reporter
3108 (make-progress-reporter
3109 (if trashing "Trashing..." "Deleting...")
3110 succ count))
3111 failures) ;; files better be in reverse order for this loop!
3112 (while l
3113 (goto-char (cdr (car l)))
3114 (let ((inhibit-read-only t))
3115 (condition-case err
3116 (let ((fn (car (car l))))
3117 (dired-delete-file fn dired-recursive-deletes trash)
3118 ;; if we get here, removing worked
3119 (setq succ (1+ succ))
3120 (progress-reporter-update progress-reporter succ)
3121 (dired-fun-in-all-buffers
3122 (file-name-directory fn) (file-name-nondirectory fn)
3123 #'dired-delete-entry fn))
3124 (quit (throw '--delete-cancel (message "OK, canceled")))
3125 (error ;; catch errors from failed deletions
3126 (dired-log "%s: %s\n" (car err) (error-message-string err))
3127 (setq failures (cons (car (car l)) failures)))))
3128 (setq l (cdr l)))
3129 (if (not failures)
3130 (progress-reporter-done progress-reporter)
3131 (dired-log-summary
3132 (format "%d of %d deletion%s failed"
3133 (length failures) count
3134 (dired-plural-s count))
3135 failures)))))
3136 (message "(No deletions performed)")))
3137 (dired-move-to-filename))
3139 (defun dired-fun-in-all-buffers (directory file fun &rest args)
3140 ;; In all buffers dired'ing DIRECTORY, run FUN with ARGS.
3141 ;; If the buffer has a wildcard pattern, check that it matches FILE.
3142 ;; (FILE does not include a directory component.)
3143 ;; FILE may be nil, in which case ignore it.
3144 ;; Return list of buffers where FUN succeeded (i.e., returned non-nil).
3145 (let (success-list)
3146 (dolist (buf (dired-buffers-for-dir (expand-file-name directory)
3147 file))
3148 (with-current-buffer buf
3149 (if (apply fun args)
3150 (setq success-list (cons (buffer-name buf) success-list)))))
3151 success-list))
3153 ;; Delete the entry for FILE from
3154 (defun dired-delete-entry (file)
3155 (save-excursion
3156 (and (dired-goto-file file)
3157 (let ((inhibit-read-only t))
3158 (delete-region (progn (beginning-of-line) (point))
3159 (save-excursion (forward-line 1) (point))))))
3160 (dired-clean-up-after-deletion file))
3162 (defvar dired-clean-up-buffers-too)
3163 (defvar dired-clean-confirm-killing-deleted-buffers)
3165 (defun dired-clean-up-after-deletion (fn)
3166 "Clean up after a deleted file or directory FN.
3167 Removes any expanded subdirectory of deleted directory. If
3168 `dired-x' is loaded and `dired-clean-up-buffers-too' is non-nil,
3169 kill any buffers visiting those files, prompting for
3170 confirmation. To disable the confirmation, see
3171 `dired-clean-confirm-killing-deleted-buffers'."
3172 (save-excursion (and (cdr dired-subdir-alist)
3173 (dired-goto-subdir fn)
3174 (dired-kill-subdir)))
3175 ;; Offer to kill buffer of deleted file FN.
3176 (when (and (featurep 'dired-x) dired-clean-up-buffers-too)
3177 (let ((buf (get-file-buffer fn)))
3178 (and buf
3179 (and dired-clean-confirm-killing-deleted-buffers
3180 (funcall #'y-or-n-p
3181 (format "Kill buffer of %s, too? "
3182 (file-name-nondirectory fn))))
3183 (kill-buffer buf)))
3184 (let ((buf-list (dired-buffers-for-dir (expand-file-name fn))))
3185 (and buf-list
3186 (and dired-clean-confirm-killing-deleted-buffers
3187 (y-or-n-p (format "Kill Dired buffer%s of %s, too? "
3188 (dired-plural-s (length buf-list))
3189 (file-name-nondirectory fn))))
3190 (dolist (buf buf-list)
3191 (kill-buffer buf))))))
3194 ;; Confirmation
3196 (defun dired-marker-regexp ()
3197 (concat "^" (regexp-quote (char-to-string dired-marker-char))))
3199 (defun dired-plural-s (count)
3200 (if (= 1 count) "" "s"))
3202 (defun dired-mark-prompt (arg files)
3203 "Return a string suitable for use in a Dired prompt.
3204 ARG is normally the prefix argument for the calling command.
3205 FILES should be a list of file names.
3207 The return value has a form like \"foo.txt\", \"[next 3 files]\",
3208 or \"* [3 files]\"."
3209 ;; distinguish-one-marked can cause the first element to be just t.
3210 (if (eq (car files) t) (setq files (cdr files)))
3211 (let ((count (length files)))
3212 (if (= count 1)
3213 (car files)
3214 ;; more than 1 file:
3215 (if (integerp arg)
3216 ;; abs(arg) = count
3217 ;; Perhaps this is nicer, but it also takes more screen space:
3218 ;;(format "[%s %d files]" (if (> arg 0) "next" "previous")
3219 ;; count)
3220 (format "[next %d files]" arg)
3221 (format "%c [%d files]" dired-marker-char count)))))
3223 (defun dired-pop-to-buffer (buf)
3224 "Pop up buffer BUF in a way suitable for Dired."
3225 (declare (obsolete dired-mark-pop-up "24.3"))
3226 (let ((split-window-preferred-function
3227 (lambda (window)
3228 (or (and (let ((split-height-threshold 0))
3229 (window-splittable-p (selected-window)))
3230 ;; Try to split the selected window vertically if
3231 ;; that's possible. (Bug#1806)
3232 (split-window-below))
3233 ;; Otherwise, try to split WINDOW sensibly.
3234 (split-window-sensibly window))))
3235 pop-up-frames)
3236 (pop-to-buffer (get-buffer-create buf)))
3237 ;; See Bug#12281.
3238 (set-window-start nil (point-min))
3239 ;; If dired-shrink-to-fit is t, make its window fit its contents.
3240 (when dired-shrink-to-fit
3241 ;; Try to not delete window when we want to display less than
3242 ;; `window-min-height' lines.
3243 (fit-window-to-buffer (get-buffer-window buf) nil 1 nil nil t)))
3245 (defcustom dired-no-confirm nil
3246 "A list of symbols for commands Dired should not confirm, or t.
3247 Command symbols are `byte-compile', `chgrp', `chmod', `chown', `compress',
3248 `copy', `delete', `hardlink', `load', `move', `print', `shell', `symlink',
3249 `touch' and `uncompress'.
3250 If t, confirmation is never needed."
3251 :group 'dired
3252 :type '(choice (const :tag "Confirmation never needed" t)
3253 (set (const byte-compile) (const chgrp)
3254 (const chmod) (const chown) (const compress)
3255 (const copy) (const delete) (const hardlink)
3256 (const load) (const move) (const print)
3257 (const shell) (const symlink) (const touch)
3258 (const uncompress))))
3260 (defun dired-mark-pop-up (buffer-or-name op-symbol files function &rest args)
3261 "Return FUNCTION's result on ARGS after showing which files are marked.
3262 Displays the file names in a window showing a buffer named
3263 BUFFER-OR-NAME; the default name being \" *Marked Files*\". The
3264 window is not shown if there is just one file, `dired-no-confirm'
3265 is t, or OP-SYMBOL is a member of the list in `dired-no-confirm'.
3267 By default, Dired shrinks the display buffer to fit the marked files.
3268 To disable this, use the Customization interface to add a new rule
3269 to `display-buffer-alist' where condition regexp is \"^ \\*Marked Files\\*$\",
3270 action argument symbol is `window-height' and its value is nil.
3272 FILES is the list of marked files. It can also be (t FILENAME)
3273 in the case of one marked file, to distinguish that from using
3274 just the current file.
3276 FUNCTION should not manipulate files, just read input (an
3277 argument or confirmation)."
3278 (if (or (eq dired-no-confirm t)
3279 (memq op-symbol dired-no-confirm)
3280 ;; If FILES defaulted to the current line's file.
3281 (= (length files) 1))
3282 (apply function args)
3283 (let ((buffer (get-buffer-create (or buffer-or-name " *Marked Files*")))
3284 ;; Mark *Marked Files* window as softly-dedicated, to prevent
3285 ;; other buffers e.g. *Completions* from reusing it (bug#17554).
3286 (display-buffer-mark-dedicated 'soft))
3287 (with-displayed-buffer-window
3288 buffer
3289 (cons 'display-buffer-below-selected
3290 '((window-height . fit-window-to-buffer)
3291 (preserve-size . (nil . t))))
3292 #'(lambda (window _value)
3293 (with-selected-window window
3294 (unwind-protect
3295 (apply function args)
3296 (when (window-live-p window)
3297 (quit-restore-window window 'kill)))))
3298 ;; Handle (t FILE) just like (FILE), here. That value is
3299 ;; used (only in some cases), to mean just one file that was
3300 ;; marked, rather than the current line file.
3301 (with-current-buffer buffer
3302 (dired-format-columns-of-files
3303 (if (eq (car files) t) (cdr files) files))
3304 (remove-text-properties (point-min) (point-max)
3305 '(mouse-face nil help-echo nil)))))))
3307 (defun dired-format-columns-of-files (files)
3308 (let ((beg (point)))
3309 (completion--insert-strings files)
3310 (put-text-property beg (point) 'mouse-face nil)))
3312 ;; Commands to mark or flag file(s) at or near current line.
3314 (defun dired-repeat-over-lines (arg function)
3315 ;; This version skips non-file lines.
3316 (let ((pos (make-marker)))
3317 (beginning-of-line)
3318 (while (and (> arg 0) (not (eobp)))
3319 (setq arg (1- arg))
3320 (beginning-of-line)
3321 (while (and (not (eobp)) (dired-between-files)) (forward-line 1))
3322 (save-excursion
3323 (forward-line 1)
3324 (move-marker pos (1+ (point))))
3325 (save-excursion (funcall function))
3326 ;; Advance to the next line--actually, to the line that *was* next.
3327 ;; (If FUNCTION inserted some new lines in between, skip them.)
3328 (goto-char pos))
3329 (while (and (< arg 0) (not (bobp)))
3330 (setq arg (1+ arg))
3331 (forward-line -1)
3332 (while (and (not (bobp)) (dired-between-files)) (forward-line -1))
3333 (beginning-of-line)
3334 (save-excursion (funcall function)))
3335 (move-marker pos nil)
3336 (dired-move-to-filename)))
3338 (defun dired-between-files ()
3339 ;; This used to be a regexp match of the `total ...' line output by
3340 ;; ls, which is slightly faster, but that is not very robust; notably,
3341 ;; it fails for non-english locales.
3342 (save-excursion (not (dired-move-to-filename))))
3344 (defun dired-next-marked-file (arg &optional wrap opoint)
3345 "Move to the ARGth next marked file.
3346 ARG is the numeric prefix argument and defaults to 1.
3347 If WRAP is non-nil, which happens interactively, wrap around
3348 to the beginning of the buffer and search from there, if no
3349 marked file is found after this line.
3350 Optional argument OPOINT specifies the buffer position to
3351 return to if no ARGth marked file is found; it defaults to
3352 the position where this command was invoked."
3353 (interactive "p\np")
3354 (or opoint (setq opoint (point)));; return to where interactively started
3355 (if (if (> arg 0)
3356 (re-search-forward dired-re-mark nil t arg)
3357 (beginning-of-line)
3358 (re-search-backward dired-re-mark nil t (- arg)))
3359 (dired-move-to-filename)
3360 (if (null wrap)
3361 (progn
3362 (goto-char opoint)
3363 (error "No next marked file"))
3364 (message "(Wraparound for next marked file)")
3365 (goto-char (if (> arg 0) (point-min) (point-max)))
3366 (dired-next-marked-file arg nil opoint))))
3368 (defun dired-prev-marked-file (arg &optional wrap)
3369 "Move to the ARGth previous marked file.
3370 ARG is the numeric prefix argument and defaults to 1.
3371 If WRAP is non-nil, which happens interactively, wrap around
3372 to the end of the buffer and search backwards from there, if
3373 no ARGth marked file is found before this line."
3374 (interactive "p\np")
3375 (dired-next-marked-file (- arg) wrap))
3377 (defun dired-file-marker (file)
3378 ;; Return FILE's marker, or nil if unmarked.
3379 (save-excursion
3380 (and (dired-goto-file file)
3381 (progn
3382 (beginning-of-line)
3383 (if (not (equal ?\040 (following-char)))
3384 (following-char))))))
3386 (defun dired-mark-files-in-region (start end)
3387 (let ((inhibit-read-only t))
3388 (if (> start end)
3389 (error "start > end"))
3390 (goto-char start) ; assumed at beginning of line
3391 (while (< (point) end)
3392 ;; Skip subdir line and following garbage like the `total' line:
3393 (while (and (< (point) end) (dired-between-files))
3394 (forward-line 1))
3395 (if (and (not (looking-at-p dired-re-dot))
3396 (dired-get-filename nil t))
3397 (progn
3398 (delete-char 1)
3399 (insert dired-marker-char)))
3400 (forward-line 1))))
3402 (defun dired-mark (arg &optional interactive)
3403 "Mark the file at point in the Dired buffer.
3404 If the region is active, mark all files in the region.
3405 Otherwise, with a prefix arg, mark files on the next ARG lines.
3407 If on a subdir headerline, mark all its files except `.' and `..'.
3409 Use \\[dired-unmark-all-files] to remove all marks
3410 and \\[dired-unmark] on a subdir to remove the marks in
3411 this subdir."
3412 (interactive (list current-prefix-arg t))
3413 (cond
3414 ;; Mark files in the active region.
3415 ((and interactive (use-region-p))
3416 (save-excursion
3417 (let ((beg (region-beginning))
3418 (end (region-end)))
3419 (dired-mark-files-in-region
3420 (progn (goto-char beg) (line-beginning-position))
3421 (progn (goto-char end) (line-beginning-position))))))
3422 ;; Mark subdir files from the subdir headerline.
3423 ((dired-get-subdir)
3424 (save-excursion (dired-mark-subdir-files)))
3425 ;; Mark the current (or next ARG) files.
3427 (let ((inhibit-read-only t))
3428 (dired-repeat-over-lines
3429 (prefix-numeric-value arg)
3430 (lambda () (delete-char 1) (insert dired-marker-char)))))))
3432 (defun dired-unmark (arg &optional interactive)
3433 "Unmark the file at point in the Dired buffer.
3434 If the region is active, unmark all files in the region.
3435 Otherwise, with a prefix arg, unmark files on the next ARG lines.
3437 If looking at a subdir, unmark all its files except `.' and `..'.
3438 If the region is active in Transient Mark mode, unmark all files
3439 in the active region."
3440 (interactive (list current-prefix-arg t))
3441 (let ((dired-marker-char ?\040))
3442 (dired-mark arg interactive)))
3444 (defun dired-flag-file-deletion (arg &optional interactive)
3445 "In Dired, flag the current line's file for deletion.
3446 If the region is active, flag all files in the region.
3447 Otherwise, with a prefix arg, flag files on the next ARG lines.
3449 If on a subdir headerline, flag all its files except `.' and `..'.
3450 If the region is active in Transient Mark mode, flag all files
3451 in the active region."
3452 (interactive (list current-prefix-arg t))
3453 (let ((dired-marker-char dired-del-marker))
3454 (dired-mark arg interactive)))
3456 (defun dired-unmark-backward (arg)
3457 "In Dired, move up lines and remove marks or deletion flags there.
3458 Optional prefix ARG says how many lines to unmark/unflag; default
3459 is one line.
3460 If the region is active in Transient Mark mode, unmark all files
3461 in the active region."
3462 (interactive "p")
3463 (dired-unmark (- arg) t))
3465 (defun dired-toggle-marks ()
3466 "Toggle marks: marked files become unmarked, and vice versa.
3467 Files marked with other flags (such as `D') are not affected.
3468 `.' and `..' are never toggled.
3469 As always, hidden subdirs are not affected."
3470 (interactive)
3471 (save-excursion
3472 (goto-char (point-min))
3473 (let ((inhibit-read-only t))
3474 (while (not (eobp))
3475 (or (dired-between-files)
3476 (looking-at-p dired-re-dot)
3477 ;; use subst instead of insdel because it does not move
3478 ;; the gap and thus should be faster and because
3479 ;; other characters are left alone automatically
3480 (apply 'subst-char-in-region
3481 (point) (1+ (point))
3482 (if (eq ?\040 (following-char)) ; SPC
3483 (list ?\040 dired-marker-char)
3484 (list dired-marker-char ?\040))))
3485 (forward-line 1)))))
3487 ;;; Commands to mark or flag files based on their characteristics or names.
3489 (defvar dired-regexp-history nil
3490 "History list of regular expressions used in Dired commands.")
3492 (defun dired-read-regexp (prompt &optional default history)
3493 "Read a regexp using `read-regexp'."
3494 (declare (obsolete read-regexp "24.5"))
3495 (read-regexp prompt default (or history 'dired-regexp-history)))
3497 (defun dired-mark-files-regexp (regexp &optional marker-char)
3498 "Mark all files matching REGEXP for use in later commands.
3499 A prefix argument means to unmark them instead.
3500 `.' and `..' are never marked.
3502 REGEXP is an Emacs regexp, not a shell wildcard. Thus, use `\\.o$' for
3503 object files--just `.o' will mark more than you might think."
3504 (interactive
3505 (list (read-regexp (concat (if current-prefix-arg "Unmark" "Mark")
3506 " files (regexp): ")
3507 ;; Add more suggestions into the default list
3508 (cons nil (list (dired-get-filename t t)
3509 (and (dired-get-filename nil t)
3510 (concat (regexp-quote
3511 (file-name-extension
3512 (dired-get-filename nil t) t))
3513 "\\'"))))
3514 'dired-regexp-history)
3515 (if current-prefix-arg ?\040)))
3516 (let ((dired-marker-char (or marker-char dired-marker-char)))
3517 (dired-mark-if
3518 (and (not (looking-at-p dired-re-dot))
3519 (not (eolp)) ; empty line
3520 (let ((fn (dired-get-filename t t)))
3521 (and fn (string-match-p regexp fn))))
3522 "matching file")))
3524 (defun dired-mark-files-containing-regexp (regexp &optional marker-char)
3525 "Mark all files with contents containing REGEXP for use in later commands.
3526 A prefix argument means to unmark them instead.
3527 `.' and `..' are never marked.
3529 Note that if a file is visited in an Emacs buffer, and
3530 `dired-always-read-filesystem' is nil, this command will
3531 look in the buffer without revisiting the file, so the results might
3532 be inconsistent with the file on disk if its contents has changed
3533 since it was last visited."
3534 (interactive
3535 (list (read-regexp (concat (if current-prefix-arg "Unmark" "Mark")
3536 " files containing (regexp): ")
3537 nil 'dired-regexp-history)
3538 (if current-prefix-arg ?\040)))
3539 (let ((dired-marker-char (or marker-char dired-marker-char)))
3540 (dired-mark-if
3541 (and (not (looking-at-p dired-re-dot))
3542 (not (eolp)) ; empty line
3543 (let ((fn (dired-get-filename nil t)))
3544 (when (and fn (file-readable-p fn)
3545 (not (file-directory-p fn)))
3546 (let ((prebuf (get-file-buffer fn)))
3547 (message "Checking %s" fn)
3548 ;; For now we do it inside emacs
3549 ;; Grep might be better if there are a lot of files
3550 (if (and prebuf (not dired-always-read-filesystem))
3551 (with-current-buffer prebuf
3552 (save-excursion
3553 (goto-char (point-min))
3554 (re-search-forward regexp nil t)))
3555 (with-temp-buffer
3556 (insert-file-contents fn)
3557 (goto-char (point-min))
3558 (re-search-forward regexp nil t))))
3560 "matching file")))
3562 (defun dired-flag-files-regexp (regexp)
3563 "In Dired, flag all files containing the specified REGEXP for deletion.
3564 The match is against the non-directory part of the filename. Use `^'
3565 and `$' to anchor matches. Exclude subdirs by hiding them.
3566 `.' and `..' are never flagged."
3567 (interactive (list (read-regexp "Flag for deletion (regexp): "
3568 nil 'dired-regexp-history)))
3569 (dired-mark-files-regexp regexp dired-del-marker))
3571 (defun dired-mark-symlinks (unflag-p)
3572 "Mark all symbolic links.
3573 With prefix argument, unmark or unflag all those files."
3574 (interactive "P")
3575 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
3576 (dired-mark-if (looking-at-p dired-re-sym) "symbolic link")))
3578 (defun dired-mark-directories (unflag-p)
3579 "Mark all directory file lines except `.' and `..'.
3580 With prefix argument, unmark or unflag all those files."
3581 (interactive "P")
3582 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
3583 (dired-mark-if (and (looking-at-p dired-re-dir)
3584 (not (looking-at-p dired-re-dot)))
3585 "directory file")))
3587 (defun dired-mark-executables (unflag-p)
3588 "Mark all executable files.
3589 With prefix argument, unmark or unflag all those files."
3590 (interactive "P")
3591 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
3592 (dired-mark-if (looking-at-p dired-re-exe) "executable file")))
3594 ;; dired-x.el has a dired-mark-sexp interactive command: mark
3595 ;; files for which PREDICATE returns non-nil.
3597 (defun dired-flag-auto-save-files (&optional unflag-p)
3598 "Flag for deletion files whose names suggest they are auto save files.
3599 A prefix argument says to unmark or unflag those files instead."
3600 (interactive "P")
3601 (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
3602 (dired-mark-if
3603 ;; It is less than general to check for # here,
3604 ;; but it's the only way this runs fast enough.
3605 (and (save-excursion (end-of-line)
3607 (eq (preceding-char) ?#)
3608 ;; Handle executables in case of -F option.
3609 ;; We need not worry about the other kinds
3610 ;; of markings that -F makes, since they won't
3611 ;; appear on real auto-save files.
3612 (if (eq (preceding-char) ?*)
3613 (progn
3614 (forward-char -1)
3615 (eq (preceding-char) ?#)))))
3616 (not (looking-at-p dired-re-dir))
3617 (let ((fn (dired-get-filename t t)))
3618 (if fn (auto-save-file-name-p
3619 (file-name-nondirectory fn)))))
3620 "auto save file")))
3622 (defcustom dired-garbage-files-regexp
3623 ;; `log' here is dubious, since it's typically used for useful log
3624 ;; files, not just TeX stuff. -- fx
3625 (concat (regexp-opt
3626 '(".log" ".toc" ".dvi" ".bak" ".orig" ".rej" ".aux"))
3627 "\\'")
3628 "Regular expression to match \"garbage\" files for `dired-flag-garbage-files'."
3629 :type 'regexp
3630 :group 'dired)
3632 (defun dired-flag-garbage-files ()
3633 "Flag for deletion all files that match `dired-garbage-files-regexp'."
3634 (interactive)
3635 (dired-flag-files-regexp dired-garbage-files-regexp))
3637 (defun dired-flag-backup-files (&optional unflag-p)
3638 "Flag all backup files (names ending with `~') for deletion.
3639 With prefix argument, unmark or unflag these files."
3640 (interactive "P")
3641 (let ((dired-marker-char (if unflag-p ?\s dired-del-marker)))
3642 (dired-mark-if
3643 ;; Don't call backup-file-name-p unless the last character looks like
3644 ;; it might be the end of a backup file name. This isn't very general,
3645 ;; but it's the only way this runs fast enough.
3646 (and (save-excursion (end-of-line)
3647 ;; Handle executables in case of -F option.
3648 ;; We need not worry about the other kinds
3649 ;; of markings that -F makes, since they won't
3650 ;; appear on real backup files.
3651 (if (eq (preceding-char) ?*)
3652 (forward-char -1))
3653 (eq (preceding-char) ?~))
3654 (not (looking-at-p dired-re-dir))
3655 (let ((fn (dired-get-filename t t)))
3656 (if fn (backup-file-name-p fn))))
3657 "backup file")))
3659 (defun dired-change-marks (&optional old new)
3660 "Change all OLD marks to NEW marks.
3661 OLD and NEW are both characters used to mark files."
3662 (interactive
3663 (let* ((cursor-in-echo-area t)
3664 (old (progn (message "Change (old mark): ") (read-char)))
3665 (new (progn (message "Change %c marks to (new mark): " old)
3666 (read-char))))
3667 (list old new)))
3668 (if (or (eq old ?\r) (eq new ?\r))
3669 (ding)
3670 (let ((string (format "\n%c" old))
3671 (inhibit-read-only t))
3672 (save-excursion
3673 (goto-char (point-min))
3674 (while (search-forward string nil t)
3675 (if (if (= old ?\s)
3676 (save-match-data
3677 (dired-get-filename 'no-dir t))
3679 (subst-char-in-region (match-beginning 0)
3680 (match-end 0) old new)))))))
3682 (defun dired-unmark-all-marks ()
3683 "Remove all marks from all files in the Dired buffer."
3684 (interactive)
3685 (dired-unmark-all-files ?\r))
3687 ;; Bound in dired-unmark-all-files
3688 (defvar dired-unmark-all-files-query)
3690 (defun dired-unmark-all-files (mark &optional arg)
3691 "Remove a specific mark (or any mark) from every file.
3692 After this command, type the mark character to remove,
3693 or type RET to remove all marks.
3694 With prefix arg, query for each marked file.
3695 Type \\[help-command] at that time for help."
3696 (interactive "cRemove marks (RET means all): \nP")
3697 (save-excursion
3698 (let* ((count 0)
3699 (inhibit-read-only t) case-fold-search
3700 dired-unmark-all-files-query
3701 (string (format "\n%c" mark))
3702 (help-form "\
3703 Type SPC or `y' to unmark one file, DEL or `n' to skip to next,
3704 `!' to unmark all remaining files with no more questions."))
3705 (goto-char (point-min))
3706 (while (if (eq mark ?\r)
3707 (re-search-forward dired-re-mark nil t)
3708 (search-forward string nil t))
3709 (if (or (not arg)
3710 (let ((file (dired-get-filename t t)))
3711 (and file
3712 (dired-query 'dired-unmark-all-files-query
3713 "Unmark file `%s'? "
3714 file))))
3715 (progn (subst-char-in-region (1- (point)) (point)
3716 (preceding-char) ?\s)
3717 (setq count (1+ count)))))
3718 (message (if (= count 1) "1 mark removed"
3719 "%d marks removed")
3720 count))))
3722 ;; Logging failures operating on files, and showing the results.
3724 (defvar dired-log-buffer "*Dired log*")
3726 (defun dired-why ()
3727 "Pop up a buffer with error log output from Dired.
3728 A group of errors from a single command ends with a formfeed.
3729 Thus, use \\[backward-page] to find the beginning of a group of errors."
3730 (interactive)
3731 (if (get-buffer dired-log-buffer)
3732 (let ((owindow (selected-window))
3733 (window (display-buffer (get-buffer dired-log-buffer))))
3734 (unwind-protect
3735 (progn
3736 (select-window window)
3737 (goto-char (point-max))
3738 (forward-line -1)
3739 (backward-page 1)
3740 (recenter 0))
3741 (select-window owindow)))))
3743 (defun dired-log (log &rest args)
3744 ;; Log a message or the contents of a buffer.
3745 ;; If LOG is a string and there are more args, it is formatted with
3746 ;; those ARGS. Usually the LOG string ends with a \n.
3747 ;; End each bunch of errors with (dired-log t):
3748 ;; this inserts the current time and buffer at the start of the page,
3749 ;; and \f (formfeed) at the end.
3750 (let ((obuf (current-buffer)))
3751 (with-current-buffer (get-buffer-create dired-log-buffer)
3752 (goto-char (point-max))
3753 (let ((inhibit-read-only t))
3754 (cond ((stringp log)
3755 (insert (if args
3756 (apply #'format-message log args)
3757 log)))
3758 ((bufferp log)
3759 (insert-buffer-substring log))
3760 ((eq t log)
3761 (backward-page 1)
3762 (unless (bolp)
3763 (insert "\n"))
3764 (insert (current-time-string)
3765 (format-message "\tBuffer `%s'\n" (buffer-name obuf)))
3766 (goto-char (point-max))
3767 (insert "\f\n")))))))
3769 (defun dired-log-summary (string failures)
3770 "State a summary of a command's failures, in echo area and log buffer.
3771 STRING is an overall summary of the failures.
3772 FAILURES is a list of file names that we failed to operate on,
3773 or nil if file names are not applicable."
3774 (if (= (length failures) 1)
3775 (message "%s"
3776 (with-current-buffer dired-log-buffer
3777 (goto-char (point-max))
3778 (backward-page 1)
3779 (if (eolp) (forward-line 1))
3780 (buffer-substring (point) (point-max))))
3781 (message (if failures "%s--type ? for details (%s)"
3782 "%s--type ? for details")
3783 string failures))
3784 ;; Log a summary describing a bunch of errors.
3785 (dired-log (concat "\n" string "\n"))
3786 (dired-log t))
3788 ;;; Sorting
3790 ;; Most ls can only sort by name or by date (with -t), nothing else.
3791 ;; GNU ls sorts on size with -S, on extension with -X, and unsorted with -U.
3792 ;; So anything that does not contain these is sort "by name".
3794 (defvar dired-ls-sorting-switches "SXU"
3795 "String of `ls' switches (single letters) except \"t\" that influence sorting.
3797 This indicates to Dired which option switches to watch out for because they
3798 will change the sorting order behavior of `ls'.
3800 To change the default sorting order (e.g. add a `-v' option), see the
3801 variable `dired-listing-switches'. To temporarily override the listing
3802 format, use `\\[universal-argument] \\[dired]'.")
3804 (defvar dired-sort-by-date-regexp
3805 (concat "\\(\\`\\| \\)-[^- ]*t"
3806 ;; `dired-ls-sorting-switches' after -t overrides -t.
3807 "[^ " dired-ls-sorting-switches "]*"
3808 "\\(\\(\\`\\| +\\)\\(--[^ ]+\\|-[^- t"
3809 dired-ls-sorting-switches "]+\\)\\)* *$")
3810 "Regexp recognized by Dired to set `by date' mode.")
3812 (defvar dired-sort-by-name-regexp
3813 (concat "\\`\\(\\(\\`\\| +\\)\\(--[^ ]+\\|"
3814 "-[^- t" dired-ls-sorting-switches "]+\\)\\)* *$")
3815 "Regexp recognized by Dired to set `by name' mode.")
3817 (defvar dired-sort-inhibit nil
3818 "Non-nil means the Dired sort command is disabled.
3819 The idea is to set this buffer-locally in special Dired buffers.")
3821 (defun dired-sort-set-mode-line ()
3822 ;; Set mode line display according to dired-actual-switches.
3823 ;; Mode line display of "by name" or "by date" guarantees the user a
3824 ;; match with the corresponding regexps. Non-matching switches are
3825 ;; shown literally.
3826 (when (eq major-mode 'dired-mode)
3827 (setq mode-name
3828 (let (case-fold-search)
3829 (cond ((string-match-p
3830 dired-sort-by-name-regexp dired-actual-switches)
3831 "Dired by name")
3832 ((string-match-p
3833 dired-sort-by-date-regexp dired-actual-switches)
3834 "Dired by date")
3836 (concat "Dired " dired-actual-switches)))))
3837 (force-mode-line-update)))
3839 (define-obsolete-function-alias 'dired-sort-set-modeline
3840 'dired-sort-set-mode-line "24.3")
3842 (defun dired-sort-toggle-or-edit (&optional arg)
3843 "Toggle sorting by date, and refresh the Dired buffer.
3844 With a prefix argument, edit the current listing switches instead."
3845 (interactive "P")
3846 (when dired-sort-inhibit
3847 (error "Cannot sort this Dired buffer"))
3848 (if arg
3849 (dired-sort-other
3850 (read-string "ls switches (must contain -l): " dired-actual-switches))
3851 (dired-sort-toggle)))
3853 (defun dired-sort-toggle ()
3854 ;; Toggle between sort by date/name. Reverts the buffer.
3855 (let ((sorting-by-date (string-match-p dired-sort-by-date-regexp
3856 dired-actual-switches))
3857 ;; Regexp for finding (possibly embedded) -t switches.
3858 (switch-regexp "\\(\\`\\| \\)-\\([a-su-zA-Z]*\\)\\(t\\)\\([^ ]*\\)")
3859 case-fold-search)
3860 ;; Remove the -t switch.
3861 (while (string-match switch-regexp dired-actual-switches)
3862 (if (and (equal (match-string 2 dired-actual-switches) "")
3863 (equal (match-string 4 dired-actual-switches) ""))
3864 ;; Remove a stand-alone -t switch.
3865 (setq dired-actual-switches
3866 (replace-match "" t t dired-actual-switches))
3867 ;; Remove a switch of the form -XtY for some X and Y.
3868 (setq dired-actual-switches
3869 (replace-match "" t t dired-actual-switches 3))))
3871 ;; Now, if we weren't sorting by date before, add the -t switch.
3872 ;; Some simple-minded ls implementations (eg ftp servers) only
3873 ;; allow a single option string, so try not to add " -t" if possible.
3874 (unless sorting-by-date
3875 (setq dired-actual-switches
3876 (concat dired-actual-switches
3877 (if (string-match-p "\\`-[[:alnum:]]+\\'"
3878 dired-actual-switches)
3880 " -t")))))
3881 (dired-sort-set-mode-line)
3882 (revert-buffer))
3884 ;; Some user code loads dired especially for this.
3885 ;; Don't do that--use replace-regexp-in-string instead.
3886 (defun dired-replace-in-string (regexp newtext string)
3887 ;; Replace REGEXP with NEWTEXT everywhere in STRING and return result.
3888 ;; NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
3889 (let ((result "") (start 0) mb me)
3890 (while (string-match regexp string start)
3891 (setq mb (match-beginning 0)
3892 me (match-end 0)
3893 result (concat result (substring string start mb) newtext)
3894 start me))
3895 (concat result (substring string start))))
3897 (defun dired-sort-other (switches &optional no-revert)
3898 "Specify new `ls' SWITCHES for current Dired buffer.
3899 Values matching `dired-sort-by-date-regexp' or `dired-sort-by-name-regexp'
3900 set the minor mode accordingly, others appear literally in the mode line.
3901 With optional second arg NO-REVERT, don't refresh the listing afterwards."
3902 (dired-sort-R-check switches)
3903 (setq dired-actual-switches switches)
3904 (dired-sort-set-mode-line)
3905 (or no-revert (revert-buffer)))
3907 (defvar-local dired-subdir-alist-pre-R nil
3908 "Value of `dired-subdir-alist' before -R switch added.")
3910 (defun dired-sort-R-check (switches)
3911 "Additional processing of -R in ls option string SWITCHES.
3912 Saves `dired-subdir-alist' when R is set and restores saved value
3913 minus any directories explicitly deleted when R is cleared.
3914 To be called first in body of `dired-sort-other', etc."
3915 (cond
3916 ((and (dired-switches-recursive-p switches)
3917 (not (dired-switches-recursive-p dired-actual-switches)))
3918 ;; Adding -R to ls switches -- save `dired-subdir-alist':
3919 (setq dired-subdir-alist-pre-R dired-subdir-alist))
3920 ((and (dired-switches-recursive-p dired-actual-switches)
3921 (not (dired-switches-recursive-p switches)))
3922 ;; Deleting -R from ls switches -- revert to pre-R subdirs
3923 ;; that are still present:
3924 (setq dired-subdir-alist
3925 (if dired-subdir-alist-pre-R
3926 (let (subdirs)
3927 (while dired-subdir-alist-pre-R
3928 (if (assoc (caar dired-subdir-alist-pre-R)
3929 dired-subdir-alist)
3930 ;; subdir still present...
3931 (setq subdirs
3932 (cons (car dired-subdir-alist-pre-R)
3933 subdirs)))
3934 (setq dired-subdir-alist-pre-R
3935 (cdr dired-subdir-alist-pre-R)))
3936 (reverse subdirs))
3937 ;; No pre-R subdir alist, so revert to main directory
3938 ;; listing:
3939 (list (car (reverse dired-subdir-alist))))))))
3942 ;;;; Drag and drop support
3944 (defcustom dired-recursive-copies 'top
3945 "Whether Dired copies directories recursively.
3946 If nil, never copy recursively.
3947 `always' means to copy recursively without asking.
3948 `top' means to ask for each directory at top level.
3949 Any other value means to ask for each directory."
3950 :type '(choice :tag "Copy directories"
3951 (const :tag "No recursive copies" nil)
3952 (const :tag "Ask for each directory" t)
3953 (const :tag "Ask for each top directory only" top)
3954 (const :tag "Copy directories without asking" always))
3955 :group 'dired)
3957 (defun dired-dnd-popup-notice ()
3958 (message-box
3959 "Dired recursive copies are currently disabled.\nSee the variable `dired-recursive-copies'."))
3961 (declare-function x-popup-menu "menu.c" (position menu))
3963 (defun dired-dnd-do-ask-action (uri)
3964 ;; No need to get actions and descriptions from the source,
3965 ;; we only have three actions anyway.
3966 (let ((action (x-popup-menu
3968 (list "What action?"
3969 (cons ""
3970 '(("Copy here" . copy)
3971 ("Move here" . move)
3972 ("Link here" . link)
3973 "--"
3974 ("Cancel" . nil)))))))
3975 (if action
3976 (dired-dnd-handle-local-file uri action)
3977 nil)))
3979 (declare-function dired-relist-entry "dired-aux" (file))
3980 (declare-function make-symbolic-link "fileio.c")
3982 ;; Only used when (featurep 'dnd).
3983 (declare-function dnd-get-local-file-name "dnd" (uri &optional must-exist))
3984 (declare-function dnd-get-local-file-uri "dnd" (uri))
3986 (defvar dired-overwrite-confirmed) ;Defined in dired-aux.
3988 (defun dired-dnd-handle-local-file (uri action)
3989 "Copy, move or link a file to the Dired directory.
3990 URI is the file to handle, ACTION is one of copy, move, link or ask.
3991 Ask means pop up a menu for the user to select one of copy, move or link."
3992 (require 'dired-aux)
3993 (let* ((from (dnd-get-local-file-name uri t))
3994 (to (when from
3995 (concat (dired-current-directory)
3996 (file-name-nondirectory from)))))
3997 (when from
3998 (cond ((eq action 'ask)
3999 (dired-dnd-do-ask-action uri))
4000 ;; If copying a directory and dired-recursive-copies is
4001 ;; nil, dired-copy-file fails. Pop up a notice.
4002 ((and (memq action '(copy private))
4003 (file-directory-p from)
4004 (not dired-recursive-copies))
4005 (dired-dnd-popup-notice))
4006 ((memq action '(copy private move link))
4007 (let ((overwrite (and (file-exists-p to)
4008 (y-or-n-p
4009 (format-message
4010 "Overwrite existing file `%s'? " to))))
4011 ;; Binding dired-overwrite-confirmed to nil makes
4012 ;; dired-handle-overwrite a no-op. We instead use
4013 ;; y-or-n-p, which pops a graphical menu.
4014 dired-overwrite-confirmed backup-file)
4015 (when (and overwrite
4016 ;; d-b-o is defined in dired-aux.
4017 (boundp 'dired-backup-overwrite)
4018 dired-backup-overwrite
4019 (setq backup-file
4020 (car (find-backup-file-name to)))
4021 (or (eq dired-backup-overwrite 'always)
4022 (y-or-n-p
4023 (format-message
4024 "Make backup for existing file `%s'? " to))))
4025 (rename-file to backup-file 0)
4026 (dired-relist-entry backup-file))
4027 (cond ((memq action '(copy private))
4028 (dired-copy-file from to overwrite))
4029 ((eq action 'move)
4030 (dired-rename-file from to overwrite))
4031 ((eq action 'link)
4032 (make-symbolic-link from to overwrite)))
4033 (dired-relist-entry to)
4034 action))))))
4036 (defun dired-dnd-handle-file (uri action)
4037 "Copy, move or link a file to the Dired directory if it is a local file.
4038 URI is the file to handle. If the hostname in the URI isn't local, do nothing.
4039 ACTION is one of copy, move, link or ask.
4040 Ask means pop up a menu for the user to select one of copy, move or link."
4041 (let ((local-file (dnd-get-local-file-uri uri)))
4042 (if local-file (dired-dnd-handle-local-file local-file action)
4043 nil)))
4046 ;;;; Desktop support
4048 (eval-when-compile (require 'desktop))
4049 (declare-function desktop-file-name "desktop" (filename dirname))
4051 (defun dired-desktop-buffer-misc-data (dirname)
4052 "Auxiliary information to be saved in desktop file."
4053 (cons
4054 ;; Value of `dired-directory'.
4055 (if (consp dired-directory)
4056 ;; Directory name followed by list of files.
4057 (cons (desktop-file-name (car dired-directory) dirname)
4058 (cdr dired-directory))
4059 ;; Directory name, optionally with shell wildcard.
4060 (desktop-file-name dired-directory dirname))
4061 ;; Subdirectories in `dired-subdir-alist'.
4062 (cdr
4063 (nreverse
4064 (mapcar
4065 (lambda (f) (desktop-file-name (car f) dirname))
4066 dired-subdir-alist)))))
4068 (defun dired-restore-desktop-buffer (_file-name
4069 _buffer-name
4070 misc-data)
4071 "Restore a Dired buffer specified in a desktop file."
4072 ;; First element of `misc-data' is the value of `dired-directory'.
4073 ;; This value is a directory name, optionally with shell wildcard or
4074 ;; a directory name followed by list of files.
4075 (let* ((dired-dir (car misc-data))
4076 (dir (if (consp dired-dir) (car dired-dir) dired-dir)))
4077 (if (file-directory-p (file-name-directory dir))
4078 (with-demoted-errors "Desktop: Problem restoring directory: %S"
4079 (dired dired-dir)
4080 ;; The following elements of `misc-data' are the keys
4081 ;; from `dired-subdir-alist'.
4082 (mapc 'dired-maybe-insert-subdir (cdr misc-data))
4083 (current-buffer))
4084 (message "Desktop: Directory %s no longer exists." dir)
4085 (when desktop-missing-file-warning (sit-for 1))
4086 nil)))
4088 (add-to-list 'desktop-buffer-mode-handlers
4089 '(dired-mode . dired-restore-desktop-buffer))
4091 (provide 'dired)
4093 (run-hooks 'dired-load-hook) ; for your customizations
4095 ;;; dired.el ends here