(easy-menu-intern):
[emacs.git] / lisp / dired.el
blobc0fc33729c219f0cd5d934cb94f0444d154b577b
1 ;;; dired.el --- directory-browsing commands
3 ;; Copyright (C) 1985, 86, 92, 93, 94, 95, 96, 97, 2000, 01, 03, 2004
4 ;; Free Software Foundation, Inc.
6 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>
7 ;; Maintainer: FSF
8 ;; Keywords: files
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
27 ;;; Commentary:
29 ;; This is a major mode for directory browsing and editing. It is
30 ;; documented in the Emacs manual.
32 ;; Rewritten in 1990/1991 to add tree features, file marking and
33 ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
34 ;; Finished up by rms in 1992.
36 ;;; Code:
38 ;;; Customizable variables
40 (defgroup dired nil
41 "Directory editing."
42 :link '(custom-manual "(emacs)Dired")
43 :group 'files)
45 (defgroup dired-mark nil
46 "Handling marks in Dired."
47 :prefix "dired-"
48 :group 'dired)
51 ;;;###autoload
52 (defcustom dired-listing-switches "-al"
53 "*Switches passed to `ls' for dired. MUST contain the `l' option.
54 May contain all other options that don't contradict `-l';
55 may contain even `F', `b', `i' and `s'. See also the variable
56 `dired-ls-F-marks-symlinks' concerning the `F' switch.
57 On systems such as MS-DOS and MS-Windows, which use `ls' emulation in Lisp,
58 some of the `ls' switches are not supported; see the doc string of
59 `insert-directory' on ls-lisp.el for more details."
60 :type 'string
61 :group 'dired)
63 (defvar dired-subdir-switches nil
64 "If non-nil, switches passed to `ls' for inserting subdirectories.
65 If nil, `dired-listing-switches' is used.")
67 ; Don't use absolute file names as /bin should be in any PATH and people
68 ; may prefer /usr/local/gnu/bin or whatever. However, chown is
69 ; usually not in PATH.
71 ;;;###autoload
72 (defvar dired-chown-program
73 (if (memq system-type '(hpux dgux usg-unix-v irix linux gnu/linux cygwin))
74 "chown"
75 (if (file-exists-p "/usr/sbin/chown")
76 "/usr/sbin/chown"
77 "/etc/chown"))
78 "Name of chown command (usually `chown' or `/etc/chown').")
80 (defvar dired-use-ls-dired (not (not (string-match "gnu" system-configuration)))
81 "Non-nil means Dired should use `ls --dired'.")
83 (defvar dired-chmod-program "chmod"
84 "Name of chmod command (usually `chmod').")
86 (defvar dired-touch-program "touch"
87 "Name of touch command (usually `touch').")
89 ;;;###autoload
90 (defcustom dired-ls-F-marks-symlinks nil
91 "*Informs dired about how `ls -lF' marks symbolic links.
92 Set this to t if `ls' (or whatever program is specified by
93 `insert-directory-program') with `-lF' marks the symbolic link
94 itself with a trailing @ (usually the case under Ultrix).
96 Example: if `ln -s foo bar; ls -F bar' gives `bar -> foo', set it to
97 nil (the default), if it gives `bar@ -> foo', set it to t.
99 Dired checks if there is really a @ appended. Thus, if you have a
100 marking `ls' program on one host and a non-marking on another host, and
101 don't care about symbolic links which really end in a @, you can
102 always set this variable to t."
103 :type 'boolean
104 :group 'dired-mark)
106 ;;;###autoload
107 (defcustom dired-trivial-filenames "^\\.\\.?$\\|^#"
108 "*Regexp of files to skip when finding first file of a directory.
109 A value of nil means move to the subdir line.
110 A value of t means move to first file."
111 :type '(choice (const :tag "Move to subdir" nil)
112 (const :tag "Move to first" t)
113 regexp)
114 :group 'dired)
116 ;;;###autoload
117 (defcustom dired-keep-marker-rename t
118 ;; Use t as default so that moved files "take their markers with them".
119 "*Controls marking of renamed files.
120 If t, files keep their previous marks when they are renamed.
121 If a character, renamed files (whether previously marked or not)
122 are afterward marked with that character."
123 :type '(choice (const :tag "Keep" t)
124 (character :tag "Mark"))
125 :group 'dired-mark)
127 ;;;###autoload
128 (defcustom dired-keep-marker-copy ?C
129 "*Controls marking of copied files.
130 If t, copied files are marked if and as the corresponding original files were.
131 If a character, copied files are unconditionally marked with that character."
132 :type '(choice (const :tag "Keep" t)
133 (character :tag "Mark"))
134 :group 'dired-mark)
136 ;;;###autoload
137 (defcustom dired-keep-marker-hardlink ?H
138 "*Controls marking of newly made hard links.
139 If t, they are marked if and as the files linked to were marked.
140 If a character, new links are unconditionally marked with that character."
141 :type '(choice (const :tag "Keep" t)
142 (character :tag "Mark"))
143 :group 'dired-mark)
145 ;;;###autoload
146 (defcustom dired-keep-marker-symlink ?Y
147 "*Controls marking of newly made symbolic links.
148 If t, they are marked if and as the files linked to were marked.
149 If a character, new links are unconditionally marked with that character."
150 :type '(choice (const :tag "Keep" t)
151 (character :tag "Mark"))
152 :group 'dired-mark)
154 ;;;###autoload
155 (defcustom dired-dwim-target nil
156 "*If non-nil, dired tries to guess a default target directory.
157 This means: if there is a dired buffer displayed in the next window,
158 use its current subdir, instead of the current subdir of this dired buffer.
160 The target is used in the prompt for file copy, rename etc."
161 :type 'boolean
162 :group 'dired)
164 ;;;###autoload
165 (defcustom dired-copy-preserve-time t
166 "*If non-nil, Dired preserves the last-modified time in a file copy.
167 \(This works on only some systems.)"
168 :type 'boolean
169 :group 'dired)
171 ; These variables were deleted and the replacements are on files.el.
172 ; We leave aliases behind for back-compatibility.
173 (defvaralias 'dired-free-space-program 'directory-free-space-program)
174 (defvaralias 'dired-free-space-args 'directory-free-space-args)
176 ;;; Hook variables
178 (defcustom dired-load-hook nil
179 "Run after loading dired.
180 You can customize key bindings or load extensions with this."
181 :group 'dired
182 :type 'hook)
184 (defcustom dired-mode-hook nil
185 "Run at the very end of dired-mode."
186 :group 'dired
187 :type 'hook)
189 (defcustom dired-before-readin-hook nil
190 "This hook is run before a dired buffer is read in (created or reverted)."
191 :group 'dired
192 :type 'hook)
194 (defcustom dired-after-readin-hook nil
195 "Hook run after each time a file or directory is read by Dired.
196 After each listing of a file or directory, this hook is run
197 with the buffer narrowed to the listing."
198 :group 'dired
199 :type 'hook)
200 ;; Note this can't simply be run inside function `dired-ls' as the hook
201 ;; functions probably depend on the dired-subdir-alist to be OK.
203 ;; Fixme: This should use mailcap.
204 (defcustom dired-view-command-alist
205 '(("\\.\\(ps\\|ps_pages\\|eps\\)\\'" . "gv %s")
206 ("\\.pdf\\'" . "xpdf %s")
207 ;; ("\\.pod\\'" . "perldoc %s")
208 ("\\.\\(jpe?g\\|gif\\|png\\)\\'" . "eog %s")
209 ("\\.dvi\\'" . "xdvi %s"))
210 "Alist specifying how to view special types of files.
211 Each element has the form (REGEXP . SHELL-COMMAND).
212 When the file name matches REGEXP, `dired-view-file'
213 invokes SHELL-COMMAND to view the file, processing it through `format'.
214 Use `%s' in SHELL-COMMAND to specify where to put the file name."
215 :group 'dired
216 :type '(alist :key-type regexp :value-type string)
217 :version "21.4")
219 ;; Internal variables
221 (defvar dired-marker-char ?* ; the answer is 42
222 ;; so that you can write things like
223 ;; (let ((dired-marker-char ?X))
224 ;; ;; great code using X markers ...
225 ;; )
226 ;; For example, commands operating on two sets of files, A and B.
227 ;; Or marking files with digits 0-9. This could implicate
228 ;; concentric sets or an order for the marked files.
229 ;; The code depends on dynamic scoping on the marker char.
230 "In Dired, the current mark character.
231 This is what the `do' commands look for and what the `mark' commands store.")
233 (defvar dired-del-marker ?D
234 "Character used to flag files for deletion.")
236 (defvar dired-shrink-to-fit
238 ;; I see no reason ever to make this nil -- rms.
239 ;; (> baud-rate search-slow-speed)
240 "Non-nil means Dired shrinks the display buffer to fit the marked files.")
242 (defvar dired-flagging-regexp nil);; Last regexp used to flag files.
244 (defvar dired-file-version-alist)
246 ;;;###autoload
247 (defvar dired-directory nil
248 "The directory name or wildcard spec that this Dired directory lists.
249 Local to each dired buffer. May be a list, in which case the car is the
250 directory name and the cdr is the list of files to mention.
251 The directory name must be absolute, but need not be fully expanded.")
253 (defvar dired-actual-switches nil
254 "The value of `dired-listing-switches' used to make this buffer's text.")
256 (defvar dired-re-inode-size "[0-9 \t]*"
257 "Regexp for optional initial inode and file size as made by `ls -i -s'.")
259 ;; These regexps must be tested at beginning-of-line, but are also
260 ;; used to search for next matches, so neither omitting "^" nor
261 ;; replacing "^" by "\n" (to make it slightly faster) will work.
263 (defvar dired-re-mark "^[^ \n]")
264 ;; "Regexp matching a marked line.
265 ;; Important: the match ends just after the marker."
266 (defvar dired-re-maybe-mark "^. ")
267 ;; The [^:] part after "d" and "l" is to avoid confusion with the
268 ;; DOS/Windows-style drive letters in directory names, like in "d:/foo".
269 (defvar dired-re-dir (concat dired-re-maybe-mark dired-re-inode-size "d[^:]"))
270 (defvar dired-re-sym (concat dired-re-maybe-mark dired-re-inode-size "l[^:]"))
271 (defvar dired-re-exe;; match ls permission string of an executable file
272 (mapconcat (function
273 (lambda (x)
274 (concat dired-re-maybe-mark dired-re-inode-size x)))
275 '("-[-r][-w][xs][-r][-w].[-r][-w]."
276 "-[-r][-w].[-r][-w][xs][-r][-w]."
277 "-[-r][-w].[-r][-w].[-r][-w][xst]")
278 "\\|"))
279 (defvar dired-re-perms "[-bcdlps][-r][-w].[-r][-w].[-r][-w].")
280 (defvar dired-re-dot "^.* \\.\\.?/?$")
282 ;; The subdirectory names in the next two lists are expanded.
283 (defvar dired-subdir-alist nil
284 "Association list of subdirectories and their buffer positions.
285 Each subdirectory has an element: (DIRNAME . STARTMARKER).
286 The order of elements is the reverse of the order in the buffer.
287 In simple cases, this list contains one element.")
289 (defvar dired-switches-alist nil
290 "Keeps track of which switches to use for inserted subdirectories.
291 This is an alist of the form (SUBDIR . SWITCHES).")
292 (make-variable-buffer-local 'dired-switches-alist)
294 (defvar dired-subdir-regexp "^. \\([^\n\r]+\\)\\(:\\)[\n\r]"
295 "Regexp matching a maybe hidden subdirectory line in `ls -lR' output.
296 Subexpression 1 is the subdirectory proper, no trailing colon.
297 The match starts at the beginning of the line and ends after the end
298 of the line (\\n or \\r).
299 Subexpression 2 must end right before the \\n or \\r.")
301 (defgroup dired-faces nil
302 "Faces used by dired."
303 :group 'dired
304 :group 'faces)
306 (defface dired-header
307 '((t (:inherit font-lock-type-face)))
308 "Face used for directory headers."
309 :group 'dired-faces
310 :version "21.4")
311 (defvar dired-header-face 'dired-header
312 "Face name used for directory headers.")
314 (defface dired-mark
315 '((t (:inherit font-lock-constant-face)))
316 "Face used for dired marks."
317 :group 'dired-faces
318 :version "21.4")
319 (defvar dired-mark-face 'dired-mark
320 "Face name used for dired marks.")
322 (defface dired-marked
323 '((t (:inherit font-lock-warning-face)))
324 "Face used for marked files."
325 :group 'dired-faces
326 :version "21.4")
327 (defvar dired-marked-face 'dired-marked
328 "Face name used for marked files.")
330 (defface dired-flagged
331 '((t (:inherit font-lock-warning-face)))
332 "Face used for flagged files."
333 :group 'dired-faces
334 :version "21.4")
335 (defvar dired-flagged-face 'dired-flagged
336 "Face name used for flagged files.")
338 (defface dired-warning
339 '((t (:inherit font-lock-comment-face)))
340 "Face used to highlight a part of a buffer that needs user attention."
341 :group 'dired-faces
342 :version "21.4")
343 (defvar dired-warning-face 'dired-warning
344 "Face name used for a part of a buffer that needs user attention.")
346 (defface dired-directory
347 '((t (:inherit font-lock-function-name-face)))
348 "Face used for subdirectories."
349 :group 'dired-faces
350 :version "21.4")
351 (defvar dired-directory-face 'dired-directory
352 "Face name used for subdirectories.")
354 (defface dired-symlink
355 '((t (:inherit font-lock-keyword-face)))
356 "Face used for symbolic links."
357 :group 'dired-faces
358 :version "21.4")
359 (defvar dired-symlink-face 'dired-symlink
360 "Face name used for symbolic links.")
362 (defface dired-ignored
363 '((t (:inherit font-lock-string-face)))
364 "Face used for files suffixed with `completion-ignored-extensions'."
365 :group 'dired-faces
366 :version "21.4")
367 (defvar dired-ignored-face 'dired-ignored
368 "Face name used for files suffixed with `completion-ignored-extensions'.")
370 (defvar dired-font-lock-keywords
371 (list
373 ;; Directory headers.
374 (list dired-subdir-regexp '(1 dired-header-face))
376 ;; Dired marks.
377 (list dired-re-mark '(0 dired-mark-face))
379 ;; We make heavy use of MATCH-ANCHORED, since the regexps don't identify the
380 ;; file name itself. We search for Dired defined regexps, and then use the
381 ;; Dired defined function `dired-move-to-filename' before searching for the
382 ;; simple regexp ".+". It is that regexp which matches the file name.
384 ;; Marked files.
385 (list (concat "^[" (char-to-string dired-marker-char) "]")
386 '(".+" (dired-move-to-filename) nil (0 dired-marked-face)))
388 ;; Flagged files.
389 (list (concat "^[" (char-to-string dired-del-marker) "]")
390 '(".+" (dired-move-to-filename) nil (0 dired-flagged-face)))
391 ;; People who are paranoid about security would consider this more
392 ;; important than other things such as whether it is a directory.
393 ;; But we don't want to encourage paranoia, so our default
394 ;; should be what's most useful for non-paranoids. -- rms.
395 ;;; ;;
396 ;;; ;; Files that are group or world writable.
397 ;;; (list (concat dired-re-maybe-mark dired-re-inode-size
398 ;;; "\\([-d]\\(....w....\\|.......w.\\)\\)")
399 ;;; '(1 dired-warning-face)
400 ;;; '(".+" (dired-move-to-filename) nil (0 dired-warning-face)))
401 ;; However, we don't need to highlight the file name, only the
402 ;; permissions, to win generally. -- fx.
403 ;; Fixme: we could also put text properties on the permission
404 ;; fields with keymaps to frob the permissions, somewhat a la XEmacs.
405 (list (concat dired-re-maybe-mark dired-re-inode-size
406 "[-d]....\\(w\\)....") ; group writable
407 '(1 dired-warning-face))
408 (list (concat dired-re-maybe-mark dired-re-inode-size
409 "[-d].......\\(w\\).") ; world writable
410 '(1 dired-warning-face))
412 ;; Subdirectories.
413 (list dired-re-dir
414 '(".+" (dired-move-to-filename) nil (0 dired-directory-face)))
416 ;; Symbolic links.
417 (list dired-re-sym
418 '(".+" (dired-move-to-filename) nil (0 dired-symlink-face)))
420 ;; Files suffixed with `completion-ignored-extensions'.
421 '(eval .
422 ;; It is quicker to first find just an extension, then go back to the
423 ;; start of that file name. So we do this complex MATCH-ANCHORED form.
424 (list (concat "\\(" (regexp-opt completion-ignored-extensions) "\\|#\\)$")
425 '(".+" (dired-move-to-filename) nil (0 dired-ignored-face)))))
426 "Additional expressions to highlight in Dired mode.")
428 ;;; Macros must be defined before they are used, for the byte compiler.
430 (defmacro dired-mark-if (predicate msg)
431 "Mark all files for which PREDICATE evals to non-nil.
432 PREDICATE is evaluated on each line, with point at beginning of line.
433 MSG is a noun phrase for the type of files being marked.
434 It should end with a noun that can be pluralized by adding `s'.
435 Return value is the number of files marked, or nil if none were marked."
436 `(let (buffer-read-only count)
437 (save-excursion
438 (setq count 0)
439 (if ,msg (message "Marking %ss..." ,msg))
440 (goto-char (point-min))
441 (while (not (eobp))
442 (if ,predicate
443 (progn
444 (delete-char 1)
445 (insert dired-marker-char)
446 (setq count (1+ count))))
447 (forward-line 1))
448 (if ,msg (message "%s %s%s %s%s."
449 count
450 ,msg
451 (dired-plural-s count)
452 (if (eq dired-marker-char ?\040) "un" "")
453 (if (eq dired-marker-char dired-del-marker)
454 "flagged" "marked"))))
455 (and (> count 0) count)))
457 (defmacro dired-map-over-marks (body arg &optional show-progress)
458 "Eval BODY with point on each marked line. Return a list of BODY's results.
459 If no marked file could be found, execute BODY on the current line.
460 If ARG is an integer, use the next ARG (or previous -ARG, if ARG<0)
461 files instead of the marked files.
462 In that case point is dragged along. This is so that commands on
463 the next ARG (instead of the marked) files can be chained easily.
464 If ARG is otherwise non-nil, use current file instead.
465 If optional third arg SHOW-PROGRESS evaluates to non-nil,
466 redisplay the dired buffer after each file is processed.
467 No guarantee is made about the position on the marked line.
468 BODY must ensure this itself if it depends on this.
469 Search starts at the beginning of the buffer, thus the car of the list
470 corresponds to the line nearest to the buffer's bottom. This
471 is also true for (positive and negative) integer values of ARG.
472 BODY should not be too long as it is expanded four times."
474 ;;Warning: BODY must not add new lines before point - this may cause an
475 ;;endless loop.
476 ;;This warning should not apply any longer, sk 2-Sep-1991 14:10.
477 `(prog1
478 (let (buffer-read-only case-fold-search found results)
479 (if ,arg
480 (if (integerp ,arg)
481 (progn ;; no save-excursion, want to move point.
482 (dired-repeat-over-lines
483 ,arg
484 (function (lambda ()
485 (if ,show-progress (sit-for 0))
486 (setq results (cons ,body results)))))
487 (if (< ,arg 0)
488 (nreverse results)
489 results))
490 ;; non-nil, non-integer ARG means use current file:
491 (list ,body))
492 (let ((regexp (dired-marker-regexp)) next-position)
493 (save-excursion
494 (goto-char (point-min))
495 ;; remember position of next marked file before BODY
496 ;; can insert lines before the just found file,
497 ;; confusing us by finding the same marked file again
498 ;; and again and...
499 (setq next-position (and (re-search-forward regexp nil t)
500 (point-marker))
501 found (not (null next-position)))
502 (while next-position
503 (goto-char next-position)
504 (if ,show-progress (sit-for 0))
505 (setq results (cons ,body results))
506 ;; move after last match
507 (goto-char next-position)
508 (forward-line 1)
509 (set-marker next-position nil)
510 (setq next-position (and (re-search-forward regexp nil t)
511 (point-marker)))))
512 (if found
513 results
514 (list ,body)))))
515 ;; save-excursion loses, again
516 (dired-move-to-filename)))
518 (defun dired-get-marked-files (&optional localp arg filter)
519 "Return the marked files' names as list of strings.
520 The list is in the same order as the buffer, that is, the car is the
521 first marked file.
522 Values returned are normally absolute file names.
523 Optional arg LOCALP as in `dired-get-filename'.
524 Optional second argument ARG specifies files near point
525 instead of marked files. If ARG is an integer, use the next ARG files.
526 If ARG is otherwise non-nil, use file. Usually ARG comes from
527 the command's prefix arg.
528 Optional third argument FILTER, if non-nil, is a function to select
529 some of the files--those for which (funcall FILTER FILENAME) is non-nil."
530 (let ((all-of-them
531 (save-excursion
532 (dired-map-over-marks (dired-get-filename localp) arg)))
533 result)
534 (if (not filter)
535 (nreverse all-of-them)
536 (dolist (file all-of-them)
537 (if (funcall filter file)
538 (push file result)))
539 result)))
541 ;; The dired command
543 (defun dired-read-dir-and-switches (str)
544 ;; For use in interactive.
545 (reverse (list
546 (if current-prefix-arg
547 (read-string "Dired listing switches: "
548 dired-listing-switches))
549 (read-directory-name (format "Dired %s(directory): " str)
550 nil default-directory nil))))
552 ;;;###autoload (define-key ctl-x-map "d" 'dired)
553 ;;;###autoload
554 (defun dired (dirname &optional switches)
555 "\"Edit\" directory DIRNAME--delete, rename, print, etc. some files in it.
556 Optional second argument SWITCHES specifies the `ls' options used.
557 \(Interactively, use a prefix argument to be able to specify SWITCHES.)
558 Dired displays a list of files in DIRNAME (which may also have
559 shell wildcards appended to select certain files). If DIRNAME is a cons,
560 its first element is taken as the directory name and the rest as an explicit
561 list of files to make directory entries for.
562 \\<dired-mode-map>\
563 You can move around in it with the usual commands.
564 You can flag files for deletion with \\[dired-flag-file-deletion] and then
565 delete them by typing \\[dired-do-flagged-delete].
566 Type \\[describe-mode] after entering dired for more info.
568 If DIRNAME is already in a dired buffer, that buffer is used without refresh."
569 ;; Cannot use (interactive "D") because of wildcards.
570 (interactive (dired-read-dir-and-switches ""))
571 (switch-to-buffer (dired-noselect dirname switches)))
573 ;;;###autoload (define-key ctl-x-4-map "d" 'dired-other-window)
574 ;;;###autoload
575 (defun dired-other-window (dirname &optional switches)
576 "\"Edit\" directory DIRNAME. Like `dired' but selects in another window."
577 (interactive (dired-read-dir-and-switches "in other window "))
578 (switch-to-buffer-other-window (dired-noselect dirname switches)))
580 ;;;###autoload (define-key ctl-x-5-map "d" 'dired-other-frame)
581 ;;;###autoload
582 (defun dired-other-frame (dirname &optional switches)
583 "\"Edit\" directory DIRNAME. Like `dired' but makes a new frame."
584 (interactive (dired-read-dir-and-switches "in other frame "))
585 (switch-to-buffer-other-frame (dired-noselect dirname switches)))
587 ;;;###autoload
588 (defun dired-noselect (dir-or-list &optional switches)
589 "Like `dired' but returns the dired buffer as value, does not select it."
590 (or dir-or-list (setq dir-or-list default-directory))
591 ;; This loses the distinction between "/foo/*/" and "/foo/*" that
592 ;; some shells make:
593 (let (dirname initially-was-dirname)
594 (if (consp dir-or-list)
595 (setq dirname (car dir-or-list))
596 (setq dirname dir-or-list))
597 (setq initially-was-dirname
598 (string= (file-name-as-directory dirname) dirname))
599 (setq dirname (abbreviate-file-name
600 (expand-file-name (directory-file-name dirname))))
601 (if find-file-visit-truename
602 (setq dirname (file-truename dirname)))
603 ;; If the argument was syntactically a directory name not a file name,
604 ;; or if it happens to name a file that is a directory,
605 ;; convert it syntactically to a directory name.
606 ;; The reason for checking initially-was-dirname
607 ;; and not just file-directory-p
608 ;; is that file-directory-p is slow over ftp.
609 (if (or initially-was-dirname (file-directory-p dirname))
610 (setq dirname (file-name-as-directory dirname)))
611 (if (consp dir-or-list)
612 (setq dir-or-list (cons dirname (cdr dir-or-list)))
613 (setq dir-or-list dirname))
614 (dired-internal-noselect dir-or-list switches)))
616 ;; The following is an internal dired function. It returns non-nil if
617 ;; the directory visited by the current dired buffer has changed on
618 ;; disk. DIRNAME should be the directory name of that directory.
619 (defun dired-directory-changed-p (dirname)
620 (not (let ((attributes (file-attributes dirname))
621 (modtime (visited-file-modtime)))
622 (or (eq modtime 0)
623 (not (eq (car attributes) t))
624 (equal (nth 5 attributes) modtime)))))
626 (defun dired-buffer-stale-p (&optional noconfirm)
627 "Return non-nil if current dired buffer needs updating.
628 If NOCONFIRM is non-nil, then this function always returns nil
629 for a remote directory. This feature is used by Auto Revert Mode."
630 (let ((dirname
631 (if (consp dired-directory) (car dired-directory) dired-directory)))
632 (and (stringp dirname)
633 (not (when noconfirm (file-remote-p dirname)))
634 (file-readable-p dirname)
635 (dired-directory-changed-p dirname))))
637 ;; Separate function from dired-noselect for the sake of dired-vms.el.
638 (defun dired-internal-noselect (dir-or-list &optional switches mode)
639 ;; If there is an existing dired buffer for DIRNAME, just leave
640 ;; buffer as it is (don't even call dired-revert).
641 ;; This saves time especially for deep trees or with ange-ftp.
642 ;; The user can type `g' easily, and it is more consistent with find-file.
643 ;; But if SWITCHES are given they are probably different from the
644 ;; buffer's old value, so call dired-sort-other, which does
645 ;; revert the buffer.
646 ;; A pity we can't possibly do "Directory has changed - refresh? "
647 ;; like find-file does.
648 ;; Optional argument MODE is passed to dired-find-buffer-nocreate,
649 ;; see there.
650 (let* (dirname
651 buffer
652 ;; note that buffer already is in dired-mode, if found
653 new-buffer-p
654 (old-buf (current-buffer)))
655 (if (consp dir-or-list)
656 (setq dirname (car dir-or-list))
657 (setq dirname dir-or-list))
658 ;; Look for an existing buffer.
659 (setq buffer (dired-find-buffer-nocreate dirname mode)
660 new-buffer-p (null buffer))
661 (or buffer
662 (let ((default-major-mode 'fundamental-mode))
663 ;; We don't want default-major-mode to run hooks and set auto-fill
664 ;; or whatever, now that dired-mode does not
665 ;; kill-all-local-variables any longer.
666 (setq buffer (create-file-buffer (directory-file-name dirname)))))
667 (set-buffer buffer)
668 (if (not new-buffer-p) ; existing buffer ...
669 (cond (switches ; ... but new switches
670 ;; file list may have changed
671 (setq dired-directory dir-or-list)
672 ;; this calls dired-revert
673 (dired-sort-other switches))
674 ;; If directory has changed on disk, offer to revert.
675 ((when (dired-directory-changed-p dirname)
676 (message "%s"
677 (substitute-command-keys
678 "Directory has changed on disk; type \\[revert-buffer] to update Dired")))))
679 ;; Else a new buffer
680 (setq default-directory
681 ;; We can do this unconditionally
682 ;; because dired-noselect ensures that the name
683 ;; is passed in directory name syntax
684 ;; if it was the name of a directory at all.
685 (file-name-directory dirname))
686 (or switches (setq switches dired-listing-switches))
687 (if mode (funcall mode)
688 (dired-mode dir-or-list switches))
689 ;; default-directory and dired-actual-switches are set now
690 ;; (buffer-local), so we can call dired-readin:
691 (let ((failed t))
692 (unwind-protect
693 (progn (dired-readin)
694 (setq failed nil))
695 ;; dired-readin can fail if parent directories are inaccessible.
696 ;; Don't leave an empty buffer around in that case.
697 (if failed (kill-buffer buffer))))
698 (goto-char (point-min))
699 (dired-initial-position dirname))
700 (set-buffer old-buf)
701 buffer))
703 (defvar dired-buffers nil
704 ;; Enlarged by dired-advertise
705 ;; Queried by function dired-buffers-for-dir. When this detects a
706 ;; killed buffer, it is removed from this list.
707 "Alist of expanded directories and their associated dired buffers.")
709 (defun dired-find-buffer-nocreate (dirname &optional mode)
710 ;; This differs from dired-buffers-for-dir in that it does not consider
711 ;; subdirs of default-directory and searches for the first match only.
712 ;; Also, the major mode must be MODE.
713 (setq dirname (expand-file-name dirname))
714 (let (found (blist dired-buffers)) ; was (buffer-list)
715 (or mode (setq mode 'dired-mode))
716 (while blist
717 (if (null (buffer-name (cdr (car blist))))
718 (setq blist (cdr blist))
719 (save-excursion
720 (set-buffer (cdr (car blist)))
721 (if (and (eq major-mode mode)
722 dired-directory ;; nil during find-alternate-file
723 (equal dirname
724 (expand-file-name
725 (if (consp dired-directory)
726 (car dired-directory)
727 dired-directory))))
728 (setq found (cdr (car blist))
729 blist nil)
730 (setq blist (cdr blist))))))
731 found))
734 ;; Read in a new dired buffer
736 (defun dired-readin ()
737 "Read in a new dired buffer.
738 Differs from dired-insert-subdir in that it accepts
739 wildcards, erases the buffer, and builds the subdir-alist anew
740 \(including making it buffer-local and clearing it first)."
742 ;; default-directory and dired-actual-switches must be buffer-local
743 ;; and initialized by now.
744 (let (dirname)
745 (if (consp dired-directory)
746 (setq dirname (car dired-directory))
747 (setq dirname dired-directory))
748 (setq dirname (expand-file-name dirname))
749 (save-excursion
750 ;; This hook which may want to modify dired-actual-switches
751 ;; based on dired-directory, e.g. with ange-ftp to a SysV host
752 ;; where ls won't understand -Al switches.
753 (run-hooks 'dired-before-readin-hook)
754 (if (consp buffer-undo-list)
755 (setq buffer-undo-list nil))
756 (let (buffer-read-only
757 ;; Don't make undo entries for readin.
758 (buffer-undo-list t))
759 (widen)
760 (erase-buffer)
761 (dired-readin-insert))
762 (goto-char (point-min))
763 ;; Must first make alist buffer local and set it to nil because
764 ;; dired-build-subdir-alist will call dired-clear-alist first
765 (set (make-local-variable 'dired-subdir-alist) nil)
766 (dired-build-subdir-alist)
767 (let ((attributes (file-attributes dirname)))
768 (if (eq (car attributes) t)
769 (set-visited-file-modtime (nth 5 attributes))))
770 (set-buffer-modified-p nil)
771 ;; No need to narrow since the whole buffer contains just
772 ;; dired-readin's output, nothing else. The hook can
773 ;; successfully use dired functions (e.g. dired-get-filename)
774 ;; as the subdir-alist has been built in dired-readin.
775 (run-hooks 'dired-after-readin-hook))))
777 ;; Subroutines of dired-readin
779 (defun dired-readin-insert ()
780 ;; Insert listing for the specified dir (and maybe file list)
781 ;; already in dired-directory, assuming a clean buffer.
782 (let (dir file-list)
783 (if (consp dired-directory)
784 (setq dir (car dired-directory)
785 file-list (cdr dired-directory))
786 (setq dir dired-directory
787 file-list nil))
788 (setq dir (expand-file-name dir))
789 (if (and (equal "" (file-name-nondirectory dir))
790 (not file-list))
791 ;; If we are reading a whole single directory...
792 (dired-insert-directory dir dired-actual-switches nil nil t)
793 (if (not (file-readable-p
794 (directory-file-name (file-name-directory dir))))
795 (error "Directory %s inaccessible or nonexistent" dir)
796 ;; Else treat it as a wildcard spec
797 ;; unless we have an explicit list of files.
798 (dired-insert-directory dir dired-actual-switches
799 file-list (not file-list) t)))))
801 (defun dired-align-file (beg end)
802 "Align the fields of a file to the ones of surrounding lines.
803 BEG..END is the line where the file info is located."
804 ;; Some versions of ls try to adjust the size of each field so as to just
805 ;; hold the largest element ("largest" in the current invocation, of
806 ;; course). So when a single line is output, the size of each field is
807 ;; just big enough for that one output. Thus when dired refreshes one
808 ;; line, the alignment if this line w.r.t the rest is messed up because
809 ;; the fields of that one line will generally be smaller.
811 ;; To work around this problem, we here add spaces to try and re-align the
812 ;; fields as needed. Since this is purely aesthetic, it is of utmost
813 ;; importance that it doesn't mess up anything like
814 ;; `dired-move-to-filename'. To this end, we limit ourselves to adding
815 ;; spaces only, and to only add them at places where there was already at
816 ;; least one space. This way, as long as `dired-move-to-filename-regexp'
817 ;; always matches spaces with "*" or "+", we know we haven't made anything
818 ;; worse. There is one spot where the exact number of spaces is
819 ;; important, which is just before the actual filename, so we refrain from
820 ;; adding spaces there (and within the filename as well, of course).
821 (save-excursion
822 (let (file file-col other other-col)
823 ;; Check the there is indeed a file, and that there is anoter adjacent
824 ;; file with which to align, and that additional spaces are needed to
825 ;; align the filenames.
826 (when (and (setq file (progn (goto-char beg)
827 (dired-move-to-filename nil end)))
828 (setq file-col (current-column))
829 (setq other
830 (or (and (goto-char beg)
831 (zerop (forward-line -1))
832 (dired-move-to-filename))
833 (and (goto-char beg)
834 (zerop (forward-line 1))
835 (dired-move-to-filename))))
836 (setq other-col (current-column))
837 (/= file other)
838 ;; Make sure there is some work left to do.
839 (> other-col file-col))
840 ;; If we've only looked at the line above, check to see if the line
841 ;; below exists as well and if so, align with the shorter one.
842 (when (and (< other file)
843 (goto-char beg)
844 (zerop (forward-line 1))
845 (dired-move-to-filename))
846 (let ((alt-col (current-column)))
847 (when (< alt-col other-col)
848 (setq other-col alt-col)
849 (setq other (point)))))
850 ;; Keep positions uptodate when we insert stuff.
851 (if (> other file) (setq other (copy-marker other)))
852 (setq file (copy-marker file))
853 ;; Main loop.
854 (goto-char beg)
855 (while (and (> other-col file-col)
856 (skip-chars-forward "^ ")
857 ;; Skip the spaces, and make sure there's at least one.
858 (> (skip-chars-forward " ") 0)
859 ;; Don't touch anything just before (and after) the
860 ;; beginning of the filename.
861 (> file (point)))
862 ;; We're now just in front of a field, with a space behind us.
863 (let* ((curcol (current-column))
864 ;; Nums are right-aligned.
865 (num-align (looking-at "[0-9]"))
866 ;; Let's look at the other line, in the same column: we
867 ;; should be either near the end of the previous field, or
868 ;; in the space between that field and the next.
869 ;; [ Of course, it's also possible that we're already within
870 ;; the next field or even past it, but that's unlikely since
871 ;; other-col > file-col. ]
872 ;; Let's find the distance to the alignment-point (either
873 ;; the beginning or the end of the next field, depending on
874 ;; whether this field is left or right aligned).
875 (align-pt-offset
876 (save-excursion
877 (goto-char other)
878 (move-to-column curcol)
879 (when (looking-at
880 (concat
881 (if (eq (char-before) ?\ ) " *" "[^ ]* *")
882 (if num-align "[0-9][^ ]*")))
883 (- (match-end 0) (match-beginning 0)))))
884 ;; Now, the number of spaces to insert is align-pt-offset
885 ;; minus the distance to the equivalent point on the
886 ;; current line.
887 (spaces
888 (if (not num-align)
889 align-pt-offset
890 (and align-pt-offset
891 (save-excursion
892 (skip-chars-forward "^ ")
893 (- align-pt-offset (- (current-column) curcol)))))))
894 (when (and spaces (> spaces 0))
895 (setq file-col (+ spaces file-col))
896 (if (> file-col other-col)
897 (setq spaces (- spaces (- file-col other-col))))
898 (insert-char ?\s spaces)
899 ;; Let's just make really sure we did not mess up.
900 (unless (save-excursion
901 (equal (dired-move-to-filename) (marker-position file)))
902 ;; Damn! We messed up: let's revert the change.
903 (delete-char (- spaces))))))
904 (set-marker file nil)))))
907 (defun dired-insert-directory (dir switches &optional file-list wildcard hdr)
908 "Insert a directory listing of DIR, Dired style.
909 Use SWITCHES to make the listings.
910 If FILE-LIST is non-nil, list only those files.
911 Otherwise, if WILDCARD is non-nil, expand wildcards;
912 in that case, DIR should be a file name that uses wildcards.
913 In other cases, DIR should be a directory name or a directory filename.
914 If HDR is non-nil, insert a header line with the directory name."
915 (let ((opoint (point))
916 (process-environment (copy-sequence process-environment))
917 end)
918 (if (or dired-use-ls-dired (file-remote-p dir))
919 (setq switches (concat "--dired " switches)))
920 ;; We used to specify the C locale here, to force English month names;
921 ;; but this should not be necessary any more,
922 ;; with the new value of dired-move-to-filename-regexp.
923 (if file-list
924 (dolist (f file-list)
925 (let ((beg (point)))
926 (insert-directory f switches nil nil)
927 ;; Re-align fields, if necessary.
928 (dired-align-file beg (point))))
929 (insert-directory dir switches wildcard (not wildcard)))
930 ;; Quote certain characters, unless ls quoted them for us.
931 (if (not (string-match "b" dired-actual-switches))
932 (save-excursion
933 (setq end (point-marker))
934 (goto-char opoint)
935 (while (search-forward "\\" end t)
936 (replace-match (apply #'propertize
937 "\\\\"
938 (text-properties-at (match-beginning 0)))
939 nil t))
940 (goto-char opoint)
941 (while (search-forward "\^m" end t)
942 (replace-match (apply #'propertize
943 "\\015"
944 (text-properties-at (match-beginning 0)))
945 nil t))
946 (set-marker end nil)))
947 (dired-insert-set-properties opoint (point))
948 ;; If we used --dired and it worked, the lines are already indented.
949 ;; Otherwise, indent them.
950 (unless (save-excursion
951 (goto-char opoint)
952 (looking-at " "))
953 (let ((indent-tabs-mode nil))
954 (indent-rigidly opoint (point) 2)))
955 ;; Insert text at the beginning to standardize things.
956 (save-excursion
957 (goto-char opoint)
958 (if (and (or hdr wildcard) (not (looking-at "^ /.*:$")))
959 ;; Note that dired-build-subdir-alist will replace the name
960 ;; by its expansion, so it does not matter whether what we insert
961 ;; here is fully expanded, but it should be absolute.
962 (insert " " (directory-file-name (file-name-directory dir)) ":\n"))
963 (when wildcard
964 ;; Insert "wildcard" line where "total" line would be for a full dir.
965 (insert " wildcard " (file-name-nondirectory dir) "\n")))))
967 (defun dired-insert-set-properties (beg end)
968 "Make the file names highlight when the mouse is on them."
969 (save-excursion
970 (goto-char beg)
971 (while (< (point) end)
972 (condition-case nil
973 (if (dired-move-to-filename)
974 (add-text-properties
975 (point)
976 (save-excursion
977 (dired-move-to-end-of-filename)
978 (point))
979 '(mouse-face highlight
980 help-echo "mouse-2: visit this file in other window")))
981 (error nil))
982 (forward-line 1))))
984 ;; Reverting a dired buffer
986 (defun dired-revert (&optional arg noconfirm)
987 "Reread the dired buffer.
988 Must also be called after dired-actual-switches have changed.
989 Should not fail even on completely garbaged buffers.
990 Preserves old cursor, marks/flags, hidden-p."
991 (widen) ; just in case user narrowed
992 (let ((modflag (buffer-modified-p))
993 (opoint (point))
994 (ofile (dired-get-filename nil t))
995 (mark-alist nil) ; save marked files
996 (hidden-subdirs (dired-remember-hidden))
997 (old-subdir-alist (cdr (reverse dired-subdir-alist))) ; except pwd
998 (case-fold-search nil) ; we check for upper case ls flags
999 buffer-read-only)
1000 (goto-char (point-min))
1001 (setq mark-alist;; only after dired-remember-hidden since this unhides:
1002 (dired-remember-marks (point-min) (point-max)))
1003 ;; treat top level dir extra (it may contain wildcards)
1004 (dired-uncache
1005 (if (consp dired-directory) (car dired-directory) dired-directory))
1006 (dired-readin)
1007 (let ((dired-after-readin-hook nil))
1008 ;; don't run that hook for each subdir...
1009 (dired-insert-old-subdirs old-subdir-alist))
1010 (dired-mark-remembered mark-alist) ; mark files that were marked
1011 ;; ... run the hook for the whole buffer, and only after markers
1012 ;; have been reinserted (else omitting in dired-x would omit marked files)
1013 (run-hooks 'dired-after-readin-hook) ; no need to narrow
1014 (or (and ofile (dired-goto-file ofile)) ; move cursor to where it
1015 (goto-char opoint)) ; was before
1016 (dired-move-to-filename)
1017 (save-excursion ; hide subdirs that were hidden
1018 (dolist (dir hidden-subdirs)
1019 (if (dired-goto-subdir dir)
1020 (dired-hide-subdir 1))))
1021 (unless modflag (restore-buffer-modified-p nil)))
1022 ;; outside of the let scope
1023 ;;; Might as well not override the user if the user changed this.
1024 ;;; (setq buffer-read-only t)
1027 ;; Subroutines of dired-revert
1028 ;; Some of these are also used when inserting subdirs.
1030 (defun dired-remember-marks (beg end)
1031 "Return alist of files and their marks, from BEG to END."
1032 (if selective-display ; must unhide to make this work.
1033 (let (buffer-read-only)
1034 (subst-char-in-region beg end ?\r ?\n)))
1035 (let (fil chr alist)
1036 (save-excursion
1037 (goto-char beg)
1038 (while (re-search-forward dired-re-mark end t)
1039 (if (setq fil (dired-get-filename nil t))
1040 (setq chr (preceding-char)
1041 alist (cons (cons fil chr) alist)))))
1042 alist))
1044 (defun dired-mark-remembered (alist)
1045 "Mark all files remembered in ALIST.
1046 Each element of ALIST looks like (FILE . MARKERCHAR)."
1047 (let (elt fil chr)
1048 (while alist
1049 (setq elt (car alist)
1050 alist (cdr alist)
1051 fil (car elt)
1052 chr (cdr elt))
1053 (if (dired-goto-file fil)
1054 (save-excursion
1055 (beginning-of-line)
1056 (delete-char 1)
1057 (insert chr))))))
1059 (defun dired-remember-hidden ()
1060 "Return a list of names of subdirs currently hidden."
1061 (let ((l dired-subdir-alist) dir pos result)
1062 (while l
1063 (setq dir (car (car l))
1064 pos (cdr (car l))
1065 l (cdr l))
1066 (goto-char pos)
1067 (skip-chars-forward "^\r\n")
1068 (if (eq (following-char) ?\r)
1069 (setq result (cons dir result))))
1070 result))
1072 (defun dired-insert-old-subdirs (old-subdir-alist)
1073 "Try to insert all subdirs that were displayed before.
1074 Do so according to the former subdir alist OLD-SUBDIR-ALIST."
1075 (or (string-match "R" dired-actual-switches)
1076 (let (elt dir)
1077 (while old-subdir-alist
1078 (setq elt (car old-subdir-alist)
1079 old-subdir-alist (cdr old-subdir-alist)
1080 dir (car elt))
1081 (condition-case ()
1082 (progn
1083 (dired-uncache dir)
1084 (dired-insert-subdir dir))
1085 (error nil))))))
1087 (defun dired-uncache (dir)
1088 "Remove directory DIR from any directory cache."
1089 (let ((handler (find-file-name-handler dir 'dired-uncache)))
1090 (if handler
1091 (funcall handler 'dired-uncache dir))))
1093 ;; dired mode key bindings and initialization
1095 (defvar dired-mode-map
1096 ;; This looks ugly when substitute-command-keys uses C-d instead d:
1097 ;; (define-key dired-mode-map "\C-d" 'dired-flag-file-deletion)
1098 (let ((map (make-keymap)))
1099 (suppress-keymap map)
1100 (define-key map [mouse-2] 'dired-mouse-find-file-other-window)
1101 ;; Commands to mark or flag certain categories of files
1102 (define-key map "#" 'dired-flag-auto-save-files)
1103 (define-key map "." 'dired-clean-directory)
1104 (define-key map "~" 'dired-flag-backup-files)
1105 (define-key map "&" 'dired-flag-garbage-files)
1106 ;; Upper case keys (except !) for operating on the marked files
1107 (define-key map "A" 'dired-do-search)
1108 (define-key map "C" 'dired-do-copy)
1109 (define-key map "B" 'dired-do-byte-compile)
1110 (define-key map "D" 'dired-do-delete)
1111 (define-key map "G" 'dired-do-chgrp)
1112 (define-key map "H" 'dired-do-hardlink)
1113 (define-key map "L" 'dired-do-load)
1114 (define-key map "M" 'dired-do-chmod)
1115 (define-key map "O" 'dired-do-chown)
1116 (define-key map "P" 'dired-do-print)
1117 (define-key map "Q" 'dired-do-query-replace-regexp)
1118 (define-key map "R" 'dired-do-rename)
1119 (define-key map "S" 'dired-do-symlink)
1120 (define-key map "T" 'dired-do-touch)
1121 (define-key map "X" 'dired-do-shell-command)
1122 (define-key map "Z" 'dired-do-compress)
1123 (define-key map "!" 'dired-do-shell-command)
1124 ;; Comparison commands
1125 (define-key map "=" 'dired-diff)
1126 (define-key map "\M-=" 'dired-backup-diff)
1127 ;; Tree Dired commands
1128 (define-key map "\M-\C-?" 'dired-unmark-all-files)
1129 (define-key map "\M-\C-d" 'dired-tree-down)
1130 (define-key map "\M-\C-u" 'dired-tree-up)
1131 (define-key map "\M-\C-n" 'dired-next-subdir)
1132 (define-key map "\M-\C-p" 'dired-prev-subdir)
1133 ;; move to marked files
1134 (define-key map "\M-{" 'dired-prev-marked-file)
1135 (define-key map "\M-}" 'dired-next-marked-file)
1136 ;; Make all regexp commands share a `%' prefix:
1137 ;; We used to get to the submap via a symbol dired-regexp-prefix,
1138 ;; but that seems to serve little purpose, and copy-keymap
1139 ;; does a better job without it.
1140 (define-key map "%" nil)
1141 (define-key map "%u" 'dired-upcase)
1142 (define-key map "%l" 'dired-downcase)
1143 (define-key map "%d" 'dired-flag-files-regexp)
1144 (define-key map "%g" 'dired-mark-files-containing-regexp)
1145 (define-key map "%m" 'dired-mark-files-regexp)
1146 (define-key map "%r" 'dired-do-rename-regexp)
1147 (define-key map "%C" 'dired-do-copy-regexp)
1148 (define-key map "%H" 'dired-do-hardlink-regexp)
1149 (define-key map "%R" 'dired-do-rename-regexp)
1150 (define-key map "%S" 'dired-do-symlink-regexp)
1151 ;; Commands for marking and unmarking.
1152 (define-key map "*" nil)
1153 (define-key map "**" 'dired-mark-executables)
1154 (define-key map "*/" 'dired-mark-directories)
1155 (define-key map "*@" 'dired-mark-symlinks)
1156 (define-key map "*%" 'dired-mark-files-regexp)
1157 (define-key map "*c" 'dired-change-marks)
1158 (define-key map "*s" 'dired-mark-subdir-files)
1159 (define-key map "*m" 'dired-mark)
1160 (define-key map "*u" 'dired-unmark)
1161 (define-key map "*?" 'dired-unmark-all-files)
1162 (define-key map "*!" 'dired-unmark-all-marks)
1163 (define-key map "U" 'dired-unmark-all-marks)
1164 (define-key map "*\177" 'dired-unmark-backward)
1165 (define-key map "*\C-n" 'dired-next-marked-file)
1166 (define-key map "*\C-p" 'dired-prev-marked-file)
1167 (define-key map "*t" 'dired-toggle-marks)
1168 ;; Lower keys for commands not operating on all the marked files
1169 (define-key map "a" 'dired-find-alternate-file)
1170 (define-key map "d" 'dired-flag-file-deletion)
1171 (define-key map "e" 'dired-find-file)
1172 (define-key map "f" 'dired-find-file)
1173 (define-key map "\C-m" 'dired-advertised-find-file)
1174 (define-key map "g" 'revert-buffer)
1175 (define-key map "\M-g" 'dired-goto-file)
1176 (define-key map "h" 'describe-mode)
1177 (define-key map "i" 'dired-maybe-insert-subdir)
1178 (define-key map "k" 'dired-do-kill-lines)
1179 (define-key map "l" 'dired-do-redisplay)
1180 (define-key map "m" 'dired-mark)
1181 (define-key map "n" 'dired-next-line)
1182 (define-key map "o" 'dired-find-file-other-window)
1183 (define-key map "\C-o" 'dired-display-file)
1184 (define-key map "p" 'dired-previous-line)
1185 (define-key map "q" 'quit-window)
1186 (define-key map "s" 'dired-sort-toggle-or-edit)
1187 (define-key map "t" 'dired-toggle-marks)
1188 (define-key map "u" 'dired-unmark)
1189 (define-key map "v" 'dired-view-file)
1190 (define-key map "w" 'dired-copy-filename-as-kill)
1191 (define-key map "x" 'dired-do-flagged-delete)
1192 (define-key map "y" 'dired-show-file-type)
1193 (define-key map "+" 'dired-create-directory)
1194 ;; moving
1195 (define-key map "<" 'dired-prev-dirline)
1196 (define-key map ">" 'dired-next-dirline)
1197 (define-key map "^" 'dired-up-directory)
1198 (define-key map " " 'dired-next-line)
1199 (define-key map "\C-n" 'dired-next-line)
1200 (define-key map "\C-p" 'dired-previous-line)
1201 (define-key map [down] 'dired-next-line)
1202 (define-key map [up] 'dired-previous-line)
1203 ;; hiding
1204 (define-key map "$" 'dired-hide-subdir)
1205 (define-key map "\M-$" 'dired-hide-all)
1206 ;; misc
1207 (define-key map "?" 'dired-summary)
1208 (define-key map "\177" 'dired-unmark-backward)
1209 (define-key map "\C-_" 'dired-undo)
1210 (define-key map "\C-xu" 'dired-undo)
1212 ;; Make menu bar items.
1214 ;; No need to fo this, now that top-level items are fewer.
1215 ;;;;
1216 ;; Get rid of the Edit menu bar item to save space.
1217 ;(define-key map [menu-bar edit] 'undefined)
1219 (define-key map [menu-bar subdir]
1220 (cons "Subdir" (make-sparse-keymap "Subdir")))
1222 (define-key map [menu-bar subdir hide-all]
1223 '(menu-item "Hide All" dired-hide-all
1224 :help "Hide all subdirectories, leave only header lines"))
1225 (define-key map [menu-bar subdir hide-subdir]
1226 '(menu-item "Hide/UnHide Subdir" dired-hide-subdir
1227 :help "Hide or unhide current directory listing"))
1228 (define-key map [menu-bar subdir tree-down]
1229 '(menu-item "Tree Down" dired-tree-down
1230 :help "Go to first subdirectory header down the tree"))
1231 (define-key map [menu-bar subdir tree-up]
1232 '(menu-item "Tree Up" dired-tree-up
1233 :help "Go to first subdirectory header up the tree"))
1234 (define-key map [menu-bar subdir up]
1235 '(menu-item "Up Directory" dired-up-directory
1236 :help "Edit the parent directory"))
1237 (define-key map [menu-bar subdir prev-subdir]
1238 '(menu-item "Prev Subdir" dired-prev-subdir
1239 :help "Go to previous subdirectory header line"))
1240 (define-key map [menu-bar subdir next-subdir]
1241 '(menu-item "Next Subdir" dired-next-subdir
1242 :help "Go to next subdirectory header line"))
1243 (define-key map [menu-bar subdir prev-dirline]
1244 '(menu-item "Prev Dirline" dired-prev-dirline
1245 :help "Move to next directory-file line"))
1246 (define-key map [menu-bar subdir next-dirline]
1247 '(menu-item "Next Dirline" dired-next-dirline
1248 :help "Move to previous directory-file line"))
1249 (define-key map [menu-bar subdir insert]
1250 '(menu-item "Insert This Subdir" dired-maybe-insert-subdir
1251 :help "Insert contents of subdirectory"))
1253 (define-key map [menu-bar immediate]
1254 (cons "Immediate" (make-sparse-keymap "Immediate")))
1256 (define-key map [menu-bar immediate revert-buffer]
1257 '(menu-item "Refresh" revert-buffer
1258 :help "Update contents of shown directories"))
1260 (define-key map [menu-bar immediate dashes]
1261 '("--"))
1263 (define-key map [menu-bar immediate backup-diff]
1264 '(menu-item "Compare with Backup" dired-backup-diff
1265 :help "Diff file at cursor with its latest backup"))
1266 (define-key map [menu-bar immediate diff]
1267 '(menu-item "Diff..." dired-diff
1268 :help "Compare file at cursor with another file"))
1269 (define-key map [menu-bar immediate view]
1270 '(menu-item "View This File" dired-view-file
1271 :help "Examine file at cursor in read-only mode"))
1272 (define-key map [menu-bar immediate display]
1273 '(menu-item "Display in Other Window" dired-display-file
1274 :help "Display file at cursor in other window"))
1275 (define-key map [menu-bar immediate find-file-other-window]
1276 '(menu-item "Find in Other Window" dired-find-file-other-window
1277 :help "Edit file at cursor in other window"))
1278 (define-key map [menu-bar immediate find-file]
1279 '(menu-item "Find This File" dired-find-file
1280 :help "Edit file at cursor"))
1281 (define-key map [menu-bar immediate create-directory]
1282 '(menu-item "Create Directory..." dired-create-directory))
1283 (define-key map [menu-bar immediate wdired-mode]
1284 '(menu-item "Edit File Names" wdired-change-to-wdired-mode))
1286 (define-key map [menu-bar regexp]
1287 (cons "Regexp" (make-sparse-keymap "Regexp")))
1289 (define-key map [menu-bar regexp downcase]
1290 '(menu-item "Downcase" dired-downcase
1291 ;; When running on plain MS-DOS, there's only one
1292 ;; letter-case for file names.
1293 :enable (or (not (fboundp 'msdos-long-file-names))
1294 (msdos-long-file-names))
1295 :help "Rename marked files to lower-case name"))
1296 (define-key map [menu-bar regexp upcase]
1297 '(menu-item "Upcase" dired-upcase
1298 :enable (or (not (fboundp 'msdos-long-file-names))
1299 (msdos-long-file-names))
1300 :help "Rename marked files to upper-case name"))
1301 (define-key map [menu-bar regexp hardlink]
1302 '(menu-item "Hardlink..." dired-do-hardlink-regexp
1303 :help "Make hard links for files matching regexp"))
1304 (define-key map [menu-bar regexp symlink]
1305 '(menu-item "Symlink..." dired-do-symlink-regexp
1306 :visible (fboundp 'make-symbolic-link)
1307 :help "Make symbolic links for files matching regexp"))
1308 (define-key map [menu-bar regexp rename]
1309 '(menu-item "Rename..." dired-do-rename-regexp
1310 :help "Rename marked files matching regexp"))
1311 (define-key map [menu-bar regexp copy]
1312 '(menu-item "Copy..." dired-do-copy-regexp
1313 :help "Copy marked files matching regexp"))
1314 (define-key map [menu-bar regexp flag]
1315 '(menu-item "Flag..." dired-flag-files-regexp
1316 :help "Flag files matching regexp for deletion"))
1317 (define-key map [menu-bar regexp mark]
1318 '(menu-item "Mark..." dired-mark-files-regexp
1319 :help "Mark files matching regexp for future operations"))
1320 (define-key map [menu-bar regexp mark-cont]
1321 '(menu-item "Mark Containing..." dired-mark-files-containing-regexp
1322 :help "Mark files whose contents matches regexp"))
1324 (define-key map [menu-bar mark]
1325 (cons "Mark" (make-sparse-keymap "Mark")))
1327 (define-key map [menu-bar mark prev]
1328 '(menu-item "Previous Marked" dired-prev-marked-file
1329 :help "Move to previous marked file"))
1330 (define-key map [menu-bar mark next]
1331 '(menu-item "Next Marked" dired-next-marked-file
1332 :help "Move to next marked file"))
1333 (define-key map [menu-bar mark marks]
1334 '(menu-item "Change Marks..." dired-change-marks
1335 :help "Replace marker with another character"))
1336 (define-key map [menu-bar mark unmark-all]
1337 '(menu-item "Unmark All" dired-unmark-all-marks))
1338 (define-key map [menu-bar mark symlinks]
1339 '(menu-item "Mark Symlinks" dired-mark-symlinks
1340 :visible (fboundp 'make-symbolic-link)
1341 :help "Mark all symbolic links"))
1342 (define-key map [menu-bar mark directories]
1343 '(menu-item "Mark Directories" dired-mark-directories
1344 :help "Mark all directories except `.' and `..'"))
1345 (define-key map [menu-bar mark directory]
1346 '(menu-item "Mark Old Backups" dired-clean-directory
1347 :help "Flag old numbered backups for deletion"))
1348 (define-key map [menu-bar mark executables]
1349 '(menu-item "Mark Executables" dired-mark-executables
1350 :help "Mark all executable files"))
1351 (define-key map [menu-bar mark garbage-files]
1352 '(menu-item "Flag Garbage Files" dired-flag-garbage-files
1353 :help "Flag unneeded files for deletion"))
1354 (define-key map [menu-bar mark backup-files]
1355 '(menu-item "Flag Backup Files" dired-flag-backup-files
1356 :help "Flag all backup files for deletion"))
1357 (define-key map [menu-bar mark auto-save-files]
1358 '(menu-item "Flag Auto-save Files" dired-flag-auto-save-files
1359 :help "Flag auto-save files for deletion"))
1360 (define-key map [menu-bar mark deletion]
1361 '(menu-item "Flag" dired-flag-file-deletion
1362 :help "Flag current line's file for deletion"))
1363 (define-key map [menu-bar mark unmark]
1364 '(menu-item "Unmark" dired-unmark
1365 :help "Unmark or unflag current line's file"))
1366 (define-key map [menu-bar mark mark]
1367 '(menu-item "Mark" dired-mark
1368 :help "Mark current line's file for future operations"))
1369 (define-key map [menu-bar mark toggle-marks]
1370 '(menu-item "Toggle Marks" dired-toggle-marks
1371 :help "Mark unmarked files, unmark marked ones"))
1373 (define-key map [menu-bar operate]
1374 (cons "Operate" (make-sparse-keymap "Operate")))
1376 (define-key map [menu-bar operate query-replace]
1377 '(menu-item "Query Replace in Files..." dired-do-query-replace-regexp
1378 :help "Replace regexp in marked files"))
1379 (define-key map [menu-bar operate search]
1380 '(menu-item "Search Files..." dired-do-search
1381 :help "Search marked files for regexp"))
1382 (define-key map [menu-bar operate chown]
1383 '(menu-item "Change Owner..." dired-do-chown
1384 :visible (not (memq system-type '(ms-dos windows-nt)))
1385 :help "Change the owner of marked files"))
1386 (define-key map [menu-bar operate chgrp]
1387 '(menu-item "Change Group..." dired-do-chgrp
1388 :visible (not (memq system-type '(ms-dos windows-nt)))
1389 :help "Change the group of marked files"))
1390 (define-key map [menu-bar operate chmod]
1391 '(menu-item "Change Mode..." dired-do-chmod
1392 :help "Change mode (attributes) of marked files"))
1393 (define-key map [menu-bar operate touch]
1394 '(menu-item "Change Timestamp..." dired-do-touch
1395 :help "Change timestamp of marked files"))
1396 (define-key map [menu-bar operate load]
1397 '(menu-item "Load" dired-do-load
1398 :help "Load marked Emacs Lisp files"))
1399 (define-key map [menu-bar operate compile]
1400 '(menu-item "Byte-compile" dired-do-byte-compile
1401 :help "Byte-compile marked Emacs Lisp files"))
1402 (define-key map [menu-bar operate compress]
1403 '(menu-item "Compress" dired-do-compress
1404 :help "Compress/uncompress marked files"))
1405 (define-key map [menu-bar operate print]
1406 '(menu-item "Print..." dired-do-print
1407 :help "Ask for print command and print marked files"))
1408 (define-key map [menu-bar operate hardlink]
1409 '(menu-item "Hardlink to..." dired-do-hardlink
1410 :help "Make hard links for current or marked files"))
1411 (define-key map [menu-bar operate symlink]
1412 '(menu-item "Symlink to..." dired-do-symlink
1413 :visible (fboundp 'make-symbolic-link)
1414 :help "Make symbolic links for current or marked files"))
1415 (define-key map [menu-bar operate command]
1416 '(menu-item "Shell Command..." dired-do-shell-command
1417 :help "Run a shell command on each of marked files"))
1418 (define-key map [menu-bar operate delete]
1419 '(menu-item "Delete" dired-do-delete
1420 :help "Delete current file or all marked files"))
1421 (define-key map [menu-bar operate rename]
1422 '(menu-item "Rename to..." dired-do-rename
1423 :help "Rename current file or move marked files"))
1424 (define-key map [menu-bar operate copy]
1425 '(menu-item "Copy to..." dired-do-copy
1426 :help "Copy current file or all marked files"))
1428 map)
1429 "Local keymap for `dired-mode' buffers.")
1431 ;; Dired mode is suitable only for specially formatted data.
1432 (put 'dired-mode 'mode-class 'special)
1434 (defun dired-mode (&optional dirname switches)
1436 Mode for \"editing\" directory listings.
1437 In Dired, you are \"editing\" a list of the files in a directory and
1438 \(optionally) its subdirectories, in the format of `ls -lR'.
1439 Each directory is a page: use \\[backward-page] and \\[forward-page] to move pagewise.
1440 \"Editing\" means that you can run shell commands on files, visit,
1441 compress, load or byte-compile them, change their file attributes
1442 and insert subdirectories into the same buffer. You can \"mark\"
1443 files for later commands or \"flag\" them for deletion, either file
1444 by file or all files matching certain criteria.
1445 You can move using the usual cursor motion commands.\\<dired-mode-map>
1446 Letters no longer insert themselves. Digits are prefix arguments.
1447 Instead, type \\[dired-flag-file-deletion] to flag a file for Deletion.
1448 Type \\[dired-mark] to Mark a file or subdirectory for later commands.
1449 Most commands operate on the marked files and use the current file
1450 if no files are marked. Use a numeric prefix argument to operate on
1451 the next ARG (or previous -ARG if ARG<0) files, or just `1'
1452 to operate on the current file only. Prefix arguments override marks.
1453 Mark-using commands display a list of failures afterwards. Type \\[dired-summary]
1454 to see why something went wrong.
1455 Type \\[dired-unmark] to Unmark a file or all files of a subdirectory.
1456 Type \\[dired-unmark-backward] to back up one line and unflag.
1457 Type \\[dired-do-flagged-delete] to eXecute the deletions requested.
1458 Type \\[dired-advertised-find-file] to Find the current line's file
1459 (or dired it in another buffer, if it is a directory).
1460 Type \\[dired-find-file-other-window] to find file or dired directory in Other window.
1461 Type \\[dired-maybe-insert-subdir] to Insert a subdirectory in this buffer.
1462 Type \\[dired-do-rename] to Rename a file or move the marked files to another directory.
1463 Type \\[dired-do-copy] to Copy files.
1464 Type \\[dired-sort-toggle-or-edit] to toggle sorting by name/date or change the `ls' switches.
1465 Type \\[revert-buffer] to read all currently expanded directories again.
1466 This retains all marks and hides subdirs again that were hidden before.
1467 SPC and DEL can be used to move down and up by lines.
1469 If dired ever gets confused, you can either type \\[revert-buffer] \
1470 to read the
1471 directories again, type \\[dired-do-redisplay] \
1472 to relist a single or the marked files or a
1473 subdirectory, or type \\[dired-build-subdir-alist] to parse the buffer
1474 again for the directory tree.
1476 Customization variables (rename this buffer and type \\[describe-variable] on each line
1477 for more info):
1479 dired-listing-switches
1480 dired-trivial-filenames
1481 dired-shrink-to-fit
1482 dired-marker-char
1483 dired-del-marker
1484 dired-keep-marker-rename
1485 dired-keep-marker-copy
1486 dired-keep-marker-hardlink
1487 dired-keep-marker-symlink
1489 Hooks (use \\[describe-variable] to see their documentation):
1491 dired-before-readin-hook
1492 dired-after-readin-hook
1493 dired-mode-hook
1494 dired-load-hook
1496 Keybindings:
1497 \\{dired-mode-map}"
1498 ;; Not to be called interactively (e.g. dired-directory will be set
1499 ;; to default-directory, which is wrong with wildcards).
1500 (kill-all-local-variables)
1501 (use-local-map dired-mode-map)
1502 (dired-advertise) ; default-directory is already set
1503 (setq major-mode 'dired-mode
1504 mode-name "Dired"
1505 ;; case-fold-search nil
1506 buffer-read-only t
1507 selective-display t ; for subdirectory hiding
1508 mode-line-buffer-identification
1509 (propertized-buffer-identification "%17b"))
1510 (set (make-local-variable 'revert-buffer-function)
1511 (function dired-revert))
1512 (set (make-local-variable 'buffer-stale-function)
1513 (function dired-buffer-stale-p))
1514 (set (make-local-variable 'page-delimiter)
1515 "\n\n")
1516 (set (make-local-variable 'dired-directory)
1517 (or dirname default-directory))
1518 ;; list-buffers uses this to display the dir being edited in this buffer.
1519 (set (make-local-variable 'list-buffers-directory)
1520 (expand-file-name (if (listp dired-directory)
1521 (car dired-directory)
1522 dired-directory)))
1523 (set (make-local-variable 'dired-actual-switches)
1524 (or switches dired-listing-switches))
1525 (set (make-local-variable 'font-lock-defaults)
1526 '(dired-font-lock-keywords t nil nil beginning-of-line))
1527 (set (make-local-variable 'desktop-save-buffer)
1528 'dired-desktop-buffer-misc-data)
1529 (setq dired-switches-alist nil)
1530 (dired-sort-other dired-actual-switches t)
1531 (run-mode-hooks 'dired-mode-hook)
1532 (when (featurep 'x-dnd)
1533 (make-variable-buffer-local 'x-dnd-test-function)
1534 (make-variable-buffer-local 'x-dnd-protocol-alist)
1535 (setq x-dnd-test-function 'dired-dnd-test-function)
1536 (setq x-dnd-protocol-alist
1537 (append '(("^file:///" . dired-dnd-handle-local-file)
1538 ("^file://" . dired-dnd-handle-file)
1539 ("^file:" . dired-dnd-handle-local-file))
1540 x-dnd-protocol-alist))))
1542 ;; Idiosyncratic dired commands that don't deal with marks.
1544 (defun dired-summary ()
1545 "Summarize basic Dired commands and show recent Dired errors."
1546 (interactive)
1547 (dired-why)
1548 ;>> this should check the key-bindings and use substitute-command-keys if non-standard
1549 (message
1550 "d-elete, u-ndelete, x-punge, f-ind, o-ther window, R-ename, C-opy, h-elp"))
1552 (defun dired-undo ()
1553 "Undo in a dired buffer.
1554 This doesn't recover lost files, it just undoes changes in the buffer itself.
1555 You can use it to recover marks, killed lines or subdirs."
1556 (interactive)
1557 (let (buffer-read-only)
1558 (undo))
1559 (dired-build-subdir-alist)
1560 (message "Change in Dired buffer undone.
1561 Actual changes in files cannot be undone by Emacs."))
1563 (defun dired-next-line (arg)
1564 "Move down lines then position at filename.
1565 Optional prefix ARG says how many lines to move; default is one line."
1566 (interactive "p")
1567 (next-line arg)
1568 (dired-move-to-filename))
1570 (defun dired-previous-line (arg)
1571 "Move up lines then position at filename.
1572 Optional prefix ARG says how many lines to move; default is one line."
1573 (interactive "p")
1574 (previous-line arg)
1575 (dired-move-to-filename))
1577 (defun dired-next-dirline (arg &optional opoint)
1578 "Goto ARG'th next directory file line."
1579 (interactive "p")
1580 (or opoint (setq opoint (point)))
1581 (if (if (> arg 0)
1582 (re-search-forward dired-re-dir nil t arg)
1583 (beginning-of-line)
1584 (re-search-backward dired-re-dir nil t (- arg)))
1585 (dired-move-to-filename) ; user may type `i' or `f'
1586 (goto-char opoint)
1587 (error "No more subdirectories")))
1589 (defun dired-prev-dirline (arg)
1590 "Goto ARG'th previous directory file line."
1591 (interactive "p")
1592 (dired-next-dirline (- arg)))
1594 (defun dired-up-directory (&optional other-window)
1595 "Run Dired on parent directory of current directory.
1596 Find the parent directory either in this buffer or another buffer.
1597 Creates a buffer if necessary."
1598 (interactive "P")
1599 (let* ((dir (dired-current-directory))
1600 (up (file-name-directory (directory-file-name dir))))
1601 (or (dired-goto-file (directory-file-name dir))
1602 ;; Only try dired-goto-subdir if buffer has more than one dir.
1603 (and (cdr dired-subdir-alist)
1604 (dired-goto-subdir up))
1605 (progn
1606 (if other-window
1607 (dired-other-window up)
1608 (dired up))
1609 (dired-goto-file dir)))))
1611 (defun dired-get-file-for-visit ()
1612 "Get the current line's file name, with an error if file does not exist."
1613 (interactive)
1614 ;; We pass t for second arg so that we don't get error for `.' and `..'.
1615 (let ((raw (dired-get-filename nil t))
1616 file-name)
1617 (if (null raw)
1618 (error "No file on this line"))
1619 (setq file-name (file-name-sans-versions raw t))
1620 (if (file-exists-p file-name)
1621 file-name
1622 (if (file-symlink-p file-name)
1623 (error "File is a symlink to a nonexistent target")
1624 (error "File no longer exists; type `g' to update Dired buffer")))))
1626 ;; Force `f' rather than `e' in the mode doc:
1627 (defalias 'dired-advertised-find-file 'dired-find-file)
1628 (defun dired-find-file ()
1629 "In Dired, visit the file or directory named on this line."
1630 (interactive)
1631 ;; Bind `find-file-run-dired' so that the command works on directories
1632 ;; too, independent of the user's setting.
1633 (let ((find-file-run-dired t))
1634 (find-file (dired-get-file-for-visit))))
1636 (defun dired-find-alternate-file ()
1637 "In Dired, visit this file or directory instead of the dired buffer."
1638 (interactive)
1639 (set-buffer-modified-p nil)
1640 (find-alternate-file (dired-get-file-for-visit)))
1641 ;; Don't override the setting from .emacs.
1642 ;;;###autoload (put 'dired-find-alternate-file 'disabled t)
1644 (defun dired-mouse-find-file-other-window (event)
1645 "In Dired, visit the file or directory name you click on."
1646 (interactive "e")
1647 (let (window pos file)
1648 (save-excursion
1649 (setq window (posn-window (event-end event))
1650 pos (posn-point (event-end event)))
1651 (if (not (windowp window))
1652 (error "No file chosen"))
1653 (set-buffer (window-buffer window))
1654 (goto-char pos)
1655 (setq file (dired-get-file-for-visit)))
1656 (if (file-directory-p file)
1657 (or (and (cdr dired-subdir-alist)
1658 (dired-goto-subdir file))
1659 (progn
1660 (select-window window)
1661 (dired-other-window file)))
1662 (let (cmd)
1663 ;; Look for some other way to view a certain file.
1664 (dolist (elt dired-view-command-alist)
1665 (if (string-match (car elt) file)
1666 (setq cmd (cdr elt))))
1667 (if cmd
1668 (call-process shell-file-name nil 0 nil
1669 "-c"
1670 (concat (format cmd (shell-quote-argument file))
1671 " &"))
1672 (select-window window)
1673 (find-file-other-window (file-name-sans-versions file t)))))))
1675 (defun dired-view-file ()
1676 "In Dired, examine a file in view mode, returning to dired when done.
1677 When file is a directory, show it in this buffer if it is inserted.
1678 Some kinds of files are displayed using external viewer programs;
1679 see `dired-view-command-alist'. Otherwise, display it in another buffer."
1680 (interactive)
1681 (let ((file (dired-get-file-for-visit)))
1682 (if (file-directory-p file)
1683 (or (and (cdr dired-subdir-alist)
1684 (dired-goto-subdir file))
1685 (dired file))
1686 (let (cmd)
1687 ;; Look for some other way to view a certain file.
1688 (dolist (elt dired-view-command-alist)
1689 (if (string-match (car elt) file)
1690 (setq cmd (cdr elt))))
1691 (if cmd
1692 (call-process shell-file-name nil 0 nil
1693 "-c"
1694 (concat (format cmd (shell-quote-argument file))
1695 " &"))
1696 (view-file file))))))
1698 (defun dired-find-file-other-window ()
1699 "In Dired, visit this file or directory in another window."
1700 (interactive)
1701 (find-file-other-window (dired-get-file-for-visit)))
1703 (defun dired-display-file ()
1704 "In Dired, display this file or directory in another window."
1705 (interactive)
1706 (display-buffer (find-file-noselect (dired-get-file-for-visit))))
1708 ;;; Functions for extracting and manipulating file names in Dired buffers.
1710 (defun dired-get-filename (&optional localp no-error-if-not-filep)
1711 "In Dired, return name of file mentioned on this line.
1712 Value returned normally includes the directory name.
1713 Optional arg LOCALP with value `no-dir' means don't include directory
1714 name in result. A value of `verbatim' means to return the name exactly as
1715 it occurs in the buffer, and a value of t means construct name relative to
1716 `default-directory', which still may contain slashes if in a subdirectory.
1717 Optional arg NO-ERROR-IF-NOT-FILEP means treat `.' and `..' as
1718 regular filenames and return nil if no filename on this line.
1719 Otherwise, an error occurs in these cases."
1720 (let (case-fold-search file p1 p2 already-absolute)
1721 (save-excursion
1722 (if (setq p1 (dired-move-to-filename (not no-error-if-not-filep)))
1723 (setq p2 (dired-move-to-end-of-filename no-error-if-not-filep))))
1724 ;; nil if no file on this line, but no-error-if-not-filep is t:
1725 (if (setq file (and p1 p2 (buffer-substring p1 p2)))
1726 (progn
1727 ;; Get rid of the mouse-face property that file names have.
1728 (set-text-properties 0 (length file) nil file)
1729 ;; Unquote names quoted by ls or by dired-insert-directory.
1730 ;; Using read to unquote is much faster than substituting
1731 ;; \007 (4 chars) -> ^G (1 char) etc. in a lisp loop.
1732 (setq file
1733 (read
1734 (concat "\""
1735 ;; Some ls -b don't escape quotes, argh!
1736 ;; This is not needed for GNU ls, though.
1737 (or (dired-string-replace-match
1738 "\\([^\\]\\|\\`\\)\"" file "\\1\\\\\"" nil t)
1739 file)
1740 "\"")))
1741 ;; The above `read' will return a unibyte string if FILE
1742 ;; contains eight-bit-control/graphic characters.
1743 (if (and enable-multibyte-characters
1744 (not (multibyte-string-p file)))
1745 (setq file (string-to-multibyte file)))))
1746 (and file (file-name-absolute-p file)
1747 ;; A relative file name can start with ~.
1748 ;; Don't treat it as absolute in this context.
1749 (not (eq (aref file 0) ?~))
1750 (setq already-absolute t))
1751 (cond
1752 ((null file)
1753 nil)
1754 ((eq localp 'verbatim)
1755 file)
1756 ((and (not no-error-if-not-filep)
1757 (member file '("." "..")))
1758 (error "Cannot operate on `.' or `..'"))
1759 ((and (eq localp 'no-dir) already-absolute)
1760 (file-name-nondirectory file))
1761 (already-absolute
1762 (let ((handler (find-file-name-handler file nil)))
1763 ;; check for safe-magic property so that we won't
1764 ;; put /: for names that don't really need them.
1765 ;; For instance, .gz files when auto-compression-mode is on.
1766 (if (and handler (not (get handler 'safe-magic)))
1767 (concat "/:" file)
1768 file)))
1769 ((eq localp 'no-dir)
1770 file)
1771 ((equal (dired-current-directory) "/")
1772 (setq file (concat (dired-current-directory localp) file))
1773 (let ((handler (find-file-name-handler file nil)))
1774 ;; check for safe-magic property so that we won't
1775 ;; put /: for names that don't really need them.
1776 ;; For instance, .gz files when auto-compression-mode is on.
1777 (if (and handler (not (get handler 'safe-magic)))
1778 (concat "/:" file)
1779 file)))
1781 (concat (dired-current-directory localp) file)))))
1783 (defun dired-string-replace-match (regexp string newtext
1784 &optional literal global)
1785 "Replace first match of REGEXP in STRING with NEWTEXT.
1786 If it does not match, nil is returned instead of the new string.
1787 Optional arg LITERAL means to take NEWTEXT literally.
1788 Optional arg GLOBAL means to replace all matches."
1789 (if global
1790 (let ((start 0) ret)
1791 (while (string-match regexp string start)
1792 (let ((from-end (- (length string) (match-end 0))))
1793 (setq ret (setq string (replace-match newtext t literal string)))
1794 (setq start (- (length string) from-end))))
1795 ret)
1796 (if (not (string-match regexp string 0))
1798 (replace-match newtext t literal string))))
1800 (defun dired-make-absolute (file &optional dir)
1801 ;;"Convert FILE (a file name relative to DIR) to an absolute file name."
1802 ;; We can't always use expand-file-name as this would get rid of `.'
1803 ;; or expand in / instead default-directory if DIR=="".
1804 ;; This should be good enough for ange-ftp, but might easily be
1805 ;; redefined (for VMS?).
1806 ;; It should be reasonably fast, though, as it is called in
1807 ;; dired-get-filename.
1808 (concat (or dir default-directory) file))
1810 (defun dired-make-relative (file &optional dir ignore)
1811 "Convert FILE (an absolute file name) to a name relative to DIR.
1812 If this is impossible, return FILE unchanged.
1813 DIR must be a directory name, not a file name."
1814 (or dir (setq dir default-directory))
1815 ;; This case comes into play if default-directory is set to
1816 ;; use ~.
1817 (if (and (> (length dir) 0) (= (aref dir 0) ?~))
1818 (setq dir (expand-file-name dir)))
1819 (if (string-match (concat "^" (regexp-quote dir)) file)
1820 (substring file (match-end 0))
1821 ;;; (or no-error
1822 ;;; (error "%s: not in directory tree growing at %s" file dir))
1823 file))
1825 ;;; Functions for finding the file name in a dired buffer line.
1827 (defvar dired-move-to-filename-regexp
1828 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
1829 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
1830 ;; In some locales, month abbreviations are as short as 2 letters,
1831 ;; and they can be followed by ".".
1832 ;; In Breton, a month name can include a quote character.
1833 (month (concat l-or-quote l-or-quote "+\\.?"))
1834 (s " ")
1835 (yyyy "[0-9][0-9][0-9][0-9]")
1836 (dd "[ 0-3][0-9]")
1837 (HH:MM "[ 0-2][0-9][:.][0-5][0-9]")
1838 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
1839 (zone "[-+][0-2][0-9][0-5][0-9]")
1840 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
1841 (iso-time (concat HH:MM "\\(:" seconds "\\( ?" zone "\\)?\\)?"))
1842 (iso (concat "\\(\\(" yyyy "-\\)?" iso-mm-dd "[ T]" iso-time
1843 "\\|" yyyy "-" iso-mm-dd "\\)"))
1844 (western (concat "\\(" month s "+" dd "\\|" dd "\\.?" s month "\\)"
1845 s "+"
1846 "\\(" HH:MM "\\|" yyyy "\\)"))
1847 (western-comma (concat month s "+" dd "," s "+" yyyy))
1848 ;; Japanese MS-Windows ls-lisp has one-digit months, and
1849 ;; omits the Kanji characters after month and day-of-month.
1850 (mm "[ 0-1]?[0-9]")
1851 (japanese
1852 (concat mm l "?" s dd l "?" s "+"
1853 "\\(" HH:MM "\\|" yyyy l "?" "\\)")))
1854 ;; The "[0-9]" below requires the previous column to end in a digit.
1855 ;; This avoids recognizing `1 may 1997' as a date in the line:
1856 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
1857 ;; The "[kKMGTPEZY]?" below supports "ls -alh" output.
1858 ;; The ".*" below finds the last match if there are multiple matches.
1859 ;; This avoids recognizing `jservice 10 1024' as a date in the line:
1860 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
1861 (concat ".*[0-9][kKMGTPEZY]?" s
1862 "\\(" western "\\|" western-comma "\\|" japanese "\\|" iso "\\)"
1863 s "+"))
1864 "Regular expression to match up to the file name in a directory listing.
1865 The default value is designed to recognize dates and times
1866 regardless of the language.")
1868 (defvar dired-permission-flags-regexp
1869 "\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)"
1870 "Regular expression to match the permission flags in `ls -l'.")
1872 ;; Move to first char of filename on this line.
1873 ;; Returns position (point) or nil if no filename on this line."
1874 (defun dired-move-to-filename (&optional raise-error eol)
1875 "Move to the beginning of the filename on the current line.
1876 Return the position of the beginning of the filename, or nil if none found."
1877 ;; This is the UNIX version.
1878 (or eol (setq eol (line-end-position)))
1879 (beginning-of-line)
1880 ;; First try assuming `ls --dired' was used.
1881 (let ((change (next-single-property-change (point) 'dired-filename nil eol)))
1882 (cond
1883 ((and change (< change eol))
1884 (goto-char change))
1885 ((re-search-forward dired-move-to-filename-regexp eol t)
1886 (goto-char (match-end 0)))
1887 ((re-search-forward dired-permission-flags-regexp eol t)
1888 ;; Ha! There *is* a file. Our regexp-from-hell just failed to find it.
1889 (if raise-error
1890 (error "Unrecognized line! Check dired-move-to-filename-regexp"))
1891 (beginning-of-line)
1892 nil)
1893 (raise-error
1894 (error "No file on this line")))))
1896 (defun dired-move-to-end-of-filename (&optional no-error)
1897 ;; Assumes point is at beginning of filename,
1898 ;; thus the rwx bit re-search-backward below will succeed in *this*
1899 ;; line if at all. So, it should be called only after
1900 ;; (dired-move-to-filename t).
1901 ;; On failure, signals an error (with non-nil NO-ERROR just returns nil).
1902 ;; This is the UNIX version.
1903 (if (get-text-property (point) 'dired-filename)
1904 (goto-char (next-single-property-change (point) 'dired-filename))
1905 (let (opoint file-type executable symlink hidden case-fold-search used-F eol)
1906 ;; case-fold-search is nil now, so we can test for capital F:
1907 (setq used-F (string-match "F" dired-actual-switches)
1908 opoint (point)
1909 eol (save-excursion (end-of-line) (point))
1910 hidden (and selective-display
1911 (save-excursion (search-forward "\r" eol t))))
1912 (if hidden
1914 (save-excursion ;; Find out what kind of file this is:
1915 ;; Restrict perm bits to be non-blank,
1916 ;; otherwise this matches one char to early (looking backward):
1917 ;; "l---------" (some systems make symlinks that way)
1918 ;; "----------" (plain file with zero perms)
1919 (if (re-search-backward
1920 dired-permission-flags-regexp nil t)
1921 (setq file-type (char-after (match-beginning 1))
1922 symlink (eq file-type ?l)
1923 ;; Only with -F we need to know whether it's an executable
1924 executable (and
1925 used-F
1926 (string-match
1927 "[xst]" ;; execute bit set anywhere?
1928 (concat
1929 (match-string 2)
1930 (match-string 3)
1931 (match-string 4)))))
1932 (or no-error (error "No file on this line"))))
1933 ;; Move point to end of name:
1934 (if symlink
1935 (if (search-forward " -> " eol t)
1936 (progn
1937 (forward-char -4)
1938 (and used-F
1939 dired-ls-F-marks-symlinks
1940 (eq (preceding-char) ?@) ;; did ls really mark the link?
1941 (forward-char -1))))
1942 (goto-char eol) ;; else not a symbolic link
1943 ;; ls -lF marks dirs, sockets and executables with exactly one
1944 ;; trailing character. (Executable bits on symlinks ain't mean
1945 ;; a thing, even to ls, but we know it's not a symlink.)
1946 (and used-F
1947 (or (memq file-type '(?d ?s))
1948 executable)
1949 (forward-char -1))))
1950 (or no-error
1951 (not (eq opoint (point)))
1952 (error (if hidden
1953 (substitute-command-keys
1954 "File line is hidden, type \\[dired-hide-subdir] to unhide")
1955 "No file on this line")))
1956 (if (eq opoint (point))
1958 (point)))))
1961 ;;; COPY NAMES OF MARKED FILES INTO KILL-RING.
1963 (defun dired-copy-filename-as-kill (&optional arg)
1964 "Copy names of marked (or next ARG) files into the kill ring.
1965 The names are separated by a space.
1966 With a zero prefix arg, use the absolute file name of each marked file.
1967 With \\[universal-argument], use the file name sans directory of each marked file.
1969 If on a subdir headerline, use subdirname instead; prefix arg is ignored
1970 in this case.
1972 You can then feed the file name(s) to other commands with \\[yank]."
1973 (interactive "P")
1974 (let ((string
1975 (or (dired-get-subdir)
1976 (mapconcat (function identity)
1977 (if arg
1978 (cond ((zerop (prefix-numeric-value arg))
1979 (dired-get-marked-files))
1980 ((integerp arg)
1981 (dired-get-marked-files 'no-dir arg))
1982 (t ; else a raw arg
1983 (dired-get-marked-files t)))
1984 (dired-get-marked-files 'no-dir))
1985 " "))))
1986 (if (eq last-command 'kill-region)
1987 (kill-append string nil)
1988 (kill-new string))
1989 (message "%s" string)))
1992 ;; Keeping Dired buffers in sync with the filesystem and with each other
1994 (defun dired-buffers-for-dir (dir &optional file)
1995 ;; Return a list of buffers that dired DIR (top level or in-situ subdir).
1996 ;; If FILE is non-nil, include only those whose wildcard pattern (if any)
1997 ;; matches FILE.
1998 ;; The list is in reverse order of buffer creation, most recent last.
1999 ;; As a side effect, killed dired buffers for DIR are removed from
2000 ;; dired-buffers.
2001 (setq dir (file-name-as-directory dir))
2002 (let ((alist dired-buffers) result elt buf)
2003 (while alist
2004 (setq elt (car alist)
2005 buf (cdr elt))
2006 (if (buffer-name buf)
2007 (if (dired-in-this-tree dir (car elt))
2008 (with-current-buffer buf
2009 (and (assoc dir dired-subdir-alist)
2010 (or (null file)
2011 (let ((wildcards
2012 (file-name-nondirectory dired-directory)))
2013 (or (= 0 (length wildcards))
2014 (string-match (dired-glob-regexp wildcards)
2015 file))))
2016 (setq result (cons buf result)))))
2017 ;; else buffer is killed - clean up:
2018 (setq dired-buffers (delq elt dired-buffers)))
2019 (setq alist (cdr alist)))
2020 result))
2022 (defun dired-glob-regexp (pattern)
2023 "Convert glob-pattern PATTERN to a regular expression."
2024 (let ((matched-in-pattern 0) ;; How many chars of PATTERN we've handled.
2025 regexp)
2026 (while (string-match "[[?*]" pattern matched-in-pattern)
2027 (let ((op-end (match-end 0))
2028 (next-op (aref pattern (match-beginning 0))))
2029 (setq regexp (concat regexp
2030 (regexp-quote
2031 (substring pattern matched-in-pattern
2032 (match-beginning 0)))))
2033 (cond ((= next-op ??)
2034 (setq regexp (concat regexp "."))
2035 (setq matched-in-pattern op-end))
2036 ((= next-op ?\[)
2037 ;; Fails to handle ^ yet ????
2038 (let* ((set-start (match-beginning 0))
2039 (set-cont
2040 (if (= (aref pattern (1+ set-start)) ?^)
2041 (+ 3 set-start)
2042 (+ 2 set-start)))
2043 (set-end (string-match "]" pattern set-cont))
2044 (set (substring pattern set-start (1+ set-end))))
2045 (setq regexp (concat regexp set))
2046 (setq matched-in-pattern (1+ set-end))))
2047 ((= next-op ?*)
2048 (setq regexp (concat regexp ".*"))
2049 (setq matched-in-pattern op-end)))))
2050 (concat "\\`"
2051 regexp
2052 (regexp-quote
2053 (substring pattern matched-in-pattern))
2054 "\\'")))
2058 (defun dired-advertise ()
2059 ;;"Advertise in variable `dired-buffers' that we dired `default-directory'."
2060 ;; With wildcards we actually advertise too much.
2061 (let ((expanded-default (expand-file-name default-directory)))
2062 (if (memq (current-buffer) (dired-buffers-for-dir expanded-default))
2063 t ; we have already advertised ourselves
2064 (setq dired-buffers
2065 (cons (cons expanded-default (current-buffer))
2066 dired-buffers)))))
2068 (defun dired-unadvertise (dir)
2069 ;; Remove DIR from the buffer alist in variable dired-buffers.
2070 ;; This has the effect of removing any buffer whose main directory is DIR.
2071 ;; It does not affect buffers in which DIR is a subdir.
2072 ;; Removing is also done as a side-effect in dired-buffer-for-dir.
2073 (setq dired-buffers
2074 (delq (assoc (expand-file-name dir) dired-buffers) dired-buffers)))
2076 ;; Tree Dired
2078 ;;; utility functions
2080 (defun dired-in-this-tree (file dir)
2081 ;;"Is FILE part of the directory tree starting at DIR?"
2082 (let (case-fold-search)
2083 (string-match (concat "^" (regexp-quote dir)) file)))
2085 (defun dired-normalize-subdir (dir)
2086 ;; Prepend default-directory to DIR if relative file name.
2087 ;; dired-get-filename must be able to make a valid file name from a
2088 ;; file and its directory DIR.
2089 (file-name-as-directory
2090 (if (file-name-absolute-p dir)
2092 (expand-file-name dir default-directory))))
2094 (defun dired-get-subdir ()
2095 ;;"Return the subdir name on this line, or nil if not on a headerline."
2096 ;; Look up in the alist whether this is a headerline.
2097 (save-excursion
2098 (let ((cur-dir (dired-current-directory)))
2099 (beginning-of-line) ; alist stores b-o-l positions
2100 (and (zerop (- (point)
2101 (dired-get-subdir-min (assoc cur-dir
2102 dired-subdir-alist))))
2103 cur-dir))))
2105 ;(defun dired-get-subdir-min (elt)
2106 ; (cdr elt))
2107 ;; can't use macro, must be redefinable for other alist format in dired-nstd.
2108 (defalias 'dired-get-subdir-min 'cdr)
2110 (defun dired-get-subdir-max (elt)
2111 (save-excursion
2112 (goto-char (dired-get-subdir-min elt))
2113 (dired-subdir-max)))
2115 (defun dired-clear-alist ()
2116 (while dired-subdir-alist
2117 (set-marker (dired-get-subdir-min (car dired-subdir-alist)) nil)
2118 (setq dired-subdir-alist (cdr dired-subdir-alist))))
2120 (defun dired-subdir-index (dir)
2121 ;; Return an index into alist for use with nth
2122 ;; for the sake of subdir moving commands.
2123 (let (found (index 0) (alist dired-subdir-alist))
2124 (while alist
2125 (if (string= dir (car (car alist)))
2126 (setq alist nil found t)
2127 (setq alist (cdr alist) index (1+ index))))
2128 (if found index nil)))
2130 (defun dired-next-subdir (arg &optional no-error-if-not-found no-skip)
2131 "Go to next subdirectory, regardless of level."
2132 ;; Use 0 arg to go to this directory's header line.
2133 ;; NO-SKIP prevents moving to end of header line, returning whatever
2134 ;; position was found in dired-subdir-alist.
2135 (interactive "p")
2136 (let ((this-dir (dired-current-directory))
2137 pos index)
2138 ;; nth with negative arg does not return nil but the first element
2139 (setq index (- (dired-subdir-index this-dir) arg))
2140 (setq pos (if (>= index 0)
2141 (dired-get-subdir-min (nth index dired-subdir-alist))))
2142 (if pos
2143 (progn
2144 (goto-char pos)
2145 (or no-skip (skip-chars-forward "^\n\r"))
2146 (point))
2147 (if no-error-if-not-found
2148 nil ; return nil if not found
2149 (error "%s directory" (if (> arg 0) "Last" "First"))))))
2151 (defun dired-build-subdir-alist (&optional switches)
2152 "Build `dired-subdir-alist' by parsing the buffer.
2153 Returns the new value of the alist.
2154 If optional arg SWITCHES is non-nil, use its value
2155 instead of `dired-actual-switches'."
2156 (interactive)
2157 (dired-clear-alist)
2158 (save-excursion
2159 (let* ((count 0)
2160 (buffer-read-only nil)
2161 (switches (or switches dired-actual-switches))
2162 new-dir-name
2163 (R-ftp-base-dir-regex
2164 ;; Used to expand subdirectory names correctly in recursive
2165 ;; ange-ftp listings.
2166 (and (string-match "R" switches)
2167 (string-match "\\`/.*:\\(/.*\\)" default-directory)
2168 (concat "\\`" (match-string 1 default-directory)))))
2169 (goto-char (point-min))
2170 (setq dired-subdir-alist nil)
2171 (while (and (re-search-forward dired-subdir-regexp nil t)
2172 ;; Avoid taking a file name ending in a colon
2173 ;; as a subdir name.
2174 (not (save-excursion
2175 (goto-char (match-beginning 0))
2176 (beginning-of-line)
2177 (forward-char 2)
2178 (save-match-data (looking-at dired-re-perms)))))
2179 (save-excursion
2180 (goto-char (match-beginning 1))
2181 (setq new-dir-name
2182 (buffer-substring-no-properties (point) (match-end 1))
2183 new-dir-name
2184 (save-match-data
2185 (if (and R-ftp-base-dir-regex
2186 (not (string= new-dir-name default-directory))
2187 (string-match R-ftp-base-dir-regex new-dir-name))
2188 (concat default-directory
2189 (substring new-dir-name (match-end 0)))
2190 (expand-file-name new-dir-name))))
2191 (delete-region (point) (match-end 1))
2192 (insert new-dir-name))
2193 (setq count (1+ count))
2194 (dired-alist-add-1 new-dir-name
2195 ;; Place a sub directory boundary between lines.
2196 (save-excursion
2197 (goto-char (match-beginning 0))
2198 (beginning-of-line)
2199 (point-marker))))
2200 (if (and (> count 1) (interactive-p))
2201 (message "Buffer includes %d directories" count))
2202 ;; We don't need to sort it because it is in buffer order per
2203 ;; constructionem. Return new alist:
2204 dired-subdir-alist)))
2206 (defun dired-alist-add-1 (dir new-marker)
2207 ;; Add new DIR at NEW-MARKER. Don't sort.
2208 (setq dired-subdir-alist
2209 (cons (cons (dired-normalize-subdir dir) new-marker)
2210 dired-subdir-alist)))
2212 (defun dired-goto-next-nontrivial-file ()
2213 ;; Position point on first nontrivial file after point.
2214 (dired-goto-next-file);; so there is a file to compare with
2215 (if (stringp dired-trivial-filenames)
2216 (while (and (not (eobp))
2217 (string-match dired-trivial-filenames
2218 (file-name-nondirectory
2219 (or (dired-get-filename nil t) ""))))
2220 (forward-line 1)
2221 (dired-move-to-filename))))
2223 (defun dired-goto-next-file ()
2224 (let ((max (1- (dired-subdir-max))))
2225 (while (and (not (dired-move-to-filename)) (< (point) max))
2226 (forward-line 1))))
2228 (defun dired-goto-file (file)
2229 "Go to file line of FILE in this dired buffer."
2230 ;; Return value of point on success, else nil.
2231 ;; FILE must be an absolute file name.
2232 ;; Loses if FILE contains control chars like "\007" for which ls
2233 ;; either inserts "?" or "\\007" into the buffer, so we won't find
2234 ;; it in the buffer.
2235 (interactive
2236 (prog1 ; let push-mark display its message
2237 (list (expand-file-name
2238 (read-file-name "Goto file: "
2239 (dired-current-directory))))
2240 (push-mark)))
2241 (setq file (directory-file-name file)) ; does no harm if no directory
2242 (let (found case-fold-search dir)
2243 (setq dir (or (file-name-directory file)
2244 (error "File name `%s' is not absolute" file)))
2245 (save-excursion
2246 ;; The hair here is to get the result of dired-goto-subdir
2247 ;; without really calling it if we don't have any subdirs.
2248 (if (if (string= dir (expand-file-name default-directory))
2249 (goto-char (point-min))
2250 (and (cdr dired-subdir-alist)
2251 (dired-goto-subdir dir)))
2252 (let ((base (file-name-nondirectory file))
2253 search-string
2254 (boundary (dired-subdir-max)))
2255 (setq search-string
2256 (replace-regexp-in-string "\^m" "\\^m" base nil t))
2257 (setq search-string
2258 (replace-regexp-in-string "\\\\" "\\\\" search-string nil t))
2259 (while (and (not found)
2260 ;; filenames are preceded by SPC, this makes
2261 ;; the search faster (e.g. for the filename "-"!).
2262 (search-forward (concat " " search-string)
2263 boundary 'move))
2264 ;; Match could have BASE just as initial substring or
2265 ;; or in permission bits or date or
2266 ;; not be a proper filename at all:
2267 (if (equal base (dired-get-filename 'no-dir t))
2268 ;; Must move to filename since an (actually
2269 ;; correct) match could have been elsewhere on the
2270 ;; ;; line (e.g. "-" would match somewhere in the
2271 ;; permission bits).
2272 (setq found (dired-move-to-filename))
2273 ;; If this isn't the right line, move forward to avoid
2274 ;; trying this line again.
2275 (forward-line 1))))))
2276 (and found
2277 ;; return value of point (i.e., FOUND):
2278 (goto-char found))))
2280 (defun dired-initial-position (dirname)
2281 ;; Where point should go in a new listing of DIRNAME.
2282 ;; Point assumed at beginning of new subdir line.
2283 ;; You may redefine this function as you wish, e.g. like in dired-x.el.
2284 (end-of-line)
2285 (if dired-trivial-filenames (dired-goto-next-nontrivial-file)))
2287 ;; These are hooks which make tree dired work.
2288 ;; They are in this file because other parts of dired need to call them.
2289 ;; But they don't call the rest of tree dired unless there are subdirs loaded.
2291 ;; This function is called for each retrieved filename.
2292 ;; It could stand to be faster, though it's mostly function call
2293 ;; overhead. Avoiding the function call seems to save about 10% in
2294 ;; dired-get-filename. Make it a defsubst?
2295 (defun dired-current-directory (&optional localp)
2296 "Return the name of the subdirectory to which this line belongs.
2297 This returns a string with trailing slash, like `default-directory'.
2298 Optional argument means return a file name relative to `default-directory'."
2299 (let ((here (point))
2300 (alist (or dired-subdir-alist
2301 ;; probably because called in a non-dired buffer
2302 (error "No subdir-alist in %s" (current-buffer))))
2303 elt dir)
2304 (while alist
2305 (setq elt (car alist)
2306 dir (car elt)
2307 ;; use `<=' (not `<') as subdir line is part of subdir
2308 alist (if (<= (dired-get-subdir-min elt) here)
2309 nil ; found
2310 (cdr alist))))
2311 (if localp
2312 (dired-make-relative dir default-directory)
2313 dir)))
2315 ;; Subdirs start at the beginning of their header lines and end just
2316 ;; before the beginning of the next header line (or end of buffer).
2318 (defun dired-subdir-max ()
2319 (save-excursion
2320 (if (or (null (cdr dired-subdir-alist)) (not (dired-next-subdir 1 t t)))
2321 (point-max)
2322 (point))))
2324 ;; Deleting files
2326 (defcustom dired-recursive-deletes nil ; Default only delete empty directories.
2327 "*Decide whether recursive deletes are allowed.
2328 nil means no recursive deletes.
2329 `always' means delete recursively without asking. This is DANGEROUS!
2330 `top' means ask for each directory at top level, but delete its subdirectories
2331 without asking.
2332 Anything else means ask for each directory."
2333 :type '(choice :tag "Delete non-empty directories"
2334 (const :tag "Yes" always)
2335 (const :tag "No--only delete empty directories" nil)
2336 (const :tag "Confirm for each directory" t)
2337 (const :tag "Confirm for each top directory only" top))
2338 :group 'dired)
2340 ;; Match anything but `.' and `..'.
2341 (defvar dired-re-no-dot "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*")
2343 ;; Delete file, possibly delete a directory and all its files.
2344 ;; This function is usefull outside of dired. One could change it's name
2345 ;; to e.g. recursive-delete-file and put it somewhere else.
2346 (defun dired-delete-file (file &optional recursive) "\
2347 Delete FILE or directory (possibly recursively if optional RECURSIVE is true.)
2348 RECURSIVE determines what to do with a non-empty directory. If RECURSIVE is:
2349 Nil, do not delete.
2350 `always', delete recursively without asking.
2351 `top', ask for each directory at top level.
2352 Anything else, ask for each sub-directory."
2353 (let (files)
2354 ;; This test is equivalent to
2355 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2356 ;; but more efficient
2357 (if (not (eq t (car (file-attributes file))))
2358 (delete-file file)
2359 (when (and recursive
2360 (setq files
2361 (directory-files file t dired-re-no-dot)) ; Not empty.
2362 (or (eq recursive 'always)
2363 (yes-or-no-p (format "Recursive delete of %s "
2364 (dired-make-relative file)))))
2365 (if (eq recursive 'top) (setq recursive 'always)) ; Don't ask again.
2366 (while files ; Recursively delete (possibly asking).
2367 (dired-delete-file (car files) recursive)
2368 (setq files (cdr files))))
2369 (delete-directory file))))
2371 (defun dired-do-flagged-delete (&optional nomessage)
2372 "In Dired, delete the files flagged for deletion.
2373 If NOMESSAGE is non-nil, we don't display any message
2374 if there are no flagged files."
2375 (interactive)
2376 (let* ((dired-marker-char dired-del-marker)
2377 (regexp (dired-marker-regexp))
2378 case-fold-search)
2379 (if (save-excursion (goto-char (point-min))
2380 (re-search-forward regexp nil t))
2381 (dired-internal-do-deletions
2382 ;; this can't move point since ARG is nil
2383 (dired-map-over-marks (cons (dired-get-filename) (point))
2384 nil)
2385 nil)
2386 (or nomessage
2387 (message "(No deletions requested)")))))
2389 (defun dired-do-delete (&optional arg)
2390 "Delete all marked (or next ARG) files."
2391 ;; This is more consistent with the file marking feature than
2392 ;; dired-do-flagged-delete.
2393 (interactive "P")
2394 (dired-internal-do-deletions
2395 ;; this may move point if ARG is an integer
2396 (dired-map-over-marks (cons (dired-get-filename) (point))
2397 arg)
2398 arg))
2400 (defvar dired-deletion-confirmer 'yes-or-no-p) ; or y-or-n-p?
2402 (defun dired-internal-do-deletions (l arg)
2403 ;; L is an alist of files to delete, with their buffer positions.
2404 ;; ARG is the prefix arg.
2405 ;; Filenames are absolute (VMS needs this for logical search paths).
2406 ;; (car L) *must* be the *last* (bottommost) file in the dired buffer.
2407 ;; That way as changes are made in the buffer they do not shift the
2408 ;; lines still to be changed, so the (point) values in L stay valid.
2409 ;; Also, for subdirs in natural order, a subdir's files are deleted
2410 ;; before the subdir itself - the other way around would not work.
2411 (let ((files (mapcar (function car) l))
2412 (count (length l))
2413 (succ 0))
2414 ;; canonicalize file list for pop up
2415 (setq files (nreverse (mapcar (function dired-make-relative) files)))
2416 (if (dired-mark-pop-up
2417 " *Deletions*" 'delete files dired-deletion-confirmer
2418 (format "Delete %s " (dired-mark-prompt arg files)))
2419 (save-excursion
2420 (let (failures);; files better be in reverse order for this loop!
2421 (while l
2422 (goto-char (cdr (car l)))
2423 (let (buffer-read-only)
2424 (condition-case err
2425 (let ((fn (car (car l))))
2426 (dired-delete-file fn dired-recursive-deletes)
2427 ;; if we get here, removing worked
2428 (setq succ (1+ succ))
2429 (message "%s of %s deletions" succ count)
2430 (dired-fun-in-all-buffers
2431 (file-name-directory fn) (file-name-nondirectory fn)
2432 (function dired-delete-entry) fn))
2433 (error;; catch errors from failed deletions
2434 (dired-log "%s\n" err)
2435 (setq failures (cons (car (car l)) failures)))))
2436 (setq l (cdr l)))
2437 (if (not failures)
2438 (message "%d deletion%s done" count (dired-plural-s count))
2439 (dired-log-summary
2440 (format "%d of %d deletion%s failed"
2441 (length failures) count
2442 (dired-plural-s count))
2443 failures))))
2444 (message "(No deletions performed)")))
2445 (dired-move-to-filename))
2447 (defun dired-fun-in-all-buffers (directory file fun &rest args)
2448 ;; In all buffers dired'ing DIRECTORY, run FUN with ARGS.
2449 ;; If the buffer has a wildcard pattern, check that it matches FILE.
2450 ;; (FILE does not include a directory component.)
2451 ;; FILE may be nil, in which case ignore it.
2452 ;; Return list of buffers where FUN succeeded (i.e., returned non-nil).
2453 (let (success-list)
2454 (dolist (buf (dired-buffers-for-dir (expand-file-name directory)
2455 file))
2456 (with-current-buffer buf
2457 (if (apply fun args)
2458 (setq success-list (cons (buffer-name buf) success-list)))))
2459 success-list))
2461 ;; Delete the entry for FILE from
2462 (defun dired-delete-entry (file)
2463 (save-excursion
2464 (and (dired-goto-file file)
2465 (let (buffer-read-only)
2466 (delete-region (progn (beginning-of-line) (point))
2467 (save-excursion (forward-line 1) (point))))))
2468 (dired-clean-up-after-deletion file))
2470 ;; This is a separate function for the sake of dired-x.el.
2471 (defun dired-clean-up-after-deletion (fn)
2472 ;; Clean up after a deleted file or directory FN.
2473 (save-excursion (and (cdr dired-subdir-alist)
2474 (dired-goto-subdir fn)
2475 (dired-kill-subdir))))
2477 ;; Confirmation
2479 (defun dired-marker-regexp ()
2480 (concat "^" (regexp-quote (char-to-string dired-marker-char))))
2482 (defun dired-plural-s (count)
2483 (if (= 1 count) "" "s"))
2485 (defun dired-mark-prompt (arg files)
2486 ;; Return a string for use in a prompt, either the current file
2487 ;; name, or the marker and a count of marked files.
2488 (let ((count (length files)))
2489 (if (= count 1)
2490 (car files)
2491 ;; more than 1 file:
2492 (if (integerp arg)
2493 ;; abs(arg) = count
2494 ;; Perhaps this is nicer, but it also takes more screen space:
2495 ;;(format "[%s %d files]" (if (> arg 0) "next" "previous")
2496 ;; count)
2497 (format "[next %d files]" arg)
2498 (format "%c [%d files]" dired-marker-char count)))))
2500 (defun dired-pop-to-buffer (buf)
2501 ;; Pop up buffer BUF.
2502 ;; If dired-shrink-to-fit is t, make its window fit its contents.
2503 (if (not dired-shrink-to-fit)
2504 (pop-to-buffer (get-buffer-create buf))
2505 ;; let window shrink to fit:
2506 (let ((window (selected-window))
2507 target-lines w2)
2508 (cond ;; if split-height-threshold is enabled, use the largest window
2509 ((and (> (window-height (setq w2 (get-largest-window)))
2510 split-height-threshold)
2511 (= (frame-width) (window-width w2)))
2512 (setq window w2))
2513 ;; if the least-recently-used window is big enough, use it
2514 ((and (> (window-height (setq w2 (get-lru-window)))
2515 (* 2 window-min-height))
2516 (= (frame-width) (window-width w2)))
2517 (setq window w2)))
2518 (save-excursion
2519 (set-buffer buf)
2520 (goto-char (point-max))
2521 (skip-chars-backward "\n\r\t ")
2522 (setq target-lines (count-lines (point-min) (point)))
2523 ;; Don't forget to count the last line.
2524 (if (not (bolp))
2525 (setq target-lines (1+ target-lines))))
2526 (if (<= (window-height window) (* 2 window-min-height))
2527 ;; At this point, every window on the frame is too small to split.
2528 (setq w2 (display-buffer buf))
2529 (setq w2 (split-window window
2530 (max window-min-height
2531 (- (window-height window)
2532 (1+ (max window-min-height target-lines)))))))
2533 (set-window-buffer w2 buf)
2534 (if (< (1- (window-height w2)) target-lines)
2535 (progn
2536 (select-window w2)
2537 (enlarge-window (- target-lines (1- (window-height w2))))))
2538 (set-window-start w2 1)
2541 (defvar dired-no-confirm nil
2542 "A list of symbols for commands dired should not confirm.
2543 Command symbols are `byte-compile', `chgrp', `chmod', `chown', `compress',
2544 `copy', `delete', `hardlink', `load', `move', `print', `shell', `symlink',
2545 `touch' and `uncompress'.")
2547 (defun dired-mark-pop-up (bufname op-symbol files function &rest args)
2548 "Return FUNCTION's result on ARGS after showing which files are marked.
2549 Displays the file names in a buffer named BUFNAME;
2550 nil gives \" *Marked Files*\".
2551 This uses function `dired-pop-to-buffer' to do that.
2553 FUNCTION should not manipulate files, just read input
2554 (an argument or confirmation).
2555 The window is not shown if there is just one file or
2556 OP-SYMBOL is a member of the list in `dired-no-confirm'.
2557 FILES is the list of marked files."
2558 (or bufname (setq bufname " *Marked Files*"))
2559 (if (or (eq dired-no-confirm t)
2560 (memq op-symbol dired-no-confirm)
2561 (= (length files) 1))
2562 (apply function args)
2563 (with-current-buffer (get-buffer-create bufname)
2564 (erase-buffer)
2565 (dired-format-columns-of-files files)
2566 (remove-text-properties (point-min) (point-max)
2567 '(mouse-face nil help-echo nil)))
2568 (save-window-excursion
2569 (dired-pop-to-buffer bufname)
2570 (apply function args))))
2572 (defun dired-format-columns-of-files (files)
2573 ;; Files should be in forward order for this loop.
2574 ;; i.e., (car files) = first file in buffer.
2575 ;; Returns the number of lines used.
2576 (let* ((maxlen (+ 2 (apply 'max (mapcar 'length files))))
2577 (width (- (window-width (selected-window)) 2))
2578 (columns (max 1 (/ width maxlen)))
2579 (nfiles (length files))
2580 (rows (+ (/ nfiles columns)
2581 (if (zerop (% nfiles columns)) 0 1)))
2582 (i 0)
2583 (j 0))
2584 (setq files (nconc (copy-sequence files) ; fill up with empty fns
2585 (make-list (- (* columns rows) nfiles) "")))
2586 (setcdr (nthcdr (1- (length files)) files) files) ; make circular
2587 (while (< j rows)
2588 (while (< i columns)
2589 (indent-to (* i maxlen))
2590 (insert (car files))
2591 (setq files (nthcdr rows files)
2592 i (1+ i)))
2593 (insert "\n")
2594 (setq i 0
2595 j (1+ j)
2596 files (cdr files)))
2597 rows))
2599 ;; Commands to mark or flag file(s) at or near current line.
2601 (defun dired-repeat-over-lines (arg function)
2602 ;; This version skips non-file lines.
2603 (let ((pos (make-marker)))
2604 (beginning-of-line)
2605 (while (and (> arg 0) (not (eobp)))
2606 (setq arg (1- arg))
2607 (beginning-of-line)
2608 (while (and (not (eobp)) (dired-between-files)) (forward-line 1))
2609 (save-excursion
2610 (forward-line 1)
2611 (move-marker pos (1+ (point))))
2612 (save-excursion (funcall function))
2613 ;; Advance to the next line--actually, to the line that *was* next.
2614 ;; (If FUNCTION inserted some new lines in between, skip them.)
2615 (goto-char pos))
2616 (while (and (< arg 0) (not (bobp)))
2617 (setq arg (1+ arg))
2618 (forward-line -1)
2619 (while (and (not (bobp)) (dired-between-files)) (forward-line -1))
2620 (beginning-of-line)
2621 (save-excursion (funcall function)))
2622 (move-marker pos nil)
2623 (dired-move-to-filename)))
2625 (defun dired-between-files ()
2626 ;; This used to be a regexp match of the `total ...' line output by
2627 ;; ls, which is slightly faster, but that is not very robust; notably,
2628 ;; it fails for non-english locales.
2629 (save-excursion (not (dired-move-to-filename))))
2631 (defun dired-next-marked-file (arg &optional wrap opoint)
2632 "Move to the next marked file, wrapping around the end of the buffer."
2633 (interactive "p\np")
2634 (or opoint (setq opoint (point)));; return to where interactively started
2635 (if (if (> arg 0)
2636 (re-search-forward dired-re-mark nil t arg)
2637 (beginning-of-line)
2638 (re-search-backward dired-re-mark nil t (- arg)))
2639 (dired-move-to-filename)
2640 (if (null wrap)
2641 (progn
2642 (goto-char opoint)
2643 (error "No next marked file"))
2644 (message "(Wraparound for next marked file)")
2645 (goto-char (if (> arg 0) (point-min) (point-max)))
2646 (dired-next-marked-file arg nil opoint))))
2648 (defun dired-prev-marked-file (arg &optional wrap)
2649 "Move to the previous marked file, wrapping around the end of the buffer."
2650 (interactive "p\np")
2651 (dired-next-marked-file (- arg) wrap))
2653 (defun dired-file-marker (file)
2654 ;; Return FILE's marker, or nil if unmarked.
2655 (save-excursion
2656 (and (dired-goto-file file)
2657 (progn
2658 (beginning-of-line)
2659 (if (not (equal ?\040 (following-char)))
2660 (following-char))))))
2662 (defun dired-mark-files-in-region (start end)
2663 (let (buffer-read-only)
2664 (if (> start end)
2665 (error "start > end"))
2666 (goto-char start) ; assumed at beginning of line
2667 (while (< (point) end)
2668 ;; Skip subdir line and following garbage like the `total' line:
2669 (while (and (< (point) end) (dired-between-files))
2670 (forward-line 1))
2671 (if (and (not (looking-at dired-re-dot))
2672 (dired-get-filename nil t))
2673 (progn
2674 (delete-char 1)
2675 (insert dired-marker-char)))
2676 (forward-line 1))))
2678 (defun dired-mark (arg)
2679 "Mark the current (or next ARG) files.
2680 If on a subdir headerline, mark all its files except `.' and `..'.
2682 Use \\[dired-unmark-all-files] to remove all marks
2683 and \\[dired-unmark] on a subdir to remove the marks in
2684 this subdir."
2685 (interactive "P")
2686 (if (dired-get-subdir)
2687 (save-excursion (dired-mark-subdir-files))
2688 (let (buffer-read-only)
2689 (dired-repeat-over-lines
2690 (prefix-numeric-value arg)
2691 (function (lambda () (delete-char 1) (insert dired-marker-char)))))))
2693 (defun dired-unmark (arg)
2694 "Unmark the current (or next ARG) files.
2695 If looking at a subdir, unmark all its files except `.' and `..'."
2696 (interactive "P")
2697 (let ((dired-marker-char ?\040))
2698 (dired-mark arg)))
2700 (defun dired-flag-file-deletion (arg)
2701 "In Dired, flag the current line's file for deletion.
2702 With prefix arg, repeat over several lines.
2704 If on a subdir headerline, mark all its files except `.' and `..'."
2705 (interactive "P")
2706 (let ((dired-marker-char dired-del-marker))
2707 (dired-mark arg)))
2709 (defun dired-unmark-backward (arg)
2710 "In Dired, move up lines and remove deletion flag there.
2711 Optional prefix ARG says how many lines to unflag; default is one line."
2712 (interactive "p")
2713 (dired-unmark (- arg)))
2715 (defun dired-toggle-marks ()
2716 "Toggle marks: marked files become unmarked, and vice versa.
2717 Files marked with other flags (such as `D') are not affected.
2718 `.' and `..' are never toggled.
2719 As always, hidden subdirs are not affected."
2720 (interactive)
2721 (save-excursion
2722 (goto-char (point-min))
2723 (let (buffer-read-only)
2724 (while (not (eobp))
2725 (or (dired-between-files)
2726 (looking-at dired-re-dot)
2727 ;; use subst instead of insdel because it does not move
2728 ;; the gap and thus should be faster and because
2729 ;; other characters are left alone automatically
2730 (apply 'subst-char-in-region
2731 (point) (1+ (point))
2732 (if (eq ?\040 (following-char)) ; SPC
2733 (list ?\040 dired-marker-char)
2734 (list dired-marker-char ?\040))))
2735 (forward-line 1)))))
2737 ;;; Commands to mark or flag files based on their characteristics or names.
2739 (defvar dired-regexp-history nil
2740 "History list of regular expressions used in Dired commands.")
2742 (defun dired-read-regexp (prompt)
2743 (read-from-minibuffer prompt nil nil nil 'dired-regexp-history))
2745 (defun dired-mark-files-regexp (regexp &optional marker-char)
2746 "Mark all files matching REGEXP for use in later commands.
2747 A prefix argument means to unmark them instead.
2748 `.' and `..' are never marked.
2750 REGEXP is an Emacs regexp, not a shell wildcard. Thus, use `\\.o$' for
2751 object files--just `.o' will mark more than you might think."
2752 (interactive
2753 (list (dired-read-regexp (concat (if current-prefix-arg "Unmark" "Mark")
2754 " files (regexp): "))
2755 (if current-prefix-arg ?\040)))
2756 (let ((dired-marker-char (or marker-char dired-marker-char)))
2757 (dired-mark-if
2758 (and (not (looking-at dired-re-dot))
2759 (not (eolp)) ; empty line
2760 (let ((fn (dired-get-filename nil t)))
2761 (and fn (string-match regexp (file-name-nondirectory fn)))))
2762 "matching file")))
2764 (defun dired-mark-files-containing-regexp (regexp &optional marker-char)
2765 "Mark all files with contents containing REGEXP for use in later commands.
2766 A prefix argument means to unmark them instead.
2767 `.' and `..' are never marked."
2768 (interactive
2769 (list (dired-read-regexp (concat (if current-prefix-arg "Unmark" "Mark")
2770 " files containing (regexp): "))
2771 (if current-prefix-arg ?\040)))
2772 (let ((dired-marker-char (or marker-char dired-marker-char)))
2773 (dired-mark-if
2774 (and (not (looking-at dired-re-dot))
2775 (not (eolp)) ; empty line
2776 (let ((fn (dired-get-filename nil t)))
2777 (when (and fn (file-readable-p fn)
2778 (not (file-directory-p fn)))
2779 (let ((prebuf (get-file-buffer fn)))
2780 (message "Checking %s" fn)
2781 ;; For now we do it inside emacs
2782 ;; Grep might be better if there are a lot of files
2783 (if prebuf
2784 (with-current-buffer prebuf
2785 (save-excursion
2786 (goto-char (point-min))
2787 (re-search-forward regexp nil t)))
2788 (with-temp-buffer
2789 (insert-file-contents fn)
2790 (goto-char (point-min))
2791 (re-search-forward regexp nil t))))
2793 "matching file")))
2795 (defun dired-flag-files-regexp (regexp)
2796 "In Dired, flag all files containing the specified REGEXP for deletion.
2797 The match is against the non-directory part of the filename. Use `^'
2798 and `$' to anchor matches. Exclude subdirs by hiding them.
2799 `.' and `..' are never flagged."
2800 (interactive (list (dired-read-regexp "Flag for deletion (regexp): ")))
2801 (dired-mark-files-regexp regexp dired-del-marker))
2803 (defun dired-mark-symlinks (unflag-p)
2804 "Mark all symbolic links.
2805 With prefix argument, unflag all those files."
2806 (interactive "P")
2807 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
2808 (dired-mark-if (looking-at dired-re-sym) "symbolic link")))
2810 (defun dired-mark-directories (unflag-p)
2811 "Mark all directory file lines except `.' and `..'.
2812 With prefix argument, unflag all those files."
2813 (interactive "P")
2814 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
2815 (dired-mark-if (and (looking-at dired-re-dir)
2816 (not (looking-at dired-re-dot)))
2817 "directory file")))
2819 (defun dired-mark-executables (unflag-p)
2820 "Mark all executable files.
2821 With prefix argument, unflag all those files."
2822 (interactive "P")
2823 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
2824 (dired-mark-if (looking-at dired-re-exe) "executable file")))
2826 ;; dired-x.el has a dired-mark-sexp interactive command: mark
2827 ;; files for which PREDICATE returns non-nil.
2829 (defun dired-flag-auto-save-files (&optional unflag-p)
2830 "Flag for deletion files whose names suggest they are auto save files.
2831 A prefix argument says to unflag those files instead."
2832 (interactive "P")
2833 (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
2834 (dired-mark-if
2835 ;; It is less than general to check for # here,
2836 ;; but it's the only way this runs fast enough.
2837 (and (save-excursion (end-of-line)
2839 (eq (preceding-char) ?#)
2840 ;; Handle executables in case of -F option.
2841 ;; We need not worry about the other kinds
2842 ;; of markings that -F makes, since they won't
2843 ;; appear on real auto-save files.
2844 (if (eq (preceding-char) ?*)
2845 (progn
2846 (forward-char -1)
2847 (eq (preceding-char) ?#)))))
2848 (not (looking-at dired-re-dir))
2849 (let ((fn (dired-get-filename t t)))
2850 (if fn (auto-save-file-name-p
2851 (file-name-nondirectory fn)))))
2852 "auto save file")))
2854 (defcustom dired-garbage-files-regexp
2855 ;; `log' here is dubious, since it's typically used for useful log
2856 ;; files, not just TeX stuff. -- fx
2857 (concat (regexp-opt
2858 '(".log" ".toc" ".dvi" ".bak" ".orig" ".rej" ".aux"))
2859 "\\'")
2860 "Regular expression to match \"garbage\" files for `dired-flag-garbage-files'."
2861 :type 'regexp
2862 :group 'dired)
2864 (defun dired-flag-garbage-files ()
2865 "Flag for deletion all files that match `dired-garbage-files-regexp'."
2866 (interactive)
2867 (dired-flag-files-regexp dired-garbage-files-regexp))
2869 (defun dired-flag-backup-files (&optional unflag-p)
2870 "Flag all backup files (names ending with `~') for deletion.
2871 With prefix argument, unflag these files."
2872 (interactive "P")
2873 (let ((dired-marker-char (if unflag-p ?\ dired-del-marker)))
2874 (dired-mark-if
2875 ;; Don't call backup-file-name-p unless the last character looks like
2876 ;; it might be the end of a backup file name. This isn't very general,
2877 ;; but it's the only way this runs fast enough.
2878 (and (save-excursion (end-of-line)
2879 ;; Handle executables in case of -F option.
2880 ;; We need not worry about the other kinds
2881 ;; of markings that -F makes, since they won't
2882 ;; appear on real backup files.
2883 (if (eq (preceding-char) ?*)
2884 (forward-char -1))
2885 (eq (preceding-char) ?~))
2886 (not (looking-at dired-re-dir))
2887 (let ((fn (dired-get-filename t t)))
2888 (if fn (backup-file-name-p fn))))
2889 "backup file")))
2891 (defun dired-change-marks (&optional old new)
2892 "Change all OLD marks to NEW marks.
2893 OLD and NEW are both characters used to mark files."
2894 (interactive
2895 (let* ((cursor-in-echo-area t)
2896 (old (progn (message "Change (old mark): ") (read-char)))
2897 (new (progn (message "Change %c marks to (new mark): " old)
2898 (read-char))))
2899 (list old new)))
2900 (if (or (eq old ?\r) (eq new ?\r))
2901 (ding)
2902 (let ((string (format "\n%c" old))
2903 (buffer-read-only))
2904 (save-excursion
2905 (goto-char (point-min))
2906 (while (search-forward string nil t)
2907 (if (if (= old ?\ )
2908 (save-match-data
2909 (dired-get-filename 'no-dir t))
2911 (subst-char-in-region (match-beginning 0)
2912 (match-end 0) old new)))))))
2914 (defun dired-unmark-all-marks ()
2915 "Remove all marks from all files in the Dired buffer."
2916 (interactive)
2917 (dired-unmark-all-files ?\r))
2919 (defun dired-unmark-all-files (mark &optional arg)
2920 "Remove a specific mark (or any mark) from every file.
2921 After this command, type the mark character to remove,
2922 or type RET to remove all marks.
2923 With prefix arg, query for each marked file.
2924 Type \\[help-command] at that time for help."
2925 (interactive "cRemove marks (RET means all): \nP")
2926 (save-excursion
2927 (let* ((count 0)
2928 buffer-read-only case-fold-search query
2929 (string (format "\n%c" mark))
2930 (help-form "\
2931 Type SPC or `y' to unmark one file, DEL or `n' to skip to next,
2932 `!' to unmark all remaining files with no more questions."))
2933 (goto-char (point-min))
2934 (while (if (eq mark ?\r)
2935 (re-search-forward dired-re-mark nil t)
2936 (search-forward string nil t))
2937 (if (or (not arg)
2938 (let ((file (dired-get-filename t t)))
2939 (and file
2940 (dired-query 'query "Unmark file `%s'? "
2941 file))))
2942 (progn (subst-char-in-region (1- (point)) (point)
2943 (preceding-char) ?\ )
2944 (setq count (1+ count)))))
2945 (message (if (= count 1) "1 mark removed"
2946 "%d marks removed")
2947 count))))
2949 ;; Logging failures operating on files, and showing the results.
2951 (defvar dired-log-buffer "*Dired log*")
2953 (defun dired-why ()
2954 "Pop up a buffer with error log output from Dired.
2955 A group of errors from a single command ends with a formfeed.
2956 Thus, use \\[backward-page] to find the beginning of a group of errors."
2957 (interactive)
2958 (if (get-buffer dired-log-buffer)
2959 (let ((owindow (selected-window))
2960 (window (display-buffer (get-buffer dired-log-buffer))))
2961 (unwind-protect
2962 (progn
2963 (select-window window)
2964 (goto-char (point-max))
2965 (forward-line -1)
2966 (backward-page 1)
2967 (recenter 0))
2968 (select-window owindow)))))
2970 (defun dired-log (log &rest args)
2971 ;; Log a message or the contents of a buffer.
2972 ;; If LOG is a string and there are more args, it is formatted with
2973 ;; those ARGS. Usually the LOG string ends with a \n.
2974 ;; End each bunch of errors with (dired-log t):
2975 ;; this inserts the current time and buffer at the start of the page,
2976 ;; and \f (formfeed) at the end.
2977 (let ((obuf (current-buffer)))
2978 (with-current-buffer (get-buffer-create dired-log-buffer)
2979 (goto-char (point-max))
2980 (let ((inhibit-read-only t))
2981 (cond ((stringp log)
2982 (insert (if args
2983 (apply (function format) log args)
2984 log)))
2985 ((bufferp log)
2986 (insert-buffer log))
2987 ((eq t log)
2988 (backward-page 1)
2989 (unless (bolp)
2990 (insert "\n"))
2991 (insert (current-time-string)
2992 "\tBuffer `" (buffer-name obuf) "'\n")
2993 (goto-char (point-max))
2994 (insert "\f\n")))))))
2996 (defun dired-log-summary (string failures)
2997 (if (= (length failures) 1)
2998 (message "%s"
2999 (with-current-buffer dired-log-buffer
3000 (goto-char (point-max))
3001 (backward-page 1)
3002 (if (eolp) (forward-line 1))
3003 (buffer-substring (point) (point-max))))
3004 (message (if failures "%s--type ? for details (%s)"
3005 "%s--type ? for details")
3006 string failures))
3007 ;; Log a summary describing a bunch of errors.
3008 (dired-log (concat "\n" string "\n"))
3009 (dired-log t))
3011 ;;; Sorting
3013 ;; Most ls can only sort by name or by date (with -t), nothing else.
3014 ;; GNU ls sorts on size with -S, on extension with -X, and unsorted with -U.
3015 ;; So anything that does not contain these is sort "by name".
3017 (defvar dired-ls-sorting-switches "SXU"
3018 "String of `ls' switches \(single letters\) except `t' that influence sorting.
3020 This indicates to Dired which option switches to watch out for because they
3021 will change the sorting order behavior of `ls'.
3023 To change the default sorting order \(e.g. add a `-v' option\), see the
3024 variable `dired-listing-switches'. To temporarily override the listing
3025 format, use `\\[universal-argument] \\[dired]'.")
3027 (defvar dired-sort-by-date-regexp
3028 (concat "^-[^" dired-ls-sorting-switches
3029 "]*t[^" dired-ls-sorting-switches "]*$")
3030 "Regexp recognized by dired to set `by date' mode.")
3032 (defvar dired-sort-by-name-regexp
3033 (concat "^-[^t" dired-ls-sorting-switches "]+$")
3034 "Regexp recognized by dired to set `by name' mode.")
3036 (defvar dired-sort-inhibit nil
3037 "Non-nil means the Dired sort command is disabled.
3038 The idea is to set this buffer-locally in special Dired buffers.")
3040 (defun dired-sort-set-modeline ()
3041 ;; Set modeline display according to dired-actual-switches.
3042 ;; Modeline display of "by name" or "by date" guarantees the user a
3043 ;; match with the corresponding regexps. Non-matching switches are
3044 ;; shown literally.
3045 (setq mode-name
3046 (let (case-fold-search)
3047 (cond ((string-match dired-sort-by-name-regexp dired-actual-switches)
3048 "Dired by name")
3049 ((string-match dired-sort-by-date-regexp dired-actual-switches)
3050 "Dired by date")
3052 (concat "Dired " dired-actual-switches)))))
3053 (force-mode-line-update))
3055 (defun dired-sort-toggle-or-edit (&optional arg)
3056 "Toggle between sort by date/name and refresh the dired buffer.
3057 With a prefix argument you can edit the current listing switches instead."
3058 (interactive "P")
3059 (when dired-sort-inhibit
3060 (error "Cannot sort this Dired buffer"))
3061 (if arg
3062 (dired-sort-other
3063 (read-string "ls switches (must contain -l): " dired-actual-switches))
3064 (dired-sort-toggle)))
3066 (defun dired-sort-toggle ()
3067 ;; Toggle between sort by date/name. Reverts the buffer.
3068 (setq dired-actual-switches
3069 (let (case-fold-search)
3070 (if (string-match " " dired-actual-switches)
3071 ;; New toggle scheme: add/remove a trailing " -t"
3072 (if (string-match " -t\\'" dired-actual-switches)
3073 (substring dired-actual-switches 0 (match-beginning 0))
3074 (concat dired-actual-switches " -t"))
3075 ;; old toggle scheme: look for some 't' switch and add/remove it
3076 (concat
3077 "-l"
3078 (dired-replace-in-string (concat "[-lt"
3079 dired-ls-sorting-switches "]")
3081 dired-actual-switches)
3082 (if (string-match (concat "[t" dired-ls-sorting-switches "]")
3083 dired-actual-switches)
3085 "t")))))
3086 (dired-sort-set-modeline)
3087 (revert-buffer))
3089 ;; Some user code loads dired especially for this.
3090 ;; Don't do that--use replace-regexp-in-string instead.
3091 (defun dired-replace-in-string (regexp newtext string)
3092 ;; Replace REGEXP with NEWTEXT everywhere in STRING and return result.
3093 ;; NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
3094 (let ((result "") (start 0) mb me)
3095 (while (string-match regexp string start)
3096 (setq mb (match-beginning 0)
3097 me (match-end 0)
3098 result (concat result (substring string start mb) newtext)
3099 start me))
3100 (concat result (substring string start))))
3102 (defun dired-sort-other (switches &optional no-revert)
3103 "Specify new ls SWITCHES for current dired buffer.
3104 Values matching `dired-sort-by-date-regexp' or `dired-sort-by-name-regexp'
3105 set the minor mode accordingly, others appear literally in the mode line.
3106 With optional second arg NO-REVERT, don't refresh the listing afterwards."
3107 (dired-sort-R-check switches)
3108 (setq dired-actual-switches switches)
3109 (if (eq major-mode 'dired-mode) (dired-sort-set-modeline))
3110 (or no-revert (revert-buffer)))
3112 (make-variable-buffer-local
3113 (defvar dired-subdir-alist-pre-R nil
3114 "Value of `dired-subdir-alist' before -R switch added."))
3116 (defun dired-sort-R-check (switches)
3117 "Additional processing of -R in ls option string SWITCHES.
3118 Saves `dired-subdir-alist' when R is set and restores saved value
3119 minus any directories explicitly deleted when R is cleared.
3120 To be called first in body of `dired-sort-other', etc."
3121 (cond
3122 ((and (string-match "R" switches)
3123 (not (string-match "R" dired-actual-switches)))
3124 ;; Adding -R to ls switches -- save `dired-subdir-alist':
3125 (setq dired-subdir-alist-pre-R dired-subdir-alist))
3126 ((and (string-match "R" dired-actual-switches)
3127 (not (string-match "R" switches)))
3128 ;; Deleting -R from ls switches -- revert to pre-R subdirs
3129 ;; that are still present:
3130 (setq dired-subdir-alist
3131 (if dired-subdir-alist-pre-R
3132 (let (subdirs)
3133 (while dired-subdir-alist-pre-R
3134 (if (assoc (caar dired-subdir-alist-pre-R)
3135 dired-subdir-alist)
3136 ;; subdir still present...
3137 (setq subdirs
3138 (cons (car dired-subdir-alist-pre-R)
3139 subdirs)))
3140 (setq dired-subdir-alist-pre-R
3141 (cdr dired-subdir-alist-pre-R)))
3142 (reverse subdirs))
3143 ;; No pre-R subdir alist, so revert to main directory
3144 ;; listing:
3145 (list (car (reverse dired-subdir-alist))))))))
3148 ;;;; Drag and drop support
3150 (defun dired-dnd-test-function (window action types)
3151 "The test function for drag and drop into dired buffers.
3152 WINDOW is where the mouse is when this function is called. It may be a frame
3153 if the mouse is over the menu bar, scroll bar or tool bar.
3154 ACTION is the suggested action from the source, and TYPES are the
3155 types the drop data can have. This function only accepts drops with
3156 types in `x-dnd-known-types'. It returns the action suggested by the source."
3157 (let ((type (x-dnd-choose-type types)))
3158 (if type
3159 (cons action type)
3160 nil)))
3162 (defun dired-dnd-popup-notice ()
3163 (x-popup-dialog
3165 '("Recursive copies not enabled.\nSee variable dired-recursive-copies."
3166 ("Ok" . nil))))
3169 (defun dired-dnd-do-ask-action (uri)
3170 ;; No need to get actions and descriptions from the source,
3171 ;; we only have three actions anyway.
3172 (let ((action (x-popup-menu
3174 (list "What action?"
3175 (cons ""
3176 '(("Copy here" . copy)
3177 ("Move here" . move)
3178 ("Link here" . link)
3179 "--"
3180 ("Cancel" . nil)))))))
3181 (if action
3182 (dired-dnd-handle-local-file uri action)
3183 nil)))
3185 (defun dired-dnd-handle-local-file (uri action)
3186 "Copy, move or link a file to the dired directory.
3187 URI is the file to handle, ACTION is one of copy, move, link or ask.
3188 Ask means pop up a menu for the user to select one of copy, move or link."
3189 (require 'dired-aux)
3190 (let* ((from (x-dnd-get-local-file-name uri t))
3191 (to (if from (concat (dired-current-directory)
3192 (file-name-nondirectory from))
3193 nil)))
3194 (if from
3195 (cond ((or (eq action 'copy)
3196 (eq action 'private)) ; Treat private as copy.
3198 ;; If copying a directory and dired-recursive-copies is nil,
3199 ;; dired-copy-file silently fails. Pop up a notice.
3200 (if (and (file-directory-p from)
3201 (not dired-recursive-copies))
3202 (dired-dnd-popup-notice)
3203 (progn
3204 (dired-copy-file from to 1)
3205 (dired-relist-entry to)
3206 action)))
3208 ((eq action 'move)
3209 (dired-rename-file from to 1)
3210 (dired-relist-entry to)
3211 action)
3213 ((eq action 'link)
3214 (make-symbolic-link from to 1)
3215 (dired-relist-entry to)
3216 action)
3218 ((eq action 'ask)
3219 (dired-dnd-do-ask-action uri))
3221 (t nil)))))
3223 (defun dired-dnd-handle-file (uri action)
3224 "Copy, move or link a file to the dired directory if it is a local file.
3225 URI is the file to handle. If the hostname in the URI isn't local, do nothing.
3226 ACTION is one of copy, move, link or ask.
3227 Ask means pop up a menu for the user to select one of copy, move or link."
3228 (let ((local-file (x-dnd-get-local-file-uri uri)))
3229 (if local-file (dired-dnd-handle-local-file local-file action)
3230 nil)))
3233 ;;;; Desktop support
3235 (eval-when-compile (require 'desktop))
3237 (defun dired-desktop-buffer-misc-data (desktop-dirname)
3238 "Auxiliary information to be saved in desktop file."
3239 (cons
3240 ;; Value of `dired-directory'.
3241 (if (consp dired-directory)
3242 ;; Directory name followed by list of files.
3243 (cons (desktop-file-name (car dired-directory) desktop-dirname)
3244 (cdr dired-directory))
3245 ;; Directory name, optionally with with shell wildcard.
3246 (desktop-file-name dired-directory desktop-dirname))
3247 ;; Subdirectories in `dired-subdir-alist'.
3248 (cdr
3249 (nreverse
3250 (mapcar
3251 (function (lambda (f) (desktop-file-name (car f) desktop-dirname)))
3252 dired-subdir-alist)))))
3254 ;;;###autoload
3255 (defun dired-restore-desktop-buffer (desktop-buffer-file-name
3256 desktop-buffer-name
3257 desktop-buffer-misc)
3258 "Restore a dired buffer specified in a desktop file."
3259 ;; First element of `desktop-buffer-misc' is the value of `dired-directory'.
3260 ;; This value is a directory name, optionally with with shell wildcard or
3261 ;; a directory name followed by list of files.
3262 (let* ((dired-dir (car desktop-buffer-misc))
3263 (dir (if (consp dired-dir) (car dired-dir) dired-dir)))
3264 (if (file-directory-p (file-name-directory dir))
3265 (progn
3266 (dired dired-dir)
3267 ;; The following elements of `desktop-buffer-misc' are the keys
3268 ;; from `dired-subdir-alist'.
3269 (mapcar 'dired-maybe-insert-subdir (cdr desktop-buffer-misc))
3270 (current-buffer))
3271 (message "Desktop: Directory %s no longer exists." dir)
3272 (when desktop-missing-file-warning (sit-for 1))
3273 nil)))
3276 (if (eq system-type 'vax-vms)
3277 (load "dired-vms"))
3279 (provide 'dired)
3281 (run-hooks 'dired-load-hook) ; for your customizations
3283 ;;; arch-tag: e1af7a8f-691c-41a0-aac1-ddd4d3c87517
3284 ;;; dired.el ends here