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