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