Initial Commit
[packages] / xemacs-packages / dired / dired.el
1 ;; -*- Emacs-Lisp -*-
2 ;; DIRED commands for Emacs.
3 ;; Copyright (C) 1985, 1986, 1991 Free Software Foundation, Inc.
4 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
5 ;;
6 ;; File:          dired.el
7 ;; RCS:
8 ;; Dired Version: 7.17
9 ;; Description:   The DIRectory EDitor is for manipulating, and running
10 ;;                commands on files in a directory.
11 ;; Authors:       FSF,
12 ;;                Sebastian Kremer <sk@thp.uni-koeln.de>,
13 ;;                Sandy Rutherford <sandy@ibm550.sissa.it>,
14 ;;                Mike Sperber <sperber@informatik.uni-tuebingen.de>
15 ;;                Cast of thousands...
16 ;;
17 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
18
19 ;; This program is free software; you can redistribute it and/or modify
20 ;; it under the terms of the GNU General Public License as published by
21 ;; the Free Software Foundation; either version 1, or (at your option)
22 ;; any later version.
23
24 ;; This program is distributed in the hope that it will be useful,
25 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
26 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 ;; GNU General Public License for more details.
28
29 ;; You should have received a copy of the GNU General Public License
30 ;; along with GNU Emacs; see the file COPYING.  If not, write to
31 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
32
33 ;; Rewritten in 1990/1991 to add tree features, file marking and
34 ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
35 ;; 7-1993: Added special features for efs interaction and upgraded to Emacs 19.
36 ;;         Sandy Rutherford <sandy@ibm550.sissa.it>
37
38 ;;; Dired Version
39
40 (defconst dired-version (substring "#Revision: 7.17 $" 11 -2)
41   "The revision number of Tree Dired (as a string).
42
43 Don't forget to mention this when reporting bugs to:
44
45    elisp-code-dired@nongnu.org")
46
47 ;; Global key bindings:
48 ;; --------------------
49 ;;
50 ;; By convention, dired uses the following global key-bindings.
51 ;; These may or may not already be set up in your local emacs. If not
52 ;; then you will need to add them to your .emacs file, or the system
53 ;; default.el file. We don't set them automatically here, as users may
54 ;; have individual preferences.
55 ;;
56 ;; (define-key ctl-x-map "d" 'dired)
57 ;; (define-key ctl-x-4-map "d" 'dired-other-window)
58 ;; (define-key ctl-x-map "\C-j" 'dired-jump-back)
59 ;; (define-key ctl-x-4-map "\C-j" 'dired-jump-back-other-window)
60 ;;
61 ;; For V19 emacs only. (Make sure that the ctl-x-5-map exists.)
62 ;; (define-key ctl-x-5-map "d" 'dired-other-frame)
63 ;; (define-key Ctl-x-5-map "\C-j" 'dired-jump-back-other-frame)
64
65
66 ;;; Grok the current emacs version
67 ;;
68 ;; Hopefully these two variables provide us with enough version sensitivity.
69
70 ;; Make sure that we have a frame-width function
71 (or (fboundp 'frame-width) (fset 'frame-width 'screen-width))
72
73 ;;; Requirements and provisions
74
75 (provide 'dired)
76 (require 'backquote) ; For macros.
77 (require 'custom)
78
79 ;; Compatibility requirements for the file-name-handler-alist.
80 ;; Testing against the string `Lucid' breaks InfoDock.  How many years has
81 ;; it been since Lucid went away?
82 (let ((lucid-p (string-match "XEmacs" emacs-version))
83       (ver emacs-major-version)
84       (subver emacs-minor-version))
85   (unless ver
86     (or (string-match "^\\([0-9]+\\)\\.\\([0-9]+\\)" emacs-version)
87         (error "dired does not work with emacs version %s" emacs-version))
88     (setq ver (string-to-int (substring emacs-version (match-beginning 1)
89                                         (match-end 1)))
90           subver (string-to-int (substring emacs-version (match-beginning 2)
91                                            (match-end 2)))))
92   (cond
93    ((= ver 18)
94     (require 'emacs-19)
95     (require 'fn-handler))
96    ((and (= ver 19) (if lucid-p (< subver 10) (< subver 23)))
97     (require 'fn-handler))
98    ((< ver 18)
99     (error "dired does not work with emacs version %s" emacs-version))))
100
101 ;; We duplicate default-dir stuff to avoid its overwrites unless
102 ;; they are explicitly requested.
103
104 (defvar default-directory-function nil
105   "A function to call to compute the default-directory for the current buffer.
106 If this is nil, the function default-directory will return the value of the
107 variable default-directory.
108 Buffer local.")
109 (make-variable-buffer-local 'default-directory-function)
110
111 ;;;###autoload
112 (defun default-directory ()
113   " Returns the default-directory for the current buffer.
114 Will use the variable default-directory-function if it non-nil."
115   (if default-directory-function
116       (funcall default-directory-function)
117     (if (string-match "XEmacs" emacs-version)
118         (abbreviate-file-name default-directory t)
119       (abbreviate-file-name default-directory))))
120 \f
121 ;;;;----------------------------------------------------------------
122 ;;;; Customizable variables
123 ;;;;----------------------------------------------------------------
124 ;;
125
126 (defgroup dired nil
127   "Directory editing."
128   :group 'environment)
129
130 ;; The funny comments are for autoload.el, to automagically update
131 ;; loaddefs.
132
133 ;;; Variables for compressing files.
134
135 (defgroup dired-programs nil
136   "External programs used by Dired."
137   :group 'dired)
138
139 ;;;###autoload
140 (defcustom dired-compression-method 'gzip
141   "*Type of compression program to use.
142 Give as a symbol.
143 Currently-recognized methods are: gzip pack compact compress.
144 To change this variable use \\[dired-do-compress] with a zero prefix."
145   :type '(choice (const gzip)
146                  (const pack)
147                  (const pack)
148                  (const compact)
149                  (const compress))
150   :group 'dired-programs)
151
152 ;;;###autoload
153 (defvar dired-compression-method-alist
154   '((gzip     ".gz" ("gzip")          ("gzip" "-d") "-f")
155     ;; Put compress before pack, so that it wins out if we are using
156     ;; efs to work on a case insensitive OS. The -f flag does
157     ;; two things in compress. No harm in giving it twice.
158     (compress ".Z"  ("compress" "-f") ("compress" "-d") "-f")
159     ;; pack support may not work well.  pack is too chatty and there is no way
160     ;; to force overwrites.
161     (pack     ".z"  ("pack" "-f")     ("unpack"))
162     (compact  ".C"  ("compact")       ("uncompact"))
163     (bzip2    ".bz2" ("bzip2")        ("bunzip2") "-f"))
164
165   "*Association list of compression method descriptions.
166  Each element of the table should be a list of the form
167
168      \(compress-type extension (compress-args) (decompress-args) force-flag\)
169
170  where
171    `compress-type' is a unique symbol in the alist to which
172       `dired-compression-method' can be set;
173    `extension' is the file extension (as a string) used by files compressed
174       by this method;
175    `compress-args' is a list of the path of the compression program and
176       flags to pass as separate arguments;
177    `decompress-args' is a list of the path of the decompression
178       program and flags to pass as separate arguments.
179    `force-flag' is the switch to pass to the command to force overwriting
180       of existing files.
181
182  For example:
183
184    \(setq dired-compression-method-alist
185          \(cons '\(frobnicate \".frob\" \(\"frob\"\) \(\"frob\" \"-d\"\) \"-f\"\)
186                dired-compression-method-alist\)\)
187    => \(\(frobnicate \".frob\" \(\"frob\"\) \(\"frob\" \"-d\"\)\)
188        \(gzip \".gz\" \(\"gzip\"\) \(\"gunzip\"\)\)
189        ...\)
190
191  See also: dired-compression-method <V>")
192
193 ;;; Variables for the ls program.
194
195 ;;;###autoload
196 (defcustom dired-ls-program "ls"
197   "*Absolute or relative name of the ls program used by dired."
198   :type 'string
199   :group 'dired-programs)
200
201 ;;;###autoload
202 (defcustom dired-listing-switches "-al"
203   "*Switches passed to ls for dired. MUST contain the `l' option.
204 Can contain even `h', `F', `b', `i' and `s'."
205   :type '(choice string
206                  (repeat string))
207   :group 'dired-programs)
208
209 ;;;###autolaod
210 (defcustom dired-ls-locale nil
211   "*Locale to use when running `dired-ls-program'.
212 If non-nil, Dired will set the environment variable LC_ALL
213 to this value.  Setting it to \"POSIX\" may avoid problems Dired
214 has with parsing non-English locales."
215   :type '(choice (const nil)
216                  (const "POSIX")
217                  string)
218   :group 'dired-programs)
219
220 ;;;###autoload
221 (defcustom dired-use-ls-dired
222   (and (string-match "gnu\\|linux" system-configuration)
223        ;; Only supported for XEmacs >= 21.5 and GNU Emacs >= 21.4 (I think)
224        (if (featurep 'xemacs)
225            (and (fboundp 'emacs-version>=)
226                 (emacs-version>= 21 5))
227          (and (boundp 'emacs-major-version)
228               (boundp 'emacs-minor-version)
229               (or (> emacs-major-version 21)
230                   (and (= emacs-major-version 21)
231                        (>= emacs-minor-version 4))))))
232   "Non-nil means Dired should use `ls --dired'."
233   :type 'boolean
234   :group 'dired-programs)
235
236 (defcustom dired-ls-F-marks-symlinks
237   (memq system-type '(aix-v3 hpux silicon-graphics-unix))
238   ;; Both SunOS and Ultrix have system-type berkeley-unix. But
239   ;; SunOS doesn't mark symlinks, but Ultrix does. Therefore,
240   ;; can't grok this case.
241   "*Informs dired about how ls -lF marks symbolic links.
242 Set this to t if `dired-ls-program' with -lF marks the name of the symbolic
243 link itself with a trailing @.
244
245 For example: If foo is a link pointing to bar, and \"ls -F bar\" gives
246
247      ...   bar -> foo
248
249 set this variable to nil. If it gives
250
251       ...   bar@ -> foo
252
253 set this variable to t.
254
255 Dired checks if there is really a @ appended.  Thus, if you have a
256 marking ls program on one host and a non-marking on another host, and
257 don't care about symbolic links which really end in a @, you can
258 always set this variable to t.
259
260 If you use efs, it will make this variable buffer-local, and control
261 it according to its assessment of how the remote host marks symbolic
262 links."
263   :type 'boolean
264   :group 'dired-programs)
265
266 (defcustom dired-show-ls-switches nil
267   "*If non-nil dired will show the dired ls switches on the modeline.
268 If nil, it will indicate how the files are sorted by either \"by name\" or
269 \"by date\". If it is unable to recognize the sorting defined by the switches,
270 then the switches will be shown explicitly on the modeline, regardless of the
271 setting of this variable."
272   :type 'boolean
273   :group 'dired-programs)
274
275 ;;; Variables for other unix utility programs.
276
277 ;; For most program names, don't use absolute paths so that dired
278 ;; uses the user's value of the environment variable PATH. chown is
279 ;; an exception as it is not always in the PATH.
280
281 ;;;###autoload
282 (defcustom dired-chown-program
283   (if (memq system-type '(hpux dgux usg-unix-v linux)) "chown" "/etc/chown")
284   "*Name of chown command (usually `chown' or `/etc/chown')."
285   :type 'string
286   :group 'dired-programs)
287
288 ;;;###autoload
289 (defcustom dired-gnutar-program nil
290   "*If non-nil, name of the GNU tar executable (e.g. \"tar\" or \"gnutar\").
291 GNU tar's `z' switch is used for compressed tar files.
292 If you don't have GNU tar, set this to nil: a pipe using `zcat' is then used."
293   :type '(choice string
294                  (const nil))
295   :group 'dired-programs)
296
297 ;;;###autoload
298 (defcustom dired-unshar-program nil
299   "*Set to the name of the unshar program, if you have it."
300   :type '(choice string
301                  (const nil))
302   :group 'dired-programs)
303
304 ;;; Markers
305
306 (defgroup dired-markers nil
307   "Dealing with markers."
308   :group 'dired)
309
310 (defcustom dired-keep-marker-rename t
311   ;; Use t as default so that moved files `take their markers with them'
312   "*Controls marking of renamed files.
313 If t, files keep their previous marks when they are renamed.
314 If a character, renamed files (whether previously marked or not)
315 are afterward marked with that character."
316   :type '(choice (const t)
317                  character)
318   :group 'dired-markers)
319
320 (defcustom dired-keep-marker-compress t
321   "*Controls marking of compressed or uncompressed files.
322 If t, files keep their previous marks when they are compressed.
323 If a character, compressed or uncompressed files (whether previously
324 marked or not) are afterward marked with that character."
325   :type '(choice (const t)
326                  character)
327   :group 'dired-markers)
328
329 (defcustom dired-keep-marker-uucode ?U
330   "*Controls marking of uuencoded or uudecoded files.
331 If t, files keep their previous marks when they are uuencoded.
332 If a character, uuencoded or uudecoded files (whether previously
333 marked or not) are afterward marked with that character."
334   :type '(choice (const t)
335                  character)
336   :group 'dired-markers)
337
338 (defcustom dired-keep-marker-copy ?C
339   "*Controls marking of copied files.
340 If t, copied files are marked if and as the corresponding original files were.
341 If a character, copied files are unconditionally marked with that character."
342   :type '(choice (const t)
343                  character)
344   :group 'dired-markers)
345
346 (defcustom dired-keep-marker-hardlink ?H
347   "*Controls marking of newly made hard links.
348 If t, they are marked if and as the files linked to were marked.
349 If a character, new links are unconditionally marked with that character."
350   :type '(choice (const t)
351                  character)
352   :group 'dired-markers)
353
354
355 (defcustom dired-keep-marker-symlink ?S
356   "*Controls marking of newly made symbolic links.
357 If t, they are marked if and as the files linked to were marked.
358 If a character, new links are unconditionally marked with that character."
359   :type '(choice (const t)
360                  character)
361   :group 'dired-markers)
362
363 (defcustom dired-keep-marker-kill ?K
364   "*When killed file lines are redisplayed, they will have this marker.
365 Setting this to nil means that they will not have any marker."
366   :type '(choice (const nil)
367                  character)
368   :group 'dired-markers)
369
370 (defcustom dired-failed-marker-shell ?!
371   "*If non-nil, a character with which to mark files of failed shell commands.
372 Applies to the command `dired-do-shell-command'.  Files for which the shell
373 command has a nonzero exit status will be marked with this character"
374   :type '(choice (const nil)
375                  character)
376   :group 'dired-markers)
377
378 ;;; Behavioral Variables
379
380 (defgroup dired-behavior nil
381   "Dired behavior."
382   :group 'dired)
383
384 ;;;###autoload
385 (defcustom dired-local-variables-file ".dired"
386   "*If non-nil, filename for local variables for Dired.
387 If Dired finds a file with that name in the current directory, it will
388 temporarily insert it into the dired buffer and run `hack-local-variables'.
389
390 Type \\[info] and `g' `(emacs)File Variables' `RET' for more info on
391 local variables."
392   :type 'string
393   :group 'dired-behavior)
394
395 ;; Usually defined in files.el. Define here anyway, to be safe.
396 ;;;###autoload
397 (defcustom dired-kept-versions 2
398   "*When cleaning directory, number of versions to keep."
399   :type 'integer
400   :group 'dired-behavior)
401
402 ;;;###autoload
403 (defcustom dired-find-subdir nil
404   "*Determines whether dired tries to lookup a subdir in existing buffers.
405 If non-nil, dired does not make a new buffer for a directory if it can be
406 found (perhaps as subdir) in some existing dired buffer. If there are several
407 dired buffers for a directory, then the most recently used one is chosen.
408
409 Dired avoids switching to the current buffer, so that if you have
410 a normal and a wildcard buffer for the same directory, C-x d RET will
411 toggle between those two."
412   :type 'boolean
413   :group 'dired-behavior)
414
415 ;;;###autoload
416 (defcustom dired-use-file-transformers t
417   "*Determines whether dired uses file transformers.
418 If non-nil `dired-do-shell-command' will apply file transformers to file names.
419 See \\[describe-function] for dired-do-shell-command for more information."
420   :type 'boolean
421   :group 'dired-behavior)
422
423 ;;;###autoload
424 (defcustom dired-dwim-target nil
425   "*If non-nil, dired tries to guess a default target directory.
426 This means that if there is a dired buffer displayed in the next window,
427 use its current subdir, instead of the current subdir of this dired buffer.
428 The target is put in the prompt for file copy, rename, etc."
429   :type 'boolean
430   :group 'dired-behavior)
431
432 ;;;###autoload
433 (defcustom dired-copy-preserve-time t
434   "*If non-nil, Dired preserves the last-modified time in a file copy.
435 \(This works on only some systems.)\\<dired-mode-map>
436 Use `\\[dired-do-copy]' with a zero prefix argument to toggle its value."
437   :type 'boolean
438   :group 'dired-behavior)
439
440 ;;;###autoload
441 (defcustom dired-no-confirm nil
442   "*If non-nil, a list of symbols for commands dired should not confirm.
443 It can be a sublist of
444
445   '(byte-compile chgrp chmod chown compress copy delete hardlink load
446     move print shell symlink uncompress recursive-delete kill-file-buffer
447     kill-dired-buffer patch create-top-dir revert-subdirs)
448
449 The meanings of most of the symbols are obvious.  A few exceptions:
450
451     'compress applies to compression or decompression by any of the
452      compression program in `dired-compression-method-alist'.
453
454     'kill-dired-buffer applies to offering to kill dired buffers for
455      directories which have been deleted.
456
457     'kill-file-buffer applies to offering to kill buffers visiting files
458      which have been deleted.
459
460     'recursive-delete applies to recursively deleting non-empty
461      directories, and all of their contents.
462
463     'create-top-dir applies to `dired-up-directory' creating a new top level
464      directory for the dired buffer.
465
466     'revert-subdirs applies to re-reading subdirectories which have
467      been modified on disk.
468
469 Note that this list also applies to remote files accessed with efs
470 or ange-ftp."
471   :type '(set (const byte-compile) (const chgrp) (const chmod)
472               (const chown) (const compress) (const copy)
473               (const delete) (const hardlink) (const load)
474               (const move) (const print) (const shell)
475               (const symlink) (const uncompress)
476               (const recursive-delete) (const recursive-copy)
477               (const kill-file-buffer) (const kill-dired-buffer)
478               (const patch)
479               (const create-top-dir) (const revert-subdirs))
480 :group 'dired-behavior)
481
482 ;;;###autoload
483 (defcustom dired-backup-if-overwrite nil
484   "*Non-nil if Dired should ask about making backups before overwriting files.
485 Special value 'always suppresses confirmation."
486   :type 'boolean
487   :group 'dired-behavior)
488
489 ;;;###autoload
490 (defcustom dired-omit-files nil
491   "*If non-nil un-interesting files will be omitted from this dired buffer.
492 Use \\[dired-omit-toggle] to see these files. (buffer local)"
493   :type 'boolean
494   :group 'dired-behavior)
495 (make-variable-buffer-local 'dired-omit-files)
496
497 ;;;###autoload
498 (defcustom dired-mail-reader 'vm
499   "*Mail reader used by dired for dired-read-mail \(\\[dired-read-mail]\).
500 The symbols 'rmail and 'vm are the only two allowed values."
501   :type '(choice (const rmail)
502                  (const vm))
503   :group 'dired-behavior)
504
505 (defcustom dired-verify-modtimes t
506   "*If non-nil dired will revert dired buffers for modified subdirectories.
507 See also dired-no-confirm <V>."
508   :type 'boolean
509   :group 'dired-behavior)
510
511 ;;;###autoload
512 (defcustom dired-refresh-automatically t
513   "*If non-nil, refresh dired buffers automatically after file operations."
514   :type 'boolean
515   :group 'dired-behavior)
516
517 ;;;###autoload
518 (defcustom dired-find-file-compare-truenames t
519   "If nil, set find-file-compare-truenames to nil while opening dired buffer"
520   :type 'boolean
521   :group 'dired-behavior)
522
523 ;;; File name regular expressions and extensions.
524
525 (defgroup dired-file-names nil
526   "How Dired deals with files with certain names."
527   :group 'dired)
528
529 (defcustom dired-trivial-filenames "\\`\\.\\.?\\'\\|\\`#"
530   "*Regexp of files to skip when finding first file of a directory listing.
531 A value of nil means move to the subdir line.
532 A value of t means move to first file."
533   :type 'string
534   :group 'dired-file-names)
535
536 (defcustom dired-cleanup-alist
537   (list
538    '("tex" ".toc" ".log" ".aux" ".dvi")
539    '("latex" ".toc" ".log" ".aux" ".idx" ".lof" ".lot" ".glo" ".dvi")
540    '("bibtex" ".blg" ".bbl")
541    '("texinfo" ".cp" ".cps" ".fn" ".fns" ".ky" ".kys" ".pg" ".pgs"
542      ".tp" ".tps" ".vr" ".vrs")
543    '("patch" ".rej" ".orig")
544    '("backups" "~")
545    (cons "completion-ignored-extensions" completion-ignored-extensions))
546   "*Alist of extensions for temporary files created by various programs.
547 Used by `dired-cleanup'."
548   :type '(repeat (list (string :tag "program")
549                        (repeat :tag "extensions" :inline t
550                                string)))
551   :group 'dired-file-names)
552
553 (defcustom dired-omit-extensions
554   (let ((alist dired-cleanup-alist)
555         x result)
556     (while alist
557       (setq x (cdr (car alist))
558             alist (cdr alist))
559       (while x
560         (or (member (car x) result)
561             (setq result (cons (car x) result)))
562         (setq x (cdr x))))
563     result)
564   "*List of extensions for file names that will be omitted (buffer-local).
565 This only has effect when the subdirectory is in omission mode.
566 To make omission mode the default, set `dired-omit-files' to t.
567 See also `dired-omit-regexps'."
568   :type '(repeat string)
569   :group 'dired-file-names)
570 (make-variable-buffer-local 'dired-omit-extensions)
571
572 (defcustom dired-omit-regexps '("\\`#" "\\`\\.")
573   "*File names matching these regexp may be omitted (buffer-local).
574 This only has effect when the subdirectory is in omission mode.
575 To make omission mode the default, set `dired-omit-files' to t.
576 This only has effect when `dired-omit-files' is t.
577 See also `dired-omit-extensions'."
578   :type '(repeat regexp)
579   :group 'dired-file-names)
580 (make-variable-buffer-local 'dired-omit-regexps)
581
582 (defcustom dired-filename-re-ext "\\..+\\'"   ; start from the first dot. last dot?
583   "*Defines what is the extension of a file name.
584 \(match-beginning 0\) for this regexp in the file name without directory will
585 be taken to be the start of the extension."
586   :type 'string
587   :group 'dired-file-names)
588
589 ;;; Hook variables
590
591 (defgroup dired-hooks nil
592   "Dired hooks."
593   :group 'dired)
594
595 (defcustom dired-load-hook nil
596   "Run after loading dired.
597 You can customize key bindings or load extensions with this."
598   :type 'hook
599   :group 'dired-hooks)
600
601 (defcustom dired-grep-load-hook nil
602   "Run after loading dired-grep."
603   :type 'hook
604   :group 'dired-hooks)
605
606 (defcustom dired-mode-hook nil
607   "Run at the very end of dired-mode."
608   :type 'hook
609   :group 'dired-hooks)
610
611 (defcustom dired-before-readin-hook nil
612   "Hook run before a dired buffer is newly read in, created,or reverted."
613   :type 'hook
614   :group 'dired-hooks)
615
616 (defcustom dired-after-readin-hook nil
617   "Hook run after each listing of a file or directory.
618 The buffer is narrowed to the new listing."
619   :type 'hook
620   :group 'dired-hooks)
621
622 (defcustom dired-setup-keys-hook nil
623   "Hook run when dired sets up its keymap.
624 This happens the first time that `dired-mode' is called, and runs after
625 `dired-mode-hook'.  This hook can be used to make alterations to the
626 dired keymap."
627   :type 'hook
628   :group 'dired-hooks)
629
630 ;;; Internal variables
631 ;;
632 ;;  If you set these, know what you are doing.
633
634 ;;; Marker chars.
635
636 (defvar dired-marker-char ?*            ; the answer is 42
637                                         ; life the universe and everything
638   ;; so that you can write things like
639   ;; (let ((dired-marker-char ?X))
640   ;;    ;; great code using X markers ...
641   ;;    )
642   ;; For example, commands operating on two sets of files, A and B.
643   ;; Or marking files with digits 0-9.  This could implicate
644   ;; concentric sets or an order for the marked files.
645   ;; The code depends on dynamic scoping on the marker char.
646   "In dired, character used to mark files for later commands.")
647 (make-variable-buffer-local 'dired-marker-char)
648
649 (defconst dired-default-marker dired-marker-char)
650 ;; Stores the default value of dired-marker-char when dynamic markers
651 ;; are being used.
652
653 (defvar dired-del-marker ?D
654   "Character used to flag files for deletion.")
655
656 ;; \017=^O for Omit - other packages can chose other control characters.
657 (defvar dired-omit-marker-char ?\017)
658 ;; Marker used for omitted files.  Shouldn't be used by anything else.
659
660 (defvar dired-kill-marker-char ?\C-k)
661 ;; Marker used by dired-do-kill.  Shouldn't be used by anything else.
662
663 ;;; State variables
664
665 (defvar dired-mode-line-modified "-%s%s%s-"
666   "*Format string to show the modification status of the buffer.")
667
668 (defvar dired-del-flags-number 0)
669 (make-variable-buffer-local 'dired-del-flags-number)
670 (defvar dired-marks-number 0)
671 (make-variable-buffer-local 'dired-marks-number)
672 (defvar dired-other-marks-number 0)
673 (make-variable-buffer-local 'dired-other-marks-number)
674
675 (defvar dired-marked-files nil
676   "List of filenames from last `dired-copy-filename-as-kill' call.")
677
678 (defvar dired-directory nil
679   "The directory name or shell wildcard that was used as argument to `ls'.
680 Local to each dired buffer.  May be a list, in which case the car is the
681 directory name and the cdr is the actual files to list.")
682 (make-variable-buffer-local 'dired-directory)
683
684 (defvar dired-internal-switches nil
685   "The actual (buffer-local) value of `dired-listing-switches'.
686 The switches are represented as a list of characters.")
687 (make-variable-buffer-local 'dired-internal-switches)
688
689 (defvar dired-subdir-alist nil
690   "Association list of subdirectories and their buffer positions.
691 Each subdirectory has an element: (DIRNAME . STARTMARKER).
692 The order of elements is the reverse of the order in the buffer.")
693 (make-variable-buffer-local 'dired-subdir-alist)
694
695 (defvar dired-curr-subdir-min 0)
696 ;; Cache for modeline tracking of the cursor
697 (make-variable-buffer-local 'dired-curr-subdir-min)
698
699 (defvar dired-curr-subdir-max 0)
700 ;; Cache for modeline tracking of the cursor
701 (make-variable-buffer-local 'dired-curr-subdir-max)
702
703 (defvar dired-subdir-omit nil)
704 ;; Controls whether the modeline shows Omit.
705 (make-variable-buffer-local 'dired-subdir-omit)
706
707 (defvar dired-in-query nil)
708 ;; let-bound to t when dired is in the process of querying the user.
709 ;; This is to keep asynch messaging from clobbering the query prompt.
710
711 (defvar dired-overwrite-confirmed nil)
712 ;; Fluid variable used to remember if a bunch of overwrites have been
713 ;; confirmed.
714
715 (defvar dired-overwrite-backup-query nil)
716 ;; Fluid var used to remember if backups have been requested for overwrites.
717
718 (defvar dired-file-creator-query nil)
719 ;; Fluid var to remember responses to file-creator queries.
720
721 (defvar dired-omit-silent nil)
722 ;; This is sometimes let-bound to t if messages would be annoying,
723 ;; e.g., in dired-awrh.el. Binding to 0, only suppresses
724 ;; \"(Nothing to omit)\" message.
725
726 (defvar dired-buffers nil
727   ;; Enlarged by dired-advertise
728   ;; Queried by function dired-buffers-for-dir. When this detects a
729   ;; killed buffer, it is removed from this list.
730   "Alist of directories and their associated dired buffers.")
731
732 (defvar dired-sort-mode nil
733   "Whether Dired sorts by name, date, etc.
734 \(buffer-local\)")
735 ;; This is nil outside dired buffers so it can be used in the modeline
736 (make-variable-buffer-local 'dired-sort-mode)
737
738 (defvar dired-marker-stack nil
739   "List of previously used dired marker characters.")
740 (make-variable-buffer-local 'dired-marker-stack)
741
742 (defvar dired-marker-stack-pointer 0)
743 ;; Points to the current marker in the stack
744 (make-variable-buffer-local 'dired-marker-stack-pointer)
745
746 (defvar dired-marker-stack-cursor ?\  ; space
747   "Character to use as a cursor in the dired marker stack.")
748
749 (defconst dired-marker-string ""
750   "String version of `dired-marker-stack'.")
751 (make-variable-buffer-local 'dired-marker-string)
752
753 (defvar dired-modeline-tracking-cmds nil)
754 ;; List of commands after which the modeline gets updated.
755
756 ;;; Config. variables not usually considered fair game for the user.
757
758 (defvar dired-deletion-confirmer 'yes-or-no-p) ; or y-or-n-p?
759
760 (defvar dired-copy-confirmer 'yes-or-no-p) ; or y-or-n-p?
761
762 (defvar dired-log-buffer "*Dired log*")
763 ;; Name of buffer used to log dired messages and errors.
764
765 ;;; Assoc. lists
766
767 ;; For pop ups and user input for file marking
768 (defvar dired-query-alist
769   '((?\y . y) (?\040 . y)               ; `y' or SPC means accept once
770     (?n . n) (?\177 . n)                ; `n' or DEL skips once
771     (?! . yes)                          ; `!' accepts rest
772     (?q. no) (?\e . no)                 ; `q' or ESC skips rest
773     ;; None of these keys quit - use C-g for that.
774     ))
775
776 (defvar dired-sort-type-alist
777   ;; alist of sort flags, and the sort type, as a symbol.
778   ;; Don't put ?r in here.  It's handled separately.
779   '((?t . date) (?S . size) (?U . unsort) (?X . ext)))
780
781 ;;; Internal regexps for examining ls listings.
782 ;;
783 ;; Many of these regexps must be tested at beginning-of-line, but are also
784 ;; used to search for next matches, so neither omitting "^" nor
785 ;; replacing "^" by "\n" (to make it slightly faster) will work.
786
787 (defvar dired-re-inode-size "[ \t0-9]*")
788 ;; Regexp for optional initial inode and file size.
789 ;; Must match output produced by ls' -i and -s flags.
790
791 (defvar dired-re-mark "^[^ \n\r]")
792 ;; Regexp matching a marked line.
793 ;; Important: the match ends just after the marker.
794
795 (defvar dired-re-maybe-mark "^. ")
796
797 (defvar dired-re-dir (concat dired-re-maybe-mark dired-re-inode-size "d"))
798 ;; Matches directory lines
799
800 (defvar dired-re-sym (concat dired-re-maybe-mark dired-re-inode-size "l"))
801 ;; Matches symlink lines
802
803 (defvar dired-re-exe;; match ls permission string of an executable file
804   (mapconcat (function
805               (lambda (x)
806                 (concat dired-re-maybe-mark dired-re-inode-size x)))
807              '("-[-r][-w][xs][-r][-w].[-r][-w]."
808                "-[-r][-w].[-r][-w][xs][-r][-w]."
809                "-[-r][-w].[-r][-w].[-r][-w][xst]")
810              "\\|"))
811
812 (defvar dired-re-dot "^.* \\.\\.?/?$")  ; with -F, might end in `/'
813 ;; . and .. files
814
815 ;; From FSF files.el. Extracted from directory-listing-before-filename-regexp.
816 (defconst dired-re-month-and-time
817   (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
818          (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
819          ;; In some locales, month abbreviations are as short as 2 letters,
820          ;; and they can be followed by ".".
821          ;; In Breton, a month name can include a quote character.
822          (month (concat l-or-quote l-or-quote "+\\.?"))
823          (s " ")
824          (yyyy "[0-9][0-9][0-9][0-9]")
825          (dd "[ 0-3][0-9]")
826          (HH:MM "[ 0-2][0-9][:.][0-5][0-9]")
827          (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
828          (zone "[-+][0-2][0-9][0-5][0-9]")
829          (iso-mm-dd "[01][0-9]-[0-3][0-9]")
830          (iso-time (concat HH:MM "\\(:" seconds "\\( ?" zone "\\)?\\)?"))
831          (iso (concat "\\(\\(" yyyy "-\\)?" iso-mm-dd "[ T]" iso-time
832                       "\\|" yyyy "-" iso-mm-dd "\\)"))
833          (western (concat "\\(" month s "+" dd "\\|" dd "\\.?" s month "\\)"
834                           s "+"
835                           "\\(" HH:MM "\\|" yyyy "\\)"))
836          (western-comma (concat month s "+" dd "," s "+" yyyy))
837          ;; Japanese MS-Windows ls-lisp has one-digit months, and
838          ;; omits the Kanji characters after month and day-of-month.
839          ;; On Mac OS X 10.3, the date format in East Asian locales is
840          ;; day-of-month digits followed by month digits.
841          (mm "[ 0-1]?[0-9]")
842          (east-asian
843           (concat "\\(" mm l "?" s dd l "?" s "+"
844                   "\\|" dd s mm s "+" "\\)"
845                   "\\(" HH:MM "\\|" yyyy l "?" "\\)")))
846     (concat "\\(" western "\\|" western-comma "\\|" east-asian "\\|" iso "\\)" s "+"))
847     "Regular expression matching from the date to the filename.
848 This regexp MUST match all the way to first character of the filename.")
849
850 (defconst dired-re-before-filename
851   (concat ".*[0-9]+[BkKMGTPEZY]? \\(" dired-re-month-and-time "\\)")
852   "Regular expression matching a portion of a directory line up to the filename.
853 This regexp MUST match all the way to first character of the filename.
854 The first submatch is the date portion of the filename.")
855
856 (defvar dired-subdir-regexp
857   "\\([\n\r]\n\\|\\`\\). \\([^\n\r]+\\)\\(:\\)\\(\\.\\.\\.\r\\|[\n\r]\\)")
858   ;; Regexp matching a maybe hidden subdirectory line in ls -lR output.
859   ;; Subexpression 2 is the subdirectory proper, no trailing colon.
860   ;; Subexpression 3 must end right before the \n or \r at the end of
861   ;; the subdir heading.  Matches headings after indentation has been done.
862
863 (defvar dired-unhandle-add-files nil)
864 ;; List of files that the dired handler function need not add to dired buffers.
865 ;; This is because they have already been added, most likely in
866 ;; dired-create-files.  This is because dired-create-files add files with
867 ;; special markers.
868
869 ;;; history variables
870
871 (defvar dired-regexp-history nil
872   "History list of regular expressions used in Dired commands.")
873
874 (defvar dired-chmod-history nil
875   "History of arguments to chmod in dired.")
876
877 (defvar dired-chown-history nil
878   "History of arguments to chown in dired.")
879
880 (defvar dired-chgrp-history nil
881   "History of arguments to chgrp in dired.")
882
883 (defvar dired-cleanup-history nil
884   "History of arguments to dired-cleanup.")
885
886 (defvar dired-goto-file-history nil)
887 ;; History for dired-goto-file and dired-goto-subdir
888 (put 'dired-goto-file-history 'cursor-end t) ; for gmhist
889
890 (defvar dired-history nil)
891 ;; Catch-all history variable for dired file ops without
892 ;; their own history.
893
894 (defvar dired-op-history-alist
895   ;; alist of dired file operations and history symbols
896   '((chgrp . dired-chgrp-history) (chown . dired-chown-history)
897     (chmod . dired-chmod-history) ))
898
899 ;;; Tell the byte-compiler that we know what we're doing.
900 ;;; Do we?
901
902 (defvar file-name-handler-alist)
903 (defvar inhibit-file-name-operation)
904 (defvar inhibit-file-name-handlers)
905 (defvar efs-dired-host-type)
906
907 \f
908 ;;;;------------------------------------------------------------------
909 ;;;; Utilities
910 ;;;;------------------------------------------------------------------
911
912 ;;; Macros
913 ;;
914 ;;  Macros must be defined before they are used - for the byte compiler.
915
916 (defmacro dired-get-subdir-min (elt)
917   ;; Returns the value of the subdir minumum for subdir with entry ELT in
918   ;; dired-subdir-alist.
919   (list 'nth 1 elt))
920
921 (defmacro dired-save-excursion (&rest body)
922   ;; Saves excursions of the point (not buffer) in dired buffers.
923   ;; It tries to be robust against deletion of the region about the point.
924   ;; Note that this assumes only dired-style deletions.
925   (let ((temp-bolm (make-symbol "bolm"))
926         (temp-fnlp (make-symbol "fnlp"))
927         (temp-offset-bol (make-symbol "offset-bol")))
928     (` (let (((, temp-bolm) (make-marker))
929              (, temp-fnlp) (, temp-offset-bol))
930          (let ((bol (save-excursion (skip-chars-backward "^\n\r") (point))))
931            (set-marker (, temp-bolm) bol)
932            (setq (, temp-offset-bol) (- (point) bol)
933                  (, temp-fnlp) (memq (char-after bol) '(?\n\ ?\r))))
934          (unwind-protect
935              (progn
936                (,@ body))
937            ;; Use the marker to try to find the right line, then move to
938            ;; the proper column.
939            (goto-char (, temp-bolm))
940            (and (not (, temp-fnlp))
941                 (memq (char-after (point)) '(?\n ?\r))
942                 ;; The line containing the point got deleted. Note that this
943                 ;; logic only works if we don't delete null lines, but we never
944                 ;; do.
945                 (forward-line 1)) ; don't move into a hidden line.
946            (skip-chars-forward "^\n\r" (+ (point) (, temp-offset-bol))))))))
947
948 (put 'dired-save-excursion 'lisp-indent-hook 0)
949
950 (defun dired-substitute-marker (pos old new)
951   ;; Change marker, re-fontify
952   (subst-char-in-region pos (1+ pos) old new)
953   (dired-move-to-filename))
954
955 (defmacro dired-mark-if (predicate msg)
956   ;; Mark all files for which CONDITION evals to non-nil.
957   ;; CONDITION is evaluated on each line, with point at beginning of line.
958   ;; MSG is a noun phrase for the type of files being marked.
959   ;; It should end with a noun that can be pluralized by adding `s'.
960   ;; Return value is the number of files marked, or nil if none were marked.
961   (let ((temp-pt (make-symbol "pt"))
962         (temp-count (make-symbol "count"))
963         (temp-msg (make-symbol "msg")))
964     (` (let (((, temp-msg) (, msg))
965              ((, temp-count) 0)
966              (, temp-pt) buffer-read-only)
967          (save-excursion
968            (if (, temp-msg) (message "Marking %ss..." (, temp-msg)))
969            (goto-char (point-min))
970            (while (not (eobp))
971              (if (and (, predicate)
972                       (not (char-equal (char-after (point)) dired-marker-char)))
973                  (progn
974                    ;; Doing this rather than delete-char, insert
975                    ;; avoids re-computing markers
976                    (setq (, temp-pt) (point))
977                    (dired-substitute-marker
978                     (, temp-pt)
979                     (char-after (point)) dired-marker-char)
980                    (setq (, temp-count) (1+ (, temp-count)))))
981              (forward-line 1))
982            (if (, temp-msg)
983                (message "%s %s%s %s%s."
984                         (, temp-count)
985                         (, temp-msg)
986                         (dired-plural-s (, temp-count))
987                         (if (equal dired-marker-char ?\040) "un" "")
988                         (if (equal dired-marker-char dired-del-marker)
989                             "flagged" "marked"))))
990          (and (> (, temp-count) 0) (, temp-count))))))
991
992 (defmacro dired-map-over-marks (body arg &optional show-progress)
993 ;;  Perform BODY with point somewhere on each marked line
994 ;;  and return a list of BODY's results.
995 ;;  If no marked file could be found, execute BODY on the current line.
996 ;;  If ARG is an integer, use the next ARG (or previous -ARG, if ARG<0)
997 ;;  files instead of the marked files.
998 ;;  If ARG is t, only apply to marked files.  If there are no marked files,
999 ;;  the result is a noop.
1000 ;;  If ARG is otherwise non-nil, use current file instead.
1001 ;;  If optional third arg SHOW-PROGRESS evaluates to non-nil,
1002 ;;  redisplay the dired buffer after each file is processed.
1003 ;;  No guarantee is made about the position on the marked line.
1004 ;;  BODY must ensure this itself if it depends on this.
1005 ;;  Search starts at the beginning of the buffer, thus the car of the list
1006 ;;  corresponds to the line nearest to the buffer's bottom.  This
1007 ;;  is also true for (positive and negative) integer values of ARG.
1008 ;;  To avoid code explosion, BODY should not be too long as it is
1009 ;;  expanded four times.
1010 ;;
1011 ;;  Warning: BODY must not add new lines before point - this may cause an
1012 ;;  endless loop.
1013 ;;  This warning should not apply any longer, sk  2-Sep-1991 14:10.
1014   (let ((temp-found (make-symbol "found"))
1015         (temp-results (make-symbol "results"))
1016         (temp-regexp (make-symbol "regexp"))
1017         (temp-curr-pt (make-symbol "curr-pt"))
1018         (temp-next-position (make-symbol "next-position")))
1019     (` (let (buffer-read-only case-fold-search (, temp-found) (, temp-results))
1020          (dired-save-excursion
1021            (if (and (, arg) (not (eq (, arg) t)))
1022                (if (integerp (, arg))
1023                    (and (not (zerop (, arg)))
1024                         (progn;; no save-excursion, want to move point.
1025                           (dired-repeat-over-lines
1026                            arg
1027                            (function (lambda ()
1028                                        (if (, show-progress) (sit-for 0))
1029                                        (setq (, temp-results)
1030                                              (cons (, body)
1031                                                    (, temp-results))))))
1032                           (if (<  (, arg) 0)
1033                               (nreverse (, temp-results))
1034                             (, temp-results))))
1035                  ;; non-nil, non-integer ARG means use current file:
1036                  (list (, body)))
1037              (let (((, temp-regexp)
1038                     (concat "^" (regexp-quote (char-to-string
1039                                                dired-marker-char))))
1040                    (, temp-curr-pt) (, temp-next-position))
1041                (save-excursion
1042                  (goto-char (point-min))
1043                  ;; remember position of next marked file before BODY
1044                  ;; can insert lines before the just found file,
1045                  ;; confusing us by finding the same marked file again
1046                  ;; and again and...
1047                  (setq (, temp-next-position)
1048                        (and (re-search-forward (, temp-regexp) nil t)
1049                             (point-marker))
1050                        (, temp-found) (not (null (, temp-next-position))))
1051                  (while (, temp-next-position)
1052                    (setq (, temp-curr-pt) (goto-char (, temp-next-position))
1053                          ;; need to get next position BEFORE body
1054                          (, temp-next-position)
1055                          (and (re-search-forward (, temp-regexp) nil t)
1056                               (point-marker)))
1057                    (goto-char (, temp-curr-pt))
1058                    (if (, show-progress) (sit-for 0))
1059                    (setq (, temp-results) (cons (, body) (, temp-results)))))
1060                (if (, temp-found)
1061                    (, temp-results)
1062                  ;; Do current file, unless arg is t
1063                  (and (not (eq (, arg) t))
1064                       (list (, body)))))))))))
1065
1066 ;;; General utility functions
1067
1068 (defun dired-buffer-more-recently-used-p (buffer1 buffer2)
1069   "Return t if BUFFER1 is more recently used than BUFFER2."
1070   (if (equal buffer1 buffer2)
1071       nil
1072     (let ((more-recent nil)
1073           (list (buffer-list)))
1074       (while (and list
1075                   (not (setq more-recent (equal buffer1 (car list))))
1076                   (not (equal buffer2 (car list))))
1077         (setq list (cdr list)))
1078       more-recent)))
1079
1080 (defun dired-file-modtime (file)
1081   ;; Return the modtime of FILE, which is assumed to be already expanded
1082   ;; by expand-file-name.
1083   (let ((handler (find-file-name-handler file 'dired-file-modtime)))
1084     (if handler
1085         (funcall handler 'dired-file-modtime file)
1086       (nth 5 (file-attributes file)))))
1087
1088 (defun dired-set-file-modtime (file alist)
1089   ;; Set the modtime for FILE in the subdir alist ALIST.
1090   (let ((handler (find-file-name-handler file 'dired-set-file-modtime)))
1091     (if handler
1092         (funcall handler 'dired-set-file-modtime file alist)
1093       (let ((elt (assoc file alist)))
1094         (if elt
1095             (setcar (nthcdr 4 elt) (nth 5 (file-attributes file))))))))
1096
1097 (defun dired-map-over-marks-check (fun arg op-symbol operation
1098                                        &optional show-progress no-confirm)
1099   ;; Map FUN over marked files (with second ARG like in dired-map-over-marks)
1100   ;; and display failures.
1101
1102   ;; FUN takes zero args.  It returns non-nil (the offending object, e.g.
1103   ;; the short form of the filename) for a failure and probably logs a
1104   ;; detailed error explanation using function `dired-log'.
1105
1106   ;; OP-SYMBOL is s symbol representing the operation.
1107   ;; eg. 'compress
1108
1109   ;; OPERATION is a string describing the operation performed (e.g.
1110   ;; "Compress").  It is used with `dired-mark-pop-up' to prompt the user
1111   ;; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
1112   ;; `Failed to compress 1 of 2 files - type y to see why ("foo")')
1113
1114   ;; SHOW-PROGRESS if non-nil means redisplay dired after each file.
1115
1116   (if (or no-confirm (dired-mark-confirm op-symbol operation arg))
1117       (let* ((total-list;; all of FUN's return values
1118               (dired-map-over-marks (funcall fun) arg show-progress))
1119              (total (length total-list))
1120              (failures (delq nil total-list))
1121              (count (length failures)))
1122         (if (not failures)
1123             (message "%s: %d file%s." operation total (dired-plural-s total))
1124           (message "Failed to %s %d of %d file%s - type y to see why %s"
1125                    operation count total (dired-plural-s total)
1126                    ;; this gives a short list of failed files in parens
1127                    ;; which may be sufficient for the user even
1128                    ;; without typing `W' for the process' diagnostics
1129                    failures)
1130           ;; end this bunch of errors:
1131           (dired-log-summary
1132            (buffer-name (current-buffer))
1133            (format
1134             "Failed to %s %d of %d file%s"
1135             operation count total (dired-plural-s total))
1136            failures)))))
1137
1138 (defun dired-make-switches-string (list)
1139 ;; Converts a list of cracters to a string suitable for passing to ls.
1140   (concat "-" (mapconcat 'char-to-string list "")))
1141
1142 (defun dired-make-switches-list (string)
1143 ;; Converts a string of ls switches to a list of characters.
1144   (delq ?- (mapcar 'identity string)))
1145
1146 ;; Cloning replace-match to work on strings instead of in buffer:
1147 ;; The FIXEDCASE parameter of replace-match is not implemented.
1148 (defun dired-string-replace-match (regexp string newtext
1149                                           &optional literal global)
1150   ;; Replace first match of REGEXP in STRING with NEWTEXT.
1151   ;; If it does not match, nil is returned instead of the new string.
1152   ;; Optional arg LITERAL means to take NEWTEXT literally.
1153   ;; Optional arg GLOBAL means to replace all matches.
1154   (if global
1155         (let ((result "") (start 0) mb me)
1156           (while (string-match regexp string start)
1157             (setq mb (match-beginning 0)
1158                   me (match-end 0)
1159                   result (concat result
1160                                  (substring string start mb)
1161                                  (if literal
1162                                      newtext
1163                                    (dired-expand-newtext string newtext)))
1164                   start me))
1165           (if mb                        ; matched at least once
1166               (concat result (substring string start))
1167             nil))
1168     ;; not GLOBAL
1169     (if (not (string-match regexp string 0))
1170         nil
1171       (concat (substring string 0 (match-beginning 0))
1172               (if literal newtext (dired-expand-newtext string newtext))
1173               (substring string (match-end 0))))))
1174
1175 (defun dired-expand-newtext (string newtext)
1176   ;; Expand \& and \1..\9 (referring to STRING) in NEWTEXT, using match data.
1177   ;; Note that in Emacs 18 match data are clipped to current buffer
1178   ;; size...so the buffer should better not be smaller than STRING.
1179   (let ((pos 0)
1180         (len (length newtext))
1181         (expanded-newtext ""))
1182     (while (< pos len)
1183       (setq expanded-newtext
1184             (concat expanded-newtext
1185                     (let ((c (aref newtext pos)))
1186                       (if (= ?\\ c)
1187                           (cond ((= ?\& (setq c
1188                                               (aref newtext
1189                                                     (setq pos (1+ pos)))))
1190                                  (substring string
1191                                             (match-beginning 0)
1192                                             (match-end 0)))
1193                                 ((and (>= c ?1) (<= c ?9))
1194                                  ;; return empty string if N'th
1195                                  ;; sub-regexp did not match:
1196                                  (let ((n (- c ?0)))
1197                                    (if (match-beginning n)
1198                                        (substring string
1199                                                   (match-beginning n)
1200                                                   (match-end n))
1201                                      "")))
1202                                 (t
1203                                  (char-to-string c)))
1204                         (char-to-string c)))))
1205       (setq pos (1+ pos)))
1206     expanded-newtext))
1207
1208 (defun dired-in-this-tree (file dir)
1209   ;;Is FILE part of the directory tree starting at DIR?
1210   (let ((len (length dir)))
1211     (and (>= (length file) len)
1212          (string-equal (substring file 0 len) dir))))
1213
1214 (defun dired-tree-lessp (dir1 dir2)
1215   ;; Lexicographic order on pathname components, like `ls -lR':
1216   ;; DIR1 < DIR2 iff DIR1 comes *before* DIR2 in an `ls -lR' listing,
1217   ;;   i.e., iff DIR1 is a (grand)parent dir of DIR2,
1218   ;;   or DIR1 and DIR2 are in the same parentdir and their last
1219   ;;   components are string-lessp.
1220   ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
1221   ;; string-lessp could arguably be replaced by file-newer-than-file-p
1222   ;;   if dired-internal-switches contained `t'.
1223   (let ((dir1 (file-name-as-directory dir1))
1224         (dir2 (file-name-as-directory dir2))
1225         (start1 1)
1226         (start2 1)
1227         comp1 comp2 end1 end2)
1228     (while (progn
1229              (setq end1 (string-match "/" dir1 start1)
1230                    comp1 (substring dir1 start1 end1)
1231                    end2 (string-match "/" dir2 start2)
1232                    comp2 (substring dir2 start2 end2))
1233                    (and end1 end2 (string-equal comp1 comp2)))
1234       (setq start1 (1+ end1)
1235             start2 (1+ end2)))
1236     (if (eq (null end1) (null end2))
1237         (string-lessp comp1 comp2)
1238       (null end1))))
1239
1240 ;; So that we can support case-insensitive systems.
1241 (fset 'dired-file-name-lessp 'string-lessp)
1242
1243 \f
1244 ;;;; ------------------------------------------------------------------
1245 ;;;; Initializing Dired
1246 ;;;; ------------------------------------------------------------------
1247
1248 ;;; Set the minor mode alist
1249
1250 (or (equal (assq 'dired-sort-mode minor-mode-alist)
1251            '(dired-sort-mode dired-sort-mode))
1252     ;; Test whether this has already been done in case dired is reloaded
1253     ;; There may be several elements with dired-sort-mode as car.
1254     (setq minor-mode-alist
1255           ;; cons " Omit" in first, so that it doesn't
1256           ;; get stuck between the directory and sort mode on the
1257           ;; mode line.
1258           (cons '(dired-sort-mode dired-sort-mode)
1259                 (cons '(dired-subdir-omit " Omit")
1260                       (cons '(dired-marker-stack dired-marker-string)
1261                             minor-mode-alist)))))
1262
1263 ;;; Keymaps
1264
1265 (defvar dired-mode-map nil
1266   "Local keymap for dired-mode buffers.")
1267 (defvar dired-regexp-map nil
1268   "Dired keymap for commands that use regular expressions.")
1269 (defvar dired-diff-map nil
1270   "Dired keymap for diff and related commands.")
1271 (defvar dired-subdir-map nil
1272   "Dired keymap for commands that act on subdirs, or the files within them.")
1273
1274 (defvar dired-keymap-grokked nil
1275   "Set to t after dired has grokked the global keymap.")
1276
1277 (defun dired-key-description (cmd &rest prefixes)
1278   ;; Return a key description string for a menu.  If prefixes are given,
1279   ;; they should be either strings, integers, or 'universal-argument.
1280   (let ((key (where-is-internal cmd dired-mode-map t)))
1281     (if key
1282         (key-description
1283          (apply 'vconcat
1284                 (append
1285                  (mapcar
1286                   (function
1287                    (lambda (x)
1288                      (cond ((eq x 'universal-argument)
1289                             (where-is-internal 'universal-argument
1290                                                dired-mode-map t))
1291                            ((integerp x) (int-to-string x))
1292                            (t x))))
1293                   prefixes)
1294                  (list key))))
1295       "")))
1296
1297 (defun dired-grok-keys (to-command from-command)
1298   ;; Assigns to TO-COMMAND the keys for the global binding of FROM-COMMAND.
1299   ;; Does not clobber anything in the local keymap.  In emacs 19 should
1300   ;; use substitute-key-definition, but I believe that this will
1301   ;; clobber things in the local map.
1302   (let ((keys (where-is-internal from-command)))
1303     (while keys
1304       (condition-case nil
1305           (if (eq (global-key-binding (car keys)) (key-binding (car keys)))
1306               (local-set-key (car keys) to-command))
1307         (error nil))
1308       (setq keys (cdr keys)))))
1309
1310 (defun dired-grok-keymap ()
1311   ;; Initialize the dired keymaps.
1312   ;; This is actually done the first time that dired-mode runs.
1313   ;; We do it this late, to be sure that the user's global-keymap has
1314   ;; stabilized.
1315   (if dired-keymap-grokked
1316       () ; we've done it
1317     ;; Watch out for dired being invoked from the command line.
1318     ;; This is a bit kludgy, but so is the emacs startup sequence IMHO.
1319     (if (and term-setup-hook (boundp 'command-line-args-left))
1320         (progn
1321           (if (string-equal "18." (substring emacs-version 0 3))
1322               (funcall term-setup-hook)
1323             (run-hooks 'term-setup-hook))
1324           (setq term-setup-hook nil)))
1325     (setq dired-keymap-grokked t)
1326     (run-hooks 'dired-setup-keys-hook)
1327     (dired-grok-keys 'dired-next-line 'next-line)
1328     (dired-grok-keys 'dired-previous-line 'previous-line)
1329     (dired-grok-keys 'dired-undo 'undo)
1330     (dired-grok-keys 'dired-undo 'advertised-undo)
1331     (dired-grok-keys 'dired-scroll-up 'scroll-up)
1332     (dired-grok-keys 'dired-scroll-down 'scroll-down)
1333     (dired-grok-keys 'dired-beginning-of-buffer 'beginning-of-buffer)
1334     (dired-grok-keys 'dired-end-of-buffer 'end-of-buffer)
1335     (dired-grok-keys 'dired-next-subdir 'forward-paragraph)
1336     (dired-grok-keys 'dired-prev-subdir 'backward-paragraph)))
1337
1338 ;; The regexp-map is used for commands using regexp's.
1339 (if dired-regexp-map
1340     ()
1341   (setq dired-regexp-map (make-sparse-keymap))
1342   (define-key dired-regexp-map "C" 'dired-do-copy-regexp)
1343   ;; Not really a regexp, but does transform file names.
1344   (define-key dired-regexp-map "D" 'dired-downcase)
1345   (define-key dired-regexp-map "H" 'dired-do-hardlink-regexp)
1346   (define-key dired-regexp-map "R" 'dired-do-rename-regexp)
1347   (define-key dired-regexp-map "S" 'dired-do-symlink-regexp)
1348   (define-key dired-regexp-map "U" 'dired-upcase)
1349   (define-key dired-regexp-map "Y" 'dired-do-relsymlink-regexp)
1350   (define-key dired-regexp-map "c" 'dired-cleanup)
1351   (define-key dired-regexp-map "d" 'dired-flag-files-regexp)
1352   (define-key dired-regexp-map "e" 'dired-mark-extension)
1353   (define-key dired-regexp-map "m" 'dired-mark-files-regexp)
1354   (define-key dired-regexp-map "o" 'dired-add-omit-regexp)
1355   (define-key dired-regexp-map "x" 'dired-flag-extension)) ; a string, rather
1356                                         ; than a regexp.
1357
1358 (if dired-diff-map
1359     ()
1360   (setq dired-diff-map (make-sparse-keymap))
1361   (define-key dired-diff-map "d" 'dired-diff)
1362   (define-key dired-diff-map "b" 'dired-backup-diff)
1363   (define-key dired-diff-map "m" 'dired-emerge)
1364   (define-key dired-diff-map "a" 'dired-emerge-with-ancestor)
1365   (define-key dired-diff-map "e" 'dired-ediff)
1366   (define-key dired-diff-map "p" 'dired-epatch))
1367
1368 (if dired-subdir-map
1369     ()
1370   (setq dired-subdir-map (make-sparse-keymap))
1371   (define-key dired-subdir-map "n" 'dired-redisplay-subdir)
1372   (define-key dired-subdir-map "m" 'dired-mark-subdir-files)
1373   (define-key dired-subdir-map "d" 'dired-flag-subdir-files)
1374   (define-key dired-subdir-map "z" 'dired-compress-subdir-files))
1375
1376 (fset 'dired-regexp-prefix dired-regexp-map)
1377 (fset 'dired-diff-prefix dired-diff-map)
1378 (fset 'dired-subdir-prefix dired-subdir-map)
1379 (fset 'efs-dired-prefix (function (lambda ()
1380                                     (interactive)
1381                                     (error "efs-dired not loaded yet"))))
1382
1383 ;; the main map
1384 (if dired-mode-map
1385     nil
1386   ;; Force `f' rather than `e' in the mode doc:
1387   (fset 'dired-advertised-find-file 'dired-find-file)
1388   (fset 'dired-advertised-next-subdir 'dired-next-subdir)
1389   (fset 'dired-advertised-prev-subdir 'dired-prev-subdir)
1390   (setq dired-mode-map (make-keymap))
1391   (suppress-keymap dired-mode-map)
1392   ;; Commands to mark certain categories of files
1393   (define-key dired-mode-map "~" 'dired-flag-backup-files)
1394   (define-key dired-mode-map "#" 'dired-flag-auto-save-files)
1395   (define-key dired-mode-map "*" 'dired-mark-executables)
1396   (define-key dired-mode-map "." 'dired-clean-directory)
1397   (define-key dired-mode-map "/" 'dired-mark-directories)
1398   (define-key dired-mode-map "@" 'dired-mark-symlinks)
1399   (define-key dired-mode-map "," 'dired-mark-rcs-files)
1400   (define-key dired-mode-map "\M-(" 'dired-mark-sexp)
1401   (define-key dired-mode-map "\M-d" 'dired-mark-files-from-other-dired-buffer)
1402   (define-key dired-mode-map "\M-c" 'dired-mark-files-compilation-buffer)
1403   ;; Upper case keys (except ! and &) for operating on the marked files
1404   (define-key dired-mode-map "A" 'dired-do-tags-search)
1405   (define-key dired-mode-map "B" 'dired-do-byte-compile)
1406   (define-key dired-mode-map "C" 'dired-do-copy)
1407   (define-key dired-mode-map "E" 'dired-do-grep)
1408   (define-key dired-mode-map "F" 'dired-do-find-file)
1409   (define-key dired-mode-map "G" 'dired-do-chgrp)
1410   (define-key dired-mode-map "H" 'dired-do-hardlink)
1411   (define-key dired-mode-map "I" 'dired-do-insert-subdir)
1412   (define-key dired-mode-map "K" 'dired-do-kill-file-lines)
1413   (define-key dired-mode-map "L" 'dired-do-load)
1414   (define-key dired-mode-map "M" 'dired-do-chmod)
1415   (define-key dired-mode-map "N" 'dired-do-redisplay)
1416   (define-key dired-mode-map "O" 'dired-do-chown)
1417   (define-key dired-mode-map "P" 'dired-do-print)
1418   (define-key dired-mode-map "Q" 'dired-do-tags-query-replace)
1419   (define-key dired-mode-map "R" 'dired-do-rename)
1420   (define-key dired-mode-map "S" 'dired-do-symlink)
1421   (define-key dired-mode-map "T" 'dired-do-total-size)
1422   (define-key dired-mode-map "U" 'dired-do-uucode)
1423   (define-key dired-mode-map "W" 'dired-copy-filenames-as-kill)
1424   (define-key dired-mode-map "X" 'dired-do-delete)
1425   (define-key dired-mode-map "Y" 'dired-do-relsymlink)
1426   (define-key dired-mode-map "Z" 'dired-do-compress)
1427   (define-key dired-mode-map "!" 'dired-do-shell-command)
1428   (define-key dired-mode-map "&" 'dired-do-background-shell-command)
1429   ;; Make all regexp commands share a `%' prefix:
1430   (define-key dired-mode-map "%" 'dired-regexp-prefix)
1431   ;; Lower keys for commands not operating on all the marked files
1432   (define-key dired-mode-map "a" 'dired-apropos)
1433   (define-key dired-mode-map "c" 'dired-change-marks)
1434   (define-key dired-mode-map "d" 'dired-flag-file-deletion)
1435   (define-key dired-mode-map "\C-d" 'dired-flag-file-deletion-backup)
1436   (define-key dired-mode-map "e" 'dired-find-file)
1437   (define-key dired-mode-map "f" 'dired-advertised-find-file)
1438   (define-key dired-mode-map "g" 'revert-buffer)
1439   (define-key dired-mode-map "h" 'dired-describe-mode)
1440   (define-key dired-mode-map "i" 'dired-maybe-insert-subdir)
1441   (define-key dired-mode-map "k" 'dired-kill-subdir)
1442   (define-key dired-mode-map "m" 'dired-mark)
1443   (define-key dired-mode-map "o" 'dired-find-file-other-window)
1444   (define-key dired-mode-map "q" 'dired-quit)
1445   (define-key dired-mode-map "r" 'dired-read-mail)
1446   (define-key dired-mode-map "s" 'dired-sort-toggle-or-edit)
1447   (define-key dired-mode-map "t" 'dired-get-target-directory)
1448   (define-key dired-mode-map "u" 'dired-unmark)
1449   (define-key dired-mode-map "v" 'dired-view-file)
1450   (define-key dired-mode-map "w" (if (fboundp 'find-file-other-frame)
1451                                      'dired-find-file-other-frame
1452                                    'dired-find-file-other-window))
1453   (define-key dired-mode-map "x" 'dired-expunge-deletions)
1454   (define-key dired-mode-map "y" 'dired-why)
1455   (define-key dired-mode-map "+" 'dired-create-directory)
1456   (define-key dired-mode-map "`" 'dired-recover-file)
1457   ;; dired-jump-back Should be in the global map, but put them here
1458   ;; too anyway.
1459   (define-key dired-mode-map "\C-x\C-j" 'dired-jump-back)
1460   (define-key dired-mode-map "\C-x4\C-j" 'dired-jump-back-other-window)
1461   (define-key dired-mode-map "\C-x5\C-j" 'dired-jump-back-other-frame)
1462   ;; Comparison commands
1463   (define-key dired-mode-map "=" 'dired-diff-prefix)
1464   ;; moving
1465   (define-key dired-mode-map "<" 'dired-prev-dirline)
1466   (define-key dired-mode-map ">" 'dired-next-dirline)
1467   (define-key dired-mode-map " "  'dired-next-line)
1468   (define-key dired-mode-map "n" 'dired-next-line)
1469   (define-key dired-mode-map "\C-n" 'dired-next-line)
1470   (define-key dired-mode-map "p" 'dired-previous-line)
1471   (define-key dired-mode-map "\C-p" 'dired-previous-line)
1472   (define-key dired-mode-map "\C-v" 'dired-scroll-up)
1473   (define-key dired-mode-map "\M-v" 'dired-scroll-down)
1474   (define-key dired-mode-map "\M-<" 'dired-beginning-of-buffer)
1475   (define-key dired-mode-map "\M->" 'dired-end-of-buffer)
1476   (define-key dired-mode-map "\C-m" 'dired-advertised-find-file)
1477   (define-key dired-mode-map [(control return)] 'dired-find-alternate-file)
1478   ;; motion by subdirectories
1479   (define-key dired-mode-map "^" 'dired-up-directory)
1480   (define-key dired-mode-map "\M-\C-u" 'dired-up-directory)
1481   (define-key dired-mode-map "\M-\C-d" 'dired-down-directory)
1482   (define-key dired-mode-map "\M-\C-n" 'dired-advertised-next-subdir)
1483   (define-key dired-mode-map "\M-\C-p" 'dired-advertised-prev-subdir)
1484   (define-key dired-mode-map "\C-j" 'dired-goto-subdir)
1485   ;; move to marked files
1486   (define-key dired-mode-map "\M-p" 'dired-prev-marked-file)
1487   (define-key dired-mode-map "\M-n" 'dired-next-marked-file)
1488   ;; hiding
1489   (define-key dired-mode-map "$" 'dired-hide-subdir)
1490   (define-key dired-mode-map "\M-$" 'dired-hide-all)
1491   ;; omitting
1492   (define-key dired-mode-map "\C-o" 'dired-omit-toggle)
1493   ;; markers
1494   (define-key dired-mode-map "\(" 'dired-set-marker-char)
1495   (define-key dired-mode-map "\)" 'dired-restore-marker-char)
1496   (define-key dired-mode-map "'" 'dired-marker-stack-left)
1497   (define-key dired-mode-map "\\" 'dired-marker-stack-right)
1498   ;; misc
1499   (define-key dired-mode-map "\C-i" 'dired-mark-prefix)
1500   (define-key dired-mode-map "?" 'dired-summary)
1501   (define-key dired-mode-map "\177" 'dired-backup-unflag)
1502   (define-key dired-mode-map "\C-_" 'dired-undo)
1503   (define-key dired-mode-map "\C-xu" 'dired-undo)
1504   (define-key dired-mode-map "\M-\C-?" 'dired-unmark-all-files)
1505   (define-key dired-mode-map "\C-c\C-f" 'dired-do-find-marked-files)
1506   ;; The subdir map
1507   (define-key dired-mode-map "|" 'dired-subdir-prefix)
1508   ;; efs submap
1509   (define-key dired-mode-map "\M-e" 'efs-dired-prefix))
1510
1511
1512 \f
1513 ;;;;------------------------------------------------------------------
1514 ;;;; The dired command
1515 ;;;;------------------------------------------------------------------
1516
1517 ;;; User commands:
1518 ;;; All of these commands should have a binding in the global keymap.
1519
1520 ;;;###autoload (define-key ctl-x-map "d" 'dired)
1521 ;;;###autoload
1522 (defun dired (dirname &optional switches)
1523   "\"Edit\" directory DIRNAME--delete, rename, print, etc. some files in it.
1524 Optional second argument SWITCHES specifies the `ls' options used.
1525 \(Interactively, use a prefix argument to be able to specify SWITCHES.)
1526 Dired displays a list of files in DIRNAME (which may also have
1527 shell wildcards appended to select certain files).  If DIRNAME is a cons,
1528 its first element is taken as the directory name and the resr as an explicit
1529 list of files to make directory entries for.
1530 \\<dired-mode-map>\
1531 You can move around in it with the usual commands.
1532 You can flag files for deletion with \\[dired-flag-file-deletion] and then
1533 delete them by typing \\[dired-expunge-deletions].
1534 Type \\[dired-describe-mode] after entering dired for more info.
1535
1536 If DIRNAME is already in a dired buffer, that buffer is used without refresh."
1537   ;; Cannot use (interactive "D") because of wildcards.
1538   (interactive (dired-read-dir-and-switches ""))
1539   (switch-to-buffer (dired-noselect dirname switches)))
1540
1541 ;;;###autoload (define-key ctl-x-4-map "d" 'dired-other-window)
1542 ;;;###autoload
1543 (defun dired-other-window (dirname &optional switches)
1544   "\"Edit\" directory DIRNAME.  Like `dired' but selects in another window."
1545   (interactive (dired-read-dir-and-switches "in other window "))
1546   (switch-to-buffer-other-window (dired-noselect dirname switches)))
1547
1548 ;;;###autoload (define-key ctl-x-5-map "d" 'dired-other-frame)
1549 ;;;###autoload
1550 (defun dired-other-frame (dirname &optional switches)
1551   "\"Edit\" directory DIRNAME.  Like `dired' but makes a new frame."
1552   (interactive (dired-read-dir-and-switches "in other frame "))
1553   (switch-to-buffer-other-frame (dired-noselect dirname switches)))
1554
1555 ;;;###autoload
1556 (defun dired-noselect (dir-or-list &optional switches)
1557   "Like `dired' but returns the dired buffer as value, does not select it."
1558   (let ((find-file-compare-truenames (and (boundp 'find-file-compare-truenames)
1559                                           find-file-compare-truenames
1560                                           dired-find-file-compare-truenames)))
1561     (or dir-or-list (setq dir-or-list (expand-file-name default-directory)))
1562     ;; This loses the distinction between "/foo/*/" and "/foo/*" that
1563     ;; some shells make:
1564     (let (dirname)
1565       (if (consp dir-or-list)
1566           (setq dirname (car dir-or-list))
1567         (setq dirname dir-or-list))
1568       (setq dirname (expand-file-name (directory-file-name dirname)))
1569       (if (file-directory-p dirname)
1570           (setq dirname (file-name-as-directory dirname)))
1571       (if (consp dir-or-list)
1572           (setq dir-or-list (cons dirname (cdr dir-or-list)))
1573         (setq dir-or-list dirname))
1574       (dired-internal-noselect dir-or-list switches))))
1575
1576 ;; Adapted from code by wurgler@zippysun.math.uakron.edu (Tom Wurgler).
1577 ;;;###autoload (define-key ctl-x-map "\C-j" 'dired-jump-back)
1578 ;;;###autoload
1579 (defun dired-jump-back ()
1580   "Jump back to dired.
1581 If in a file, dired the current directory and move to file's line.
1582 If in dired already, pop up a level and goto old directory's line.
1583 In case the proper dired file line cannot be found, refresh the dired
1584   buffer and try again."
1585   (interactive)
1586   (let* ((file (if (eq major-mode 'dired-mode)
1587                    (directory-file-name (dired-current-directory))
1588                  buffer-file-name))
1589          (dir (if file
1590                   (file-name-directory file)
1591                 default-directory)))
1592     (dired dir)
1593     (if file (dired-really-goto-file file))))
1594
1595 ;;;###autoload (define-key ctl-x-4-map "\C-j" 'dired-jump-back-other-window)
1596 ;;;###autoload
1597 (defun dired-jump-back-other-window ()
1598   "Like \\[dired-jump-back], but to other window."
1599   (interactive)
1600   (let* ((file (if (eq major-mode 'dired-mode)
1601                    (directory-file-name (dired-current-directory))
1602                  buffer-file-name))
1603          (dir (if file
1604                   (file-name-directory file)
1605                 default-directory)))
1606     (dired-other-window dir)
1607     (if file (dired-really-goto-file file))))
1608
1609 ;;;###autoload (define-key ctl-x-5-map "\C-j" 'dired-jump-back-other-frame)
1610 ;;;###autoload
1611 (defun dired-jump-back-other-frame ()
1612   "Like \\[dired-jump-back], but in another frame."
1613   (interactive)
1614   (let* ((file (if (eq major-mode 'dired-mode)
1615                    (directory-file-name (dired-current-directory))
1616                  buffer-file-name))
1617          (dir (if file
1618                   (file-name-directory file)
1619                 default-directory)))
1620     (dired-other-frame dir)
1621     (if file (dired-really-goto-file file))))
1622
1623 ;;; Dired mode
1624
1625 ;; Dired mode is suitable only for specially formatted data.
1626 (put 'dired-mode 'mode-class 'special)
1627
1628 (defun dired-mode (&optional dirname switches)
1629   "\\<dired-mode-map>Dired mode is for \"editing\" directory trees.
1630
1631 For a simple one-line help message, type \\[dired-summary]
1632 For a moderately detailed description of dired mode, type \\[dired-describe-mode]
1633 For the full dired info tree, type \\[universal-argument] \\[dired-describe-mode]"
1634   ;; Not to be called interactively (e.g. dired-directory will be set
1635   ;; to default-directory, which is wrong with wildcards).
1636   (kill-all-local-variables)
1637   (use-local-map dired-mode-map)
1638   (setq major-mode 'dired-mode
1639         mode-name "Dired"
1640         case-fold-search nil
1641         buffer-read-only t
1642         selective-display t             ; for subdirectory hiding
1643         selective-display-ellipses nil  ; for omit toggling
1644         mode-line-buffer-identification '("Dired: %12b")
1645         mode-line-modified (format dired-mode-line-modified "--" "--" "-")
1646         dired-directory (expand-file-name (or dirname default-directory))
1647         dired-internal-switches (dired-make-switches-list
1648                                (or switches dired-listing-switches)))
1649   (dired-advertise)                     ; default-directory is already set
1650   (set (make-local-variable 'revert-buffer-function)
1651        (function dired-revert))
1652   (set (make-local-variable 'default-directory-function)
1653        'dired-current-directory)
1654   (set (make-local-variable 'page-delimiter)
1655        "\n\n")
1656   (set (make-local-variable 'list-buffers-directory)
1657        dired-directory)
1658   ;; Will only do something in Emacs 19.
1659   (add-hook (make-local-variable 'kill-buffer-hook)
1660             'dired-unadvertise-current-buffer)
1661   ;; Same here
1662   (if window-system
1663       (add-hook (make-local-variable 'post-command-hook)
1664                 (function
1665                  (lambda ()
1666                    (if (memq this-command dired-modeline-tracking-cmds)
1667                        (dired-update-mode-line t))))))
1668   (dired-sort-other dired-internal-switches t)
1669   (dired-hack-local-variables)
1670   (run-hooks 'dired-mode-hook)
1671   ;; Run this after dired-mode-hook, in case that hook makes changes to
1672   ;; the keymap.
1673   (dired-grok-keymap))
1674
1675 ;;; Internal functions for starting dired
1676
1677 (defun dired-read-dir-and-switches (str)
1678   ;; For use in interactive.
1679   (reverse (list
1680             (if current-prefix-arg
1681                 (read-string "Dired listing switches: "
1682                              dired-listing-switches))
1683             (let ((default-directory (default-directory)))
1684               (read-file-name (format "Dired %s(directory): " str)
1685                               nil default-directory nil)))))
1686
1687 (defun dired-hack-local-variables ()
1688   "Parse, bind or evaluate any local variables for current dired buffer.
1689 See variable `dired-local-variables-file'."
1690   (if (and dired-local-variables-file
1691            (file-exists-p dired-local-variables-file))
1692       (let (buffer-read-only opoint )
1693         (save-excursion
1694           (goto-char (point-max))
1695           (setq opoint (point-marker))
1696           (insert "\^L\n")
1697           (insert-file-contents dired-local-variables-file))
1698         (let ((buffer-file-name dired-local-variables-file))
1699           (condition-case err
1700               (hack-local-variables)
1701             (error (message "Error in dired-local-variables-file: %s" err)
1702                    (sit-for 1))))
1703         ;; Must delete it as (eobp) is often used as test for last
1704         ;; subdir in dired.el.
1705         (delete-region opoint (point-max))
1706         (set-marker opoint nil))))
1707
1708 ;; Separate function from dired-noselect for the sake of dired-vms.el.
1709 (defun dired-internal-noselect (dir-or-list &optional switches mode)
1710   ;; If there is an existing dired buffer for DIRNAME, just leave
1711   ;; buffer as it is (don't even call dired-revert).
1712   ;; This saves time especially for deep trees or with efs.
1713   ;; The user can type `g'easily, and it is more consistent with find-file.
1714   ;; But if SWITCHES are given they are probably different from the
1715   ;; buffer's old value, so call dired-sort-other, which does
1716   ;; revert the buffer.
1717   ;; If the user specifies a directory with emacs startup, eg.
1718   ;; emacs ~, dir-or-list may be unexpanded at this point.
1719
1720   (let* ((dirname (expand-file-name (if (consp dir-or-list)
1721                                         (car dir-or-list)
1722                                       dir-or-list)))
1723          (buffer (dired-find-buffer-nocreate dir-or-list mode))
1724          ;; note that buffer already is in dired-mode, if found
1725          (new-buffer-p (not buffer))
1726          (old-buf (current-buffer))
1727          wildcard)
1728     (or buffer
1729         (let ((default-major-mode 'fundamental-mode))
1730           ;; We don't want default-major-mode to run hooks and set auto-fill
1731           ;; or whatever, now that dired-mode does not
1732           ;; kill-all-local-variables any longer.
1733           (setq buffer (create-file-buffer (directory-file-name dirname)))))
1734     (set-buffer buffer)
1735     (if (not new-buffer-p)              ; existing buffer ...
1736         (progn
1737           (if switches
1738               (dired-sort-other
1739                (if (stringp switches)
1740                    (dired-make-switches-list switches)
1741                  switches)))
1742           (if dired-verify-modtimes (dired-verify-modtimes))
1743           (if (and dired-find-subdir
1744                    (not (string-equal (dired-current-directory)
1745                                       (file-name-as-directory dirname))))
1746               (dired-initial-position dirname)))
1747       ;; Else a new buffer
1748       (if (file-directory-p dirname)
1749           (setq default-directory dirname
1750                 wildcard (consp dir-or-list))
1751         (setq default-directory (file-name-directory dirname)
1752               wildcard t))
1753       (or switches (setq switches dired-listing-switches))
1754       (if mode 
1755           (funcall mode)
1756         (dired-mode dirname switches))
1757       ;; default-directory and dired-internal-switches are set now
1758       ;; (buffer-local), so we can call dired-readin:
1759       (let ((failed t))
1760         (unwind-protect
1761             (progn (dired-readin dir-or-list buffer wildcard)
1762                    (setq failed nil))
1763           ;; dired-readin can fail if parent directories are inaccessible.
1764           ;; Don't leave an empty buffer around in that case.
1765           (if failed (kill-buffer buffer))))
1766       ;; No need to narrow since the whole buffer contains just
1767       ;; dired-readin's output, nothing else.  The hook can
1768       ;; successfully use dired functions (e.g. dired-get-filename)
1769       ;; as the subdir-alist has been built in dired-readin.
1770       (run-hooks 'dired-after-readin-hook)
1771       ;; I put omit-expunge after the dired-after-readin-hook
1772       ;; in case that hook marks files. Does this make sense? Also, users
1773       ;; might want to set dired-omit-files in some incredibly clever
1774       ;; way depending on the contents of the directory... I don't know...
1775       (if dired-omit-files
1776           (dired-omit-expunge nil t))
1777       (goto-char (point-min))
1778       (dired-initial-position dirname))
1779     (set-buffer old-buf)
1780     buffer))
1781
1782 (defun dired-find-buffer-nocreate (dir-or-list &optional mode)
1783   ;; Returns a dired buffer for DIR-OR-LIST. DIR-OR-LIST may be wildcard,
1784   ;; or a directory and alist of files.
1785   ;; If dired-find-subdir is non-nil, is satisfied with a dired
1786   ;; buffer containing DIR-OR-LIST as a subdirectory. If there is more
1787   ;; than one candidate, returns the most recently used.
1788   (let ((find-file-compare-truenames (and (boundp 'find-file-compare-truenames)
1789                                           find-file-compare-truenames
1790                                           dired-find-file-compare-truenames)))
1791     (if dired-find-subdir
1792         (let ((buffers (sort (delq (current-buffer)
1793                                    (dired-buffers-for-dir dir-or-list t))
1794                              (function dired-buffer-more-recently-used-p))))
1795           (or (car buffers)
1796               ;; Couldn't find another buffer. Will the current one do?
1797               ;; It is up dired-initial-position to actually go to the subdir.
1798               (and (or (equal dir-or-list dired-directory) ; covers wildcards
1799                        (and (stringp dir-or-list)
1800                             (not (string-equal
1801                                   dir-or-list
1802                                   (expand-file-name default-directory)))
1803                             (assoc (file-name-as-directory dir-or-list)
1804                                    dired-subdir-alist)))
1805                    (current-buffer))))
1806       ;; Else just look through the buffer list.
1807       (let (found
1808             (search-directory
1809              (if (or (not (boundp 'find-file-compare-truenames))
1810                      find-file-compare-truenames)
1811                  (dired-directory-truename dir-or-list)
1812                dir-or-list))
1813             (blist (buffer-list)))
1814         (or mode (setq mode 'dired-mode))
1815         (save-excursion
1816           (while blist
1817             (set-buffer (car blist))
1818             (if (and (eq major-mode mode)
1819                      (equal (if (or (not (boundp 'find-file-compare-truenames))
1820                                     find-file-compare-truenames)
1821                                 (condition-case nil
1822                                     (dired-directory-truename dired-directory)
1823                                   (error nil))
1824                               dired-directory)
1825                             search-directory))
1826                 (setq found (car blist)
1827                       blist nil)
1828               (setq blist (cdr blist)))))
1829         found))))
1830
1831 (defun dired-directory-truename (dir)
1832   "Convert value of `dired-directory' to truename form."
1833   (if (consp dir)
1834       (cons (file-truename (car dir))
1835             (cdr dir))
1836     (file-truename dir)))
1837
1838 (defun dired-initial-position (dirname)
1839   ;; Where point should go in a new listing of DIRNAME.
1840   ;; Point assumed at beginning of new subdir line.
1841   (end-of-line)
1842   (if dired-find-subdir (dired-goto-subdir dirname))
1843   (if dired-trivial-filenames (dired-goto-next-nontrivial-file))
1844   (dired-update-mode-line t))
1845
1846 (defun dired-readin (dir-or-list buffer &optional wildcard)
1847   ;; Read in a new dired buffer
1848   ;; dired-readin differs from dired-insert-subdir in that it accepts
1849   ;; wildcards, erases the buffer, and builds the subdir-alist anew
1850   ;; (including making it buffer-local and clearing it first).
1851   ;; default-directory and dired-internal-switches must be buffer-local
1852   ;; and initialized by now.
1853   ;; Thus we can test (equal default-directory dirname) instead of
1854   ;; (file-directory-p dirname) and save a filesystem transaction.
1855   ;; This is wrong, if dired-before-readin-hook changes default-directory
1856   ;; Also, we can run this hook which may want to modify the switches
1857   ;; based on default-directory, e.g. with efs to a SysV host
1858   ;; where ls won't understand -Al switches.
1859   (let (dirname other-dirs)
1860     (if (consp dir-or-list)
1861         (setq dir-or-list (dired-frob-dir-list dir-or-list)
1862               other-dirs (cdr dir-or-list)
1863               dir-or-list (car dir-or-list)
1864               dirname (car dir-or-list))
1865       (setq dirname dir-or-list))
1866     (setq dirname (expand-file-name dirname))
1867     (if (consp dir-or-list)
1868         (setq dir-or-list (cons dirname (cdr dir-or-list))))
1869     (save-excursion
1870       (set-buffer buffer)
1871       (run-hooks 'dired-before-readin-hook)
1872       (message "Reading directory %s..." dirname)
1873       (let (buffer-read-only)
1874         (widen)
1875         (erase-buffer)
1876         (dired-readin-insert dir-or-list wildcard)
1877         ;; We need this to make the root dir have a header line as all
1878         ;; other subdirs have:
1879         (goto-char (point-min))
1880         (dired-insert-headerline (expand-file-name default-directory)))
1881       (message "Reading directory %s...done" dirname)
1882       (set-buffer-modified-p nil)
1883       ;; Must first make alist buffer local and set it to nil because
1884       ;; dired-build-subdir-alist will call dired-clear-alist first
1885       (setq dired-subdir-alist nil)
1886       (if (memq ?R dired-internal-switches)
1887           (dired-build-subdir-alist)
1888         ;; no need to parse the buffer if listing is not recursive
1889         (dired-simple-subdir-alist))
1890       (if other-dirs
1891           (mapcar
1892            (function
1893             (lambda (x)
1894               (if (dired-in-this-tree (car x) dirname)
1895                   (dired-insert-subdir x))))
1896            other-dirs)))))
1897
1898 ;;; Subroutines of dired-readin
1899
1900 (defun dired-readin-insert (dir-or-list &optional wildcard)
1901   ;; Just insert listing for the passed-in directory or
1902   ;; directory-and-file list, assuming a clean buffer.
1903   (let* ((switches (dired-make-switches-string dired-internal-switches))
1904          (dir-is-list (consp dir-or-list))
1905          (dirname (if dir-is-list (car dir-or-list) dir-or-list)))
1906     (if wildcard
1907         (progn
1908           (or (file-readable-p
1909                (if dir-is-list
1910                    dirname
1911                  (directory-file-name (file-name-directory dirname))))
1912               (error "Directory %s inaccessible or nonexistent" dirname))
1913           ;; else assume it contains wildcards
1914           (dired-insert-directory dir-or-list switches t)
1915           (save-excursion
1916             ;; insert wildcard instead of total line:
1917             (goto-char (point-min))
1918             (if dir-is-list
1919                 (insert "list wildcard\n")
1920               (insert "wildcard " (file-name-nondirectory dirname) "\n"))))
1921       (dired-insert-directory dir-or-list switches nil t))))
1922
1923 (defun dired-insert-directory (dir-or-list switches &optional wildcard full-p)
1924   ;; Do the right thing whether dir-or-list is atomic or not.  If it is,
1925   ;; insert all files listed in the cdr -- the car is the passed-in directory
1926   ;; list.
1927   (let ((opoint (point))
1928         (insert-directory-program dired-ls-program) end)
1929     (if dired-use-ls-dired
1930         (setq switches (concat "--dired " switches)))
1931     (if (consp dir-or-list)
1932         (mapcar
1933          (function
1934           (lambda (x)
1935             (dired-call-insert-directory x switches wildcard)))
1936          (cdr dir-or-list))
1937       (dired-call-insert-directory dir-or-list switches wildcard full-p))
1938     (setq end (point-marker))
1939     (dired-indent-listing opoint end)
1940     (dired-insert-set-properties opoint end))
1941   (setq dired-directory dir-or-list))
1942
1943 (defun dired-call-insert-directory (&rest args)
1944   "Call `insert-directory' in the correct process environment."
1945   (let ((process-environment
1946          (if dired-ls-locale
1947              (cons (concat "LC_ALL=" dired-ls-locale)
1948                    process-environment)
1949            process-environment)))
1950     (apply 'insert-directory args)))
1951
1952 (defun dired-frob-dir-list (dir-list)
1953   (let* ((top (file-name-as-directory (expand-file-name (car dir-list))))
1954          (tail (cdr dir-list))
1955          (result (list (list top)))
1956          elt dir)
1957     (setq tail
1958           (mapcar
1959            (function
1960             (lambda (x)
1961               (directory-file-name (expand-file-name x top))))
1962            tail))
1963     (while tail
1964       (setq dir (file-name-directory (car tail)))
1965       (if (setq elt (assoc dir result))
1966           (nconc elt (list (car tail)))
1967         (nconc result (list (list dir (car tail)))))
1968       (setq tail (cdr tail)))
1969     result))
1970
1971 (defun dired-insert-headerline (dir);; also used by dired-insert-subdir
1972   ;; Insert DIR's headerline with no trailing slash, exactly like ls
1973   ;; would, and put cursor where dired-build-subdir-alist puts subdir
1974   ;; boundaries.
1975   (if (fboundp 'dired-insert-set-headerline-properties)
1976       ;; code activate `headerline popup menu'
1977       (save-excursion (prog1
1978                           (save-excursion
1979                             (insert "  " (directory-file-name dir) ":\n"))
1980                         (dired-insert-set-headerline-properties)
1981                         ))
1982     ;; Original code
1983     (save-excursion (insert "  " (directory-file-name dir) ":\n"))))
1984
1985 (defun dired-verify-modtimes ()
1986   ;; Check the modtimes of all subdirs.
1987   (let ((alist dired-subdir-alist)
1988         on-disk in-mem badies)
1989     (while alist
1990       (and (setq in-mem (nth 4 (car alist)))
1991            (setq on-disk (dired-file-modtime (car (car alist))))
1992            (not (equal in-mem on-disk))
1993            (setq badies (cons (cons (car (car alist))
1994                                     (nth 3 (car alist)))
1995                               badies)))
1996       (setq alist (cdr alist)))
1997     (and badies
1998          (let* ((ofile (dired-get-filename nil t))
1999                 (osub (and (null ofile) (dired-get-subdir)))
2000                 (opoint (point))
2001                 (ocol (current-column)))
2002            (unwind-protect
2003                (and
2004                 (or (memq 'revert-subdirs dired-no-confirm)
2005                     (save-window-excursion
2006                       (let ((flist (mapcar
2007                                     (function
2008                                      (lambda (f)
2009                                        (dired-abbreviate-file-name (car f))))
2010                                     badies)))
2011                         (switch-to-buffer (current-buffer))
2012                        (dired-mark-pop-up
2013                         "*Stale Subdirectories*" 'revert-subdirs
2014                         flist 'y-or-n-p
2015                         (if (= (length flist) 1)
2016                             (concat "Subdirectory " (car flist)
2017                                     " has changed on disk.  Re-list? ")
2018                           "Subdirectories have changed on disk.  Re-list? "))
2019                        )))
2020                 (while badies
2021                   (dired-insert-subdir (car (car badies))
2022                                        (cdr (car badies)) nil t)
2023                   (setq badies (cdr badies))))
2024              ;; We can't use dired-save-excursion here, because we are
2025              ;; rewriting the entire listing, and not just changing a single
2026              ;; file line.
2027              (or (if ofile
2028                      (dired-goto-file ofile)
2029                    (if osub
2030                        (dired-goto-subdir osub)))
2031                  (progn
2032                    (goto-char opoint)
2033                    (beginning-of-line)
2034                    (skip-chars-forward "^\n\r" (+ (point) ocol))))
2035              (dired-update-mode-line t)
2036              (dired-update-mode-line-modified t))))))
2037
2038 (defun dired-indent-listing (start end)
2039   ;; If we used --dired and it worked, the lines are already indented.
2040   (unless (save-excursion
2041             (goto-char start)
2042             (looking-at "  "))
2043     ;; Indent a dired listing.
2044     (let (indent-tabs-mode)
2045       (indent-rigidly start end 2)
2046       ;; Quote any null lines that shouldn't be.
2047       (save-excursion
2048         (goto-char start)
2049         (while (search-forward "\n\n" end t)
2050           (forward-char -2)
2051           (if (looking-at dired-subdir-regexp)
2052               (goto-char (match-end 3))
2053             (progn
2054               (forward-char 1)
2055               (insert " "))))))))
2056
2057 \f
2058 ;;;; ------------------------------------------------------------
2059 ;;;; Reverting a dired buffer, or specific file lines within it.
2060 ;;;; ------------------------------------------------------------
2061
2062 (defun dired-revert (&optional arg noconfirm)
2063   ;; Reread the dired buffer.  Must also be called after
2064   ;; dired-internal-switches have changed.
2065   ;; Should not fail even on completely garbaged buffers.
2066   ;; Preserves old cursor, marks/flags, hidden-p.
2067   (widen)                               ; just in case user narrowed
2068   (let ((opoint (point))
2069         (ofile (dired-get-filename nil t))
2070         (hidden-subdirs (dired-remember-hidden))
2071         ;; switches for top-level dir
2072         (oswitches (or (nth 3 (nth (1- (length dired-subdir-alist))
2073                                    dired-subdir-alist))
2074                        (delq ?R (copy-sequence dired-internal-switches))))
2075         ;; all other subdirs
2076         (old-subdir-alist (cdr (reverse dired-subdir-alist)))
2077         (omitted-subdirs (dired-remember-omitted))
2078         ;; do this after dired-remember-hidden, since this unhides
2079         (mark-alist (dired-remember-marks (point-min) (point-max)))
2080         (kill-files-p (save-excursion
2081                         (goto-char (point))
2082                         (search-forward
2083                          (concat (char-to-string ?\r)
2084                                  (regexp-quote
2085                                   (char-to-string
2086                                    dired-kill-marker-char)))
2087                          nil t)))
2088         buffer-read-only)
2089     ;; This is bogus, as it will not handle all the ways that efs uses cache.
2090     ;; Better to just use the fact that revert-buffer-function is a
2091     ;; buffer-local variable, and reset it to something that knows about
2092     ;; cache.
2093     ;; (dired-uncache
2094     ;;   (if (consp dired-directory) (car dired-directory) dired-directory))
2095     ;; treat top level dir extra (it may contain wildcards)
2096     (let ((dired-after-readin-hook nil)
2097           ;; don't run that hook for each subdir...
2098           (dired-omit-files nil)
2099           (dired-internal-switches oswitches))
2100       (dired-readin dired-directory (current-buffer)
2101                     ;; Don't test for wildcards by checking string=
2102                     ;; default-directory and dired-directory
2103                     ;; in case default-directory got munged.
2104                     (or (consp dired-directory)
2105                         (null (file-directory-p dired-directory))))
2106       ;; The R-switch will clobber sorting of subdirs.
2107       ;; What is the right thing to do here?
2108       (dired-insert-old-subdirs old-subdir-alist))
2109     (dired-mark-remembered mark-alist)  ; mark files that were marked
2110     (if kill-files-p (dired-do-hide dired-kill-marker-char))
2111     (run-hooks 'dired-after-readin-hook)        ; no need to narrow
2112     ;; omit-expunge after the readin hook
2113     (save-excursion
2114       (mapcar (function (lambda (dir)
2115                           (if (dired-goto-subdir dir)
2116                               (dired-omit-expunge))))
2117               omitted-subdirs))
2118     ;; hide subdirs that were hidden
2119     (save-excursion
2120       (mapcar (function (lambda (dir)
2121                           (if (dired-goto-subdir dir)
2122                               (dired-hide-subdir 1))))
2123               hidden-subdirs))
2124     ;; Try to get back to where we were
2125     (or (and ofile (dired-goto-file ofile))
2126         (goto-char opoint))
2127     (dired-move-to-filename)
2128     (dired-update-mode-line t)
2129     (dired-update-mode-line-modified t)))
2130
2131 (defun dired-do-redisplay (&optional arg)
2132   "Redisplay all marked (or next ARG) files."
2133   (interactive "P")
2134   ;; message instead of making dired-map-over-marks show-progress is
2135   ;; much faster
2136   (dired-map-over-marks (let ((fname (dired-get-filename)))
2137                           (dired-uncache fname nil)
2138                           (message "Redisplaying %s..." fname)
2139                           (dired-update-file-line fname))
2140                         arg)
2141   (dired-update-mode-line-modified t)
2142   (message "Redisplaying...done"))
2143
2144 (defun dired-redisplay-subdir (&optional arg)
2145   "Redisplay the current subdirectory.
2146 With a prefix prompts for listing switches."
2147   (interactive "P")
2148   (let ((switches (and arg (dired-make-switches-list
2149                             (read-string "Switches for listing: "
2150                                          (dired-make-switches-string
2151                                           dired-internal-switches)))))
2152         (dir (dired-current-directory))
2153         (opoint (point))
2154         (ofile (dired-get-filename nil t)))
2155     (or switches
2156         (setq switches (nth 3 (assoc dir dired-subdir-alist))))
2157     (or switches
2158         (setq switches (delq ?R (copy-sequence dired-internal-switches))))
2159     (message "Redisplaying %s..." dir)
2160     (dired-uncache dir t)
2161     (dired-insert-subdir dir switches)
2162     (dired-update-mode-line-modified t)
2163     (or (and ofile (dired-goto-file ofile)) (goto-char opoint))
2164     (message "Redisplaying %s... done" dir)))
2165
2166 (defun dired-update-file-line (file)
2167   ;; Delete the current line, and insert an entry for FILE.
2168   ;; Does not update other dired buffers.  Use dired-relist-file for that.
2169   (let* ((start (save-excursion (skip-chars-backward "^\n\r") (point)))
2170          (char (char-after start)))
2171     (dired-save-excursion
2172      ;; don't remember omit marks
2173      (if (memq char (list ?\040 dired-omit-marker-char))
2174          (setq char nil))
2175      ;; Delete the current-line. Even though dired-add-entry will not
2176      ;; insert duplicates, the file for the current line may not be the same as
2177      ;; FILE. eg. dired-do-compress
2178      (delete-region (save-excursion (skip-chars-backward "^\n\r") (1- (point)))
2179                     (progn (skip-chars-forward "^\n\r") (point)))
2180      ;; dired-add-entry inserts at the end of the previous line.
2181      (forward-char 1)
2182      (dired-add-entry file char t))))
2183
2184 ;;; Subroutines of dired-revert
2185 ;;; Some of these are also used when inserting subdirs.
2186
2187 ;; Don't want to remember omit marks, in case omission regexps
2188 ;; were changed, before the dired-revert. If we don't unhide
2189 ;; omitted files, we won't see their marks. Therefore we use
2190 ;; dired-omit-unhide-region.
2191
2192 (defun dired-remember-marks (beg end)
2193   ;; Return alist of files and their marks, from BEG to END.
2194   (if selective-display                 ; must unhide to make this work.
2195       (let (buffer-read-only)
2196         (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2197         (dired-do-hide dired-omit-marker-char)))
2198   (let (fil chr alist)
2199     (save-excursion
2200       (goto-char beg)
2201       (while (re-search-forward dired-re-mark end t)
2202         (if (setq fil (dired-get-filename nil t))
2203             (setq chr (char-before)
2204                   alist (cons (cons fil chr) alist)))))
2205     alist))
2206
2207 (defun dired-mark-remembered (alist)
2208   ;; Mark all files remembered in ALIST.
2209   (let (elt fil chr)
2210     (while alist
2211       (setq elt (car alist)
2212             alist (cdr alist)
2213             fil (car elt)
2214             chr (cdr elt))
2215       (if (dired-goto-file fil)
2216           (save-excursion
2217             (beginning-of-line)
2218             (dired-substitute-marker (point) (char-after (point)) chr))))))
2219
2220 (defun dired-remember-hidden ()
2221   ;; Return a list of all hidden subdirs.
2222   (let ((l dired-subdir-alist) dir result min)
2223     (while l
2224       (setq dir (car (car l))
2225             min (dired-get-subdir-min (car l))
2226             l (cdr l))
2227       (if (and (>= min (point-min)) (<= min (point-max))
2228                (dired-subdir-hidden-p dir))
2229           (setq result (cons dir result))))
2230     result))
2231
2232 (defun dired-insert-old-subdirs (old-subdir-alist)
2233   ;; Try to insert all subdirs that were displayed before
2234   (let (elt dir switches)
2235     (while old-subdir-alist
2236       (setq elt (car old-subdir-alist)
2237             old-subdir-alist (cdr old-subdir-alist)
2238             dir (car elt)
2239             switches (or (nth 3 elt) dired-internal-switches))
2240       (condition-case ()
2241           (dired-insert-subdir dir switches)
2242         (error nil)))))
2243
2244 (defun dired-uncache (file dir-p)
2245   ;; Remove directory DIR from any directory cache.
2246   ;; If DIR-P is non-nil, then FILE is a directory
2247   (let ((handler (find-file-name-handler file 'dired-uncache)))
2248     (if handler
2249         (funcall handler 'dired-uncache file dir-p))))
2250
2251 \f
2252 ;;;; -------------------------------------------------------------
2253 ;;;; Inserting subdirectories
2254 ;;;; -------------------------------------------------------------
2255
2256 (defun dired-maybe-insert-subdir (dirname &optional
2257                                           switches no-error-if-not-dir-p)
2258   "Insert this subdirectory into the same dired buffer.
2259 If it is already present, just move to it (type \\[dired-do-redisplay] to
2260   refresh), else inserts it at its natural place (as ls -lR would have done).
2261 With a prefix arg, you may edit the ls switches used for this listing.
2262   You can add `R' to the switches to expand the whole tree starting at
2263   this subdirectory.
2264 This function takes some pains to conform to ls -lR output."
2265   (interactive
2266    (list (dired-get-filename)
2267          (if current-prefix-arg
2268              (dired-make-switches-list
2269               (read-string "Switches for listing: "
2270                            (dired-make-switches-string
2271                             dired-internal-switches))))))
2272   (let ((opoint (point)))
2273     ;; We don't need a marker for opoint as the subdir is always
2274     ;; inserted *after* opoint.
2275     (setq dirname (file-name-as-directory dirname))
2276     (or (and (not switches)
2277              (dired-goto-subdir dirname))
2278         (dired-insert-subdir dirname switches no-error-if-not-dir-p))
2279     ;; Push mark so that it's easy to find back.  Do this after the
2280     ;; insert message so that the user sees the `Mark set' message.
2281     (push-mark opoint)))
2282
2283 (defun dired-insert-subdir (dir-or-list &optional
2284                                         switches no-error-if-not-dir-p no-posn)
2285   "Insert this subdirectory into the same dired buffer.
2286 If it is already present, overwrites previous entry,
2287   else inserts it at its natural place (as ls -lR would have done).
2288 With a prefix arg, you may edit the ls switches used for this listing.
2289   You can add `R' to the switches to expand the whole tree starting at
2290   this subdirectory.
2291 This function takes some pains to conform to ls -lR output."
2292   ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
2293   ;; Prospero where dired-ls does the right thing, but
2294   ;; file-directory-p has not been redefined.
2295   ;; SWITCHES should be a list.
2296   ;; If NO-POSN is non-nil, doesn't bother position the point at
2297   ;; the first nontrivial file line.  This can be used as an efficiency
2298   ;; hack when calling this from a program.
2299   (interactive
2300    (list (dired-get-filename)
2301          (if current-prefix-arg
2302              (dired-make-switches-list
2303               (read-string "Switches for listing: "
2304                            (dired-make-switches-string
2305                             dired-internal-switches))))))
2306   (let ((dirname (if (consp dir-or-list) (car dir-or-list) dir-or-list)))
2307     (setq dirname (file-name-as-directory (expand-file-name dirname)))
2308     (or (dired-in-this-tree dirname (expand-file-name default-directory))
2309         (error  "%s: not in this directory tree" dirname))
2310     (or no-error-if-not-dir-p
2311         (file-directory-p dirname)
2312         (error  "Attempt to insert a non-directory: %s" dirname))
2313     (if switches
2314         (or (dired-compatible-switches-p dired-internal-switches switches)
2315             (error "Cannot have subdirs with %s and %s switches together."
2316                    (dired-make-switches-string dired-internal-switches)
2317                    (dired-make-switches-string switches)))
2318       (setq switches dired-internal-switches))
2319     (let ((elt (assoc dirname dired-subdir-alist))
2320           mark-alist opoint-max buffer-read-only)
2321       (if (memq ?R switches)
2322           ;; avoid duplicated subdirs
2323           (progn
2324             (setq mark-alist (dired-kill-tree dirname t))
2325             (dired-insert-subdir-newpos dirname))
2326         (if elt
2327             ;; If subdir is already present, remove it and remember its marks
2328             (setq mark-alist (dired-insert-subdir-del elt))
2329           ;; else move to new position
2330           (dired-insert-subdir-newpos dirname)))
2331       (setq opoint-max (point-max))
2332       (condition-case nil
2333           (dired-insert-subdir-doupdate
2334            dirname (dired-insert-subdir-doinsert dir-or-list switches)
2335            switches elt mark-alist)
2336         (quit ; watch out for aborted inserts
2337          (and (= opoint-max (point-max))
2338               (null elt)
2339               (equal (char-before) ?\n)
2340               (delete-char -1))
2341          (signal 'quit nil))))
2342     (or no-posn (dired-initial-position dirname))))
2343
2344 (defun dired-do-insert-subdir ()
2345   "Insert all marked subdirectories in situ that are not yet inserted.
2346 Non-directories are silently ignored."
2347   (interactive)
2348   (let ((files (or (dired-get-marked-files)
2349                    (error "No files marked."))))
2350     (while files
2351       (if (file-directory-p (car files))
2352           (save-excursion (dired-maybe-insert-subdir (car files))))
2353       (setq files (cdr files)))))
2354
2355 ;;; Utilities for inserting subdirectories
2356
2357 (defun dired-insert-subdir-newpos (new-dir)
2358   ;; Find pos for new subdir, according to tree order.
2359   (let ((alist dired-subdir-alist) elt dir new-pos)
2360     (while alist
2361       (setq elt (car alist)
2362             alist (cdr alist)
2363             dir (car elt))
2364       (if (dired-tree-lessp dir new-dir)
2365           ;; Insert NEW-DIR after DIR
2366           (setq new-pos (dired-get-subdir-max elt)
2367                 alist nil)))
2368     (goto-char new-pos))
2369   (insert "\n")
2370   (point))
2371
2372 (defun dired-insert-subdir-del (element)
2373   ;; Erase an already present subdir (given by ELEMENT) from buffer.
2374   ;; Move to that buffer position.  Return a mark-alist.
2375   (let ((begin-marker (dired-get-subdir-min element)))
2376     (goto-char begin-marker)
2377     ;; Are at beginning of subdir (and inside it!).  Now determine its end:
2378     (goto-char (dired-subdir-max))
2379     (prog1
2380         (dired-remember-marks begin-marker (point))
2381       (delete-region begin-marker (point)))))
2382
2383 (defun dired-insert-subdir-doinsert (dir-or-list switches)
2384   ;; Insert ls output after point and put point on the correct
2385   ;; position for the subdir alist.
2386   ;; Return the boundary of the inserted text (as list of BEG and END).
2387   ;; SWITCHES should be a non-nil list.
2388   (let ((begin (point))
2389         (dirname (if (consp dir-or-list) (car dir-or-list) dir-or-list))
2390         end)
2391     (message "Reading directory %s..." dirname)
2392     (if (string-equal dirname (car (car (reverse dired-subdir-alist))))
2393         ;; top level directory may contain wildcards:
2394         (let ((dired-internal-switches switches))
2395           (dired-readin-insert dired-directory
2396                                (null (file-directory-p dired-directory)))
2397           (setq end (point-marker)))
2398       (let ((switches (dired-make-switches-string switches))
2399             (insert-directory-program dired-ls-program))
2400         (if dired-use-ls-dired
2401             (setq switches (concat "--dired " switches)))
2402         (if (consp dir-or-list)
2403             (progn
2404               (insert "list wildcard\n")
2405               (mapcar
2406                (function
2407                 (lambda (x)
2408                   (dired-call-insert-directory x switches t)))
2409                (cdr dir-or-list)))
2410           (dired-call-insert-directory dirname switches nil t))
2411         (setq end (point-marker))
2412         (dired-indent-listing begin end)
2413         (dired-insert-set-properties begin end)))
2414     (message "Reading directory %s...done" dirname)
2415     ;;  call dired-insert-headerline afterwards, as under VMS dired-ls
2416     ;;  does insert the headerline itself and the insert function just
2417     ;;  moves point.
2418     ;;  Need a marker for END as this inserts text.
2419     (goto-char begin)
2420     (dired-insert-headerline dirname)
2421     ;; point is now like in dired-build-subdir-alist
2422     (prog1
2423         (list begin (marker-position end))
2424       (set-marker end nil))))
2425
2426 (defun dired-insert-subdir-doupdate (dirname beg-end switches elt mark-alist)
2427   ;; Point is at the correct subdir alist position for ELT,
2428   ;; BEG-END is the subdir-region (as list of begin and end).
2429   ;; SWITCHES must be a non-nil list.
2430   (if (memq ?R switches)
2431       ;; This will remove ?R from switches on purpose.
2432       (let ((dired-internal-switches (delq ?R switches)))
2433         (dired-build-subdir-alist))
2434     (if elt
2435         (progn
2436           (set-marker (dired-get-subdir-min elt) (point-marker))
2437           (setcar (nthcdr 3 elt) switches)
2438           (if dired-verify-modtimes
2439               (dired-set-file-modtime dirname dired-subdir-alist)))
2440       (dired-alist-add dirname (point-marker) dired-omit-files switches)))
2441   (save-excursion
2442     (let ((begin (nth 0 beg-end))
2443           (end (nth 1 beg-end)))
2444       (goto-char begin)
2445       (save-restriction
2446         (narrow-to-region begin end)
2447         ;; hook may add or delete lines, but the subdir boundary
2448         ;; marker floats
2449         (run-hooks 'dired-after-readin-hook)
2450         (if mark-alist (dired-mark-remembered mark-alist))
2451         (dired-do-hide dired-kill-marker-char)
2452         (if (if elt (nth 2 elt) dired-omit-files)
2453             (dired-omit-expunge nil t))))))
2454
2455 \f
2456 ;;;; --------------------------------------------------------------
2457 ;;;; Dired motion commands -- moving around in the dired buffer.
2458 ;;;; --------------------------------------------------------------
2459
2460 (defun dired-next-line (arg)
2461   "Move down lines then position at filename.
2462 Optional prefix ARG says how many lines to move; default is one line."
2463   (interactive "p")
2464   (next-line arg)
2465   (dired-move-to-filename)
2466   (dired-update-mode-line)
2467   (setq zmacs-region-stays t))
2468
2469 (defun dired-previous-line (arg)
2470   "Move up lines then position at filename.
2471 Optional prefix ARG says how many lines to move; default is one line."
2472   (interactive "p")
2473   (previous-line arg)
2474   (dired-move-to-filename)
2475   (dired-update-mode-line)
2476   (setq zmacs-region-stays t))
2477
2478 (defun dired-scroll-up (arg)
2479   "Dired version of scroll up.
2480 Scroll text of current window upward ARG lines; or near full screen if no ARG.
2481 When calling from a program, supply a number as argument or nil."
2482   (interactive "P")
2483   (scroll-up arg)
2484   (dired-move-to-filename)
2485   (dired-update-mode-line)
2486   (setq zmacs-region-stays t))
2487
2488 (defun dired-scroll-down (arg)
2489   "Dired version of scroll-down.
2490 Scroll text of current window down ARG lines; or near full screen if no ARG.
2491 When calling from a program, supply a number as argument or nil."
2492   (interactive "P")
2493   (scroll-down arg)
2494   (dired-move-to-filename)
2495   (dired-update-mode-line)
2496   (setq zmacs-region-stays t))
2497
2498 (defun dired-beginning-of-buffer (arg)
2499   "Dired version of `beginning of buffer'."
2500   (interactive "P")
2501   (beginning-of-buffer arg)
2502   (dired-update-mode-line)
2503   (setq zmacs-region-stays t))
2504
2505 (defun dired-end-of-buffer (arg)
2506   "Dired version of `end-of-buffer'."
2507   (interactive "P")
2508   (end-of-buffer arg)
2509   (while (not (or (dired-move-to-filename) (dired-get-subdir) (bobp)))
2510     (forward-line -1))
2511   (dired-update-mode-line t)
2512   (setq zmacs-region-stays t))
2513
2514 (defun dired-next-dirline (arg &optional opoint)
2515   "Goto ARG'th next directory file line."
2516   (interactive "p")
2517   (if dired-re-dir
2518       (progn
2519         (dired-check-ls-l)
2520         (or opoint (setq opoint (point)))
2521         (if (if (> arg 0)
2522                 (re-search-forward dired-re-dir nil t arg)
2523               (beginning-of-line)
2524               (re-search-backward dired-re-dir nil t (- arg)))
2525             (progn
2526               (dired-move-to-filename)          ; user may type `i' or `f'
2527               (dired-update-mode-line))
2528           (goto-char opoint)
2529           (error "No more subdirectories"))))
2530   (setq zmacs-region-stays t))
2531
2532 (defun dired-prev-dirline (arg)
2533   "Goto ARG'th previous directory file line."
2534   (interactive "p")
2535   (dired-next-dirline (- arg))
2536   (setq zmacs-region-stays t))
2537
2538 (defun dired-next-marked-file (arg &optional wrap opoint)
2539   "Move to the next marked file, wrapping around the end of the buffer."
2540   (interactive "p\np")
2541   (or opoint (setq opoint (point))) ; return to where interactively started
2542   (if (if (> arg 0)
2543           (re-search-forward dired-re-mark nil t arg)
2544         (beginning-of-line)
2545         (re-search-backward dired-re-mark nil t (- arg)))
2546       (dired-move-to-filename)
2547     (if (null wrap)
2548         (progn
2549           (goto-char opoint)
2550           (error "No next marked file"))
2551       (message "(Wraparound for next marked file)")
2552       (goto-char (if (> arg 0) (point-min) (point-max)))
2553       (dired-next-marked-file arg nil opoint)))
2554   (dired-update-mode-line)
2555   (setq zmacs-region-stays t))
2556
2557 (defun dired-prev-marked-file (arg &optional wrap)
2558   "Move to the previous marked file, wrapping around the end of the buffer."
2559   (interactive "p\np")
2560   (dired-next-marked-file (- arg) wrap)
2561   (dired-update-mode-line)
2562   (setq zmacs-region-stays t))
2563
2564 (defun dired-goto-file (file)
2565   "Goto file line of FILE in this dired buffer."
2566   ;; Return value of point on success, else nil.
2567   ;; FILE must be an absolute pathname.
2568   ;; Loses if FILE contains control chars like "\007" for which ls
2569   ;; either inserts "?" or "\\007" into the buffer, so we won't find
2570   ;; it in the buffer.
2571   (interactive
2572    (prog1                               ; let push-mark display its message
2573        (list
2574         (let* ((dired-completer-buffer (current-buffer))
2575                (dired-completer-switches dired-internal-switches)
2576                (stack (reverse
2577                        (mapcar (function
2578                                 (lambda (x)
2579                                   (dired-abbreviate-file-name (car x))))
2580                                dired-subdir-alist)))
2581                (initial (car stack))
2582                (dired-goto-file-history (cdr stack))
2583                dired-completer-cache)
2584           (expand-file-name
2585            (dired-completing-read "Goto file: "
2586                                   'dired-goto-file-completer
2587                                   nil t initial 'dired-goto-file-history))))
2588      (push-mark)))
2589   (setq file (directory-file-name file)) ; does no harm if no directory
2590   (let (found case-fold-search)
2591     (save-excursion
2592       (if (dired-goto-subdir (or (file-name-directory file)
2593                                  (error "Need absolute pathname for %s"
2594                                         file)))
2595           (let* ((base (file-name-nondirectory file))
2596                  ;; filenames are preceded by SPC, this makes
2597                  ;; the search faster (e.g. for the filename "-"!).
2598                  (search (concat " " (dired-make-filename-string base t)))
2599                  (boundary (dired-subdir-max))
2600                  fn)
2601             (while (and (not found) (search-forward search boundary 'move))
2602               ;; Match could have BASE just as initial substring or
2603               ;; or in permission bits or date or
2604               ;; not be a proper filename at all:
2605               (if (and (setq fn (dired-get-filename 'no-dir t))
2606                        (string-equal fn base))
2607                   ;; Must move to filename since an (actually
2608                   ;; correct) match could have been elsewhere on the
2609                   ;; line (e.g. "-" would match somewhere in the
2610                   ;; permission bits).
2611                   (setq found (dired-move-to-filename)))))))
2612     (and found
2613          ;; return value of point (i.e., FOUND):
2614          (prog1
2615              (goto-char found)
2616            (dired-update-mode-line)))))
2617
2618 ;;; Moving by subdirectories
2619
2620 (defun dired-up-directory (arg)
2621   "Move to the ARG'th (prefix arg) parent directory of current directory.
2622 Always stays within the current tree dired buffer.  Will insert new
2623 subdirectories if necessary."
2624   (interactive "p")
2625   (if (< arg 0) (error "Can't go up a negative number of directories!"))
2626   (or (zerop arg)
2627       (let* ((dir (dired-current-directory))
2628              (n arg)
2629              (up dir))
2630         (while (> n 0)
2631           (setq up (file-name-directory (directory-file-name up))
2632                 n (1- n)))
2633         (if (and (< (length up) (length dired-directory))
2634                  (dired-in-this-tree dired-directory up))
2635             (if (or (memq 'create-top-dir dired-no-confirm)
2636                     (y-or-n-p
2637                      (format "Insert new top dir %s and rename buffer? "
2638                              (dired-abbreviate-file-name up))))
2639                 (let ((newname (let (buff)
2640                                   (unwind-protect
2641                                       (buffer-name
2642                                        (setq buff
2643                                              (create-file-buffer
2644                                               (directory-file-name up))))
2645                                     (kill-buffer buff))))
2646                       (buffer-read-only nil))
2647                   (push-mark)
2648                   (widen)
2649                   (goto-char (point-min))
2650                   (insert-before-markers "\n")
2651                   (forward-char -1)
2652                   (dired-insert-subdir-doupdate
2653                    up (dired-insert-subdir-doinsert up dired-internal-switches)
2654                    dired-internal-switches nil nil)
2655                   (dired-initial-position up)
2656                   (rename-buffer newname)
2657                   (dired-unadvertise default-directory)
2658                   (setq default-directory up
2659                         dired-directory up)
2660                   (dired-advertise)))
2661           (dired-maybe-insert-subdir up)))))
2662
2663 (defun dired-down-directory ()
2664   "Go down in the dired tree.
2665 Moves to the first subdirectory of the current directory, which exists in
2666 the dired buffer.  Does not take a prefix argument."
2667   ;; What would a prefix mean here?
2668   (interactive)
2669   (let ((dir (dired-current-directory)) ; has slash
2670         (rest (reverse dired-subdir-alist))
2671         pos elt)
2672     (while rest
2673       (setq elt (car rest))
2674       (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2675           (setq rest nil
2676                 pos (dired-goto-subdir (car elt)))
2677         (setq rest (cdr rest))))
2678     (prog1
2679         (if pos
2680             (progn
2681               (push-mark)
2682               (goto-char pos))
2683           (error "At the bottom"))
2684       (dired-update-mode-line t))))
2685
2686 (defun dired-next-subdir (arg &optional no-error-if-not-found no-skip)
2687   "Go to next subdirectory, regardless of level."
2688   ;; Use 0 arg to go to this directory's header line.
2689   ;; NO-SKIP prevents moving to end of header line, returning whatever
2690   ;; position was found in dired-subdir-alist.
2691   (interactive "p")
2692   (let ((this-dir (dired-current-directory))
2693         pos index)
2694     ;; nth with negative arg does not return nil but the first element
2695     (setq index (- (length dired-subdir-alist)
2696                    (length (memq (assoc this-dir dired-subdir-alist)
2697                                  dired-subdir-alist))
2698                    arg))
2699     (setq pos (if (>= index 0)
2700                   (dired-get-subdir-min (nth index dired-subdir-alist))))
2701     (if pos
2702         (if no-skip
2703             (goto-char pos)
2704           (goto-char pos)
2705           (skip-chars-forward "^\r\n")
2706           (if (equal (char-after (point)) ?\r)
2707               (skip-chars-backward "." (- (point) 3)))
2708           (dired-update-mode-line t)
2709           (point))
2710       (if no-error-if-not-found
2711           nil                           ; return nil if not found
2712         (error "%s directory" (if (> arg 0) "Last" "First"))))))
2713
2714 (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2715   "Go to previous subdirectory, regardless of level.
2716 When called interactively and not on a subdir line, go to this subdir's line."
2717   (interactive
2718    (list (if current-prefix-arg
2719              (prefix-numeric-value current-prefix-arg)
2720            ;; if on subdir start already, don't stay there!
2721            (if (dired-get-subdir) 1 0))))
2722   (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2723
2724 (defun dired-goto-subdir (dir)
2725   "Goto end of header line of DIR in this dired buffer.
2726 Return value of point on success, otherwise return nil.
2727 The next char is either \\n, or \\r if DIR is hidden."
2728   (interactive
2729    (prog1                               ; let push-mark display its message
2730        (list
2731         (let* ((table (mapcar
2732                        (function
2733                         (lambda (x)
2734                           (list (dired-abbreviate-file-name
2735                                  (car x)))))
2736                        dired-subdir-alist))
2737                (stack (reverse (mapcar 'car table)))
2738                (initial (car stack))
2739                (dired-goto-file-history (cdr stack)))
2740           (expand-file-name
2741            (dired-completing-read "Goto subdirectory " table nil t
2742                                   initial 'dired-goto-file-history))))
2743      (push-mark)))
2744   (setq dir (file-name-as-directory dir))
2745   (let ((elt (assoc dir dired-subdir-alist)))
2746     (and elt
2747          ;; need to make sure that we get where we're going.
2748          ;; beware: narrowing might be in effect
2749          (= (goto-char (dired-get-subdir-min elt)) (point))
2750          (progn
2751            ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2752            ;; at either \n or looking-at ...\r after this function succeeds.
2753            (skip-chars-forward "^\r\n")
2754            (if (equal (char-before) ?.)
2755                (skip-chars-backward "." (- (point) 3)))
2756            (if (interactive-p) (dired-update-mode-line))
2757            (point)))))
2758
2759 ;;; Internals for motion commands
2760
2761 (defun dired-update-mode-line (&optional force)
2762   "Updates the mode line in dired according to the position of the point.
2763 Normally this uses a cache of the boundaries of the current subdirectory,
2764 but if the optional argument FORCE is non-nil, then modeline is always
2765 updated and the cache is recomputed."
2766   (if (or force
2767           (>= (point) dired-curr-subdir-max)
2768           (< (point) dired-curr-subdir-min))
2769       (let ((alist dired-subdir-alist)
2770             min max)
2771         (while (and alist (< (point)
2772                              (setq min (dired-get-subdir-min (car alist)))))
2773           (setq alist (cdr alist)
2774                 max min))
2775         (setq dired-curr-subdir-max (or max (point-max-marker))
2776               dired-curr-subdir-min (or min (point-min-marker))
2777               dired-subdir-omit (nth 2 (car alist)))
2778         (dired-sort-set-modeline (nth 3 (car alist))))))
2779
2780 (defun dired-manual-move-to-filename (&optional raise-error bol eol)
2781   "In dired, move to first char of filename on this line.
2782 Returns position (point) or nil if no filename on this line."
2783   ;; This is the UNIX version.
2784   ;; have to be careful that we don't move to omitted files
2785   (let (case-fold-search)
2786
2787     (or eol (setq eol (save-excursion (skip-chars-forward "^\r\n") (point))))
2788     (or bol (setq bol (progn (skip-chars-backward "^\r\n") (point))))
2789
2790     (let ((maybe (dired-maybe-filename-start bol eol)))
2791       (cond
2792        (maybe (goto-char maybe))
2793        ((or (memq ?l dired-internal-switches)
2794             (memq ?g dired-internal-switches))
2795         (if (and
2796              (> (- eol bol) 17) ; a valid file line must have at least
2797                                         ; 17 chars. 2 leading, 10 perms,
2798                                         ; separator, node #, separator, owner,
2799                                         ; separator
2800              (goto-char (+ bol 17))
2801              (re-search-forward dired-re-before-filename eol t))
2802             (point)
2803           (goto-char bol)
2804           (if raise-error
2805               (error "No file on this line")
2806             nil)))
2807        ;; else ls switches don't contain -l.
2808        ;; Note that even if we make dired-move-to-filename and
2809        ;; dired-move-to-end-of-filename (and thus dired-get-filename)
2810        ;; work, all commands that gleaned information from the permission
2811        ;; bits (like dired-mark-directories) will cease to work properly.
2812        (t
2813         (if (= bol eol)
2814             (if raise-error
2815                 (error "No file on this line")
2816               nil)
2817           ;; skip marker, if any
2818           (goto-char bol)
2819           (forward-char))
2820         ;; If we not going to use the l switch, and use nstd listings,
2821         ;; then we must bomb on files starting with spaces.
2822         (skip-chars-forward " \t")
2823         (point))))))
2824
2825 (defun dired-manual-move-to-end-of-filename (&optional no-error bol eol)
2826   ;; Assumes point is at beginning of filename,
2827   ;; thus the rwx bit re-search-backward below will succeed in *this*
2828   ;; line if at all.  So, it should be called only after
2829   ;; (dired-move-to-filename t).
2830   ;; On failure, signals an error (with non-nil NO-ERROR just returns nil).
2831   ;; This is the UNIX version.
2832   (let ((bof (point))
2833         file-type modes-start case-fold-search)
2834     (or eol (setq eol (save-excursion (skip-chars-forward "^\r\n") (point))))
2835     (or bol (setq bol (save-excursion (skip-chars-backward "^\r\n") (point))))
2836     (and
2837      (null no-error)
2838      selective-display
2839      (equal (char-after (1- bol)) ?\r)
2840      (cond
2841       ((dired-subdir-hidden-p (dired-current-directory))
2842        (error
2843         (substitute-command-keys
2844          "File line is hidden. Type \\[dired-hide-subdir] to unhide.")))
2845       ((error
2846         (substitute-command-keys
2847          "File line is omitted. Type \\[dired-omit-toggle] to un-omit.")))))
2848     (let ((maybe (dired-maybe-filename-end bol eol)))
2849       (cond
2850        (maybe (goto-char maybe))
2851        ((or (memq ?l dired-internal-switches)
2852             (memq ?g dired-internal-switches))
2853         (if (save-excursion
2854               (goto-char bol)
2855               (re-search-forward
2856                "[^ ][-r][-w][^ ][-r][-w][^ ][-r][-w][^ ][-+ 0-9@.]"
2857                bof t))
2858             (progn
2859               (setq modes-start (match-beginning 0)
2860                     file-type (char-after modes-start))
2861               ;; Move point to end of name:
2862               (if (equal file-type ?l)  ; symlink
2863                   (progn
2864                     (if (search-forward " -> " eol t)
2865                         (goto-char (match-beginning 0))
2866                       (goto-char eol))
2867                     (and dired-ls-F-marks-symlinks
2868                          (equal (char-before) ?@) ; link really marked?
2869                          (memq ?F dired-internal-switches)
2870                          (forward-char -1))
2871                     (point))
2872                 ;; else not a symbolic link
2873                 (goto-char eol)
2874                 ;; ls -lF marks dirs, sockets and executables with exactly
2875                 ;; one trailing character. -F may not actually be honored,
2876                 ;; e.g. by an FTP ls in efs
2877                 (and
2878                  (memq ?F dired-internal-switches)
2879                  (let ((char (char-before)))
2880                    (or (and (equal char ?*) (or
2881                                              (memq
2882                                               (char-after (+ modes-start 3))
2883                                               '(?x ?s ?t))
2884                                              (memq
2885                                               (char-after (+ modes-start 6))
2886                                               '(?x ?s ?t))
2887                                              (memq
2888                                               (char-after (+ modes-start 9))
2889                                               '(?x ?s ?t))))
2890                        (and (equal char ?=) (equal file-type ?s))))
2891                  (forward-char -1))
2892                 ;; Skip back over /'s unconditionally.  It's not a valid
2893                 ;; file name character.
2894                 (skip-chars-backward "/")
2895                 (point)))
2896           (and (null no-error)
2897                (error "No file on this line"))))
2898
2899        ;; A brief listing
2900        ((eq (point) eol)
2901         (and (null no-error)
2902              (error "No file on this line")))
2903        (t
2904         (goto-char eol)
2905         (if (and (memq (char-before) '(?@ ?* ?=))
2906                  (memq ?F dired-internal-switches))
2907             ;; A guess, since without a long listing, we can't be sure.
2908             (forward-char -1))
2909         (skip-chars-backward "/")
2910         (point))))))
2911
2912 (defun dired-goto-next-nontrivial-file ()
2913   ;; Position point on first nontrivial file after point.
2914   ;; Does not move into the next sudir.
2915   ;; If point is on a file line, moves to that file.
2916   ;; This does not move to omitted files.
2917   (skip-chars-backward "^\n\r")
2918   (if (equal (char-before) ?\r)
2919       (forward-line 1))
2920   (let ((max (dired-subdir-max))
2921         file)
2922     (while (and (or (not (setq file (dired-get-filename 'no-dir t)))
2923                     (string-match dired-trivial-filenames file))
2924                 (< (point) max))
2925       (forward-line 1)))
2926   (dired-move-to-filename))
2927
2928 (defun dired-goto-next-file ()
2929   ;; Doesn't move out of current subdir. Does go to omitted files.
2930   ;; Returns the starting position of the file, or nil if none found.
2931   (let ((max (dired-subdir-max))
2932         found)
2933     (while (and (null (setq found (dired-move-to-filename))) (< (point) max))
2934       (skip-chars-forward "^\n\r")
2935       (forward-char 1))
2936     found))
2937
2938 ;; fluid vars used by dired-goto-file-completer
2939 (defvar dired-completer-buffer nil)
2940 (defvar dired-completer-switches nil)
2941 (defvar dired-completer-cache nil)
2942
2943 (defun dired-goto-file-completer (string pred action)
2944   (save-excursion
2945     (set-buffer dired-completer-buffer)
2946     (let* ((saved-md (match-data))
2947            (file (file-name-nondirectory string))
2948            (dir (file-name-directory string))
2949            (xstring (expand-file-name string))
2950            (xdir (file-name-directory xstring))
2951            (exact (dired-goto-file xstring)))
2952       (unwind-protect
2953           (if (dired-goto-subdir xdir)
2954               (let ((table (cdr (assoc xdir dired-completer-cache)))
2955                     fn result max)
2956                 (or table
2957                     (progn
2958                       (setq table (make-vector 37 0))
2959                       (mapcar (function
2960                                (lambda (ent)
2961                                  (setq ent (directory-file-name
2962                                             (car ent)))
2963                                  (if (string-equal
2964                                       (file-name-directory ent) xdir)
2965                                      (intern
2966                                       (concat
2967                                        (file-name-nondirectory ent) "/")
2968                                       table))))
2969                               dired-subdir-alist)
2970                       (or (looking-at "\\.\\.\\.\n\r")
2971                           (progn
2972                             (setq max (dired-subdir-max))
2973                             (while (and
2974                                     (< (point) max)
2975                                     (not
2976                                      (setq fn
2977                                            (dired-get-filename 'no-dir t))))
2978                               (forward-line 1))
2979                             (if fn
2980                                 (progn
2981                                   (or (intern-soft (concat fn "/") table)
2982                                       (intern fn table))
2983                                   (forward-line 1)
2984                                   (while (setq fn
2985                                                (dired-get-filename 'no-dir t))
2986                                     (or (intern-soft (concat fn "/") table)
2987                                         (intern fn table))
2988                                     (forward-line 1))))))
2989                       (setq dired-completer-cache (cons
2990                                                    (cons xdir table)
2991                                                    dired-completer-cache))))
2992                 (cond
2993                  ((null action)
2994                   (setq result (try-completion file table))
2995                   (if exact
2996                       (if (stringp result)
2997                           string
2998                         t)
2999                     (if (stringp result)
3000                         (concat dir result)
3001                       result)))
3002                  ((eq action t)
3003                   (setq result (all-completions file table))
3004                   (if exact (cons "." result) result))
3005                  ((eq 'lambda action)
3006                   (and (or exact (intern-soft file table)))))))
3007         (store-match-data saved-md)))))
3008
3009 (defun dired-really-goto-file (file)
3010   ;; Goes to a file, even if it needs to insert it parent directory.
3011   (or (dired-goto-file file)
3012       (progn                            ; refresh and try again
3013         (dired-insert-subdir (file-name-directory file))
3014         (dired-goto-file file))))
3015
3016 (defun dired-between-files ()
3017   ;; Point must be at beginning of line
3018   (save-excursion (not (dired-move-to-filename nil (point)))))
3019
3020 (defun dired-repeat-over-lines (arg function)
3021   ;; This version skips non-file lines.
3022   ;; Skips file lines hidden with selective display.
3023   ;; BACKWARDS means move backwards after each action.  This is not the same
3024   ;; as a negative arg, as that skips the current line.
3025   (beginning-of-line)
3026   (let* ((advance (cond ((> arg 0) 1) ((< arg 0) -1) (t nil)))
3027          (check-fun (if (eq advance 1) 'eobp 'bobp))
3028          (n (if (< arg 0) (- arg) arg))
3029          (wall (funcall check-fun))
3030          (done wall))
3031     (while (not done)
3032       (if advance
3033           (progn
3034             (while  (not (or (save-excursion (dired-move-to-filename))
3035                              (setq wall (funcall check-fun))))
3036               (forward-line advance))
3037             (if wall
3038                 (setq done t)
3039               (save-excursion (funcall function))
3040               (forward-line advance)
3041               (while (not (or (save-excursion (dired-move-to-filename))
3042                               (setq wall (funcall check-fun))))
3043                 (forward-line advance))
3044               (setq done (or (zerop (setq n (1- n))) wall))))
3045         (if (save-excursion (dired-move-to-filename))
3046             (save-excursion (funcall function)))
3047         (setq done t))))
3048   (dired-move-to-filename)
3049   ;; Note that if possible the point has now been moved to the beginning of
3050   ;; the file name.
3051   (dired-update-mode-line))
3052
3053 \f
3054 ;;;; ----------------------------------------------------------------
3055 ;;;; Miscellaneous dired commands
3056 ;;;; ----------------------------------------------------------------
3057
3058 (defun dired-quit ()
3059   "Bury the current dired buffer."
3060   (interactive)
3061   (bury-buffer))
3062
3063 (defun dired-undo ()
3064   "Undo in a dired buffer.
3065 This doesn't recover lost files, it is just normal undo with temporarily
3066 writeable buffer.  You can use it to recover marks, killed lines or subdirs."
3067   (interactive)
3068   (let ((lines (count-lines (point-min) (point-max)))
3069         buffer-read-only)
3070     (undo)
3071     ;; reset dired-subdir-alist, if a dir may have been affected
3072     ;; Is there a better way to guess this?
3073     (setq lines (- (count-lines (point-min) (point-max)) lines))
3074     (if (or (>= lines 2) (<= lines -2))
3075         (dired-build-subdir-alist)))
3076   (dired-update-mode-line-modified t)
3077   (dired-update-mode-line t))
3078
3079 \f
3080 ;;;; --------------------------------------------------------
3081 ;;;; Immediate actions on files: visiting, viewing, etc.
3082 ;;;; --------------------------------------------------------
3083
3084 (defun dired-find-file ()
3085   "In dired, visit the file or directory named on this line."
3086   (interactive)
3087   (let ((find-file-run-dired t))
3088     (find-file (dired-get-filename))))
3089
3090 (defun dired-find-and-bury-buffer ()
3091   "*In dired, visit the file or directory on this line and bury it."
3092   (interactive)
3093   (let ((find-file-run-dired t))
3094     (find-file (dired-get-filename))
3095     (bury-buffer)))
3096
3097
3098 (defun dired-view-file ()
3099   "In dired, examine a file in view mode, returning to dired when done.
3100 When file is a directory, show it in this buffer if it is inserted;
3101 otherwise, display it in another buffer."
3102   (interactive)
3103   (let ((file (dired-get-filename)))
3104     (if (file-directory-p file)
3105         (or (dired-goto-subdir file)
3106             (dired file))
3107       (view-file file))))
3108
3109 (defun dired-find-file-other-window (&optional displayp)
3110   "In dired, visit this file or directory in another window.
3111 With a prefix, the file is displayed, but the window is not selected."
3112   (interactive "P")
3113   (if displayp
3114       (dired-display-file)
3115       (let ((find-file-run-dired t))
3116         (find-file-other-window (dired-get-filename)))))
3117
3118 ;; Only for Emacs 19
3119 (defun dired-find-file-other-frame ()
3120   "In dired, visit this file or directory in another frame."
3121   (interactive)
3122   (let ((find-file-run-dired t))
3123     (find-file-other-frame (dired-get-filename))))
3124
3125 (defun dired-display-file ()
3126   "In dired, displays this file or directory in the other window."
3127   (interactive)
3128   (let ((find-file-run-dired t))
3129     (display-buffer (find-file-noselect (dired-get-filename)))))
3130
3131 (defun dired-find-alternate-file ()
3132   "In dired, replace the current buffer with the file or directory named on this line."
3133     (interactive)
3134     (find-alternate-file (dired-get-filename)))
3135
3136 (defun dired-do-find-marked-files (&optional arg)
3137   "find the marked (or next ARG) files into xemacs."
3138   (interactive "P")
3139   (dired-map-over-marks-check (function dired-find-and-bury-buffer) arg 'load "load" t))
3140
3141 ;; After an idea by wurgler@zippysun.math.uakron.edu (Tom Wurgler).
3142 (defun dired-do-find-file (&optional arg)
3143   "Visit all marked files at once, and display them simultaneously.
3144 See also function `simultaneous-find-file'.
3145 If you want to keep the dired buffer displayed, type \\[split-window-vertically] first.
3146 If you want just the marked files displayed and nothing else, type \\[delete-other-windows] first."
3147   (interactive "P")
3148   (dired-simultaneous-find-file (dired-get-marked-files nil arg)))
3149
3150 (defun dired-simultaneous-find-file (file-list)
3151   "Visit all files in FILE-LIST and display them simultaneously.
3152
3153 The current window is split across all files in FILE-LIST, as evenly
3154 as possible.  Remaining lines go to the bottommost window.
3155
3156 The number of files that can be displayed this way is restricted by
3157 the height of the current window and the variable `window-min-height'."
3158   ;; It is usually too clumsy to specify FILE-LIST interactively
3159   ;; unless via dired (dired-do-find-file).
3160   (let ((size (/ (window-height) (length file-list))))
3161     (or (<= window-min-height size)
3162         (error "Too many files to visit simultaneously"))
3163     (find-file (car file-list))
3164     (setq file-list (cdr file-list))
3165     (while file-list
3166       ;; Split off vertically a window of the desired size
3167       ;; The upper window will have SIZE lines.  We select the lower
3168       ;; (larger) window because we want to split that again.
3169       (select-window (split-window nil size))
3170       (let ((find-file-run-dired t))
3171         (find-file (car file-list)))
3172       (setq file-list (cdr file-list)))))
3173
3174 (defun dired-create-directory (directory)
3175   "Create a directory called DIRECTORY."
3176   (interactive
3177    (list (read-file-name "Create directory: "
3178                          (dired-abbreviate-file-name
3179                           (dired-current-directory)))))
3180   (let ((expanded (expand-file-name directory)))
3181     (make-directory expanded)
3182     ;; Because this function is meant to be called interactively, it moves
3183     ;; the point.
3184     (dired-goto-file expanded)))
3185
3186 (defun dired-recover-file ()
3187   "Recovers file from its autosave file.
3188 If the file is an autosave file, then recovers its associated file instead."
3189   (interactive)
3190   (let* ((file (dired-get-filename))
3191          (name (file-name-nondirectory file))
3192          (asp (auto-save-file-name-p name))
3193          (orig (and
3194                 asp
3195                 (if (fboundp 'auto-save-original-name)
3196                     (auto-save-original-name file)
3197                   (error
3198                    "Need auto-save package to compute original file name."))))
3199          (buff (if asp
3200                    (and orig (get-file-buffer orig))
3201                  (get-file-buffer file))))
3202     (and
3203      buff
3204      (buffer-modified-p buff)
3205      (or
3206       (yes-or-no-p
3207        (format
3208         "Recover file will erase the modified buffer %s.  Do it? "
3209         (buffer-name buff)))
3210       (error "Recover file aborted.")))
3211     (if asp
3212         (if orig
3213             (recover-file orig)
3214           (find-file file))
3215       (recover-file file))))
3216
3217 \f
3218 ;;;; --------------------------------------------------------------------
3219 ;;;; Functions for extracting and manipulating file names
3220 ;;;; --------------------------------------------------------------------
3221
3222 (defun dired-make-filename-string (filename &optional reverse)
3223   ;; Translates the way that a file name appears in a buffer, to
3224   ;; how it is used in a path name.  This is useful for non-unix
3225   ;; support in efs.
3226   filename)
3227
3228 (defun dired-get-filename (&optional localp no-error-if-not-filep)
3229   "In dired, return name of file mentioned on this line.
3230 Value returned normally includes the directory name.
3231 Optional arg LOCALP with value `no-dir' means don't include directory
3232   name in result.  A value of t means use path name relative to
3233   `default-directory', which still may contain slashes if in a subdirectory.
3234 Optional arg NO-ERROR-IF-NOT-FILEP means return nil if no filename on
3235   this line, otherwise an error occurs."
3236
3237   ;; Compute bol & eol once, rather than twice inside move-to-filename
3238   ;; and move-to-end-of-filename
3239   (let ((eol (save-excursion (skip-chars-forward "^\n\r") (point)))
3240         (bol (save-excursion (skip-chars-backward "^\r\n") (point)))
3241         case-fold-search file p1 p2)
3242     (save-excursion
3243       (and
3244        (setq p1 (dired-move-to-filename (not no-error-if-not-filep) bol eol))
3245        (setq p2 (dired-move-to-end-of-filename no-error-if-not-filep bol eol))
3246        (setq file (buffer-substring p1 p2))
3247        ;; Check if ls quoted the names, and unquote them.
3248        ;; Using read to unquote is much faster than substituting
3249        ;; \007 (4 chars) -> ^G  (1 char) etc. in a lisp loop.
3250        (cond ((memq ?b dired-internal-switches) ; System V ls
3251               ;; This case is about 20% slower than without -b.
3252               (setq file
3253                     (read
3254                      (concat "\""
3255                                ;; some ls -b don't escape quotes, argh!
3256                              ;; This is not needed for GNU ls, though.
3257                              (or (dired-string-replace-match
3258                                     "\\([^\\]\\)\"" file "\\1\\\\\"")
3259                                  file)
3260                              "\""))))
3261                ;; If you do this, update dired-compatible-switches-p
3262              ;; ((memq ?Q dired-internal-switches) ; GNU ls
3263              ;;  (setq file (read file)))
3264                )))
3265     (and file
3266          (if (eq localp 'no-dir)
3267              (dired-make-filename-string file)
3268            (concat (dired-current-directory localp)
3269                    (dired-make-filename-string file))))))
3270
3271 (defun dired-make-relative (file &optional dir no-error)
3272   ;; Convert FILE (an *absolute* pathname) to a pathname relative to DIR.
3273   ;; FILE must be absolute, or this function will return nonsense.
3274   ;; If FILE is not in a subdir of DIR, an error is signalled,
3275   ;; unless NO-ERROR is t. Then, ".."'s are inserted to give
3276   ;; a relative representation of FILE wrto DIR
3277   ;; eg.     FILE = /vol/tex/bin/foo DIR = /vol/local/bin/
3278   ;;         results in  ../../tex/bin/foo
3279   ;; DIR must be expanded.
3280   ;; DIR defaults to default-directory.
3281   ;; DIR must be file-name-as-directory, as with all directory args in
3282   ;; elisp code.
3283   (or dir (setq dir (expand-file-name default-directory)))
3284   (let ((flen (length file))
3285         (dlen (length dir)))
3286     (if (and (> flen dlen)
3287              (string-equal (substring file 0 dlen) dir))
3288         (substring file dlen)
3289       ;; Need to insert ..'s
3290       (or no-error (error  "%s: not in directory tree growing at %s" file dir))
3291       (if (string-equal file dir)
3292           "./"
3293         (let ((index 1)
3294               (count 0))
3295           (while (and (string-match "/" dir index)
3296                       (<= (match-end 0) flen)
3297                       (string-equal (substring file index (match-end 0))
3298                                     (substring dir index (match-end 0))))
3299             (setq index (match-end 0)))
3300           (setq file (substring file index))
3301           (if (and (/= flen index)
3302                    (not (string-match "/" file))
3303                    (< flen dlen)
3304                    (string-equal file (substring dir index flen))
3305                    (= (aref dir flen) ?/))
3306               (setq file "."
3307                     count -1))
3308           ;; count how many slashes remain in dir.
3309           (while (string-match "/" dir index)
3310             (setq index (match-end 0)
3311                   count (1+ count)))
3312           (apply 'concat (nconc (make-list count "../") (list file))))))))
3313
3314 ;;; Functions for manipulating file names.
3315 ;;
3316 ;;  Used by file tranformers.
3317 ;;  Define here rather than in dired-shell.el, as it wouldn't be
3318 ;;  unreasonable to use these elsewhere.
3319
3320 (defun dired-file-name-base (fn)
3321   "Returns the base name of FN.
3322 This is the file without directory part, and extension. See the variable
3323 `dired-filename-re-ext'."
3324   (setq fn (file-name-nondirectory fn))
3325   (if (string-match dired-filename-re-ext fn 1)
3326       (substring fn 0 (match-beginning 0))
3327     fn))
3328
3329 (defun dired-file-name-extension (fn)
3330   "Returns the extension for file name FN.
3331 See the variable dired-filename-re-ext'."
3332   (setq fn (file-name-nondirectory fn))
3333   (if (string-match dired-filename-re-ext fn 1)
3334       (substring fn (match-beginning 0))
3335     ""))
3336
3337 (defun dired-file-name-sans-rcs-extension (fn)
3338   "Returns the file name FN without its RCS extension \",v\"."
3339   (setq fn (file-name-nondirectory fn))
3340   (if (string-match ",v\\'" fn 1)
3341       (substring fn 0 (match-beginning 0))
3342     fn))
3343
3344 (defun dired-file-name-sans-compress-extension (fn)
3345   "Returns the file name FN without the extension from compress or gzip."
3346   (setq fn (file-name-nondirectory fn))
3347   (if (string-match "\\.\\([zZ]\\|gz\\)\\'" fn 1)
3348       (substring fn (match-beginning 0))
3349     fn))
3350
3351 \f
3352 ;;;; ---------------------------------------------------------------------
3353 ;;;; Working with directory trees.
3354 ;;;; ---------------------------------------------------------------------
3355 ;;;
3356 ;;;  This where code for the dired-subdir-alist is.
3357
3358 ;;; Utility functions for dired-subdir-alist
3359
3360 (defun dired-normalize-subdir (dir)
3361   ;; Prepend default-directory to DIR if relative path name.
3362   ;; dired-get-filename must be able to make a valid filename from a
3363   ;; file and its directory DIR.
3364   ;; Fully expand everything.
3365   (file-name-as-directory
3366    (if (file-name-absolute-p dir)
3367        (expand-file-name dir)
3368      (expand-file-name dir (expand-file-name default-directory)))))
3369
3370 (defun dired-get-subdir ()
3371   ;;"Return the subdir name on this line, or nil if not on a headerline."
3372   ;; Look up in the alist whether this is a headerline.
3373   (save-excursion
3374     (let ((cur-dir (dired-current-directory)))
3375       (beginning-of-line)               ; alist stores b-o-l positions
3376       (and (zerop (- (point)
3377                      (dired-get-subdir-min (assoc cur-dir
3378                                                   dired-subdir-alist))))
3379            cur-dir))))
3380
3381 (defun dired-get-subdir-max (elt)
3382   ;; returns subdir max.
3383   (let ((pos (- (length dired-subdir-alist)
3384                 (length (member elt dired-subdir-alist)))))
3385     (if (zerop pos)
3386         (point-max)
3387       (1- (dired-get-subdir-min (nth (1- pos) dired-subdir-alist))))))
3388
3389 (defun dired-clear-alist ()
3390   ;; Set all markers in dired-subdir-alist to nil.  Set the alist to nil too.
3391   (while dired-subdir-alist
3392     (set-marker (dired-get-subdir-min (car dired-subdir-alist)) nil)
3393     (setq dired-subdir-alist (cdr dired-subdir-alist))))
3394
3395 (defun dired-unsubdir (dir)
3396   ;; Remove DIR from the alist
3397   (setq dired-subdir-alist
3398         (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
3399
3400 (defun dired-simple-subdir-alist ()
3401   ;; Build and return `dired-subdir-alist' assuming just the top level
3402   ;; directory to be inserted.  Don't parse the buffer.
3403   (setq dired-subdir-alist
3404         (list (list (expand-file-name default-directory)
3405                     (point-min-marker) dired-omit-files
3406                     dired-internal-switches nil)))
3407   (if dired-verify-modtimes
3408       (dired-set-file-modtime (expand-file-name default-directory)
3409                               dired-subdir-alist)))
3410
3411 (defun dired-build-subdir-alist ()
3412   "Build `dired-subdir-alist' by parsing the buffer and return its new value."
3413   (interactive)
3414   (let ((o-alist dired-subdir-alist)
3415         (count 0)
3416         subdir)
3417     (dired-clear-alist)
3418     (save-excursion
3419       (goto-char (point-min))
3420       (while (re-search-forward dired-subdir-regexp nil t)
3421         (setq count (1+ count))
3422         (apply 'dired-alist-add-1
3423                (setq subdir (buffer-substring (match-beginning 2)
3424                                               (match-end 2)))
3425                ;; Put subdir boundary between lines.
3426                (set-marker (make-marker) (match-end 1))
3427                (let ((elt (assoc subdir o-alist)))
3428                  (if elt
3429                      (list (nth 2 elt) (nth 3 elt))
3430                    (list dired-omit-files dired-internal-switches)))))
3431       (if (interactive-p)
3432           (message "%d director%s." count (if (= 1 count) "y" "ies")))
3433       ;; We don't need to sort it because it is in buffer order per
3434       ;; constructionem.  Return new alist:
3435       ;; pointers for current-subdir may be stale
3436       dired-subdir-alist)))
3437
3438 (defun dired-alist-add (dir new-marker &optional omit switches)
3439   ;; Add new DIR at NEW-MARKER.  Sort alist.
3440   (dired-alist-add-1 dir new-marker omit switches)
3441   (dired-alist-sort))
3442
3443 (defun dired-alist-add-1 (dir new-marker &optional omit switches)
3444   ;; Add new DIR at NEW-MARKER.  Don't sort.
3445   (let ((dir (dired-normalize-subdir dir)))
3446     (setq dired-subdir-alist
3447           (cons (list dir new-marker omit switches nil) dired-subdir-alist))
3448     (if dired-verify-modtimes
3449         (dired-set-file-modtime dir dired-subdir-alist))))
3450
3451 (defun dired-alist-sort ()
3452   ;; Keep the alist sorted on buffer position.
3453   (setq dired-subdir-alist
3454         (sort dired-subdir-alist
3455               (function (lambda (elt1 elt2)
3456                           (> (dired-get-subdir-min elt1)
3457                              (dired-get-subdir-min elt2)))))))
3458
3459 ;;; Utilities for working with subdirs in the dired buffer
3460
3461 ;; This function is the heart of tree dired.
3462 ;; It is called for each retrieved filename.
3463 ;; It could stand to be faster, though it's mostly function call
3464 ;; overhead.  Avoiding to funcall seems to save about 10% in
3465 ;; dired-get-filename.  Make it a defsubst?
3466 (defun dired-current-directory (&optional localp)
3467   "Return the name of the subdirectory to which this line belongs.
3468 This returns a string with trailing slash, like `default-directory'.
3469 Optional argument means return a file name relative to `default-directory'.
3470 In this it returns \"\" for the top directory."
3471   (let* ((here (point))
3472          (dir (catch 'done
3473                 (mapcar (function
3474                          (lambda (x)
3475                            (if (<= (dired-get-subdir-min x) here)
3476                                (throw 'done (car x)))))
3477                         dired-subdir-alist))))
3478     (if (listp dir) (error "dired-subdir-alist seems to be mangled"))
3479     (if localp
3480         (let ((def-dir (expand-file-name default-directory)))
3481           (if (string-equal dir def-dir)
3482               ""
3483             (dired-make-relative dir def-dir)))
3484       dir)))
3485
3486 ;; Subdirs start at the beginning of their header lines and end just
3487 ;; before the beginning of the next header line (or end of buffer).
3488
3489 (defun dired-subdir-min ()
3490   ;; Returns the minimum position of the current subdir
3491   (save-excursion
3492     (if (not (dired-prev-subdir 0 t t))
3493         (error "Not in a subdir!")
3494       (point))))
3495
3496 (defun dired-subdir-max ()
3497   ;; Returns the maximum position of the current subdir
3498   (save-excursion
3499     (if (dired-next-subdir 1 t t)
3500         (1- (point)) ; Do not include separating empty line.
3501       (point-max))))
3502
3503 \f
3504 ;;;; --------------------------------------------------------
3505 ;;;; Deleting files
3506 ;;;; --------------------------------------------------------
3507
3508 (defun dired-flag-file-deletion (arg)
3509   "In dired, flag the current line's file for deletion.
3510 With prefix arg, repeat over several lines.
3511
3512 If on a subdir headerline, mark all its files except `.' and `..'."
3513   (interactive "p")
3514   (dired-mark arg dired-del-marker))
3515
3516 (defun dired-flag-file-deletion-backup (arg)
3517   "Flag current file for deletion, and move to previous line.
3518 With a prefix ARG, repeats this ARG times."
3519   (interactive "p")
3520   ;; Use dired-mark-file and not dired-mark, as this function
3521   ;; should do nothing special on subdir headers.
3522   (dired-mark-file (- arg) dired-del-marker))
3523
3524 (defun dired-flag-subdir-files ()
3525   "Flag all the files in the current subdirectory for deletion."
3526   (interactive)
3527   (dired-mark-subdir-files dired-del-marker))
3528
3529 (defun dired-unflag (arg)
3530   "In dired, remove a deletion flag from the current line's file.
3531 Optional prefix ARG says how many lines to unflag."
3532   (interactive "p")
3533   (let (buffer-read-only)
3534     (dired-repeat-over-lines
3535      arg
3536      (function
3537       (lambda ()
3538         (if (char-equal (char-after (point)) dired-del-marker)
3539             (progn
3540               (setq dired-del-flags-number (max (1- dired-del-flags-number) 0))
3541               (dired-substitute-marker (point) dired-del-marker ?\ )))))))
3542   (dired-update-mode-line-modified))
3543
3544 (defun dired-backup-unflag (arg)
3545   "In dired, move up lines and remove deletion flag there.
3546 Optional prefix ARG says how many lines to unflag; default is one line."
3547   (interactive "p")
3548   (dired-unflag (- arg)))
3549
3550 (defun dired-update-marker-counters (char &optional remove)
3551   (or (memq char '(?\  ?\n ?\r))
3552       (let ((counter (cond
3553                       ((char-equal char dired-del-marker)
3554                        'dired-del-flags-number)
3555                       ((char-equal char dired-marker-char)
3556                        'dired-marks-number)
3557                   ('dired-other-marks-number))))
3558         (if remove
3559             (set counter (max (1- (symbol-value counter)) 0))
3560           (set counter (1+ (symbol-value counter)))))))
3561
3562 (defun dired-update-mode-line-modified (&optional check)
3563   ;; Updates the value of mode-line-modified in dired.
3564   ;; Currently assumes that it's of the form "-%%-", where % sometimes
3565   ;; gets replaced by %.  Should allow some sort of config flag.
3566   ;; SET is t to set to -DD-, nil to set to -%%-, and 'check means
3567   ;; examine the buffer to find out.
3568   (if check
3569       (save-excursion
3570         (let (char)
3571           (goto-char (point-min))
3572           (setq dired-del-flags-number 0
3573                 dired-marks-number 0
3574                 dired-other-marks-number 0)
3575           (while (not (eobp))
3576             (setq char (char-after (point)))
3577             (cond
3578              ((char-equal char dired-del-marker)
3579               (setq dired-del-flags-number (1+ dired-del-flags-number)))
3580              ((char-equal char dired-marker-char)
3581               (setq dired-marks-number (1+ dired-marks-number)))
3582              ((memq char '(?\  ?\n ?\r))
3583               nil)
3584              ((setq dired-other-marks-number (1+ dired-other-marks-number))))
3585             (forward-line 1)))))
3586   (setq mode-line-modified
3587         (format dired-mode-line-modified
3588                 (if (zerop dired-del-flags-number)
3589                     "--"
3590                   (format "%d%c" dired-del-flags-number dired-del-marker))
3591                 (if (zerop dired-marks-number)
3592                     "--"
3593                   (format "%d%c" dired-marks-number dired-marker-char))
3594                 (if (zerop dired-other-marks-number)
3595                     "-"
3596                   (int-to-string dired-other-marks-number))))
3597   (set-buffer-modified-p (buffer-modified-p)))
3598
3599 (defun dired-do-deletions (&optional nomessage)
3600   (dired-expunge-deletions))
3601
3602 (defun dired-expunge-deletions ()
3603   "In dired, delete the files flagged for deletion."
3604   (interactive)
3605   (let ((files (let ((dired-marker-char dired-del-marker))
3606                  (dired-map-over-marks (cons (dired-get-filename) (point))
3607                                        t))))
3608     (if files
3609         (progn
3610           (dired-internal-do-deletions files nil dired-del-marker)
3611           ;; In case the point gets left somewhere strange -- hope that
3612           ;; this doesn't cause asynch troubles later.
3613           (beginning-of-line)
3614           (dired-goto-next-nontrivial-file)
3615           (dired-update-mode-line-modified t)) ; play safe, it's cheap
3616       (message "(No deletions requested)"))))
3617
3618 (defun dired-do-delete (&optional arg)
3619   "Delete all marked (or next ARG) files."
3620   ;; This is more consistent with the file marking feature than
3621   ;; dired-expunge-deletions.
3622   (interactive "P")
3623   (dired-internal-do-deletions
3624    ;; this may move point if ARG is an integer
3625    (dired-map-over-marks (cons (dired-get-filename) (point))
3626                    arg)
3627    arg)
3628   (beginning-of-line)
3629   (dired-goto-next-nontrivial-file))
3630
3631 (defun dired-internal-do-deletions (l arg &optional marker-char)
3632   ;; L is an alist of files to delete, with their buffer positions.
3633   ;; ARG is the prefix arg.
3634   ;; Filenames are absolute (VMS needs this for logical search paths).
3635   ;; (car L) *must* be the *last* (bottommost) file in the dired buffer.
3636   ;; That way as changes are made in the buffer they do not shift the
3637   ;; lines still to be changed, so the (point) values in L stay valid.
3638   ;; Also, for subdirs in natural order, a subdir's files are deleted
3639   ;; before the subdir itself - the other way around would not work.
3640   (save-excursion
3641     (let ((files (mapcar (function car) l))
3642           (count (length l))
3643           (succ 0)
3644           (cdir (dired-current-directory))
3645           failures)
3646       ;; canonicalize file list for pop up
3647       (setq files (nreverse (mapcar (function
3648                                      (lambda (fn)
3649                                        (dired-make-relative fn cdir t)))
3650                                     files)))
3651       (if (or (memq 'delete dired-no-confirm)
3652               (dired-mark-pop-up
3653                " *Files Flagged for Deletion*" 'delete files
3654                dired-deletion-confirmer
3655                (format "Delete %s "
3656                        (dired-mark-prompt arg files marker-char))))
3657           (save-excursion
3658             ;; files better be in reverse order for this loop!
3659             (while l
3660               (goto-char (cdr (car l)))
3661               (condition-case err
3662                   (let ((fn (car (car l))))
3663                     ;; This test is equivalent to
3664                     ;; (and (file-directory-p fn)
3665                     ;;      (not (file-symlink-p fn)))
3666                     ;; but more efficient
3667                     (if (if (eq t (car (file-attributes fn)))
3668                             (if (<= (length (directory-files fn)) 2)
3669                                 (progn (delete-directory fn) t)
3670                               (and (or
3671                                     (memq 'recursive-delete dired-no-confirm)
3672                                     (funcall
3673                                      dired-deletion-confirmer
3674                                      (format "\
3675 Recursively delete directory and files within %s? "
3676                                              (dired-make-relative fn))))
3677                                    (progn
3678                                      (dired-recursive-delete-directory fn)
3679                                      t)))
3680                           (progn (delete-file fn) t))
3681                         (progn
3682                           (setq succ (1+ succ))
3683                           (message "%s of %s deletions" succ count)
3684                           (dired-clean-up-after-deletion fn))))
3685                 (error;; catch errors from failed deletions
3686                  (dired-log (buffer-name (current-buffer)) "%s\n" err)
3687                  (setq failures (cons (car (car l)) failures))))
3688               (setq l (cdr l)))))
3689       (if failures
3690           (dired-log-summary
3691            (buffer-name (current-buffer))
3692            (format "%d of %d deletion%s failed:" (length failures) count
3693                    (dired-plural-s count))
3694            failures)
3695         (if (zerop succ)
3696             (message "(No deletions performed)")
3697           (message "%d deletion%s done" succ (dired-plural-s succ)))))))
3698
3699 (defun dired-recursive-delete-directory (fn)
3700   ;; Recursively deletes directory FN, and all of its contents.
3701   (let* ((fn (expand-file-name fn))
3702          (handler (find-file-name-handler
3703                    fn 'dired-recursive-delete-directory)))
3704     (if handler
3705         (funcall handler 'dired-recursive-delete-directory fn)
3706       (progn
3707         (or (file-exists-p fn)
3708             (signal
3709              'file-error
3710              (list "Removing old file name" "no such directory" fn)))
3711         (let ((files (directory-files fn t)))
3712           (while files
3713             (let ((file (car files)))
3714               (if (not (member (file-name-nondirectory file)
3715                                '("." "..")))
3716                   ;; This test is equivalent to
3717                   ;; (and (file-directory-p fn)
3718                   ;;      (not (file-symlink-p fn)))
3719                   ;; but more efficient
3720                   (if (eq t (car (file-attributes file)))
3721                       (dired-recursive-delete-directory file)
3722                     (delete-file file)))
3723               (setq files (cdr files))))
3724           (delete-directory fn))))))
3725
3726 (defun dired-clean-up-after-deletion (fn)
3727   ;; Offer to kill buffer of deleted file FN.
3728   (let ((buf (get-file-buffer fn)))
3729     (and buf
3730          (or (memq 'kill-file-buffer dired-no-confirm)
3731              (funcall (function yes-or-no-p)
3732                       (format "Kill buffer of %s, too? "
3733                               (file-name-nondirectory fn))))
3734          (save-excursion ; you never know where kill-buffer leaves you
3735            (kill-buffer buf)))))
3736
3737 ;;; Cleaning a directory -- flagging backups for deletion
3738
3739 (defun dired-clean-directory (keep &optional marker msg)
3740   "Flag numerical backups for deletion.
3741 Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
3742 Positive prefix arg KEEP overrides `dired-kept-versions';
3743 Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
3744
3745 To clear the flags on these files, you can use \\[dired-flag-backup-files]
3746 with a prefix argument."
3747   (interactive "P")
3748   (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
3749   (let* ((early-retention (if (< keep 0) (- keep) kept-old-versions))
3750          (late-retention (if (<= keep 0) dired-kept-versions keep))
3751          (msg (or msg
3752                   (format
3753                    "Cleaning numerical backups (keeping %d late, %d old)"
3754                    late-retention early-retention)))
3755          (trample-marker (or marker dired-del-marker))
3756          (file-version-assoc-list))
3757     (message "%s..." msg)
3758     ;; Do this after messaging, as it may take a while.
3759     (setq file-version-assoc-list (dired-collect-file-versions))
3760     ;; Sort each VERSION-NUMBER-LIST,
3761     ;; and remove the versions to be deleted.
3762     (let ((fval file-version-assoc-list))
3763       (while fval
3764         (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
3765                (v-count (length sorted-v-list)))
3766           (if (> v-count (+ early-retention late-retention))
3767               (rplacd (nthcdr early-retention sorted-v-list)
3768                       (nthcdr (- v-count late-retention)
3769                               sorted-v-list)))
3770           (rplacd (car fval)
3771                   (cdr sorted-v-list)))
3772         (setq fval (cdr fval))))
3773     ;; Look at each file.  If it is a numeric backup file,
3774     ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
3775     (dired-map-dired-file-lines (function
3776                                  (lambda (fn)
3777                                    (dired-trample-file-versions
3778                                     fn file-version-assoc-list
3779                                     trample-marker))))
3780     (message "%s...done" msg)))
3781
3782 (defun dired-collect-file-versions ()
3783   ;; If it looks like a file has versions, return a list of the versions.
3784   ;; The return value is ((FILENAME . (VERSION1 VERSION2 ...)) ...)
3785   (let (result)
3786     (dired-map-dired-file-lines
3787      (function
3788       (lambda (fn)
3789         (let* ((base-versions
3790                 (concat (file-name-nondirectory fn) ".~"))
3791                (bv-length (length base-versions))
3792                (backup-extract-version-start (length base-versions))
3793                (possibilities (file-name-all-completions
3794                                base-versions
3795                                (file-name-directory fn))))
3796           (if possibilities
3797               (setq result (cons (cons fn
3798                                        (mapcar 'backup-extract-version
3799                                                possibilities)) result)))))))
3800     result))
3801
3802 (defun dired-trample-file-versions (fn alist marker)
3803   ;; ALIST is an alist of filenames and versions used to determine
3804   ;; if each file should be flagged for deletion.
3805   ;; This version using file-name-sans-versions is probably a lot slower
3806   ;; than Sebastian's original, but it is more easily adaptable to non-unix.
3807   (let ((base (file-name-sans-versions fn))
3808         base-version-list bv-length)
3809     (and (not (string-equal base fn))
3810          (setq base-version-list (assoc base alist))
3811          (setq bv-length (string-match "[0-9]" fn (length base)))
3812          (setq backup-extract-version-start (string-match "[0-9]" fn (length base)))
3813          (not (memq (backup-extract-version fn) base-version-list))
3814          (progn (skip-chars-backward "^\n\r")
3815                 (bolp)) ; make sure the preceding char isn't \r.
3816          (dired-substitute-marker (point) (char-after (point)) marker))))
3817
3818 (defun dired-map-dired-file-lines (fun)
3819   ;; Perform FUN with point at the end of each non-directory line.
3820   ;; FUN takes one argument, the filename (complete pathname).
3821   (dired-check-ls-l)
3822   (save-excursion
3823     (let (file buffer-read-only)
3824       (goto-char (point-min))
3825       (while (not (eobp))
3826         (save-excursion
3827           (and (not (and dired-re-dir (looking-at dired-re-dir)))
3828                (not (memq (char-after (point)) '(?\n ?\n)))
3829                (setq file (dired-get-filename nil t)) ; nil on non-file
3830                (progn (skip-chars-forward "^\n\r")
3831                       (funcall fun file))))
3832         (forward-line 1)))))            ; this guarantees that we don't
3833                                         ; operate on omitted files.
3834
3835 \f
3836 ;;;; -----------------------------------------------------------
3837 ;;;; Confirmations and prompting the user.
3838 ;;;; -----------------------------------------------------------
3839
3840 (defun dired-plural-s (count)
3841   (if (= 1 count) "" "s"))
3842
3843 (defun dired-mark-prompt (arg files &optional marker-char)
3844   ;; Return a string for use in a prompt, either the current file
3845   ;; name, or the marker and a count of marked files.
3846   (let ((count (length files)))
3847     (if (= count 1)
3848         (car files)
3849       ;; more than 1 file:
3850       (if (integerp arg)
3851           (cond ((zerop arg) "[no files]")
3852                 ((> arg 0) "[following]")
3853                 ((< arg 0) "[preceding]"))
3854         (char-to-string (or marker-char dired-marker-char))))))
3855
3856 (defun dired-pop-to-buffer (buf)
3857   ;; Pop up buffer BUF.
3858   ;; Make its window fit its contents.
3859   (if temp-buffer-show-function
3860       (funcall temp-buffer-show-function buf)
3861     (let ((window (selected-window))
3862           target-lines w2)
3863       (cond;; if split-window-threshold is enabled, use the largest window
3864        ((and (> (window-height (setq w2 (get-largest-window)))
3865                 split-height-threshold)
3866              (= (frame-width) (window-width w2)))
3867         (setq window w2))
3868        ;; if the least-recently-used window is big enough, use it
3869        ((and (> (window-height (setq w2 (get-lru-window)))
3870                 (* 2 window-min-height))
3871              (= (frame-width) (window-width w2)))
3872         (setq window w2)))
3873       (save-excursion
3874         (set-buffer buf)
3875         (goto-char (point-max))
3876         (skip-chars-backward "\n\r\t ")
3877         (setq target-lines (count-lines (point-min) (point)))
3878         ;; Don't forget to count the last line.
3879         (if (not (bolp))
3880             (setq target-lines (1+ target-lines))))
3881       (if (<= (window-height window) (* 2 window-min-height))
3882           ;; At this point, every window on the frame is too small to split.
3883           (setq w2 (display-buffer buf))
3884         (setq w2 (split-window
3885                   window
3886                   (max window-min-height
3887                        (- (window-height window)
3888                           (1+ (max window-min-height target-lines)))))))
3889       (set-window-buffer w2 buf)
3890       (if (< (1- (window-height w2)) target-lines)
3891           (progn
3892             (select-window w2)
3893             (enlarge-window (- target-lines (1- (window-height w2))))))
3894       (set-window-start w2 1))))
3895
3896 (defun dired-mark-pop-up (bufname op-symbol files function &rest args)
3897   ;; Args BUFNAME OP-SYMBOL FILES FUNCTION &rest ARGS.
3898   ;; Return FUNCTION's result on ARGS after popping up a window (in a buffer
3899   ;; named BUFNAME, nil gives \" *Marked Files*\") showing the marked
3900   ;; files.  Uses function `dired-pop-to-buffer' to do that.
3901   ;; FUNCTION should not manipulate files.
3902   ;; It should only read input (an argument or confirmation).
3903   ;; The window is not shown if there is just one file or
3904   ;; OP-SYMBOL is a member of the list in `dired-no-confirm'.
3905   ;; FILES is the list of marked files.
3906   (if (memq op-symbol dired-no-confirm)
3907       (apply function args)
3908     (or bufname (setq bufname  " *Marked Files*"))
3909     (if (<= (length files) 1)
3910         (apply function args)
3911       (save-excursion
3912         (let ((standard-output (set-buffer (get-buffer-create bufname))))
3913           (erase-buffer)
3914           (dired-format-columns-of-files files)
3915           (dired-remove-text-properties (point-min) (point-max))
3916           (setq mode-line-format (format "       %s  [%d files]"
3917                                          bufname (length files)))))
3918       (save-window-excursion
3919         (dired-pop-to-buffer bufname)
3920         (apply function args)))))
3921
3922 (defun dired-column-widths (columns list &optional across)
3923   ;; Returns the column widths for breaking LIST into
3924   ;; COLUMNS number of columns.
3925   (cond
3926    ((null list)
3927     nil)
3928    ((= columns 1)
3929     (list (apply 'max (mapcar 'length list))))
3930    ((let* ((len (length list))
3931            (col-length (/ len columns))
3932            (remainder (% len columns))
3933            (i 0)
3934            (j 0)
3935            (max-width 0)
3936            widths padding)
3937       (if (zerop remainder)
3938           (setq padding 0)
3939         (setq col-length (1+ col-length)
3940               padding (- columns remainder)))
3941       (setq list (nconc (copy-sequence list) (make-list padding nil)))
3942       (setcdr (nthcdr (1- (+ len padding)) list) list)
3943       (while (< i columns)
3944         (while (< j col-length)
3945           (setq max-width (max max-width (length (car list)))
3946                 list (if across (nthcdr columns list) (cdr list))
3947                 j (1+ j)))
3948         (setq widths (cons (+ max-width 2) widths)
3949               max-width 0
3950               j 0
3951               i (1+ i))
3952         (if across (setq list (cdr list))))
3953       (setcar widths (- (car widths) 2))
3954       (nreverse widths)))))
3955
3956 (defun dired-calculate-columns (list &optional across)
3957   ;; Returns a list of integers which are the column widths that best pack
3958   ;; LIST, a list of strings, onto the screen.
3959   (and list
3960        (let* ((width (1- (window-width)))
3961               (columns (max 1 (/ width
3962                                  (+ 2 (apply 'max (mapcar 'length list))))))
3963               col-list last-col-list)
3964          (while (<= (apply '+ (setq col-list
3965                                     (dired-column-widths columns list across)))
3966                     width)
3967            (setq columns (1+ columns)
3968                  last-col-list col-list))
3969          (or last-col-list col-list))))
3970
3971 (defun dired-format-columns-of-files (files &optional across)
3972   ;; Returns the number of lines used.
3973   ;; If ACROSS is non-nil, sorts across rather than down the buffer, like
3974   ;; ls -x
3975   (and files
3976        (let* ((columns (dired-calculate-columns files across))
3977               (ncols (length columns))
3978               (ncols1 (1- ncols))
3979               (nfiles (length files))
3980               (nrows (+ (/ nfiles ncols)
3981                         (if (zerop (% nfiles ncols)) 0 1)))
3982               (space-left (- (window-width) (apply '+ columns) 1))
3983               (i 0)
3984               (j 0)
3985               file padding stretch float-stretch)
3986          (if (zerop ncols1)
3987              (setq stretch 0
3988                    float-stretch 0)
3989            (setq stretch (/ space-left ncols1)
3990                  float-stretch (% space-left ncols1)))
3991          (setq files (nconc (copy-sequence files) ; fill up with empty fns
3992                             (make-list (- (* ncols nrows) nfiles) "")))
3993          (setcdr (nthcdr (1- (length files)) files) files) ; make circular
3994          (while (< j nrows)
3995            (while (< i ncols)
3996              (princ (setq file (car files)))
3997              (setq padding (- (nth i columns) (length file)))
3998              (or (= i ncols1)
3999                  (progn
4000                    (setq padding (+ padding stretch))
4001                    (if (< i float-stretch) (setq padding (1+ padding)))))
4002              (princ (make-string padding ?\ ))
4003              (setq files (if across (cdr files) (nthcdr nrows files))
4004                    i (1+ i)))
4005            (princ "\n")
4006            (setq i 0
4007                  j (1+ j))
4008            (or across (setq files (cdr files))))
4009          nrows)))
4010
4011 (defun dired-query (qs-var qs-prompt &rest qs-args)
4012   ;; Query user and return nil or t.
4013   ;; Store answer in symbol VAR (which must initially be bound to nil).
4014   ;; Format PROMPT with ARGS.
4015   ;; Binding variable help-form will help the user who types C-h.
4016   (let* ((char (symbol-value qs-var))
4017          (action (cdr (assoc char dired-query-alist))))
4018     (cond ((eq 'yes action)
4019            t)                           ; accept, and don't ask again
4020           ((eq 'no action)
4021            nil)                         ; skip, and don't ask again
4022           (t;; no lasting effects from last time we asked - ask now
4023            (let ((qprompt (concat qs-prompt
4024                                   (if help-form
4025                                       (format " [yn!q or %s] "
4026                                               (key-description
4027                                                (char-to-string help-char)))
4028                                     " [ynq or !] ")))
4029                  (dired-in-query t)
4030                  elt)
4031              ;; Actually it looks nicer without cursor-in-echo-area - you can
4032              ;; look at the dired buffer instead of at the prompt to decide.
4033              (apply 'message qprompt qs-args)
4034              (setq char (set qs-var (read-char)))
4035              (while (not (setq elt (assoc char dired-query-alist)))
4036                (message "Invalid char - type %c for help." help-char)
4037                (ding)
4038                (sit-for 1)
4039                (apply 'message qprompt qs-args)
4040                (setq char (set qs-var (read-char))))
4041              (memq (cdr elt) '(t y yes)))))))
4042
4043 (defun dired-mark-confirm (op-symbol operation arg)
4044   ;; Request confirmation from the user that the operation described
4045   ;; by OP-SYMBOL is to be performed on the marked files.
4046   ;; Confirmation consists in a y-or-n question with a file list
4047   ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
4048   ;; OPERATION is a string describing the operation. Used for prompting
4049   ;; the user.
4050   ;; The files used are determined by ARG (like in dired-get-marked-files).
4051   (or (memq op-symbol dired-no-confirm)
4052       (let ((files (dired-get-marked-files t arg)))
4053         (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
4054                            (concat  operation " "
4055                                     (dired-mark-prompt arg files) "? ")))))
4056
4057 (defun dired-mark-read-file-name (prompt dir op-symbol arg files)
4058   (dired-mark-pop-up
4059    nil op-symbol files
4060    (function read-file-name)
4061    (format prompt (dired-mark-prompt arg files)) dir))
4062
4063 (defun dired-mark-read-string (prompt initial op-symbol arg files
4064                                       &optional history-sym)
4065   ;; Reading arguments with history.
4066   ;; Read arguments for a mark command of type OP-SYMBOL,
4067   ;; perhaps popping up the list of marked files.
4068   ;; ARG is the prefix arg and indicates whether the files came from
4069   ;; marks (ARG=nil) or a repeat factor (integerp ARG).
4070   ;; If the current file was used, the list has but one element and ARG
4071   ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
4072   ;; PROMPT for a string, with INITIAL input.
4073   (dired-mark-pop-up
4074    nil op-symbol files
4075    (function
4076     (lambda (prompt initial)
4077       (let ((hist (or history-sym
4078                       (cdr (assq op-symbol dired-op-history-alist))
4079                       'dired-history)))
4080         (dired-read-with-history prompt initial hist))))
4081    (format prompt (dired-mark-prompt arg files)) initial))
4082
4083 \f
4084 ;;;; ----------------------------------------------------------
4085 ;;;; Marking files.
4086 ;;;; ----------------------------------------------------------
4087
4088 (defun dired-mark (arg &optional char)
4089   "Mark the current (or next ARG) files.
4090 If on a subdir headerline, mark all its files except `.' and `..'.
4091
4092 Use \\[dired-unmark-all-files] to remove all marks,
4093 and \\[dired-unmark] to remove the mark of the current file."
4094   (interactive "p")
4095   (if (dired-get-subdir)
4096       (dired-mark-subdir-files char)
4097     (dired-mark-file arg char)))
4098
4099 (defun dired-mark-file (arg &optional char)
4100   "Mark ARG files starting from the current file line.
4101 Optional CHAR indicates a marker character to use."
4102   (let (buffer-read-only)
4103     (if (memq (or char dired-marker-char) '(?\  ?\n ?\r))
4104         (error "Invalid marker character %c" dired-marker-char))
4105     (or char (setq char dired-marker-char))
4106     (dired-repeat-over-lines
4107      arg
4108      (function
4109       (lambda ()
4110         (dired-update-marker-counters (char-after (point)) t)
4111         (dired-substitute-marker (point) (char-after (point)) char)
4112         (dired-update-marker-counters char))))
4113     (dired-update-mode-line-modified)))
4114
4115 (defun dired-mark-subdir-files (&optional char)
4116   "Mark all files except `.' and `..'."
4117   (interactive)
4118   (save-excursion
4119     (dired-mark-files-in-region (dired-subdir-min) (dired-subdir-max) char)))
4120
4121 (defun dired-unmark (arg)
4122   "Unmark the current (or next ARG) files.
4123 If looking at a subdir, unmark all its files except `.' and `..'."
4124   (interactive "p")
4125   (if (dired-get-subdir)
4126       (dired-unmark-subdir-files)
4127     (let (buffer-read-only)
4128       (dired-repeat-over-lines
4129        arg
4130        (function
4131         (lambda ()
4132           (let ((char (char-after (point))))
4133             (or (memq char '(?\  ?\n ?\r))
4134                 (progn
4135                   (cond
4136                    ((char-equal char dired-marker-char)
4137                     (setq dired-marks-number (max (1- dired-marks-number) 0)))
4138                    ((char-equal char dired-del-marker)
4139                     (setq dired-del-flags-number
4140                           (max (1- dired-del-flags-number) 0)))
4141                    ((setq dired-other-marks-number
4142                           (max (1- dired-other-marks-number) 0))))
4143                   (dired-substitute-marker (point) char ?\ )))))))
4144       (dired-update-mode-line-modified))))
4145
4146 (defun dired-unmark-subdir-files ()
4147   "Unmark all files except `.' and `..'."
4148   (interactive)
4149   (save-excursion
4150     (dired-unmark-files-in-region (dired-subdir-min) (dired-subdir-max))))
4151
4152 (defun dired-mark-prefix (&optional arg)
4153   "Mark the next ARG files with the next character typed.
4154 If ARG is negative, marks the previous files."
4155   (interactive "p")
4156   (if (sit-for echo-keystrokes)
4157       (cond
4158        ((or (= arg 1) (zerop arg))
4159         (message "Mark with character?"))
4160        ((< arg 0)
4161         (message "Mark %d file%s moving backwards?"
4162                  (- arg) (dired-plural-s (- arg))))
4163        ((> arg 1)
4164         (message "Mark %d following files with character?" arg))))
4165   (dired-mark arg (read-char)))
4166
4167 (defun dired-change-marks (old new)
4168   "Change all OLD marks to NEW marks.
4169 OLD and NEW are both characters used to mark files.
4170 With a prefix, prompts for a mark to toggle. In other words, all unmarked
4171 files receive that mark, and all files currently marked with that mark become
4172 unmarked."
4173   ;; When used in a lisp program, setting NEW to nil means toggle the mark OLD.
4174   (interactive
4175    (let* ((cursor-in-echo-area t)
4176           (old nil)
4177           (new nil)
4178           (markers (dired-mark-list))
4179           (default (cond ((null markers)
4180                           (error "No markers in buffer"))
4181                          ((= (length markers) 1)
4182                           (setq old (car markers)))
4183                          ((memq dired-marker-char markers)
4184                           dired-marker-char)
4185                          ;; picks the last one in the buffer. reasonable?
4186                          ((car markers)))))
4187      (or old (setq old
4188                    (progn
4189                      (if current-prefix-arg
4190                          (message "Toggle mark (default %c): " default)
4191                        (message "Change old mark (default %c): " default))
4192                      (read-char))))
4193      (if (memq old '(?\  ?\n ?\r)) (setq old default))
4194      (or current-prefix-arg
4195          (setq new (progn
4196                      (message
4197                       "Change %c marks to new mark (RET means abort): " old)
4198                      (read-char))))
4199      (list old new)))
4200   (let ((old-count  (cond
4201                      ((char-equal old dired-marker-char)
4202                       'dired-marks-number)
4203                      ((char-equal old dired-del-marker)
4204                       'dired-del-flags-number)
4205                      ('dired-other-marks-number))))
4206     (if new
4207         (or (memq new '(?\  ?\n ?\r))
4208             ;; \n and \r aren't valid marker chars. Assume that if the
4209             ;; user hits return, he meant to abort the command.
4210             (let ((string (format "\n%c" old))
4211                   (new-count  (cond
4212                                ((char-equal new dired-marker-char)
4213                                 'dired-marks-number)
4214                                ((char-equal new dired-del-marker)
4215                                 'dired-del-flags-number)
4216                                ('dired-other-marks-number)))
4217                   (buffer-read-only nil))
4218               (save-excursion
4219                 (goto-char (point-min))
4220                 (while (search-forward string nil t)
4221                   (if (equal (char-before) old)
4222                       (progn
4223                         (dired-substitute-marker (1- (point)) old new)
4224                         (set new-count (1+ (symbol-value new-count)))
4225                         (set old-count (max (1- (symbol-value old-count)) 0))))
4226                   ))))
4227       (save-excursion
4228         (let ((ucount 0)
4229               (mcount 0)
4230               (buffer-read-only nil))
4231           (goto-char (point-min))
4232           (while (not (eobp))
4233             (or (dired-between-files)
4234                 (looking-at dired-re-dot)
4235                 (cond
4236                  ((equal (char-after (point)) ?\ )
4237                   (setq mcount (1+ mcount))
4238                   (set old-count (1+ (symbol-value old-count)))
4239                   (dired-substitute-marker (point) ?\  old))
4240                  ((equal (char-after (point)) old)
4241                   (setq ucount (1+ ucount))
4242                   (set old-count (max (1- (symbol-value old-count)) 0))
4243                   (dired-substitute-marker (point) old ?\ ))))
4244             (forward-line 1))
4245           (message "Unmarked %d file%s; marked %d file%s with %c."
4246                    ucount (dired-plural-s ucount) mcount
4247                    (dired-plural-s mcount) old)))))
4248   (dired-update-mode-line-modified))
4249
4250 (defun dired-unmark-all-files (flag &optional arg)
4251   "Remove a specific mark or any mark from every file.
4252 With prefix arg, query for each marked file.
4253 Type \\[help-command] at that time for help.
4254 With a zero prefix, only counts the number of marks."
4255   (interactive
4256    (let* ((cursor-in-echo-area t)
4257           executing-kbd-macro) ; for XEmacs
4258      (list (and (not (eq current-prefix-arg 0))
4259                 (progn (message "Remove marks (RET means all): ") (read-char)))
4260            current-prefix-arg)))
4261   (save-excursion
4262     (let* ((help-form "\
4263 Type SPC or `y' to unflag one file, DEL or `n' to skip to next,
4264 `!' to unflag all remaining files with no more questions.")
4265            (allp (memq flag '(?\n ?\r)))
4266            (count-p (eq arg 0))
4267            (count (if (or allp count-p)
4268                       (mapcar
4269                        (function
4270                         (lambda (elt)
4271                         (cons elt 0)))
4272                        (nreverse (dired-mark-list)))
4273                     0))
4274            (msg "")
4275            (no-query (or (not arg) count-p))
4276            buffer-read-only case-fold-search query)
4277       (goto-char (point-min))
4278       (if (or allp count-p)
4279           (while (re-search-forward dired-re-mark nil t)
4280             (if (or no-query
4281                     (dired-query 'query "Unmark file `%s'? "
4282                                  (dired-get-filename t)))
4283                 (let ((ent (assq (char-before) count)))
4284                   (if ent (setcdr ent (1+ (cdr ent))))
4285                   (or count-p (dired-substitute-marker
4286                                (- (point) 1) (char-before) ?\ ))))
4287             (forward-line 1))
4288         (while (search-forward (format "\n%c" flag) nil t)
4289           (if (or no-query
4290                   (dired-query 'query "Unmark file `%s'? "
4291                                (dired-get-filename t)))
4292               (progn
4293                 (dired-substitute-marker (1+ (match-beginning 0)) flag ?\ )
4294                 (setq count (1+ count))))))
4295       (if (or allp count-p)
4296           (mapcar
4297            (function
4298             (lambda (elt)
4299               (or (zerop (cdr elt))
4300                   (setq msg (format "%s%s%d %c%s"
4301                                     msg
4302                                     (if (zerop (length msg))
4303                                         " "
4304                                       ", ")
4305                                     (cdr elt)
4306                                     (car elt)
4307                                     (if (= 1 (cdr elt)) "" "'s"))))))
4308            count)
4309         (or (zerop count)
4310             (setq msg (format " %d %c%s"
4311                               count flag (if (= 1 count) "" "'s")))))
4312       (if (zerop (length msg))
4313           (setq msg " none")
4314         (or count-p (dired-update-mode-line-modified t)))
4315       (message "%s:%s" (if count-p "Number of marks" "Marks removed") msg))))
4316
4317 (defun dired-get-marked-files (&optional localp arg)
4318   "Return the marked files' names as list of strings.
4319 The list is in the same order as the buffer, that is, the car is the
4320   first marked file.
4321 Values returned are normally absolute pathnames.
4322 Optional arg LOCALP as in `dired-get-filename'.
4323 Optional second argument ARG forces to use other files.  If ARG is an
4324   integer, use the next ARG files.  If ARG is otherwise non-nil, use
4325   current file.  Usually ARG comes from the current prefix arg."
4326   (save-excursion
4327     (nreverse (dired-map-over-marks (dired-get-filename localp) arg))))
4328
4329 ;;; Utility functions for marking files
4330
4331 (defun dired-mark-files-in-region (start end &optional char)
4332   (let (buffer-read-only)
4333     (if (> start end)
4334         (error "start > end"))
4335     (goto-char start)                   ; assumed at beginning of line
4336     (or char (setq char dired-marker-char))
4337     (while (< (point) end)
4338       ;; Skip subdir line and following garbage like the `total' line:
4339       (while (and (< (point) end) (dired-between-files))
4340         (forward-line 1))
4341       (if (and (not (equal (char-after (point)) char))
4342                (not (looking-at dired-re-dot))
4343                (save-excursion
4344                  (dired-move-to-filename nil (point))))
4345           (progn
4346             (dired-update-marker-counters (char-after (point)) t)
4347             (dired-substitute-marker (point) (char-after (point)) char)
4348             (dired-update-marker-counters char)))
4349       (forward-line 1)))
4350   (dired-update-mode-line-modified))
4351
4352 (defun dired-unmark-files-in-region (start end)
4353   (let (buffer-read-only)
4354     (if (> start end)
4355         (error "start > end"))
4356     (goto-char start)                   ; assumed at beginning of line
4357     (while (< (point) end)
4358       ;; Skip subdir line and following garbage like the `total' line:
4359       (while (and (< (point) end) (dired-between-files))
4360         (forward-line 1))
4361       (let ((char (char-after (point))))
4362         (or (memq char '(?\  ?\n ?\r))
4363             (progn
4364               (cond
4365                ((char-equal char dired-marker-char)
4366                 (setq dired-marks-number (max (1- dired-marks-number) 0)))
4367                ((char-equal char dired-del-marker)
4368                 (setq dired-del-flags-number
4369                       (max (1- dired-del-flags-number) 0)))
4370                ((setq dired-other-marks-number
4371                       (max (1- dired-other-marks-number) 0))))
4372               (dired-substitute-marker (point) char ?\ ))))
4373       (forward-line 1)))
4374   (dired-update-mode-line-modified))
4375
4376 (defun dired-mark-list ()
4377   ;; Returns a list of all marks currently used in the buffer.
4378   (let ((result nil)
4379         char)
4380     (save-excursion
4381       (goto-char (point-min))
4382       (while (not (eobp))
4383         (and (not (memq (setq char (char-after (point))) '(?\  ?\n ?\r)))
4384              (not (memq char result))
4385              (setq result (cons char result)))
4386         (forward-line 1)))
4387     result))
4388
4389 ;;; Dynamic markers
4390
4391 (defun dired-set-current-marker-string ()
4392   "Computes and returns `dired-marker-string'."
4393   (prog1
4394       (setq dired-marker-string
4395             (if dired-marker-stack
4396                 (let* ((n (+ (length dired-marker-stack) 5))
4397                        (str (make-string n ?\ ))
4398                        (list dired-marker-stack)
4399                        (pointer dired-marker-stack-pointer))
4400                   (setq n (1- n))
4401                   (aset str n ?\])
4402                   (setq n (1- n))
4403                   (while list
4404                     (aset str n (car list))
4405                     (if (zerop pointer)
4406                         (progn
4407                           (setq n (1- n))
4408                           (aset str n dired-marker-stack-cursor)))
4409                     (setq n (1- n)
4410                           pointer (1- pointer)
4411                           list (cdr list)))
4412                   (aset str n dired-default-marker)
4413                   (if (zerop pointer)
4414                       (aset str 2 dired-marker-stack-cursor))
4415                   (aset str 1 ?\[)
4416                   str)
4417               ""))
4418     (set-buffer-modified-p (buffer-modified-p))))
4419
4420 (defun dired-set-marker-char (c)
4421   "Set the marker character to something else.
4422 Use \\[dired-restore-marker-char] to restore the previous value."
4423   (interactive "cNew marker character: ")
4424   (and (memq c '(?\  ?\n ?\r)) (error "invalid marker char %c" c))
4425   (setq dired-marker-stack (cons c dired-marker-stack)
4426         dired-marker-stack-pointer 0
4427         dired-marker-char c)
4428   (dired-update-mode-line-modified t)
4429   (dired-set-current-marker-string))
4430
4431 (defun dired-restore-marker-char ()
4432   "Restore the marker character to its previous value.
4433 Uses `dired-default-marker' if the marker stack is empty."
4434   (interactive)
4435   (setq dired-marker-stack (cdr dired-marker-stack)
4436         dired-marker-char (car dired-marker-stack)
4437         dired-marker-stack-pointer (min dired-marker-stack-pointer
4438                                         (length dired-marker-stack)))
4439   (or dired-marker-char
4440       (setq dired-marker-char dired-default-marker))
4441   (dired-set-current-marker-string)
4442   (dired-update-mode-line-modified t)
4443   (or dired-marker-stack (message "Marker is %c" dired-marker-char)))
4444
4445 (defun dired-marker-stack-left (n)
4446   "Moves the marker stack cursor to the left."
4447   (interactive "p")
4448   (let ((len (1+ (length dired-marker-stack))))
4449     (or dired-marker-stack (error "Dired marker stack is empty."))
4450     (setq dired-marker-stack-pointer
4451           (% (+ dired-marker-stack-pointer n) len))
4452     (if (< dired-marker-stack-pointer 0)
4453         (setq dired-marker-stack-pointer (+ dired-marker-stack-pointer
4454                                             len)))
4455     (dired-set-current-marker-string)
4456     (setq dired-marker-char
4457           (if (= dired-marker-stack-pointer (1- len))
4458               dired-default-marker
4459             (nth dired-marker-stack-pointer dired-marker-stack))))
4460   (dired-update-mode-line-modified t))
4461
4462 (defun dired-marker-stack-right (n)
4463   "Moves the marker stack cursor to the right."
4464   (interactive "p")
4465   (dired-marker-stack-left (- n)))
4466
4467 ;;; Commands to mark or flag files based on their characteristics or names.
4468
4469 (defun dired-mark-symlinks (&optional unflag-p)
4470   "Mark all symbolic links.
4471 With prefix argument, unflag all those files."
4472   (interactive "P")
4473   (dired-check-ls-l)
4474   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
4475     (dired-mark-if (looking-at dired-re-sym) "symbolic link"))
4476   (dired-update-mode-line-modified t))
4477
4478 (defun dired-mark-directories (&optional unflag-p)
4479   "Mark all directory file lines except `.' and `..'.
4480 With prefix argument, unflag all those files."
4481   (interactive "P")
4482   (if dired-re-dir
4483       (progn
4484         (dired-check-ls-l)
4485         (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
4486           (dired-mark-if (and (looking-at dired-re-dir)
4487                               (not (looking-at dired-re-dot)))
4488                          "directory file"))))
4489   (dired-update-mode-line-modified t))
4490
4491 (defun dired-mark-executables (&optional unflag-p)
4492   "Mark all executable files.
4493 With prefix argument, unflag all those files."
4494   (interactive "P")
4495   (if dired-re-exe
4496       (progn
4497         (dired-check-ls-l)
4498         (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
4499           (dired-mark-if (looking-at dired-re-exe) "executable file"))))
4500   (dired-update-mode-line-modified t))
4501
4502 (defun dired-flag-backup-files (&optional unflag-p)
4503   "Flag all backup files (names ending with `~') for deletion.
4504 With prefix argument, unflag these files."
4505   (interactive "P")
4506   (dired-check-ls-l)
4507   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
4508     (dired-mark-if
4509      (and (not (and dired-re-dir (looking-at dired-re-dir)))
4510           (let ((fn (dired-get-filename t t)))
4511             (if fn (backup-file-name-p fn))))
4512      "backup file"))
4513   (dired-update-mode-line-modified t))
4514
4515 (defun dired-flag-auto-save-files (&optional unflag-p)
4516   "Flag for deletion files whose names suggest they are auto save files.
4517 A prefix argument says to unflag those files instead."
4518   (interactive "P")
4519   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
4520     (dired-mark-if
4521      ;; It is less than general to check for ~ here,
4522      ;; but it's the only way this runs fast enough.
4523      (and (save-excursion (end-of-line)
4524                           (equal (char-before) ?#))
4525           (not (and dired-re-dir (looking-at dired-re-dir)))
4526           (let ((fn (dired-get-filename t t)))
4527             (if fn (auto-save-file-name-p
4528                     (file-name-nondirectory fn)))))
4529      "auto save file"))
4530   (dired-update-mode-line-modified t))
4531
4532 (defun dired-mark-rcs-files (&optional unflag-p)
4533   "Mark all files that are under RCS control.
4534 With prefix argument, unflag all those files.
4535 Mentions RCS files for which a working file was not found in this buffer.
4536 Type \\[dired-why] to see them again."
4537   ;; Returns failures, or nil on success.
4538   ;; Finding those with locks would require to peek into the ,v file,
4539   ;; depends slightly on the RCS version used and should be done
4540   ;; together with the Emacs RCS interface.
4541   ;; Unfortunately, there is no definitive RCS interface yet.
4542   (interactive "P")
4543   (message "%sarking RCS controlled files..." (if unflag-p "Unm" "M"))
4544   (let ((dired-marker-char (if unflag-p ?\  dired-marker-char))
4545         rcs-files wf failures count total)
4546     (mapcar                             ; loop over subdirs
4547      (function
4548       (lambda (dir)
4549         (or (equal (file-name-nondirectory (directory-file-name dir))
4550                    "RCS")
4551             ;; skip inserted RCS subdirs
4552             (setq rcs-files
4553                   (append (directory-files dir t ",v\\'") ; *,v and RCS/*,v
4554                           (let ((rcs-dir (expand-file-name "RCS" dir)))
4555                             (if (file-directory-p rcs-dir)
4556                                 (mapcar ; working files from ./RCS are in ./
4557                                  (function
4558                                   (lambda (x)
4559                                     (expand-file-name x dir)))
4560                                  (directory-files
4561                                   (file-name-as-directory rcs-dir)
4562                                   nil ",v\\'"))))
4563                           rcs-files)))))
4564      (mapcar (function car) dired-subdir-alist))
4565     (setq total (length rcs-files))
4566     (while rcs-files
4567       (setq wf (substring (car rcs-files) 0 -2)
4568             rcs-files (cdr rcs-files))
4569       (save-excursion (if (dired-goto-file wf)
4570                           (dired-mark 1) ; giving a prefix avoids checking
4571                                          ; for subdir line.
4572                         (setq failures (cons wf failures)))))
4573     (dired-update-mode-line-modified t)
4574     (if (null failures)
4575         (message "%d RCS file%s %smarked."
4576                  total (dired-plural-s total) (if unflag-p "un" ""))
4577       (setq count (length failures))
4578       (dired-log-summary (buffer-name (current-buffer))
4579                          "RCS working file not found %s" failures)
4580       (message "%d RCS file%s: %d %smarked - %d not found %s."
4581                total (dired-plural-s total) (- total count)
4582                (if unflag-p "un" "") count failures))
4583     failures))
4584
4585 \f
4586 ;;;; ------------------------------------------------------------
4587 ;;;; Logging failures
4588 ;;;; ------------------------------------------------------------
4589
4590 (defun dired-why ()
4591   "Pop up a buffer with error log output from Dired.
4592 A group of errors from a single command ends with a formfeed.
4593 Thus, use \\[backward-page] to find the beginning of a group of errors."
4594   (interactive)
4595   (if (get-buffer dired-log-buffer)
4596       (let ((owindow (selected-window))
4597             (window (display-buffer (get-buffer dired-log-buffer))))
4598         (unwind-protect
4599             (progn
4600               (select-window window)
4601               (goto-char (point-max))
4602               (recenter -1))
4603           (select-window owindow)))))
4604
4605 (defun dired-log (buffer-name log &rest args)
4606   ;; Log a message or the contents of a buffer.
4607   ;; BUFFER-NAME is the name of the dired buffer to which the message applies.
4608   ;; If LOG is a string and there are more args, it is formatted with
4609   ;; those ARGS.  Usually the LOG string ends with a \n.
4610   ;; End each bunch of errors with (dired-log t): this inserts
4611   ;; current time and buffer, and a \f (formfeed).
4612   (or (stringp buffer-name) (setq buffer-name (buffer-name buffer-name)))
4613   (let ((obuf (current-buffer)))
4614     (unwind-protect                     ; want to move point
4615         (progn
4616           (set-buffer (get-buffer-create dired-log-buffer))
4617           (goto-char (point-max))
4618           (let (buffer-read-only)
4619             (cond ((stringp log)
4620                    (insert (if args
4621                                (apply (function format) log args)
4622                              log)))
4623                   ((bufferp log)
4624                    (insert-buffer log))
4625                   ((eq t log)
4626                    (insert "\n\t" (current-time-string)
4627                            "\tBuffer `" buffer-name "'\n\f\n")))))
4628       (set-buffer obuf))))
4629
4630 (defun dired-log-summary (buffer-name string failures)
4631   (message (if failures "%s--type y for details %s"
4632              "%s--type y for details")
4633            string failures)
4634   ;; Log a summary describing a bunch of errors.
4635   (dired-log buffer-name (concat "\n" string))
4636   (if failures (dired-log buffer-name "\n%s" failures))
4637   (dired-log buffer-name t))
4638
4639 \f
4640 ;;;; -------------------------------------------------------
4641 ;;;; Sort mode of dired buffers.
4642 ;;;; -------------------------------------------------------
4643
4644 (defun dired-sort-type (list)
4645   ;; Returns the sort type of LIST, as a symbol.
4646   (let* ((list (reverse list))
4647          (alist (sort
4648                  (mapcar (function
4649                           (lambda (x)
4650                             (cons (length (memq (car x) list)) (cdr x))))
4651                          dired-sort-type-alist)
4652                  (function
4653                   (lambda (x y)
4654                     (> (car x) (car y))))))
4655          (winner (car alist)))
4656     (if (zerop (car winner))
4657         'name
4658       (cdr winner))))
4659
4660 (defun dired-sort-set-modeline (&optional switches)
4661   ;; Set modeline display according to dired-internal-switches.
4662   ;; Modeline display of "by name" or "by date" guarantees the user a
4663   ;; match with the corresponding regexps.  Non-matching switches are
4664   ;; shown literally.
4665   (or switches (setq switches dired-internal-switches))
4666   (setq dired-sort-mode
4667         (if dired-show-ls-switches
4668             (concat " " (dired-make-switches-string
4669                          (or switches dired-internal-switches)))
4670           (concat " by " (and (memq ?r switches) "rev-")
4671                   (symbol-name (dired-sort-type switches)))))
4672   ;; update mode line
4673   (set-buffer-modified-p (buffer-modified-p)))
4674
4675 (defun dired-sort-toggle-or-edit (&optional arg)
4676   "Toggle between sort by date/name for the current subdirectory.
4677
4678 With a 0 prefix argument, simply reports on the current switches.
4679
4680 With a prefix 1 allows the ls switches for the current subdirectory to be
4681 edited.
4682
4683 With a prefix 2 allows the default ls switches for newly inserted
4684 subdirectories to be edited.
4685
4686 With a prefix \\[universal-argument] allows you to sort the entire
4687 buffer by either name or date.
4688
4689 With a prefix \\[universal-argument] \\[universal-argument] allows the default switches
4690 for the entire buffer to be edited, and then reverts the buffer so that all
4691 subdirectories are sorted according to these switches.
4692
4693 Note that although dired allows different ls switches to be used for
4694 different subdirectories, certain combinations of ls switches are incompatible.
4695 If incompatible switches are detected, dired will offer to revert the buffer
4696 to force the ls switches for all subdirectories to a single value.  If you
4697 refuse to revert the buffer, any change of ls switches will be aborted."
4698   (interactive "P")
4699   (cond
4700    ((eq arg 0)
4701     ;; Report on switches
4702     (message "Switches for current subdir: %s.  Default for buffer: %s."
4703              (dired-make-switches-string
4704               (nth 3 (assoc (dired-current-directory) dired-subdir-alist)))
4705               (dired-make-switches-string dired-internal-switches)))
4706    ((null arg)
4707     ;; Toggle between sort by date/name.
4708     (let* ((dir (dired-current-directory))
4709            (curr (nth 3 (assoc dir dired-subdir-alist))))
4710       (dired-sort-other
4711        (if (eq (dired-sort-type curr) 'name)
4712            (cons ?t curr)
4713          (mapcar (function
4714                   (lambda (x)
4715                     (setq curr
4716                           (delq (car x) curr))))
4717                  dired-sort-type-alist)
4718          curr)
4719        nil dir)))
4720    ((eq arg 1)
4721     ;; Edit switches for current subdir.
4722     (let* ((dir (dired-current-directory))
4723            (switch-string
4724             (read-string
4725              "New ls switches for current subdir (must contain -l): "
4726              (dired-make-switches-string
4727               (nth 3 (assoc dir dired-subdir-alist)))))
4728            (switches (dired-make-switches-list switch-string)))
4729       (if (dired-compatible-switches-p switches dired-internal-switches)
4730           (dired-sort-other switches nil dir)
4731         (if (or
4732              (memq 'sort-revert dired-no-confirm)
4733              (y-or-n-p
4734               (format
4735                "Switches %s incompatible with default %s.  Revert buffer? "
4736                  switch-string
4737                  (dired-make-switches-string dired-internal-switches))))
4738             (dired-sort-other switches nil nil)
4739           (error "Switches unchanged.  Remain as %s." switch-string)))))
4740    ((eq arg 2)
4741     ;; Set new defaults for subdirs inserted in the future.
4742     (let* ((switch-string
4743             (read-string
4744              "Default ls switches for new subdirs (must contain -l): "
4745              (dired-make-switches-string dired-internal-switches)))
4746            (switches (dired-make-switches-list switch-string))
4747            (alist dired-subdir-alist)
4748            x bad-switches)
4749       (while alist
4750         (setq x (nth 3 (car alist))
4751               alist (cdr alist))
4752         (or (dired-compatible-switches-p x switches)
4753             (member x bad-switches)
4754             (setq bad-switches (cons x bad-switches))))
4755       (if bad-switches
4756           (if (or (memq 'sort-revert dired-no-confirm)
4757                   (y-or-n-p
4758                    (format
4759                     "Switches %s incompatible with %s.  Revert buffer? "
4760                     switch-string (mapconcat 'dired-make-switches-string
4761                                               bad-switches ", "))))
4762               (dired-sort-other switches nil nil)
4763             (error "Default switches unchanged.  Remain as %s."
4764                    (dired-make-switches-string dired-internal-switches)))
4765         (dired-sort-other switches t nil))))
4766    ((or (equal arg '(4)) (eq arg 'date) (eq arg 'name))
4767     ;; Toggle the entire buffer name/data.
4768     (let ((cursor-in-echo-area t)
4769           (switches (copy-sequence dired-internal-switches))
4770           (type (and (symbolp arg) arg))
4771           char)
4772       (while (null type)
4773         (message "Sort entire buffer according to (n)ame or (d)ate? ")
4774         (setq char (read-char)
4775               type (cond
4776                     ((char-equal char ?d) 'date)
4777                     ((char-equal char ?n) 'name)
4778                     (t (message "Type one of n or d.") (sit-for 1) nil))))
4779       (mapcar (function
4780                (lambda (x)
4781                  (setq switches
4782                        (delq (car x) switches))))
4783               dired-sort-type-alist)
4784       (dired-sort-other
4785        (if (eq type 'date) (cons ?t switches) switches) nil nil)))
4786    ((equal arg '(16))
4787     ;; Edit the switches for the entire buffer.
4788     (dired-sort-other
4789      (dired-make-switches-list
4790       (read-string
4791        "Change ls switches for entire buffer to (must contain -l): "
4792        (dired-make-switches-string dired-internal-switches)))
4793      nil nil))
4794    (t
4795     ;; No idea what's going on.
4796     (error
4797      "Invalid prefix.  See %s dired-sort-toggle-or-edit."
4798      (substitute-command-keys
4799       (if (featurep 'ehelp)
4800           "\\[electric-describe-function]"
4801         "\\[describe-function]"))))))
4802
4803 (defun dired-sort-other (switches &optional no-revert subdir)
4804   ;; Specify new ls SWITCHES for current dired buffer.
4805   ;; With optional second arg NO-REVERT, don't refresh the listing afterwards.
4806   ;; If subdir is non-nil, only changes the switches for the
4807   ;; sudirectory.
4808   (dired-build-subdir-alist)
4809   (if subdir
4810       (let ((elt (assoc subdir dired-subdir-alist)))
4811         (if elt (setcar (nthcdr 3 elt) switches)))
4812     (setq dired-internal-switches switches))
4813   (or no-revert
4814       (cond
4815
4816        (subdir
4817         (let ((ofile (dired-get-filename nil t))
4818               (opoint (point)))
4819           (message "Relisting %s..." subdir)
4820           (dired-insert-subdir subdir switches)
4821           (message "Relisting %s... done" subdir)
4822           (or (and ofile (dired-goto-file ofile)) (goto-char opoint))))
4823
4824        ((memq ?R switches)
4825         ;; We are replacing a buffer with a giant recursive listing.
4826         (let ((opoint (point))
4827               (ofile (dired-get-filename nil t))
4828               (hidden-subdirs (dired-remember-hidden))
4829               (mark-alist (dired-remember-marks (point-min) (point-max)))
4830               (kill-files-p (save-excursion
4831                               (goto-char (point))
4832                               (search-forward
4833                                (concat (char-to-string ?\r)
4834                                        (regexp-quote
4835                                         (char-to-string
4836                                          dired-kill-marker-char)))
4837                                nil t)))
4838               (omit-files (nth 2 (nth (1- (length dired-subdir-alist))
4839                                       dired-subdir-alist)))
4840               buffer-read-only)
4841           (dired-readin dired-directory (current-buffer)
4842                         (or (consp dired-directory)
4843                             (null (file-directory-p dired-directory))))
4844           (dired-mark-remembered mark-alist)    ; mark files that were marked
4845           (if kill-files-p (dired-do-hide dired-kill-marker-char))
4846           (if omit-files
4847               (dired-omit-expunge nil t))
4848           ;; hide subdirs that were hidden
4849           (save-excursion
4850             (mapcar (function (lambda (dir)
4851                                 (if (dired-goto-subdir dir)
4852                                     (dired-hide-subdir 1))))
4853                     hidden-subdirs))
4854           ;; Try to get back to where we were
4855           (or (and ofile (dired-goto-file ofile))
4856               (goto-char opoint))
4857           (dired-move-to-filename)))
4858
4859        (t
4860         ;; Clear all switches in the subdir alist
4861         (setq dired-subdir-alist
4862               (mapcar (function
4863                        (lambda (x)
4864                          (setcar (nthcdr 3 x) nil)
4865                          x))
4866                       dired-subdir-alist))
4867         (revert-buffer nil t))))
4868   (dired-update-mode-line t))
4869
4870 (defun dired-compatible-switches-p (list1 list2)
4871   ;; Returns t if list1 and list2 are allowed as switches in the same
4872   ;; dired buffer.
4873   (and (eq (null (or (memq ?l list1) (memq ?o list1) (memq ?g list1)))
4874            (null (or (memq ?l list2) (memq ?o list2) (memq ?g list2))))
4875        (eq (null (memq ?F list1)) (null (memq ?F list2)))
4876        (eq (null (memq ?p list1)) (null (memq ?p list2)))
4877        (eq (null (memq ?b list1)) (null (memq ?b list2)))))
4878
4879 (defun dired-check-ls-l (&optional switches)
4880   ;; Check for long-style listings
4881   (let ((switches (or switches dired-internal-switches)))
4882     (or (memq ?l switches) (memq ?o switches) (memq ?g switches)
4883         (error "Dired needs -l, -o, or -g in ls switches"))))
4884
4885 \f
4886 ;;;; --------------------------------------------------------------
4887 ;;;; Creating new files.
4888 ;;;; --------------------------------------------------------------
4889 ;;;
4890 ;;;  The dired-create-files paradigm is used for copying, renaming,
4891 ;;;  compressing, and making hard and soft links.
4892
4893 (defun dired-file-marker (file)
4894   ;; Return FILE's marker, or nil if unmarked.
4895   (save-excursion
4896     (and (dired-goto-file file)
4897          (progn
4898            (skip-chars-backward "^\n\r")
4899            (and (not (= ?\040 (char-after (point))))
4900                 (char-after (point)))))))
4901
4902 ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
4903 (defun dired-create-files (file-creator operation fn-list name-constructor
4904                                         &optional marker-char query
4905                                         implicit-to)
4906   ;; Create a new file for each from a list of existing files.  The user
4907   ;; is queried, dired buffers are updated, and at the end a success or
4908   ;; failure message is displayed
4909
4910   ;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
4911   ;; It is called for each file and must create newfile, the entry of
4912   ;; which will be added.  The user will be queried if the file already
4913   ;; exists.  If oldfile is removed by FILE-CREATOR (i.e, it is a
4914   ;; rename), it is FILE-CREATOR's responsibility to update dired
4915   ;; buffers.  FILE-CREATOR must abort by signalling a file-error if it
4916   ;; could not create newfile.  The error is caught and logged.
4917
4918   ;; OPERATION (a capitalized string, e.g. `Copy') describes the
4919   ;; operation performed.  It is used for error logging.
4920
4921   ;; FN-LIST is the list of files to copy (full absolute pathnames).
4922
4923   ;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
4924   ;; skip.  If it skips files, it is supposed to tell why (using dired-log).
4925
4926   ;; Optional MARKER-CHAR is a character with which to mark every
4927   ;; newfile's entry, or t to use the current marker character if the
4928   ;; oldfile was marked.
4929
4930   ;; QUERY is a function to use to prompt the user about creating a file.
4931   ;; It accepts two  args, the from and to files,
4932   ;; and must return nil or t. If QUERY is nil, then no user
4933   ;; confirmation will be requested.
4934
4935   ;; If IMPLICIT-TO is non-nil, then the file constructor does not take
4936   ;; a to-file arg. e.g. compress.
4937
4938   (let ((success-count 0)
4939         (total (length fn-list))
4940         failures skipped overwrite-query)
4941     ;; Fluid vars used for storing responses of previous queries must be
4942     ;; initialized.
4943     (dired-save-excursion
4944       (setq dired-overwrite-backup-query nil
4945             dired-file-creator-query nil)
4946       (mapcar
4947        (function
4948         (lambda (from)
4949           (let ((to (funcall name-constructor from)))
4950             (if to
4951                 (if (equal to from)
4952                     (progn
4953                       (dired-log (buffer-name (current-buffer))
4954                                  "Cannot %s to same file: %s\n"
4955                                  (downcase operation) from)
4956                       (setq skipped (cons (dired-make-relative from) skipped)))
4957                   (if (or (null query)
4958                           (funcall query from to))
4959                       (let* ((overwrite (let (jka-compr-enabled)
4960                                           ;; Don't let jka-compr fool us.
4961                                           (file-exists-p to)))
4962                              ;; for dired-handle-overwrite
4963                              (dired-overwrite-confirmed
4964                               (and overwrite
4965                                    (let ((help-form '(format "\
4966 Type SPC or `y' to overwrite file `%s',
4967 DEL or `n' to skip to next,
4968 ESC or `q' to not overwrite any of the remaining files,
4969 `!' to overwrite all remaining files with no more questions." to)))
4970                                      (dired-query 'overwrite-query
4971                                                   "Overwrite %s?" to))))
4972                              ;; must determine if FROM is marked before
4973                              ;; file-creator gets a chance to delete it
4974                              ;; (in case of a move).
4975                              (actual-marker-char
4976                               (cond  ((characterp marker-char) marker-char)
4977                                      (marker-char (dired-file-marker from))
4978                                      (t nil))))
4979                         (if (and overwrite (null dired-overwrite-confirmed))
4980                             (setq skipped (cons (dired-make-relative from)
4981                                                 skipped))
4982                           (condition-case err
4983                               (let ((dired-unhandle-add-files
4984                                      (cons to dired-unhandle-add-files)))
4985                                 (if implicit-to
4986                                     (funcall file-creator from
4987                                              dired-overwrite-confirmed)
4988                                   (funcall file-creator from to
4989                                            dired-overwrite-confirmed))
4990                                 (setq success-count (1+ success-count))
4991                                 (message "%s: %d of %d"
4992                                          operation success-count total)
4993                                 (dired-add-file to actual-marker-char))
4994                             (file-error         ; FILE-CREATOR aborted
4995                              (progn
4996                                (setq failures (cons (dired-make-relative from)
4997                                                     failures))
4998                                (dired-log (buffer-name (current-buffer))
4999                                           "%s `%s' to `%s' failed:\n%s\n"
5000                                           operation from to err))))))
5001                     (setq skipped (cons (dired-make-relative from) skipped))))
5002               (setq skipped (cons (dired-make-relative from) skipped))))))
5003        fn-list)
5004       (cond
5005        (failures
5006         (dired-log-summary
5007          (buffer-name (current-buffer))
5008          (format "%s failed for %d of %d file%s"
5009                  operation (length failures) total
5010                  (dired-plural-s total)) failures))
5011        (skipped
5012         (dired-log-summary
5013          (buffer-name (current-buffer))
5014          (format "%s: %d of %d file%s skipped"
5015                  operation (length skipped) total
5016                  (dired-plural-s total)) skipped))
5017        (t
5018         (message "%s: %s file%s."
5019                  operation success-count (dired-plural-s success-count)))))))
5020
5021 (defun dired-do-create-files (op-symbol file-creator operation arg
5022                                              &optional marker-char
5023                                              prompter how-to)
5024   ;; Create a new file for each marked file.
5025   ;; Prompts user for target, which is a directory in which to create
5026   ;;   the new files.  Target may be a plain file if only one marked
5027   ;;   file exists.
5028   ;; OP-SYMBOL is the symbol for the operation.  Function `dired-mark-pop-up'
5029   ;;   will determine whether pop-ups are appropriate for this OP-SYMBOL.
5030   ;; FILE-CREATOR and OPERATION as in dired-create-files.
5031   ;; ARG as in dired-get-marked-files.
5032   ;; PROMPTER is a function of one-arg, the list of files, to return a prompt
5033   ;;     to use for dired-read-file-name. If it is nil, then a default prompt
5034   ;;     will be used.
5035   ;; Optional arg MARKER-CHAR as in dired-create-files.
5036   ;; Optional arg HOW-TO determines how to treat target:
5037   ;;   If HOW-TO is not given (or nil), and target is a directory, the
5038   ;;     file(s) are created inside the target directory.  If target
5039   ;;     is not a directory, there must be exactly one marked file,
5040   ;;     else error.
5041   ;;   If HOW-TO is t, then target is not modified.  There must be
5042   ;;     exactly one marked file, else error.
5043   ;; Else HOW-TO is assumed to be a function of one argument, target,
5044   ;;     that looks at target and returns a value for the into-dir
5045   ;;     variable.  The function dired-into-dir-with-symlinks is provided
5046   ;;     for the case (common when creating symlinks) that symbolic
5047   ;;     links to directories are not to be considered as directories
5048   ;;     (as file-directory-p would if HOW-TO had been nil).
5049
5050   (let* ((fn-list (dired-get-marked-files nil arg))
5051          (fn-count (length fn-list))
5052          (cdir (dired-current-directory))
5053          (target (expand-file-name
5054                    (dired-mark-read-file-name
5055                     (if prompter
5056                         (funcall prompter fn-list)
5057                       (concat operation " %s to: "))
5058                     (dired-dwim-target-directory)
5059                     op-symbol arg (mapcar (function
5060                                            (lambda (fn)
5061                                              (dired-make-relative fn cdir t)))
5062                                           fn-list))))
5063          (into-dir (cond ((null how-to) (file-directory-p target))
5064                          ((eq how-to t) nil)
5065                          (t (funcall how-to target)))))
5066     (if (and (> fn-count 1)
5067              (not into-dir))
5068         (error "Marked %s: target must be a directory: %s" operation target))
5069     ;; rename-file bombs when moving directories unless we do this:
5070     (or into-dir (setq target (directory-file-name target)))
5071     (dired-create-files
5072      file-creator operation fn-list
5073      (if into-dir                       ; target is a directory
5074          (list 'lambda '(from)
5075                (list 'expand-file-name '(file-name-nondirectory from) target))
5076        (list 'lambda '(from) target))
5077      marker-char)))
5078
5079 (defun dired-into-dir-with-symlinks (target)
5080   (and (file-directory-p target)
5081        (not (file-symlink-p target))))
5082 ;; This may not always be what you want, especially if target is your
5083 ;; home directory and it happens to be a symbolic link, as is often the
5084 ;; case with NFS and automounters.  Or if you want to make symlinks
5085 ;; into directories that themselves are only symlinks, also quite
5086 ;; common.
5087 ;; So we don't use this function as value for HOW-TO in
5088 ;; dired-do-symlink, which has the minor disadvantage of
5089 ;; making links *into* a symlinked-dir, when you really wanted to
5090 ;; *overwrite* that symlink.  In that (rare, I guess) case, you'll
5091 ;; just have to remove that symlink by hand before making your marked
5092 ;; symlinks.
5093
5094 (defun dired-handle-overwrite (to)
5095   ;; Save old version of a to be overwritten file TO.
5096   ;; `dired-overwrite-confirmed' and `dired-overwrite-backup-query'
5097   ;; are fluid vars from dired-create-files.
5098   (if (and dired-backup-if-overwrite
5099            dired-overwrite-confirmed
5100            (or (eq 'always dired-backup-if-overwrite)
5101                (dired-query 'dired-overwrite-backup-query
5102                         (format "Make backup for existing file `%s'? " to))))
5103       (let ((backup (car (find-backup-file-name to))))
5104         (rename-file to backup 0))))    ; confirm overwrite of old backup
5105
5106 (defun dired-dwim-target-directory ()
5107   ;; Try to guess which target directory the user may want.
5108   ;; If there is a dired buffer displayed in the next window, use
5109   ;; its current subdir, else use current subdir of this dired buffer.
5110   ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
5111   (let* ((this-dir (and (eq major-mode 'dired-mode)
5112                         (dired-current-directory)))
5113          (dwimmed
5114           (if dired-dwim-target
5115               (let* ((other-buf (window-buffer (next-window)))
5116                      (other-dir (save-excursion
5117                                   (set-buffer other-buf)
5118                                   (and (eq major-mode 'dired-mode)
5119                                        (dired-current-directory)))))
5120                 (or other-dir this-dir))
5121             this-dir)))
5122     (and dwimmed (dired-abbreviate-file-name dwimmed))))
5123
5124 (defun dired-get-target-directory ()
5125   "Writes a copy of the current subdirectory into an active minibuffer."
5126   (interactive)
5127   (let ((mb (dired-get-active-minibuffer-window)))
5128     (if mb
5129         (let ((dir (dired-current-directory)))
5130           (select-window mb)
5131           (set-buffer (window-buffer mb))
5132           (erase-buffer)
5133           (insert dir))
5134       (error "No active minibuffer"))))
5135
5136 ;;; Copying files
5137
5138 (defun dired-do-copy (&optional arg)
5139   "Copy all marked (or next ARG) files, or copy the current file.
5140 When operating on just the current file, you specify the new name.
5141 When operating on multiple or marked files, you specify a directory
5142 and the files are copied into that directory, retaining the same file names.
5143
5144 A zero prefix argument copies nothing.  But it toggles the
5145 variable `dired-copy-preserve-time' (which see)."
5146   (interactive "P")
5147   (if (not (zerop (prefix-numeric-value arg)))
5148       (dired-do-create-files 'copy (function dired-copy-file)
5149                                (if dired-copy-preserve-time "Copy [-p]" "Copy")
5150                                arg dired-keep-marker-copy)
5151     (setq dired-copy-preserve-time (not dired-copy-preserve-time))
5152     (if dired-copy-preserve-time
5153         (message "Copy will preserve time.")
5154       (message "Copied files will get current date."))))
5155
5156 (defun dired-copy-file (from to ok-flag)
5157   (dired-handle-overwrite to)
5158   (dired-copy-file-recursive (function copy-file)
5159                              from to ok-flag dired-copy-preserve-time t))
5160
5161 (defun dired-copy-file-recursive (copy-file
5162                                   from to ok-flag &optional
5163                                   preserve-time top no-confirm-recursive)
5164   (if (and (eq t (car (file-attributes from))) ; A directory, no symbolic link.
5165            (or (memq 'recursive-copy dired-no-confirm)
5166                no-confirm-recursive
5167                (funcall dired-copy-confirmer
5168                         (format "Recursive copies of %s? " from))))
5169       (let ((files (directory-files from)))
5170         (if (file-exists-p to)
5171             (or top (dired-handle-overwrite to))
5172           (make-directory to))
5173         (while files
5174           (let ((file (car files)))
5175             (if (not (member (file-name-nondirectory file)
5176                              '("." "..")))
5177                 (dired-copy-file-recursive
5178                  copy-file
5179                  (expand-file-name file from)
5180                  (expand-file-name file to)
5181                  ok-flag preserve-time nil t)))
5182           (setq files (cdr files))))
5183     (or top (dired-handle-overwrite to)) ; Just a file.
5184     (funcall copy-file from to ok-flag preserve-time)))
5185
5186 ;;; Renaming/moving files
5187
5188 (defun dired-do-rename (&optional arg)
5189   "Rename current file or all marked (or next ARG) files.
5190 When renaming just the current file, you specify the new name.
5191 When renaming multiple or marked files, you specify a directory.
5192
5193 A zero ARG moves no files but toggles `dired-dwim-target' (which see)."
5194   (interactive "P")
5195   (if (not (zerop (prefix-numeric-value arg)))
5196       (dired-do-create-files 'move (function dired-rename-file)
5197                                "Move" arg dired-keep-marker-rename
5198                                (function
5199                                 (lambda (list)
5200                                   (if (= (length list) 1)
5201                                       "Rename %s to: "
5202                                     "Move %s to: "))))
5203     (setq dired-dwim-target (not dired-dwim-target))
5204     (message "dired-dwim-target is %s." (if dired-dwim-target "ON" "OFF"))))
5205
5206 (defun dired-rename-file (from to ok-flag)
5207   (dired-handle-overwrite to)
5208   (let ((insert (assoc (file-name-as-directory from) dired-subdir-alist)))
5209     (rename-file from to ok-flag) ; error is caught in -create-files
5210     ;; Silently rename the visited file of any buffer visiting this file.
5211     (dired-rename-update-buffers from to insert)))
5212
5213 (defun dired-rename-update-buffers (from to &optional insert)
5214   (if (get-file-buffer from)
5215       (save-excursion
5216         (set-buffer (get-file-buffer from))
5217         (let ((modflag (buffer-modified-p)))
5218           (set-visited-file-name to)    ; kills write-file-hooks
5219           (set-buffer-modified-p modflag)))
5220     ;; It's a directory.  More work to do.
5221     (let ((blist (buffer-list))
5222           (from-dir (file-name-as-directory from))
5223           (to-dir (file-name-as-directory to)))
5224       (save-excursion
5225         (while blist
5226           (set-buffer (car blist))
5227           (setq blist (cdr blist))
5228           (cond
5229            (buffer-file-name
5230             (if (dired-in-this-tree buffer-file-name from-dir)
5231                 (let ((modflag (buffer-modified-p)))
5232                   (unwind-protect
5233                       (set-visited-file-name
5234                        (concat to-dir (substring buffer-file-name
5235                                                  (length from-dir))))
5236                     (set-buffer-modified-p modflag)))))
5237            (dired-directory
5238             (if (string-equal from-dir (expand-file-name default-directory))
5239                 ;; If top level directory was renamed, lots of things
5240                 ;; have to be updated.
5241                 (progn
5242                   (dired-unadvertise from-dir)
5243                   (setq default-directory to-dir
5244                         dired-directory
5245                         ;; Need to beware of wildcards.
5246                         (expand-file-name
5247                          (file-name-nondirectory dired-directory)
5248                          to-dir))
5249                   (let ((new-name (file-name-nondirectory
5250                                    (directory-file-name dired-directory))))
5251                     ;; Try to rename buffer, but just leave old name if new
5252                     ;; name would already exist (don't try appending "<%d>")
5253                     ;; Why?  --sandy 19-8-94
5254                     (or (get-buffer new-name)
5255                         (rename-buffer new-name)))
5256                   (dired-advertise))
5257               (and insert
5258                    (assoc (file-name-directory (directory-file-name to))
5259                           dired-subdir-alist)
5260                    (dired-insert-subdir to))))))))))
5261
5262 ;;; Making symbolic links
5263
5264 (defun dired-do-symlink (&optional arg)
5265   "Make symbolic links to current file or all marked (or next ARG) files.
5266 When operating on just the current file, you specify the new name.
5267 When operating on multiple or marked files, you specify a directory
5268 and new symbolic links are made in that directory
5269 with the same names that the files currently have."
5270   (interactive "P")
5271   (dired-do-create-files 'symlink (function make-symbolic-link)
5272                            "SymLink" arg dired-keep-marker-symlink))
5273
5274 ;; Relative symlinks:
5275 ;; make-symbolic no longer expands targets (as of at least 18.57),
5276 ;; so the code to call ln has been removed.
5277
5278 (defun dired-do-relsymlink (&optional arg)
5279   "Symlink all marked (or next ARG) files into a directory,
5280 or make a symbolic link to the current file.
5281 This creates relative symbolic links like
5282
5283     foo -> ../bar/foo
5284
5285 not absolute ones like
5286
5287     foo -> /ugly/path/that/may/change/any/day/bar/foo"
5288   (interactive "P")
5289   (dired-do-create-files 'relsymlink (function dired-make-relative-symlink)
5290                          "RelSymLink" arg dired-keep-marker-symlink))
5291
5292 (defun dired-make-relative-symlink (target linkname
5293                                            &optional ok-if-already-exists)
5294   "Make a relative symbolic link pointing to TARGET with name LINKNAME.
5295 Three arguments: FILE1 FILE2 &optional OK-IF-ALREADY-EXISTS
5296 The link is relative (if possible), for example
5297
5298     \"/vol/tex/bin/foo\" \"/vol/local/bin/foo\"
5299
5300 results in
5301
5302     \"../../tex/bin/foo\" \"/vol/local/bin/foo\""
5303   (interactive
5304    (let ((target (read-string "Make relative symbolic link to file: ")))
5305      (list
5306       target
5307       (read-file-name (format "Make relsymlink to file %s: " target))
5308       0)))
5309   (let* ((target (expand-file-name target))
5310          (linkname (expand-file-name linkname))
5311          (handler (or (find-file-name-handler
5312                        linkname 'dired-make-relative-symlink)
5313                       (find-file-name-handler
5314                        target 'dired-make-relative-symlink))))
5315     (if handler
5316         (funcall handler 'dired-make-relative-symlink target linkname
5317                  ok-if-already-exists)
5318       (setq target (directory-file-name target)
5319             linkname (directory-file-name linkname))
5320       (make-symbolic-link
5321        (dired-make-relative target (file-name-directory linkname) t)
5322        linkname ok-if-already-exists))))
5323
5324 ;;; Hard links -- adding names to files
5325
5326 (defun dired-do-hardlink (&optional arg)
5327   "Add names (hard links) current file or all marked (or next ARG) files.
5328 When operating on just the current file, you specify the new name.
5329 When operating on multiple or marked files, you specify a directory
5330 and new hard links are made in that directory
5331 with the same names that the files currently have."
5332   (interactive "P")
5333   (dired-do-create-files 'hardlink (function add-name-to-file)
5334                            "HardLink" arg dired-keep-marker-hardlink))
5335
5336 \f
5337 ;;;; ---------------------------------------------------------------
5338 ;;;; Running process on marked files
5339 ;;;; ---------------------------------------------------------------
5340 ;;;
5341 ;;;  Commands for shell processes are in dired-shell.el.
5342
5343 ;;; Internal functions for running subprocesses,
5344 ;;; checking and logging of their errors.
5345
5346 (defun dired-call-process (program discard &rest arguments)
5347   ;; Run PROGRAM with output to current buffer unless DISCARD is t.
5348   ;; Remaining arguments are strings passed as command arguments to PROGRAM.
5349   ;; Returns program's exit status, as an integer.
5350   ;; This is a separate function so that efs can redefine it.
5351   (let ((return
5352          (apply 'call-process program nil (not discard) nil arguments)))
5353     (if (and (not (equal shell-file-name program))
5354              (integerp return))
5355         return
5356       ;; Fudge return code by looking for errors in current buffer.
5357       (if (zerop (buffer-size)) 0 1))))
5358
5359 (defun dired-check-process (msg program &rest arguments)
5360   ;; Display MSG while running PROGRAM, and check for output.
5361   ;; Remaining arguments are strings passed as command arguments to PROGRAM.
5362   ;; On error, insert output in a log buffer and return the
5363   ;; offending ARGUMENTS or PROGRAM.
5364   ;; Caller can cons up a list of failed args.
5365   ;; Else returns nil for success.
5366   (let ((err-buffer (get-buffer-create " *dired-check-process output*"))
5367         (dir default-directory))
5368     (message "%s..." msg)
5369     (save-excursion
5370       ;; Get a clean buffer for error output:
5371       (set-buffer err-buffer)
5372       (erase-buffer)
5373       (setq default-directory dir)      ; caller's default-directory
5374       (if (not
5375            (eq 0 (apply (function dired-call-process) program nil arguments)))
5376           (progn
5377             (dired-log (buffer-name (current-buffer))
5378                        (concat program " " (prin1-to-string arguments) "\n"))
5379             (dired-log (buffer-name (current-buffer)) err-buffer)
5380             (or arguments program t))
5381         (kill-buffer err-buffer)
5382         (message "%s...done" msg)
5383         nil))))
5384
5385 ;;; Changing file attributes
5386
5387 (defun dired-do-chxxx (attribute-name program op-symbol arg)
5388   ;; Change file attributes (mode, group, owner) of marked files and
5389   ;; refresh their file lines.
5390   ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
5391   ;; PROGRAM is the program used to change the attribute.
5392   ;; OP-SYMBOL is the type of operation (for use in dired-mark-pop-up).
5393   ;; ARG describes which files to use, like in dired-get-marked-files.
5394   (let* ((files (dired-get-marked-files t arg))
5395          (new-attribute
5396           (dired-mark-read-string
5397            (concat "Change " attribute-name " of %s to: ")
5398            nil op-symbol arg files))
5399          (operation (concat program " " new-attribute))
5400          (failures
5401           (dired-bunch-files 10000 (function dired-check-process)
5402                              (list operation program new-attribute)
5403                              files)))
5404     (dired-do-redisplay arg);; moves point if ARG is an integer
5405     (if failures
5406         (dired-log-summary (buffer-name (current-buffer))
5407                            (format "%s: error" operation) nil))))
5408
5409 (defun dired-do-chmod (&optional arg)
5410   "Change the mode of the marked (or next ARG) files.
5411 This calls chmod, thus symbolic modes like `g+w' are allowed."
5412   (interactive "P")
5413   (dired-do-chxxx "Mode" "chmod" 'chmod arg))
5414
5415 (defun dired-do-chgrp (&optional arg)
5416   "Change the group of the marked (or next ARG) files."
5417   (interactive "P")
5418   (dired-do-chxxx "Group" "chgrp" 'chgrp arg))
5419
5420 (defun dired-do-chown (&optional arg)
5421   "Change the owner of the marked (or next ARG) files."
5422   (interactive "P")
5423   (dired-do-chxxx "Owner" dired-chown-program 'chown arg))
5424
5425 ;;; Utilities for running processes on marked files.
5426
5427 ;; Process all the files in FILES in batches of a convenient size,
5428 ;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).
5429 ;; Batches are chosen to need less than MAX chars for the file names,
5430 ;; allowing 3 extra characters of separator per file name.
5431 (defun dired-bunch-files (max function args files)
5432   (let (pending
5433         (pending-length 0)
5434         failures)
5435     ;; Accumulate files as long as they fit in MAX chars,
5436     ;; then process the ones accumulated so far.
5437     (while files
5438       (let* ((thisfile (car files))
5439              (thislength (+ (length thisfile) 3))
5440              (rest (cdr files)))
5441         ;; If we have at least 1 pending file
5442         ;; and this file won't fit in the length limit, process now.
5443         (if (and pending (> (+ thislength pending-length) max))
5444             (setq failures
5445                   (nconc (apply function (append args pending))
5446                          failures)
5447                   pending nil
5448                   pending-length 0))
5449         ;; Do (setq pending (cons thisfile pending))
5450         ;; but reuse the cons that was in `files'.
5451         (setcdr files pending)
5452         (setq pending files)
5453         (setq pending-length (+ thislength pending-length))
5454         (setq files rest)))
5455     (nconc (apply function (append args pending))
5456            failures)))
5457
5458 \f
5459 ;;;; ---------------------------------------------------------------
5460 ;;;; Calculating data or properties for marked files.
5461 ;;;; ---------------------------------------------------------------
5462
5463 (defun dired-do-total-size (&optional arg)
5464   "Show total size of all marked (or next ARG) files."
5465   (interactive "P")
5466   (let* ((result (dired-map-over-marks (dired-get-file-size) arg))
5467          (total (apply (function +) result))
5468          (num (length result)))
5469     (message "%d bytes (%d kB) in %s file%s"
5470              total (/ total 1024) num (dired-plural-s num))
5471     total))
5472
5473 (defun dired-get-file-size ()
5474   ;; Returns the file size in bytes of the current file, as an integer.
5475   ;; Assumes that it is on a valid file line. It's the caller's responsibility
5476   ;; to ensure this.
5477   (beginning-of-line)
5478   (re-search-forward dired-re-before-filename)
5479   (goto-char (match-beginning 1))
5480   (skip-chars-backward " ")
5481   (dired-size-spec-to-size
5482    (buffer-substring (point)
5483                      (progn (skip-chars-backward "^ ")
5484                             (point)))))
5485
5486 (defun dired-size-spec-to-size (size-spec)
5487   "Convert a size specification to a size in bytes."
5488   (if (string-match "^[0-9]+$" size-spec)
5489       (string-to-int size-spec)
5490     (let* ((size (length size-spec))
5491            (num (string-to-int (substring size-spec 0 (- size 1))))
5492            (last ))
5493       (* num
5494          (expt 1024
5495                (or (cdr-safe
5496                     (assoc (aref size-spec (- size 1))
5497                         '((?B . 0) (?k . 1) (?K . 1) (?M . 2) (?G . 3) (?T . 4) (?P . 5))))
5498                    1)))))) ; probably bogus, but we don't know any better
5499
5500 (defun dired-copy-filenames-as-kill (&optional arg)
5501   "Copy names of marked (or next ARG) files into the kill ring.
5502 The names are separated by a space, and may be copied into other buffers
5503 with \\[yank].  The list of names is also stored in the variable
5504 `dired-marked-files' for possible manipulation in the *scratch* buffer.
5505
5506 With a 0 prefix argument, use the pathname relative to the top-level dired
5507 directory for each marked file.
5508
5509 With a prefix \\[universal-argument], use the complete pathname of each
5510 marked file.
5511
5512 With a prefix \\[universal-argument] \\[universal-argument], copy the complete
5513 file line.  In this case, the lines are separated by newlines.
5514
5515 If on a subdirectory headerline and no prefix argument given, use the
5516 subdirectory name instead."
5517   (interactive "P")
5518   (let (res)
5519     (cond
5520      ((and (null arg) (setq res (dired-get-subdir)))
5521       (kill-new res)
5522       (message "Copied %s into kill ring." res))
5523      ((equal arg '(16))
5524       (setq dired-marked-files
5525             (dired-map-over-marks
5526              (concat " " ; Don't copy the mark.
5527                      (buffer-substring
5528                       (progn (beginning-of-line) (1+ (point)))
5529                       (progn (skip-chars-forward "^\n\r") (point))))
5530                      nil))
5531       (let ((len (length dired-marked-files)))
5532         (kill-new (concat
5533                    (mapconcat 'identity dired-marked-files "\n")
5534                    "\n"))
5535         (message "Copied %d file line%s into kill ring."
5536                  len (dired-plural-s len))))
5537      (t
5538       (setq dired-marked-files
5539             (cond
5540              ((null arg)
5541               (dired-get-marked-files 'no-dir))
5542              ((eq arg 0)
5543               (dired-get-marked-files t))
5544              ((integerp arg)
5545               (dired-get-marked-files 'no-dir arg))
5546              ((equal arg '(4))
5547               (dired-get-marked-files))
5548              (t (error "Invalid prefix %s" arg))))
5549       (let ((len (length dired-marked-files)))
5550         (kill-new (mapconcat 'identity dired-marked-files " "))
5551         (message "Copied %d file name%s into kill ring."
5552                  len (dired-plural-s len)))))))
5553
5554 \f
5555 ;;;; -----------------------------------------------------------
5556 ;;;; Killing subdirectories
5557 ;;;; -----------------------------------------------------------
5558 ;;;
5559 ;;;  These commands actually remove text from the dired buffer.
5560
5561 (defun dired-kill-subdir (&optional remember-marks tree)
5562   "Remove all lines of current subdirectory.
5563 Lower levels are unaffected.  If given a prefix when called interactively,
5564 kills the entire directory tree below the current subdirectory."
5565   ;; With optional REMEMBER-MARKS, return a mark-alist.
5566   (interactive (list nil current-prefix-arg))
5567   (let ((cur-dir (dired-current-directory)))
5568     (if (string-equal cur-dir (expand-file-name default-directory))
5569         (error "Attempt to kill top level directory"))
5570     (if tree
5571         (dired-kill-tree cur-dir remember-marks)
5572       (let ((beg (dired-subdir-min))
5573             (end (dired-subdir-max))
5574             buffer-read-only)
5575         (prog1
5576             (if remember-marks (dired-remember-marks beg end))
5577           (goto-char beg)
5578           (or (bobp) (forward-char -1)) ; gobble separator
5579           (delete-region (point) end)
5580           (dired-unsubdir cur-dir)
5581           (dired-update-mode-line)
5582           (dired-update-mode-line-modified t))))))
5583
5584 (defun dired-kill-tree (dirname &optional remember-marks)
5585   "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
5586 With optional arg REMEMBER-MARKS, return an alist of marked files."
5587   (interactive "DKill tree below directory: ")
5588   (let ((s-alist dired-subdir-alist) dir m-alist)
5589     (while s-alist
5590       (setq dir (car (car s-alist))
5591             s-alist (cdr s-alist))
5592       (if (and (not (string-equal dir dirname))
5593                (dired-in-this-tree dir dirname)
5594                (dired-goto-subdir dir))
5595           (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
5596     (dired-update-mode-line)
5597     (dired-update-mode-line-modified t)
5598     m-alist))
5599
5600 \f
5601 ;;;; ------------------------------------------------------------
5602 ;;;; Killing file lines
5603 ;;;; ------------------------------------------------------------
5604 ;;;
5605
5606 (defun dired-kill-line (&optional arg)
5607   (interactive "P")
5608   (setq arg (prefix-numeric-value arg))
5609   (let (buffer-read-only file)
5610     (while (/= 0 arg)
5611       (setq file (dired-get-filename nil t))
5612       (if (not file)
5613           (error "Can only kill file lines")
5614         (save-excursion (and file
5615                              (dired-goto-subdir file)
5616                              (dired-kill-subdir)))
5617         (delete-region (progn (beginning-of-line) (point))
5618                        (progn (forward-line 1) (point)))
5619         (if (> arg 0)
5620             (setq arg (1- arg))
5621           (setq arg (1+ arg))
5622           (forward-line -1))))
5623     (dired-move-to-filename)))
5624
5625 ;;;  Uses selective diplay, rather than removing lines from the buffer.
5626
5627 (defun dired-do-kill-file-lines (&optional arg)
5628   "Kill all marked file lines, or those indicated by the prefix argument.
5629 Killing file lines means hiding them with selective display.  Giving
5630 a zero prefix redisplays all killed file lines."
5631   (interactive "P")
5632   (or selective-display
5633       (error "selective-display must be t for file line killing to work!"))
5634   (if (eq arg 0)
5635       (dired-do-unhide dired-kill-marker-char
5636                        "Successfully resuscitated %d file line%s."
5637                        dired-keep-marker-kill)
5638     (let ((files
5639            (length
5640             (dired-map-over-marks
5641              (progn
5642                (beginning-of-line)
5643                (subst-char-in-region (1- (point)) (point) ?\n ?\r)
5644                (dired-substitute-marker (point) (char-after (point))
5645                                         dired-kill-marker-char)
5646                (dired-update-marker-counters dired-marker-char t)
5647                t)
5648              arg))))
5649       ;; Beware of extreme apparent save-excursion lossage here.
5650       (let ((opoint (point)))
5651         (skip-chars-backward "^\n\r")
5652         (if (equal (char-before) ?\n)
5653             (goto-char opoint)
5654           (setq opoint (- opoint (point)))
5655           (beginning-of-line)
5656           (skip-chars-forward "^\n\r" (+ (point) opoint))))
5657       (dired-update-mode-line-modified)
5658       (message "Killed %d file line%s." files (dired-plural-s files)))))
5659
5660 \f
5661 ;;;; ----------------------------------------------------------------
5662 ;;;; Omitting files.
5663 ;;;; ----------------------------------------------------------------
5664
5665 ;; Marked files are never omitted.
5666 ;; Adapted from code submitted by:
5667 ;; Michael D. Ernst, mernst@theory.lcs.mit.edu, 1/11/91
5668 ;; Changed to work with selective display by Sandy Rutherford, 13/12/92.
5669 ;; For historical reasons, we still use the term expunge, although nothing
5670 ;; is expunged from the buffer.
5671
5672 (defun dired-omit-toggle (&optional arg)
5673   "Toggle between displaying and omitting files matching
5674 `dired-omit-regexps' in the current subdirectory.
5675 With a positive prefix, omits files in the entire tree dired buffer.
5676 With a negative prefix, forces all files in the tree dired buffer to be
5677 displayed."
5678   (interactive "P")
5679   (if arg
5680       (let ((arg (prefix-numeric-value arg)))
5681         (if (>= arg 0)
5682             (dired-omit-expunge nil t)
5683           (dired-do-unhide dired-omit-marker-char "")
5684           (mapcar
5685            (function
5686             (lambda (elt)
5687               (setcar (nthcdr 2 elt) nil)))
5688            dired-subdir-alist)))
5689     (if (dired-current-subdir-omitted-p)
5690         (save-restriction
5691           (narrow-to-region (dired-subdir-min) (dired-subdir-max))
5692           (dired-do-unhide dired-omit-marker-char "")
5693           (setcar (nthcdr 2 (assoc
5694                              (dired-current-directory) dired-subdir-alist))
5695                   nil)
5696           (setq dired-subdir-omit nil))
5697       (dired-omit-expunge)
5698       (setq dired-subdir-omit t)))
5699   (dired-update-mode-line t))
5700
5701 (defun dired-current-subdir-omitted-p ()
5702   ;; Returns t if the current subdirectory is omited.
5703   (nth 2 (assoc (dired-current-directory) dired-subdir-alist)))
5704
5705 (defun dired-remember-omitted ()
5706   ;; Returns a list of omitted subdirs.
5707   (let ((alist dired-subdir-alist)
5708         result elt)
5709     (while alist
5710       (setq elt (car alist)
5711             alist (cdr alist))
5712       (if (nth 2 elt)
5713           (setq result (cons (car elt) result))))
5714     result))
5715
5716 (defun dired-omit-expunge (&optional regexp full-buffer)
5717   ;; Hides all unmarked files matching REGEXP.
5718   ;; If REGEXP is nil or not specified, uses `dired-omit-regexps',
5719   ;; and also omits filenames ending in `dired-omit-extensions'.
5720   ;; If REGEXP is the empty string, this function is a no-op.
5721   (let ((omit-re (or regexp (dired-omit-regexp)))
5722         (alist dired-subdir-alist)
5723         elt min)
5724     (if (null omit-re)
5725         0
5726       (if full-buffer
5727           (prog1
5728               (dired-omit-region (point-min) (point-max) omit-re)
5729             ;; Set omit property in dired-subdir-alist
5730             (while alist
5731               (setq elt (car alist)
5732                     min (dired-get-subdir-min elt)
5733                     alist (cdr alist))
5734               (if (and (<= (point-min) min) (>= (point-max) min))
5735                   (setcar (nthcdr 2 elt) t))))
5736         (prog1
5737             (dired-omit-region (dired-subdir-min) (dired-subdir-max) omit-re)
5738           (setcar
5739            (nthcdr 2 (assoc (dired-current-directory)
5740                             dired-subdir-alist))
5741            t))))))
5742
5743 (defun dired-omit-region (start end regexp)
5744   ;; Omits files matching regexp in region. Returns count.
5745   (save-restriction
5746     (narrow-to-region start end)
5747     (let ((hidden-subdirs (dired-remember-hidden))
5748           buffer-read-only count)
5749       (or selective-display
5750           (error "selective-display must be t for file omission to work!"))
5751       (dired-omit-unhide-region start end)
5752       (let ((dired-marker-char dired-omit-marker-char)
5753             ;; since all subdirs are now unhidden, this fakes
5754             ;; dired-move-to-end-of-filename into working faster
5755             (selective-display nil))
5756         (or dired-omit-silent
5757             dired-in-query (message "Omitting..."))
5758         (if (dired-mark-unmarked-files regexp nil nil 'no-dir)
5759             (setq count (dired-do-hide
5760                          dired-marker-char
5761                          (and (memq dired-omit-silent '(nil 0))
5762                               (not dired-in-query)
5763                               "Omitted %d line%s.")))
5764           (or dired-omit-silent dired-in-query
5765               (message "(Nothing to omit)"))))
5766       (save-excursion           ;hide subdirs that were hidden
5767         (mapcar (function (lambda (dir)
5768                             (if (dired-goto-subdir dir)
5769                                 (dired-hide-subdir 1))))
5770                 hidden-subdirs))
5771       count)))
5772
5773 (defun dired-omit-unhide-region (beg end)
5774   ;; Unhides hidden, but not marked files in the region.
5775   (save-excursion
5776     (save-restriction
5777       (narrow-to-region beg end)
5778       (goto-char (point-min))
5779       (while (search-forward "\r" nil t)
5780         (and (char-equal (char-after (point)) ?\ )
5781              (subst-char-in-region (1- (point)) (point) ?\r ?\n))))))
5782
5783 (defun dired-do-unhide (char &optional fmt marker)
5784   ;; Unhides files marked with CHAR. Optional FMT is a message
5785   ;; to be displayed. Note that after unhiding, we will need to re-hide
5786   ;; files belonging to hidden subdirs.
5787   (save-excursion
5788     (goto-char (point-min))
5789     (let ((count 0)
5790           (string (concat "\r" (char-to-string char)))
5791           (hidden-subdirs (dired-remember-hidden))
5792           (new (if marker (concat "\n" (char-to-string marker)) "\n "))
5793           buffer-read-only)
5794       (while (search-forward string nil t)
5795         (replace-match new)
5796         (setq count (1+ count)))
5797       (or (equal "" fmt)
5798           (message (or fmt "Unhid %d line%s.") count (dired-plural-s count)))
5799       (goto-char (point-min))
5800       (mapcar (function (lambda (dir)
5801                           (if (dired-goto-subdir dir)
5802                               (dired-hide-subdir 1 t))))
5803               hidden-subdirs)
5804       (if marker (dired-update-mode-line-modified t))
5805       count)))
5806
5807 (defun dired-do-hide (char &optional fmt)
5808   ;; Hides files marked with CHAR. Otional FMT is a message
5809   ;; to be displayed. FMT is a format string taking args the number
5810   ;; of hidden file lines, and dired-plural-s.
5811   (save-excursion
5812     (goto-char (point-min))
5813     (let ((count 0)
5814           (string (concat "\n" (char-to-string char)))
5815           buffer-read-only)
5816       (while (search-forward string nil t)
5817         (subst-char-in-region (match-beginning 0)
5818                               (1+ (match-beginning 0)) ?\n ?\r t)
5819         (setq count (1+ count)))
5820       (if fmt
5821           (message fmt count (dired-plural-s count)))
5822       count)))
5823
5824 (defun dired-omit-regexp ()
5825   (let (rgxp)
5826     (if dired-omit-extensions
5827         (setq rgxp (concat
5828                     ".\\("
5829                     (mapconcat 'regexp-quote dired-omit-extensions "\\|")
5830                     "\\)\\'")))
5831     (if dired-omit-regexps
5832         (setq rgxp
5833               (concat
5834                rgxp
5835                (and rgxp "\\|")
5836                (mapconcat 'identity dired-omit-regexps "\\|"))))
5837     rgxp))
5838
5839 (defun dired-mark-unmarked-files (regexp msg &optional unflag-p localp)
5840   ;; Marks unmarked files matching REGEXP, displaying MSG.
5841   ;; REGEXP is matched against the complete pathname, unless localp is
5842   ;; specified.
5843   ;; Does not re-mark files which already have a mark.
5844   ;; Returns t if any work was done, nil otherwise.
5845   (let ((dired-marker-char (if unflag-p ?\  dired-marker-char))
5846         fn)
5847     (dired-mark-if
5848      (and
5849       ;; not already marked
5850       (equal (char-after (point)) ?\ )
5851       ;; uninteresting
5852       (setq fn (dired-get-filename localp t))
5853       (string-match regexp fn))
5854      msg)))
5855
5856 (defun dired-add-omit-regexp (rgxp &optional how)
5857   "Adds a new regular expression to the list of omit regular expresions.
5858 With a non-zero numeric prefix argument, deletes a regular expresion from
5859 the list.
5860
5861 With a prefix argument \\[universal-argument], adds a new extension to
5862 the list of file name extensions omitted.
5863 With a prefix argument \\[universal-argument] \\[universal-argument], deletes
5864 a file name extension from the list.
5865
5866 With a prefix 0, reports on the current omit regular expressions and
5867 extensions."
5868   (interactive
5869    (list
5870     (cond
5871      ((null current-prefix-arg)
5872       (read-string "New omit regular expression: "))
5873      ((equal '(4) current-prefix-arg)
5874       (read-string "New omit extension (\".\" is not implicit): "))
5875      ((equal '(16) current-prefix-arg)
5876       (completing-read
5877        "Remove from omit extensions (type SPACE for options): "
5878        (mapcar 'list dired-omit-extensions) nil t))
5879      ((eq 0 current-prefix-arg)
5880       nil)
5881      (t
5882       (completing-read
5883        "Remove from omit regexps (type SPACE for options): "
5884        (mapcar 'list dired-omit-regexps) nil t)))
5885     current-prefix-arg))
5886   (let (remove)
5887     (cond
5888      ((null how)
5889       (if (member rgxp dired-omit-regexps)
5890           (progn
5891             (describe-variable 'dired-omit-regexps)
5892             (error "%s is already included in the list." rgxp))
5893         (setq dired-omit-regexps (cons rgxp dired-omit-regexps))))
5894      ((equal how '(4))
5895       (if (member rgxp dired-omit-extensions)
5896           (progn
5897             (describe-variable 'dired-omit-extensions)
5898             (error "%s is already included in list." rgxp))
5899         (setq dired-omit-extensions (cons rgxp dired-omit-extensions))))
5900      ((equal how '(16))
5901       (let ((tail (member rgxp dired-omit-extensions)))
5902         (if tail
5903             (setq dired-omit-extensions
5904                   (delq (car tail) dired-omit-extensions)
5905                   remove t)
5906           (setq remove 'ignore))))
5907      ((eq 0 how)
5908       (setq remove 'ignore)
5909       (if (featurep 'ehelp)
5910           (with-electric-help
5911            (function
5912             (lambda ()
5913               (princ "Omit extensions (dired-omit-extensions <V>):\n")
5914               (dired-format-columns-of-files dired-omit-extensions)
5915               (princ "\n")
5916               (princ "Omit regular expressions (dired-omit-regexps <V>):\n")
5917               (dired-format-columns-of-files dired-omit-regexps)
5918               nil)))
5919         (with-output-to-temp-buffer "*Help*"
5920           (princ "Omit extensions (dired-omit-extensions <V>):\n")
5921           (dired-format-columns-of-files dired-omit-extensions)
5922           (princ "\n")
5923           (princ "Omit regular expressions (dired-omit-regexps <V>):\n")
5924           (dired-format-columns-of-files dired-omit-regexps)
5925           (print-help-return-message))))
5926      (t
5927       (let ((tail (member rgxp dired-omit-regexps)))
5928         (if tail
5929             (setq dired-omit-regexps (delq (car tail) dired-omit-regexps)
5930                   remove t)
5931           (setq remove 'ignore)))))
5932     (or (eq remove 'ignore)
5933         (save-excursion
5934           (mapcar
5935            (function
5936             (lambda (dir)
5937               (if (dired-goto-subdir dir)
5938                   (progn
5939                     (if remove
5940                         (save-restriction
5941                           (narrow-to-region
5942                            (dired-subdir-min) (dired-subdir-max))
5943                           (dired-do-unhide dired-omit-marker-char "")))
5944                     (dired-omit-expunge)))))
5945            (dired-remember-omitted))))))
5946
5947
5948 \f
5949 ;;;; ----------------------------------------------------------------
5950 ;;;; Directory hiding.
5951 ;;;; ----------------------------------------------------------------
5952 ;;;
5953 ;;; To indicate a hidden subdir, we actually insert "..." in the buffer.
5954 ;;; Aside from giving the look of ellipses (even though
5955 ;;; selective-display-ellipses is nil), it allows us to tell the difference
5956 ;;; between a dir with a single omitted file, and a hidden subdir with one
5957 ;;; file.
5958
5959 (defun dired-subdir-hidden-p (dir)
5960   (save-excursion
5961     (and selective-display
5962          (dired-goto-subdir dir)
5963          (looking-at "\\.\\.\\.\r"))))
5964
5965 (defun dired-unhide-subdir ()
5966   (let (buffer-read-only)
5967     (goto-char (dired-subdir-min))
5968     (skip-chars-forward "^\n\r")
5969     (skip-chars-backward "." (- (point) 3))
5970     (if (looking-at "\\.\\.\\.\r") (delete-char 4))
5971     (dired-omit-unhide-region (point) (dired-subdir-max))))
5972
5973 (defun dired-hide-check ()
5974   (or selective-display
5975       (error "selective-display must be t for subdir hiding to work!")))
5976
5977 (defun dired-hide-subdir (arg &optional really)
5978   "Hide or unhide the current subdirectory and move to next directory.
5979 Optional prefix arg is a repeat factor.
5980 Use \\[dired-hide-all] to (un)hide all directories.
5981 With the optional argument REALLY, we always hide
5982 the subdir, regardless of dired-subdir-hidden-p."
5983   ;; The arg REALLY is needed because when we unhide
5984   ;; omitted files in a hidden subdir, we want to
5985   ;; re-hide the subdir, regardless of whether dired
5986   ;; thinks it's already hidden.
5987   (interactive "p")
5988   (dired-hide-check)
5989   (dired-save-excursion
5990     (while (>=  (setq arg (1- arg)) 0)
5991       (let* ((cur-dir (dired-current-directory))
5992              (hidden-p (and (null really)
5993                             (dired-subdir-hidden-p cur-dir)))
5994            (elt (assoc cur-dir dired-subdir-alist))
5995            (end-pos (1- (dired-get-subdir-max elt)))
5996            buffer-read-only)
5997         ;; keep header line visible, hide rest
5998         (goto-char (dired-get-subdir-min elt))
5999         (skip-chars-forward "^\n\r")
6000         (skip-chars-backward "." (- (point) 3))
6001       (if hidden-p
6002           (progn
6003             (if (looking-at "\\.\\.\\.\r")
6004                 (progn
6005                   (delete-char 3)
6006                   (setq end-pos (- end-pos 3))))
6007             (dired-omit-unhide-region (point) end-pos))
6008         (if (looking-at "\\.\\.\\.\r")
6009             (goto-char (match-end 0))
6010           (insert "...")
6011           (setq end-pos (+ end-pos 3)))
6012         (subst-char-in-region (point) end-pos ?\n ?\r)))
6013       (dired-next-subdir 1 t))))
6014
6015 (defun dired-hide-all (arg)
6016   "Hide all subdirectories, leaving only their header lines.
6017 If there is already something hidden, make everything visible again.
6018 Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
6019   (interactive "P")
6020   (dired-hide-check)
6021   (let (buffer-read-only)
6022     (dired-save-excursion
6023       (if (let ((alist dired-subdir-alist)
6024                 (hidden nil))
6025             (while (and alist (null hidden))
6026               (setq hidden (dired-subdir-hidden-p (car (car alist)))
6027                     alist (cdr alist)))
6028             hidden)
6029           ;; unhide
6030           (let ((alist dired-subdir-alist))
6031             (while alist
6032               (goto-char (dired-get-subdir-min (car alist)))
6033               (skip-chars-forward "^\n\r")
6034               (delete-region (point) (progn (skip-chars-backward ".") (point)))
6035               (setq alist (cdr alist)))
6036             (dired-omit-unhide-region (point-min) (point-max)))
6037         ;; hide
6038         (let ((alist dired-subdir-alist))
6039           (while alist
6040             (dired-goto-subdir (car (car alist)))
6041             (dired-hide-subdir 1 t)
6042             (setq alist (cdr alist))))))))
6043
6044 \f
6045 ;;;; -----------------------------------------------------------------
6046 ;;;; Automatic dired buffer maintenance.
6047 ;;;; -----------------------------------------------------------------
6048 ;;;
6049 ;;;  Keeping Dired buffers in sync with the filesystem and with each
6050 ;;;  other.
6051 ;;;  When used with efs on remote directories, buffer maintainence is
6052 ;;;  done asynch.
6053
6054 (defun dired-buffers-for-dir (dir-or-list &optional check-wildcard)
6055 ;; Return a list of buffers that dired DIR-OR-LIST
6056 ;; (top level or in-situ subdir).
6057 ;; The list is in reverse order of buffer creation, most recent last.
6058 ;; As a side effect, killed dired buffers for DIR are removed from
6059 ;; dired-buffers. If DIR-OR-LIST is a wildcard or list, returns any
6060 ;; dired buffers for which DIR-OR-LIST is equal to `dired-directory'.
6061 ;; If check-wildcard is non-nil, only returns buffers which contain dir-or-list
6062 ;; exactly, including the wildcard part.
6063   (let ((alist dired-buffers)
6064         (as-dir (and (stringp dir-or-list)
6065                      (file-name-as-directory dir-or-list)))
6066         result buff elt)
6067     (while alist
6068       (setq buff (cdr (setq elt (car alist)))
6069             alist (cdr alist))
6070       ;; dired-in-this-tree is not fast. It doesn't pay to use this to check
6071       ;; whether the buffer is a good candidate.
6072       (if (buffer-name buff)
6073           (save-excursion
6074             (set-buffer buff)
6075             (if (or (equal dir-or-list dired-directory) ; the wildcard case.
6076                     (and as-dir
6077                          (not (and check-wildcard
6078                                    (string-equal
6079                                     as-dir
6080                                     (expand-file-name default-directory))))
6081                          (assoc as-dir dired-subdir-alist)))
6082                 (setq result (cons buff result))))
6083         ;; else buffer is killed - clean up:
6084         (setq dired-buffers (delq elt dired-buffers))))
6085     (or dired-buffers (dired-remove-from-file-name-handler-alist))
6086     result))
6087
6088 (defun dired-advertise ()
6089   ;; Advertise in variable `dired-buffers' that we dired `default-directory'.
6090   ;; With wildcards we actually advertise too much.
6091   ;; Also makes sure that we are installed in the file-name-handler-alist
6092   (prog1
6093       (let ((ddir (expand-file-name default-directory)))
6094         (if (memq (current-buffer) (dired-buffers-for-dir ddir))
6095             t                       ; we have already advertised ourselves
6096           (setq dired-buffers
6097                 (cons (cons ddir (current-buffer))
6098                       dired-buffers))))
6099     ;; Do this last, otherwise the call to dired-buffers-for-dir will
6100     ;; remove dired-handler-fn from the file-name-handler-alist.
6101     ;; Strictly speaking, we only need to do this in th else branch of
6102     ;; the if statement.  We do it unconditionally as a sanity check.
6103     (dired-check-file-name-handler-alist)))
6104
6105 (defun dired-unadvertise (dir)
6106   ;; Remove DIR from the buffer alist in variable dired-buffers.
6107   ;; This has the effect of removing any buffer whose main directory is DIR.
6108   ;; It does not affect buffers in which DIR is a subdir.
6109   ;; Removing is also done as a side-effect in dired-buffer-for-dir.
6110   (setq dired-buffers
6111       (delq (assoc dir dired-buffers) dired-buffers))
6112   ;; If there are no more dired buffers, we are no longer needed in the
6113   ;; file-name-handler-alist.
6114   (or dired-buffers (dired-remove-from-file-name-handler-alist)))
6115
6116 (defun dired-unadvertise-current-buffer ()
6117   ;; Remove all references to the current buffer in dired-buffers.
6118   (setq dired-buffers
6119         (delq nil
6120               (mapcar
6121                (function
6122                 (lambda (x)
6123                   (and (not (eq (current-buffer) (cdr x))) x)))
6124                dired-buffers)))
6125   ;; If there are no more dired buffers, we are no longer needed in the
6126   ;; file-name-handler-alist.
6127   (or dired-buffers (dired-remove-from-file-name-handler-alist)))
6128
6129 (defun dired-fun-in-all-buffers (directory fun &rest args)
6130   ;; In all buffers dired'ing DIRECTORY, run FUN with ARGS.
6131   ;; Return list of buffers where FUN succeeded (i.e., returned non-nil).
6132   (let* ((buf-list (dired-buffers-for-dir directory))
6133          (obuf (current-buffer))
6134          (owin (selected-window))
6135          (win owin)
6136          buf windows success-list)
6137     (if buf-list
6138         (unwind-protect
6139             (progn
6140               (while (not (eq (setq win (next-window win)) owin))
6141                 (and (memq (setq buf (window-buffer win)) buf-list)
6142                      (progn
6143                        (set-buffer buf)
6144                        (= (point) (window-point win)))
6145                      (setq windows (cons win windows))))
6146               (while buf-list
6147                 (setq buf (car buf-list)
6148                       buf-list (cdr buf-list))
6149                 (set-buffer buf)
6150                 (if (apply fun args)
6151                     (setq success-list (cons (buffer-name buf) success-list))))
6152               ;; dired-save-excursion prevents lossage of save-excursion
6153               ;; for point.  However, if dired buffers are displayed in
6154               ;; other windows, the setting of window-point loses, and
6155               ;; drags the point with it.  This should fix this.
6156               (while windows
6157                 (condition-case nil
6158                     (progn
6159                       (set-buffer (window-buffer (setq win (car windows))))
6160                       (set-window-point win (point)))
6161                   (error nil))
6162                 (setq windows (cdr windows))))
6163           (set-buffer obuf)))
6164     success-list))
6165
6166 (defun dired-find-file-place (subdir file)
6167   ;; Finds a position to insert in SUBDIR FILE. If it can't find SUBDIR,
6168   ;; returns nil.
6169   (let ((sort (dired-sort-type dired-internal-switches))
6170         (rev (memq ?r (nth 3 (assoc subdir dired-subdir-alist)))))
6171     (cond
6172      ((eq sort 'name)
6173       (if (dired-goto-subdir subdir)
6174           (let ((max (dired-subdir-max))
6175                 start end found)
6176             (if (dired-goto-next-file)
6177                 (progn
6178                   (skip-chars-forward "^\n\r")
6179                   (setq start (point))
6180                   (goto-char (setq end max))
6181                   (forward-char -1)
6182                   (skip-chars-backward "^\n\r")
6183                   ;; This loop must find a file.  At the very least, it will
6184                   ;; find the one found previously.
6185                   (while (not found)
6186                     (if (save-excursion (dired-move-to-filename nil (point)))
6187                         (setq found t)
6188                       (setq end (point))
6189                       (forward-char -1)
6190                       (skip-chars-backward "^\n\r")))
6191                   (if rev
6192                       (while (< start end)
6193                         (goto-char (/ (+ start end) 2))
6194                         (if (dired-file-name-lessp
6195                              (or (dired-get-filename 'no-dir t)
6196                                  (error
6197                                   "Error in dired-find-file-place"))
6198                              file)
6199                             (setq end (progn
6200                                         (skip-chars-backward "^\n\r")
6201                                         (point)))
6202                           (setq start (progn
6203                                         (skip-chars-forward "^\n\r")
6204                                         (forward-char 1)
6205                                         (skip-chars-forward "^\n\r")
6206                                         (point)))))
6207                     (while (< start end)
6208                       (goto-char (/ (+ start end) 2))
6209                       (if (dired-file-name-lessp
6210                            file
6211                            (or (dired-get-filename 'no-dir t)
6212                                (error
6213                                 "Error in dired-find-file-place")))
6214                           (setq end (progn
6215                                         (skip-chars-backward "^\n\r")
6216                                         (point)))
6217                         (setq start (progn
6218                                       (skip-chars-forward "^\n\r")
6219                                       (forward-char 1)
6220                                       (skip-chars-forward "^\n\r")
6221                                       (point))))))
6222                   (goto-char end))
6223               (goto-char max))
6224             t)))
6225      ((eq sort 'date)
6226       (if (dired-goto-subdir subdir)
6227           (if rev
6228               (goto-char (dired-subdir-max))
6229             (dired-goto-next-file)
6230             t)))
6231      ;; Put in support for other sorting types.
6232      (t
6233       (if (string-equal (dired-current-directory) subdir)
6234           (progn
6235             ;; We are already where we should be, except when
6236             ;; point is before the subdir line or its total line.
6237             (or (save-excursion (beginning-of-line) (dired-move-to-filename))
6238                 (dired-goto-next-nontrivial-file)) ; in the header somewhere
6239             t) ; return t, for found.
6240         (if (dired-goto-subdir subdir)
6241             (progn
6242               (dired-goto-next-nontrivial-file)
6243               t)))))))
6244
6245 (defun dired-add-entry (filename &optional marker-char inplace)
6246   ;; Add a new entry for FILENAME, optionally marking it
6247   ;; with MARKER-CHAR (a character, else dired-marker-char is used).
6248   ;; Hidden subdirs are exposed if a file is added there.
6249   ;;
6250   ;; This function now adds the new entry at the END of the previous line,
6251   ;; not the beginning of the current line.
6252   ;; Logically, we now think of the `newline' associated
6253   ;; with a fileline, as the one at the beginning of the line, not the end.
6254   ;; This makes it easier to keep track of omitted files.
6255   ;;
6256   ;; Uses dired-save-excursion, so that it doesn't move the
6257   ;; point around. Especially important when it runs asynch.
6258   ;;
6259   ;; If there is already an entry, delete the existing one before adding a
6260   ;; new one.  In this case, doesn't remember its mark.  Use
6261   ;; dired-update-file-line for that.
6262   ;;
6263   ;; If INPLACE eq 'relist, then the new entry is put in the
6264   ;; same place as the old, if there was an old entry.
6265   ;; If INPLACE is t, then the file entry is put on the line
6266   ;; currently containing the point.  Otherwise, dired-find-file-place
6267   ;; attempts to determine where to put the file.
6268
6269   (setq filename (directory-file-name filename))
6270   (dired-save-excursion
6271     (let ((oentry (save-excursion (dired-goto-file filename)))
6272           (directory (file-name-directory filename))
6273           (file-nodir (file-name-nondirectory filename))
6274           buffer-read-only)
6275       (if oentry
6276           ;; Remove old entry
6277           (let ((opoint (point)))
6278             (goto-char oentry)
6279             (delete-region (save-excursion
6280                              (skip-chars-backward "^\r\n")
6281                              (dired-update-marker-counters (char-after (point)) t)
6282                              (1- (point)))
6283                            (progn
6284                              (skip-chars-forward "^\r\n")
6285                              (point)))
6286             ;; Move to right place to replace deleted line.
6287             (cond ((eq inplace 'relist) (forward-char 1))
6288                   ((eq inplace t) (goto-char opoint)))
6289             (dired-update-mode-line-modified)))
6290       (if (or (eq inplace t)
6291               (and oentry (eq inplace 'relist))
6292               ;; Tries to move the point to the right place.
6293               ;; Returns t on success.
6294               (dired-find-file-place directory file-nodir))
6295           (let ((switches (dired-make-switches-string
6296                            (cons ?d dired-internal-switches)))
6297                 b-of-l)
6298             ;; Bind marker-char now, in case we are working asynch and
6299             ;; dired-marker-char changes in the meantime.
6300             (if (and marker-char (not (characterp marker-char)))
6301                 (setq marker-char dired-marker-char))
6302             ;; since we insert at the end of a line,
6303             ;; backup to the end of the previous line.
6304             (skip-chars-backward "^\n\r")
6305             (forward-char -1)
6306             (setq b-of-l (point))
6307             (if (and (featurep 'efs-dired) efs-dired-host-type)
6308                 ;; insert asynch
6309                 ;; we call the efs version explicitly here,
6310                 ;; rather than let the handler-alist work for us
6311                 ;; because we want to pass extra args.
6312                 ;; Is there a cleaner way to do this?
6313                 (efs-insert-directory filename ; don't expand `.' !
6314                                       switches nil nil
6315                                       t ; nowait
6316                                       marker-char)
6317               (let ((insert-directory-program dired-ls-program))
6318                 (if dired-use-ls-dired
6319                     (setq switches (concat "--dired " switches)))
6320                 (dired-call-insert-directory filename switches nil nil))
6321               (dired-after-add-entry b-of-l marker-char))
6322             (if dired-verify-modtimes
6323                 (dired-set-file-modtime directory dired-subdir-alist))
6324             t))))) ; return t on success, else nil.
6325
6326 (defun dired-align-file (beg end)
6327   "Align the fields of a file to the ones of surrounding lines.
6328 BEG..END is the line where the file info is located."
6329   ;; Some versions of ls try to adjust the size of each field so as to just
6330   ;; hold the largest element ("largest" in the current invocation, of
6331   ;; course).  So when a single line is output, the size of each field is
6332   ;; just big enough for that one output.  Thus when dired refreshes one
6333   ;; line, the alignment if this line w.r.t the rest is messed up because
6334   ;; the fields of that one line will generally be smaller.
6335   ;;
6336   ;; To work around this problem, we here add spaces to try and re-align the
6337   ;; fields as needed.  Since this is purely aesthetic, it is of utmost
6338   ;; importance that it doesn't mess up anything like
6339   ;; `dired-move-to-filename'.  To this end, we limit ourselves to adding
6340   ;; spaces only, and to only add them at places where there was already at
6341   ;; least one space.  This way, as long as `dired-move-to-filename-regexp'
6342   ;; always matches spaces with "*" or "+", we know we haven't made anything
6343   ;; worse.  There is one spot where the exact number of spaces is
6344   ;; important, which is just before the actual filename, so we refrain from
6345   ;; adding spaces there (and within the filename as well, of course).
6346   (save-excursion
6347     (let (file file-col other other-col)
6348       ;; Check the there is indeed a file, and that there is anoter adjacent
6349       ;; file with which to align, and that additional spaces are needed to
6350       ;; align the filenames.
6351       (when (and (setq file (dired-move-to-filename nil beg end))
6352                  (setq file-col (current-column))
6353                  (setq other
6354                        (or (and (goto-char beg)
6355                                 (zerop (forward-line -1))
6356                                 (dired-move-to-filename))
6357                            (and (goto-char beg)
6358                                 (zerop (forward-line 1))
6359                                 (dired-move-to-filename))))
6360                  (setq other-col (current-column))
6361                  (/= file other)
6362                  ;; Make sure there is some work left to do.
6363                  (> other-col file-col))
6364         ;; If we've only looked at the line above, check to see if the line
6365         ;; below exists as well and if so, align with the shorter one.
6366         (when (and (< other file)
6367                    (goto-char beg)
6368                    (zerop (forward-line 1))
6369                    (dired-move-to-filename))
6370           (let ((alt-col (current-column)))
6371             (when (< alt-col other-col)
6372               (setq other-col alt-col)
6373               (setq other (point)))))
6374         ;; Keep positions uptodate when we insert stuff.
6375         (if (> other file) (setq other (copy-marker other)))
6376         (setq file (copy-marker file))
6377         ;; Main loop.
6378         (goto-char beg)
6379         (skip-chars-forward " ")        ;Skip to the first field.
6380         (while (and (> other-col file-col)
6381                     ;; Don't touch anything just before (and after) the
6382                     ;; beginning of the filename.
6383                     (> file (point)))
6384           ;; We're now just in front of a field, with a space behind us.
6385           (let* ((curcol (current-column))
6386                  ;; Nums are right-aligned.
6387                  (num-align (looking-at "[0-9]"))
6388                  ;; Let's look at the other line, in the same column: we
6389                  ;; should be either near the end of the previous field, or
6390                  ;; in the space between that field and the next.
6391                  ;; [ Of course, it's also possible that we're already within
6392                  ;; the next field or even past it, but that's unlikely since
6393                  ;; other-col > file-col. ]
6394                  ;; Let's find the distance to the alignment-point (either
6395                  ;; the beginning or the end of the next field, depending on
6396                  ;; whether this field is left or right aligned).
6397                  (align-pt-offset
6398                   (save-excursion
6399                     (goto-char other)
6400                     (move-to-column curcol)
6401                     (when (looking-at
6402                            (concat
6403                             (if (eq (char-before) ?\ ) " *" "[^ ]* *")
6404                             (if num-align "[0-9][^ ]*")))
6405                       (- (match-end 0) (match-beginning 0)))))
6406                  ;; Now, the number of spaces to insert is align-pt-offset
6407                  ;; minus the distance to the equivalent point on the
6408                  ;; current line.
6409                  (spaces
6410                   (if (not num-align)
6411                       align-pt-offset
6412                     (and align-pt-offset
6413                          (save-excursion
6414                            (skip-chars-forward "^ ")
6415                            (- align-pt-offset (- (current-column) curcol)))))))
6416             (when (and spaces (> spaces 0))
6417               (setq file-col (+ spaces file-col))
6418               (if (> file-col other-col)
6419                   (setq spaces (- spaces (- file-col other-col))))
6420               (insert-char ?\ spaces)
6421               ;; Let's just make really sure we did not mess up.
6422               (unless (save-excursion
6423                         (eq (dired-move-to-filename) (marker-position file)))
6424                 ;; Damn!  We messed up: let's revert the change.
6425                 (delete-char (- spaces)))))
6426           ;; Now skip to next field.
6427           (skip-chars-forward "^ ") (skip-chars-forward " "))
6428         (set-marker file nil)))))
6429
6430 (defun dired-after-add-entry (start marker-char)
6431   ;; Does the cleanup of a dired entry after listing it.
6432   ;; START is the start of the new listing-line.
6433   ;; This is a separate function for the sake of efs.
6434   (save-excursion
6435     (goto-char start)
6436     ;; we make sure that the new line is bracketted by new-lines
6437     ;; so the user doesn't need to use voodoo in the
6438     ;; after-readin-hook.
6439     (insert ?\n)
6440     (dired-add-entry-do-indentation marker-char)
6441     (let* ((beg (dired-manual-move-to-filename t))
6442            ;; error for strange output
6443            (end (dired-manual-move-to-end-of-filename))
6444            (filename (buffer-substring beg end)))
6445       ;; We want to have the non-directory part only.
6446       (delete-region beg end)
6447       ;; Any markers pointing to the beginning of the filename, will
6448       ;; still point there after this insertion. Should keep
6449       ;; save-excursion from losing.
6450       (setq beg (point))
6451       (insert (file-name-nondirectory filename))
6452       (dired-insert-set-properties beg (point))
6453       (dired-move-to-filename))
6454     ;; The subdir-alist is not affected so we can run it right now.
6455     (let ((omit (dired-current-subdir-omitted-p))
6456           (hide (dired-subdir-hidden-p (dired-current-directory))))
6457       (if (or dired-after-readin-hook omit hide)
6458           (save-excursion
6459             (save-restriction
6460               ;; Use start so that we get the new-line at
6461               ;; the beginning of the line in case we want
6462               ;; to hide the file. Don't need to test (bobp)
6463               ;; here, since we never add a file at
6464               ;; the beginning of the buffer.
6465               (narrow-to-region start
6466                                 (save-excursion (forward-line 1) (point)))
6467               (run-hooks 'dired-after-readin-hook)
6468               (if omit
6469                   (let ((dired-omit-silent (or dired-omit-silent 0)))
6470                     (dired-omit-region (point-min) (point-max)
6471                                        (dired-omit-regexp))))
6472               (if hide
6473                   (subst-char-in-region (point-min) (1- (point-max))
6474                                         ?\n ?\r))))))
6475     ;; clobber the extra newline at the end of the line
6476     (end-of-line)
6477     (delete-char 1)
6478     ;; Re-align fields, if necessary.
6479     (dired-align-file (1+ start) (point))))
6480
6481 ;; This is a separate function for the sake of nested dired format.
6482 (defun dired-add-entry-do-indentation (marker-char)
6483   ;; two spaces or a marker plus a space:
6484   (cond
6485    ((not (looking-at "  "))
6486     ;; two spaces or a marker plus a space:
6487     (insert (if marker-char
6488                 (let ((char (if (characterp marker-char)
6489                                 marker-char
6490                               dired-marker-char)))
6491                   (dired-update-marker-counters char)
6492                   (dired-update-mode-line-modified)
6493                   char)
6494               ?\040)
6495             ?\040))
6496    (marker-char
6497     (delete-char)
6498     (let ((char (if (characterp marker-char)
6499                     marker-char
6500                   dired-marker-char)))
6501       (dired-update-marker-counters char)
6502       (dired-update-mode-line-modified)
6503       (insert char)))))
6504
6505 (defun dired-remove-file (file)
6506   (let ((alist dired-buffers)
6507         buff)
6508     (save-excursion
6509       (while alist
6510         (setq buff (cdr (car alist)))
6511         (if (buffer-name buff)
6512             (progn
6513               (set-buffer buff)
6514               (dired-remove-entry file))
6515           (setq dired-buffers (delq (car alist) dired-buffers)))
6516         (setq alist (cdr alist))))
6517     (or dired-buffers (dired-remove-from-file-name-handler-alist))))
6518
6519 (defun dired-remove-entry (file)
6520   (let ((ddir (expand-file-name default-directory))
6521         (dirname (file-name-as-directory file)))
6522     (if (dired-in-this-tree ddir dirname)
6523         (if (or (memq 'kill-dired-buffer dired-no-confirm)
6524                 (y-or-n-p (format "Kill dired buffer %s for %s, too? "
6525                                   (buffer-name) dired-directory)))
6526             (kill-buffer (current-buffer)))
6527       (if (dired-in-this-tree file ddir)
6528           (let ((alist dired-subdir-alist))
6529             (while alist
6530               (if (dired-in-this-tree (car (car alist)) dirname)
6531                   (save-excursion
6532                     (goto-char (dired-get-subdir-min (car alist)))
6533                     (dired-kill-subdir)))
6534               (setq alist (cdr alist)))
6535             (dired-save-excursion
6536               (and (dired-goto-file file)
6537                    (let (buffer-read-only)
6538                      (delete-region
6539                       (progn (skip-chars-backward "^\n\r")
6540                              (or (memq (char-after (point)) '(\n \r ?\ ))
6541                                  (progn
6542                                    (dired-update-marker-counters
6543                                     (char-after (point)) t)
6544                                    (dired-update-mode-line-modified)))
6545                              (1- (point)))
6546                       (progn (skip-chars-forward "^\n\r") (point)))
6547                      (if dired-verify-modtimes
6548                          (dired-set-file-modtime
6549                           (file-name-directory (directory-file-name file))
6550                           dired-subdir-alist))))))))))
6551
6552 (defun dired-add-file (filename &optional marker-char)
6553   (dired-fun-in-all-buffers
6554    (file-name-directory filename)
6555    (function dired-add-entry) filename marker-char))
6556
6557 (defun dired-relist-file (file)
6558   (dired-uncache file nil)
6559   (dired-fun-in-all-buffers (file-name-directory file)
6560                             (function dired-relist-entry) file))
6561
6562 (defun dired-relist-entry (file)
6563   ;; Relist the line for FILE, or just add it if it did not exist.
6564   ;; FILE must be an absolute pathname.
6565   (let* ((file (directory-file-name file))
6566          (directory (file-name-directory file))
6567          (dd (expand-file-name default-directory)))
6568     (if (assoc directory dired-subdir-alist)
6569         (if (or
6570              ;; Not a wildcard
6571              (equal dd dired-directory)
6572              ;; Not top-level
6573              (not (string-equal directory dd))
6574              (and (string-equal directory
6575                                 (if (consp dired-directory)
6576                                     (file-name-as-directory
6577                                      (car dired-directory))
6578                                   (file-name-directory dired-directory)))
6579                   (dired-file-in-wildcard-p dired-directory file)))
6580             (let ((marker (save-excursion
6581                             (and (dired-goto-file file)
6582                                  (dired-file-marker file)))))
6583               ;; recompute omission
6584               (if (equal marker dired-omit-marker-char)
6585                   (setq marker nil))
6586               (dired-add-entry file marker 'relist))
6587           ;; At least tell dired that we considered updating the buffer.
6588           (if dired-verify-modtimes
6589               (dired-set-file-modtime directory dired-subdir-alist))))))
6590
6591 (defun dired-file-in-wildcard-p (wildcard file)
6592   ;; Return t if a file is part of the listing for wildcard.
6593   ;; File should be the non-directory part only.
6594   ;; This version is slow, but meticulously correct.  Is it worth it?
6595   (if (consp wildcard)
6596       (let ((files (cdr wildcard))
6597             (dir (car wildcard))
6598             yep)
6599         (while (and files (not yep))
6600           (setq yep (string-equal file (expand-file-name (car files) dir))
6601                 files (cdr files)))
6602         yep)
6603     (let ((err-buff
6604            (let ((default-major-mode 'fundamental-mode))
6605              (get-buffer-create " *dired-check-process output*")))
6606           (dir default-directory)
6607           (process-connection-type nil))
6608       (save-excursion
6609         (set-buffer err-buff)
6610         (erase-buffer)
6611         (setq default-directory dir)
6612         (call-process shell-file-name nil t nil shell-command-switch
6613                     (concat dired-ls-program " -d " wildcard " | "
6614                             "egrep '(^|/)" file "$'"))
6615         (/= (buffer-size) 0)))))
6616
6617 ;; The difference between dired-add-file and dired-relist-file is that
6618 ;; the former creates the entry with a specific marker.  The later preserves
6619 ;; existing markers on a per buffer basis.  This is not the same as
6620 ;; giving dired-create-files a marker of t, which uses a marker in a specific
6621 ;; buffer to determine the marker for file line creation in all buffers.
6622
6623 \f
6624 ;;;; ----------------------------------------------------------------
6625 ;;;; Applying Lisp functions to marked files.
6626 ;;;; ----------------------------------------------------------------
6627
6628 ;;; Running tags commands on marked files.
6629 ;;
6630 ;; Written 8/30/93 by Roland McGrath <roland@gnu.ai.mit.edu>.
6631 ;; Requires tags.el as distributed with GNU Emacs 19.23, or later.
6632
6633 (defun dired-do-tags-search (regexp)
6634   "Search through all marked files for a match for REGEXP.
6635 Stops when a match is found.
6636 To continue searching for next match, use command \\[tags-loop-continue]."
6637   (interactive "sSearch marked files (regexp): ")
6638   (tags-search regexp '(dired-get-marked-files)))
6639
6640 (defun dired-do-tags-query-replace (from to &optional delimited)
6641   "Query-replace-regexp FROM with TO through all marked files.
6642 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
6643 If you exit (\\[keyboard-quit] or ESC), you can resume the query-replace
6644 with the command \\[tags-loop-continue]."
6645   (interactive
6646    "sQuery replace in marked files (regexp): \nsQuery replace %s by: \nP")
6647   (tags-query-replace from to delimited '(dired-get-marked-files)))
6648
6649 ;;; byte compiling
6650
6651 (defun dired-byte-compile ()
6652   ;; Return nil for success, offending file name else.
6653   (let* ((filename (dired-get-filename))
6654          buffer-read-only failure)
6655     (condition-case err
6656         (save-excursion (byte-compile-file filename))
6657       (error
6658        (setq failure err)))
6659     ;; We should not need to update any file lines, as this will have
6660     ;; already been done by after-write-region-hook.
6661     (and failure
6662          (progn
6663            (dired-log (buffer-name (current-buffer))
6664                       "Byte compile error for %s:\n%s\n" filename failure)
6665            (dired-make-relative filename)))))
6666
6667 (defun dired-do-byte-compile (&optional arg)
6668   "Byte compile marked (or next ARG) Emacs lisp files."
6669   (interactive "P")
6670   (dired-map-over-marks-check (function dired-byte-compile) arg
6671                               'byte-compile "byte-compile" t))
6672
6673 ;;; loading
6674
6675 (defun dired-load ()
6676   ;; Return nil for success, offending file name else.
6677   (let ((file (dired-get-filename)) failure)
6678     (condition-case err
6679       (load file nil nil t)
6680       (error (setq failure err)))
6681     (if (not failure)
6682         nil
6683       (dired-log (buffer-name (current-buffer))
6684                  "Load error for %s:\n%s\n" file failure)
6685       (dired-make-relative file))))
6686
6687 (defun dired-do-load (&optional arg)
6688   "Load the marked (or next ARG) Emacs lisp files."
6689   (interactive "P")
6690   (dired-map-over-marks-check (function dired-load) arg 'load "load" t))
6691
6692 \f
6693 ;;;; ----------------------------------------------------------------
6694 ;;;; File Name Handler Alist
6695 ;;;; ----------------------------------------------------------------
6696 ;;;
6697 ;;;  Make sure that I/O functions maintain dired buffers.
6698
6699 (defun dired-remove-from-file-name-handler-alist ()
6700   ;; Remove dired from the file-name-handler-alist
6701   (setq file-name-handler-alist
6702         (delq nil
6703               (mapcar
6704                (function
6705                 (lambda (x)
6706                   (and (not (eq (cdr x) 'dired-handler-fn))
6707                        x)))
6708                file-name-handler-alist))))
6709
6710 (defun dired-check-file-name-handler-alist ()
6711   ;; Verify that dired is installed as the first item in the alist
6712   (and dired-refresh-automatically
6713        (or (eq (cdr (car file-name-handler-alist)) 'dired-handler-fn)
6714            (setq file-name-handler-alist
6715                  (cons
6716                   '("." . dired-handler-fn)
6717                   (dired-remove-from-file-name-handler-alist))))))
6718
6719 (defun dired-handler-fn (op &rest args)
6720   ;; Function to update dired buffers after I/O.
6721   (prog1
6722       (let ((inhibit-file-name-handlers
6723              (cons 'dired-handler-fn
6724                    (and (eq inhibit-file-name-operation op)
6725                         inhibit-file-name-handlers)))
6726             (inhibit-file-name-operation op))
6727         (apply op args))
6728     (let ((dired-omit-silent t)
6729           (hf (get op 'dired)))
6730       (and hf (funcall hf args)))))
6731
6732 (defun dired-handler-fn-1 (args)
6733   (let ((to (expand-file-name (nth 1 args))))
6734     (or (member to dired-unhandle-add-files)
6735         (dired-relist-file to))))
6736
6737 (defun dired-handler-fn-2 (args)
6738   (let ((from (expand-file-name (car args)))
6739         (to (expand-file-name (nth 1 args))))
6740     ;; Don't remove the original entry if making backups.
6741     ;; Otherwise we lose marks.  I'm not completely happy with the
6742     ;; logic here.
6743     (or (and
6744          (eq (nth 2 args) t) ; backups always have OK-IF-OVERWRITE t
6745          (string-equal (car (find-backup-file-name from)) to))
6746         (dired-remove-file from))
6747     (or (member to dired-unhandle-add-files)
6748         (dired-relist-file to))))
6749
6750 (defun dired-handler-fn-3 (args)
6751   (let ((to (expand-file-name (nth 2 args))))
6752     (or (member to dired-unhandle-add-files)
6753         (dired-relist-file to))))
6754
6755 (defun dired-handler-fn-4 (args)
6756   (dired-remove-file (expand-file-name (car args))))
6757
6758 (defun dired-handler-fn-5 (args)
6759   (let ((to (expand-file-name (car args))))
6760     (or (member to dired-unhandle-add-files)
6761         (dired-relist-file to))))
6762
6763 (defun dired-handler-fn-6 (args)
6764   (let ((to (expand-file-name (nth 1 args)))
6765         (old (expand-file-name (car args))))
6766     (or (member to dired-unhandle-add-files)
6767         (dired-relist-file to))
6768     (dired-relist-file old)))
6769
6770 (put 'copy-file 'dired 'dired-handler-fn-1)
6771 (put 'dired-make-relative-symlink 'dired 'dired-handler-fn-1)
6772 (put 'make-symbolic-link 'dired 'dired-handler-fn-1)
6773 (put 'add-name-to-file 'dired 'dired-handler-fn-6)
6774 (put 'rename-file 'dired 'dired-handler-fn-2)
6775 (put 'write-region 'dired 'dired-handler-fn-3)
6776 (put 'delete-file 'dired 'dired-handler-fn-4)
6777 (put 'delete-directory 'dired 'dired-handler-fn-4)
6778 (put 'dired-recursive-delete-directory 'dired 'dired-handler-fn-4)
6779 (put 'make-directory-internal 'dired 'dired-handler-fn-5)
6780 (put 'set-file-modes 'dired 'dired-handler-fn-5)
6781
6782 ;;;; --------------------------------------------------------------
6783 ;;;; Multi-flavour Emacs support
6784 ;;;; --------------------------------------------------------------
6785
6786 (let ((lucid-p (string-match "XEmacs" emacs-version))
6787       (ver emacs-major-version))
6788   (unless ver
6789     (or (string-match "^\\([0-9]+\\)\\." emacs-version)
6790         (error "Weird emacs version %s" emacs-version))
6791     (setq ver (string-to-int (substring emacs-version (match-beginning 1)
6792                                         (match-end 1)))))
6793
6794   ;; Reading with history.
6795   (if (>= ver 19)
6796
6797       (defun dired-read-with-history (prompt initial history)
6798         (read-from-minibuffer prompt initial nil nil history))
6799
6800     (defun dired-read-with-history (prompt initial history)
6801       (let ((minibuffer-history-symbol history)) ; for gmhist
6802         (read-string prompt initial))))
6803
6804   ;; Completing read with history.
6805   (if (>= ver 19)
6806
6807       (fset 'dired-completing-read 'completing-read)
6808
6809     (defun dired-completing-read (prompt table &optional predicate
6810                                          require-match initial-input history)
6811       (let ((minibuffer-history-symbol history)) ; for gmhist
6812         (completing-read prompt table predicate require-match
6813                          initial-input))))
6814
6815   ;; Abbreviating file names.
6816   (if lucid-p
6817       (fset 'dired-abbreviate-file-name
6818             ;; Lemacs has this extra hack-homedir arg
6819             (function
6820              (lambda (fn)
6821                (abbreviate-file-name fn t))))
6822     (fset 'dired-abbreviate-file-name 'abbreviate-file-name))
6823
6824   ;; Deleting directories
6825   ;; Check for pre 19.8 versions of lucid emacs.
6826   (if lucid-p
6827       (or (fboundp 'delete-directory)
6828           (fset 'delete-directory 'remove-directory)))
6829
6830   ;; Minibuffers
6831   (if (= ver 18)
6832
6833       (defun dired-get-active-minibuffer-window ()
6834         (and (> (minibuffer-depth) 0)
6835              (minibuffer-window)))
6836
6837     (defun dired-get-active-minibuffer-window ()
6838       (let ((frames (frame-list))
6839             win found)
6840         (while frames
6841           (if (and (setq win (minibuffer-window (car frames)))
6842                    (minibuffer-window-active-p win))
6843               (setq found win
6844                     frames nil)
6845             (setq frames (cdr frames))))
6846         found)))
6847
6848   ;; Text properties and menus.
6849
6850   (cond
6851    (lucid-p
6852     (require 'dired-xemacs))
6853    ((>= ver 19)
6854     (require 'dired-fsf))
6855    (t
6856     ;; text property stuff doesn't work in V18
6857     (fset 'dired-insert-set-properties 'ignore)
6858     (fset 'dired-remove-text-properties 'ignore)
6859     (fset 'dired-set-text-properties 'ignore)
6860     (fset 'dired-maybe-filename-start 'ignore)
6861     (fset 'dired-maybe-filename-end 'ignore)
6862     (fset 'dired-move-to-filename 'dired-manual-move-to-filename)
6863     (fset 'dired-move-to-end-of-filename
6864           'dired-manual-move-to-end-of-filename))))
6865
6866 ;;; MULE
6867
6868 (if (or (boundp 'MULE) (featurep 'mule) (featurep 'file-coding)) (load "dired-mule"))
6869
6870 \f
6871 ;; Run load hook for user customization.
6872 (run-hooks 'dired-load-hook)
6873
6874 ;;; end of dired.el