*** empty log message ***
[bpt/emacs.git] / lisp / dired.el
CommitLineData
52041219
RS
1;; dired.el --- directory-browsing commands
2
3;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.
4;; Version: 5.234
5;; Last-Modified: 14 Jul 1992
6
492d2437 7;; Copyright (C) 1985, 1986, 1992 Free Software Foundation, Inc.
84fc2cfa
ER
8
9;; This file is part of GNU Emacs.
10
11;; GNU Emacs is free software; you can redistribute it and/or modify
12;; it under the terms of the GNU General Public License as published by
52041219 13;; the Free Software Foundation; either version 2, or (at your option)
84fc2cfa
ER
14;; any later version.
15
16;; GNU Emacs is distributed in the hope that it will be useful,
17;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19;; GNU General Public License for more details.
20
21;; You should have received a copy of the GNU General Public License
22;; along with GNU Emacs; see the file COPYING. If not, write to
23;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
24
52041219
RS
25;;; Commentary:
26
492d2437
RS
27;; Rewritten in 1990/1991 to add tree features, file marking and
28;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
29;; Finished up by rms in 1992.
30
52041219 31;;; Code:
492d2437
RS
32
33;; compatibility package when using Emacs 18.55
34(defvar dired-emacs-19-p (equal (substring emacs-version 0 2) "19"))
35;;;>>> install (is there a better way to test for Emacs 19?)
36(or dired-emacs-19-p
37 (require 'emacs-19))
38
39;;; Customizable variables
40
41;;; The funny comments are for autoload.el, to automagically update
42;;; loaddefs.
84fc2cfa
ER
43
44;;;###autoload
492d2437
RS
45(defvar dired-listing-switches "-al"
46 "*Switches passed to `ls' for dired. MUST contain the `l' option.
47May contain all other options that don't contradict `-l';
48may contain even `F', `b', `i' and `s'.")
84fc2cfa 49
492d2437
RS
50; Don't use absolute paths as /bin should be in any PATH and people
51; may prefer /usr/local/gnu/bin or whatever. However, chown is
52; usually not in PATH.
53
54;;;###autoload
84fc2cfa 55(defvar dired-chown-program
492d2437
RS
56 (if (memq system-type '(hpux dgux usg-unix-v)) "chown" "/etc/chown")
57 "Name of chown command (usully `chown' or `/etc/chown').")
58
59;;;###autoload
60(defvar dired-ls-program "ls"
61 "Absolute or relative name of the `ls' program used by dired.")
84fc2cfa 62
492d2437
RS
63;;;###autoload
64(defvar dired-ls-F-marks-symlinks nil
65 "*Informs dired about how `ls -lF' marks symbolic links.
66Set this to t if `dired-ls-program' with `-lF' marks the symbolic link
67itself with a trailing @ (usually the case under Ultrix).
84fc2cfa 68
492d2437
RS
69Example: if `ln -s foo bar; ls -F bar' gives `bar -> foo', set it to
70nil (the default), if it gives `bar@ -> foo', set it to t.
71
72Dired checks if there is really a @ appended. Thus, if you have a
73marking `ls' program on one host and a non-marking on another host, and
74don't care about symbolic links which really end in a @, you can
75always set this variable to t.")
76
77;;;###autoload
78(defvar dired-trivial-filenames "^\\.\\.?$\\|^#"
79 "*Regexp of files to skip when finding first file of a directory.
80A value of nil means move to the subdir line.
81A value of t means move to first file.")
82
83;;;###autoload
84(defvar dired-keep-marker-rename t
85 ;; Use t as default so that moved files "take their markers with them".
86 "*Controls marking of renamed files.
87If t, files keep their previous marks when they are renamed.
88If a character, renamed files (whether previously marked or not)
89are afterward marked with that character.")
90
91;;;###autoload
92(defvar dired-keep-marker-copy ?C
93 "*Controls marking of copied files.
94If t, copied files are marked if and as the corresponding original files were.
95If a character, copied files are unconditionally marked with that character.")
96
97;;;###autoload
98(defvar dired-keep-marker-hardlink ?H
99 "*Controls marking of newly made hard links.
100If t, they are marked if and as the files linked to were marked.
101If a character, new links are unconditionally marked with that character.")
102
103;;;###autoload
104(defvar dired-keep-marker-symlink ?Y
105 "*Controls marking of newly made symbolic links.
106If t, they are marked if and as the files linked to were marked.
107If a character, new links are unconditionally marked with that character.")
108
109;;;###autoload
110(defvar dired-dwim-target nil
111 "*If non-nil, dired tries to guess a default target directory.
112This means: if there is a dired buffer displayed in the next window,
113use its current subdir, instead of the current subdir of this dired buffer.
114
115The target is used in the prompt for file copy, rename etc.")
116
117;;;###autoload
118(defvar dired-copy-preserve-time t
119 "*If non-nil, Dired preserves the last-modified time in a file copy.
120\(This works on only some systems.)")
121
122;;; Hook variables
123
124(defvar dired-load-hook nil
125 "Run after loading dired.
126You can customize key bindings or load extensions with this.")
127
128(defvar dired-mode-hook nil
129 "Run at the very end of dired-mode.")
130
131(defvar dired-before-readin-hook nil
132 "This hook is run before a dired buffer is read in (created or reverted).")
133
134(defvar dired-after-readin-hook nil
135 "Hook run after each time a file or directory is read by Dired.
136After each listing of a file or directory, this hook is run
137with the buffer narrowed to the listing.")
138;; Note this can't simply be run inside function `dired-ls' as the hook
139;; functions probably depend on the dired-subdir-alist to be OK.
140
141;;; Internal variables
142
143(defvar dired-marker-char ?* ; the answer is 42
144 ;; so that you can write things like
145 ;; (let ((dired-marker-char ?X))
146 ;; ;; great code using X markers ...
147 ;; )
148 ;; For example, commands operating on two sets of files, A and B.
149 ;; Or marking files with digits 0-9. This could implicate
150 ;; concentric sets or an order for the marked files.
151 ;; The code depends on dynamic scoping on the marker char.
152 "In Dired, the current mark character.
153This is what the `do' commands look for and what the `mark' commands store.")
154
155(defvar dired-del-marker ?D
156 "Character used to flag files for deletion.")
157
158(defvar dired-shrink-to-fit
159 (if (fboundp 'baud-rate) (> (baud-rate) search-slow-speed) t)
160 "Non-nil means Dired shrinks the display buffer to fit the marked files.")
161
162(defvar dired-flagging-regexp nil);; Last regexp used to flag files.
163
164(defvar dired-directory nil
165 "The directory name or shell wildcard that was used as argument to `ls'.
166Local to each dired buffer.")
167
168(defvar dired-actual-switches nil
169 "The value of `dired-listing-switches' used to make this buffer's text.")
170
171(defvar dired-re-inode-size "[0-9 \t]*"
172 "Regexp for optional initial inode and file size as made by `ls -i -s'.")
173
174;; These regexps must be tested at beginning-of-line, but are also
175;; used to search for next matches, so neither omitting "^" nor
176;; replacing "^" by "\n" (to make it slightly faster) will work.
177
178(defvar dired-re-mark "^[^ \n]")
179;; "Regexp matching a marked line.
180;; Important: the match ends just after the marker."
181(defvar dired-re-maybe-mark "^. ")
182(defvar dired-re-dir (concat dired-re-maybe-mark dired-re-inode-size "d"))
183(defvar dired-re-sym (concat dired-re-maybe-mark dired-re-inode-size "l"))
184(defvar dired-re-exe;; match ls permission string of an executable file
185 (mapconcat (function
186 (lambda (x)
187 (concat dired-re-maybe-mark dired-re-inode-size x)))
188 '("-[-r][-w][xs][-r][-w].[-r][-w]."
189 "-[-r][-w].[-r][-w][xs][-r][-w]."
190 "-[-r][-w].[-r][-w].[-r][-w][xst]")
191 "\\|"))
192(defvar dired-re-dot "^.* \\.\\.?$")
193
194(defvar dired-subdir-alist nil
195 "Association list of subdirectories and their buffer positions.
196Each subdirectory has an element: (DIRNAME . STARTMARKER).
197The order of elements is the reverse of the order in the buffer.")
198
199(defvar dired-subdir-regexp "^. \\([^ \n\r]+\\)\\(:\\)[\n\r]"
200 "Regexp matching a maybe hidden subdirectory line in `ls -lR' output.
201Subexpression 1 is the subdirectory proper, no trailing colon.
202The match starts at the beginning of the line and ends after the end
203of the line (\\n or \\r).
204Subexpression 2 must end right before the \\n or \\r.")
205
206\f
207;;; Macros must be defined before they are used, for the byte compiler.
208
209;; Mark all files for which CONDITION evals to non-nil.
210;; CONDITION is evaluated on each line, with point at beginning of line.
211;; MSG is a noun phrase for the type of files being marked.
212;; It should end with a noun that can be pluralized by adding `s'.
213;; Return value is the number of files marked, or nil if none were marked.
214(defmacro dired-mark-if (predicate msg)
215 (` (let (buffer-read-only count)
216 (save-excursion
217 (setq count 0)
218 (if (, msg) (message "Marking %ss..." (, msg)))
219 (goto-char (point-min))
220 (while (not (eobp))
221 (if (, predicate)
222 (progn
223 (delete-char 1)
224 (insert dired-marker-char)
225 (setq count (1+ count))))
226 (forward-line 1))
227 (if (, msg) (message "%s %s%s %s%s."
228 count
229 (, msg)
230 (dired-plural-s count)
231 (if (eq dired-marker-char ?\040) "un" "")
232 (if (eq dired-marker-char dired-del-marker)
233 "flagged" "marked"))))
234 (and (> count 0) count))))
235
236(defmacro dired-map-over-marks (body arg &optional show-progress)
237;; "Macro: Perform BODY with point somewhere on each marked line
238;;and return a list of BODY's results.
239;;If no marked file could be found, execute BODY on the current line.
240;; If ARG is an integer, use the next ARG (or previous -ARG, if ARG<0)
241;; files instead of the marked files.
242;; In that case point is dragged along. This is so that commands on
243;; the next ARG (instead of the marked) files can be chained easily.
244;; If ARG is otherwise non-nil, use current file instead.
245;;If optional third arg SHOW-PROGRESS evaluates to non-nil,
246;; redisplay the dired buffer after each file is processed.
247;;No guarantee is made about the position on the marked line.
248;; BODY must ensure this itself if it depends on this.
249;;Search starts at the beginning of the buffer, thus the car of the list
250;; corresponds to the line nearest to the buffer's bottom. This
251;; is also true for (positive and negative) integer values of ARG.
252;;BODY should not be too long as it is expanded four times."
253;;
254;;Warning: BODY must not add new lines before point - this may cause an
255;;endless loop.
256;;This warning should not apply any longer, sk 2-Sep-1991 14:10.
257 (` (prog1
258 (let (buffer-read-only case-fold-search found results)
259 (if (, arg)
260 (if (integerp (, arg))
261 (progn;; no save-excursion, want to move point.
262 (dired-repeat-over-lines
263 (, arg)
264 (function (lambda ()
265 (if (, show-progress) (sit-for 0))
266 (setq results (cons (, body) results)))))
267 (if (< (, arg) 0)
268 (nreverse results)
269 results))
270 ;; non-nil, non-integer ARG means use current file:
271 (list (, body)))
272 (let ((regexp (dired-marker-regexp)) next-position)
273 (save-excursion
274 (goto-char (point-min))
275 ;; remember position of next marked file before BODY
276 ;; can insert lines before the just found file,
277 ;; confusing us by finding the same marked file again
278 ;; and again and...
279 (setq next-position (and (re-search-forward regexp nil t)
280 (point-marker))
281 found (not (null next-position)))
282 (while next-position
283 (goto-char next-position)
284 (if (, show-progress) (sit-for 0))
285 (setq results (cons (, body) results))
286 ;; move after last match
287 (goto-char next-position)
288 (forward-line 1)
289 (set-marker next-position nil)
290 (setq next-position (and (re-search-forward regexp nil t)
291 (point-marker)))))
292 (if found
293 results
294 (list (, body))))))
295 ;; save-excursion loses, again
296 (dired-move-to-filename))))
297
298(defun dired-get-marked-files (&optional localp arg)
299 "Return the marked files' names as list of strings.
300The list is in the same order as the buffer, that is, the car is the
301 first marked file.
302Values returned are normally absolute pathnames.
303Optional arg LOCALP as in `dired-get-filename'.
304Optional second argument ARG forces to use other files. If ARG is an
305 integer, use the next ARG files. If ARG is otherwise non-nil, use
306 current file. Usually ARG comes from the current prefix arg."
84fc2cfa 307 (save-excursion
492d2437 308 (nreverse (dired-map-over-marks (dired-get-filename localp) arg))))
84fc2cfa 309
492d2437
RS
310\f
311;; Function dired-ls is redefinable for VMS, ange-ftp, Prospero or
312;; other special applications.
313
314;; dired-ls
315;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
316;; FULL-DIRECTORY-P is nil.
317;; The single line of output must display FILE's name as it was
318;; given, namely, an absolute path name.
319;; - must insert exactly one line for each file if WILDCARD or
320;; FULL-DIRECTORY-P is t, plus one optional "total" line
321;; before the file lines, plus optional text after the file lines.
322;; Lines are delimited by "\n", so filenames containing "\n" are not
323;; allowed.
324;; File lines should display the basename, not a path name.
325;; - must drag point after inserted text
326;; - must be consistent with
327;; - functions dired-move-to-filename, (these two define what a file line is)
328;; dired-move-to-end-of-filename,
329;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
330;; dired-insert-headerline
331;; dired-after-subdir-garbage (defines what a "total" line is)
332;; - variables dired-subdir-regexp
333(defun dired-ls (file switches &optional wildcard full-directory-p)
334; "Insert `ls' output of FILE, formatted according to SWITCHES.
335;Optional third arg WILDCARD means treat FILE as shell wildcard.
336;Optional fourth arg FULL-DIRECTORY-P means file is a directory and
337;switches do not contain `d', so that a full listing is expected.
338;
339;Uses dired-ls-program (and shell-file-name if WILDCARD) to do the work."
340 (if wildcard
341 (let ((default-directory (file-name-directory file)))
342 (call-process shell-file-name nil t nil
343 "-c" (concat dired-ls-program " -d " switches " "
344 (file-name-nondirectory file))))
345 (call-process dired-ls-program nil t nil switches file)))
346\f
347;; The dired command
348
349(defun dired-read-dir-and-switches (str)
350 ;; For use in interactive.
351 (reverse (list
352 (if current-prefix-arg
353 (read-string "Dired listing switches: "
354 dired-listing-switches))
355 (read-file-name (format "Dired %s(directory): " str)
356 nil default-directory nil))))
84fc2cfa 357
492d2437 358;;;###autoload (define-key ctl-x-map "d" 'dired)
84fc2cfa 359;;;###autoload
492d2437 360(defun dired (dirname &optional switches)
84fc2cfa 361 "\"Edit\" directory DIRNAME--delete, rename, print, etc. some files in it.
492d2437
RS
362Optional second argument SWITCHES specifies the `ls' options used.
363\(Interactively, use a prefix argument to be able to specify SWITCHES.)
364Dired displays a list of files in DIRNAME (which may also have
365 shell wildcards appended to select certain files).
52041219 366\\<dired-mode-map>\
492d2437 367You can move around in it with the usual commands.
52041219 368You can flag files for deletion with \\[dired-flag-file-deletion] and then delete them by
492d2437
RS
369 typing \\[dired-do-flagged-delete].
370Type \\[describe-mode] after entering dired for more info.
84fc2cfa 371
492d2437
RS
372If DIRNAME is already in a dired buffer, that buffer is used without refresh."
373 ;; Cannot use (interactive "D") because of wildcards.
374 (interactive (dired-read-dir-and-switches ""))
375 (switch-to-buffer (dired-noselect dirname switches)))
376
377;;;###autoload (define-key ctl-x-4-map "d" 'dired-other-window)
84fc2cfa 378;;;###autoload
492d2437 379(defun dired-other-window (dirname &optional switches)
84fc2cfa 380 "\"Edit\" directory DIRNAME. Like `dired' but selects in another window."
492d2437
RS
381 (interactive (dired-read-dir-and-switches "in other window "))
382 (switch-to-buffer-other-window (dired-noselect dirname switches)))
84fc2cfa
ER
383
384;;;###autoload
492d2437 385(defun dired-noselect (dirname &optional switches)
84fc2cfa
ER
386 "Like `dired' but returns the dired buffer as value, does not select it."
387 (or dirname (setq dirname default-directory))
492d2437
RS
388 ;; This loses the distinction between "/foo/*/" and "/foo/*" that
389 ;; some shells make:
84fc2cfa
ER
390 (setq dirname (expand-file-name (directory-file-name dirname)))
391 (if (file-directory-p dirname)
392 (setq dirname (file-name-as-directory dirname)))
492d2437
RS
393 (dired-internal-noselect dirname switches))
394
395;; Separate function from dired-noselect for the sake of dired-vms.el.
396(defun dired-internal-noselect (dirname &optional switches)
397 ;; If there is an existing dired buffer for DIRNAME, just leave
398 ;; buffer as it is (don't even call dired-revert).
399 ;; This saves time especially for deep trees or with ange-ftp.
400 ;; The user can type `g'easily, and it is more consistent with find-file.
401 ;; But if SWITCHES are given they are probably different from the
402 ;; buffer's old value, so call dired-sort-other, which does
403 ;; revert the buffer.
404 ;; A pity we can't possibly do "Directory has changed - refresh? "
405 ;; like find-file does.
406 (let* ((buffer (dired-find-buffer-nocreate dirname))
407 ;; note that buffer already is in dired-mode, if found
408 (new-buffer-p (not buffer))
409 (old-buf (current-buffer)))
410 (or buffer
411 (let ((default-major-mode 'fundamental-mode))
412 ;; We don't want default-major-mode to run hooks and set auto-fill
413 ;; or whatever, now that dired-mode does not
414 ;; kill-all-local-variables any longer.
415 (setq buffer (create-file-buffer (directory-file-name dirname)))))
416 (set-buffer buffer)
417 (if (not new-buffer-p) ; existing buffer ...
418 (if switches ; ... but new switches
419 (dired-sort-other switches)) ; this calls dired-revert
420 ;; Else a new buffer
421 (setq default-directory (if (file-directory-p dirname)
422 dirname
423 (file-name-directory dirname)))
424 (or switches (setq switches dired-listing-switches))
425 (dired-mode dirname switches)
426 ;; default-directory and dired-actual-switches are set now
427 ;; (buffer-local), so we can call dired-readin:
428 (let ((failed t))
429 (unwind-protect
430 (progn (dired-readin dirname buffer)
431 (setq failed nil))
432 ;; dired-readin can fail if parent directories are inaccessible.
433 ;; Don't leave an empty buffer around in that case.
434 (if failed (kill-buffer buffer))))
435 ;; No need to narrow since the whole buffer contains just
436 ;; dired-readin's output, nothing else. The hook can
437 ;; successfully use dired functions (e.g. dired-get-filename)
438 ;; as the subdir-alist has been built in dired-readin.
439 (run-hooks 'dired-after-readin-hook)
440 (goto-char (point-min))
441 (dired-initial-position dirname))
442 (set-buffer old-buf)
84fc2cfa
ER
443 buffer))
444
492d2437
RS
445;; This differs from dired-buffers-for-dir in that it does not consider
446;; subdirs of default-directory and searches for the first match only
447(defun dired-find-buffer-nocreate (dirname)
448 (let (found (blist (buffer-list)))
449 (while blist
450 (save-excursion
451 (set-buffer (car blist))
452 (if (and (eq major-mode 'dired-mode)
453 (equal dired-directory dirname))
454 (setq found (car blist)
455 blist nil)
456 (setq blist (cdr blist)))))
457 found))
458
459\f
460;; Read in a new dired buffer
461
462;; dired-readin differs from dired-insert-subdir in that it accepts
463;; wildcards, erases the buffer, and builds the subdir-alist anew
464;; (including making it buffer-local and clearing it first).
465(defun dired-readin (dirname buffer)
466 ;; default-directory and dired-actual-switches must be buffer-local
467 ;; and initialized by now.
468 ;; Thus we can test (equal default-directory dirname) instead of
469 ;; (file-directory-p dirname) and save a filesystem transaction.
470 ;; Also, we can run this hook which may want to modify the switches
471 ;; based on default-directory, e.g. with ange-ftp to a SysV host
472 ;; where ls won't understand -Al switches.
473 (setq dirname (expand-file-name dirname))
474 (run-hooks 'dired-before-readin-hook)
475 (save-excursion
476 (message "Reading directory %s..." dirname)
477 (set-buffer buffer)
478 (let (buffer-read-only (failed t))
479 (widen)
480 (erase-buffer)
481 (dired-readin-insert dirname)
482 (indent-rigidly (point-min) (point-max) 2)
483 ;; We need this to make the root dir have a header line as all
484 ;; other subdirs have:
485 (goto-char (point-min))
486 (dired-insert-headerline default-directory)
487 ;; can't run dired-after-readin-hook here, it may depend on the subdir
488 ;; alist to be OK.
489 )
490 (message "Reading directory %s...done" dirname)
491 (set-buffer-modified-p nil)
492 ;; Must first make alist buffer local and set it to nil because
493 ;; dired-build-subdir-alist will call dired-clear-alist first
494 (set (make-local-variable 'dired-subdir-alist) nil)
495 (dired-build-subdir-alist)))
496
497;; Subroutines of dired-readin
498
499(defun dired-readin-insert (dirname)
500 ;; Just insert listing for DIRNAME, assuming a clean buffer.
501 (if (equal default-directory dirname);; i.e., (file-directory-p dirname)
502 (dired-ls dirname dired-actual-switches nil t)
503 (if (not (file-readable-p
504 (directory-file-name (file-name-directory dirname))))
505 (error "Directory %s inaccessible or nonexistent" dirname)
506 ;; else assume it contains wildcards:
507 (dired-ls dirname dired-actual-switches t)
508 (save-excursion;; insert wildcard instead of total line:
509 (goto-char (point-min))
510 (insert "wildcard " (file-name-nondirectory dirname) "\n")))))
511
512(defun dired-insert-headerline (dir);; also used by dired-insert-subdir
513 ;; Insert DIR's headerline with no trailing slash, exactly like ls
514 ;; would, and put cursor where dired-build-subdir-alist puts subdir
515 ;; boundaries.
516 (save-excursion (insert " " (directory-file-name dir) ":\n")))
517
518\f
519;; Reverting a dired buffer
520
84fc2cfa 521(defun dired-revert (&optional arg noconfirm)
492d2437
RS
522 ;; Reread the dired buffer. Must also be called after
523 ;; dired-actual-switches have changed.
524 ;; Should not fail even on completely garbaged buffers.
525 ;; Preserves old cursor, marks/flags, hidden-p.
526 (widen) ; just in case user narrowed
84fc2cfa 527 (let ((opoint (point))
492d2437
RS
528 (ofile (dired-get-filename nil t))
529 (mark-alist nil) ; save marked files
530 (hidden-subdirs (dired-remember-hidden))
531 (old-subdir-alist (cdr (reverse dired-subdir-alist))) ; except pwd
532 (case-fold-search nil) ; we check for upper case ls flags
533 buffer-read-only)
534 (goto-char (point-min))
535 (setq mark-alist;; only after dired-remember-hidden since this unhides:
536 (dired-remember-marks (point-min) (point-max)))
537 ;; treat top level dir extra (it may contain wildcards)
84fc2cfa 538 (dired-readin dired-directory (current-buffer))
492d2437
RS
539 (let ((dired-after-readin-hook nil))
540 ;; don't run that hook for each subdir...
541 (dired-insert-old-subdirs old-subdir-alist))
542 (dired-mark-remembered mark-alist) ; mark files that were marked
543 ;; ... run the hook for the whole buffer, and only after markers
544 ;; have been reinserted (else omitting in dired-x would omit marked files)
545 (run-hooks 'dired-after-readin-hook) ; no need to narrow
546 (or (and ofile (dired-goto-file ofile)) ; move cursor to where it
547 (goto-char opoint)) ; was before
84fc2cfa 548 (dired-move-to-filename)
492d2437
RS
549 (save-excursion ; hide subdirs that were hidden
550 (mapcar (function (lambda (dir)
551 (if (dired-goto-subdir dir)
552 (dired-hide-subdir 1))))
553 hidden-subdirs)))
554 ;; outside of the let scope
555;;; Might as well not override the user if the user changed this.
556;;; (setq buffer-read-only t)
557 )
558
559;; Subroutines of dired-revert
560;; Some of these are also used when inserting subdirs.
561
562(defun dired-remember-marks (beg end)
563 ;; Return alist of files and their marks, from BEG to END.
564 (if selective-display ; must unhide to make this work.
565 (let (buffer-read-only)
566 (subst-char-in-region beg end ?\r ?\n)))
567 (let (fil chr alist)
568 (save-excursion
569 (goto-char beg)
570 (while (re-search-forward dired-re-mark end t)
571 (if (setq fil (dired-get-filename nil t))
572 (setq chr (preceding-char)
573 alist (cons (cons fil chr) alist)))))
574 alist))
575
576;; Mark all files remembered in ALIST.
577;; Each element of ALIST looks like (FILE . MARKERCHAR).
578(defun dired-mark-remembered (alist)
579 (let (elt fil chr)
580 (while alist
581 (setq elt (car alist)
582 alist (cdr alist)
583 fil (car elt)
584 chr (cdr elt))
585 (if (dired-goto-file fil)
586 (save-excursion
587 (beginning-of-line)
588 (delete-char 1)
589 (insert chr))))))
590
591;; Return a list of names of subdirs currently hidden.
592(defun dired-remember-hidden ()
593 (let ((l dired-subdir-alist) dir pos result)
594 (while l
595 (setq dir (car (car l))
596 pos (cdr (car l))
597 l (cdr l))
598 (goto-char pos)
599 (skip-chars-forward "^\r\n")
52041219 600 (if (eq (following-char) ?\r)
492d2437
RS
601 (setq result (cons dir result))))
602 result))
603
604;; Try to insert all subdirs that were displayed before,
605;; according to the former subdir alist OLD-SUBDIR-ALIST.
606(defun dired-insert-old-subdirs (old-subdir-alist)
607 (or (string-match "R" dired-actual-switches)
608 (let (elt dir)
609 (while old-subdir-alist
610 (setq elt (car old-subdir-alist)
611 old-subdir-alist (cdr old-subdir-alist)
612 dir (car elt))
613 (condition-case ()
614 (dired-insert-subdir dir)
615 (error nil))))))
616\f
617;; dired mode key bindings and initialization
84fc2cfa
ER
618
619(defvar dired-mode-map nil "Local keymap for dired-mode buffers.")
620(if dired-mode-map
621 nil
492d2437
RS
622 ;; Force `f' rather than `e' in the mode doc:
623 (fset 'dired-advertised-find-file 'dired-find-file)
624 ;; This looks ugly when substitute-command-keys uses C-d instead d:
625 ;; (define-key dired-mode-map "\C-d" 'dired-flag-file-deletion)
626
84fc2cfa
ER
627 (setq dired-mode-map (make-keymap))
628 (suppress-keymap dired-mode-map)
492d2437 629 ;; Commands to mark or flag certain categories of files
84fc2cfa 630 (define-key dired-mode-map "#" 'dired-flag-auto-save-files)
492d2437 631 (define-key dired-mode-map "*" 'dired-mark-executables)
84fc2cfa 632 (define-key dired-mode-map "." 'dired-clean-directory)
492d2437
RS
633 (define-key dired-mode-map "/" 'dired-mark-directories)
634 (define-key dired-mode-map "@" 'dired-mark-symlinks)
635 (define-key dired-mode-map "~" 'dired-flag-backup-files)
636 ;; Upper case keys (except !, c) for operating on the marked files
637 (define-key dired-mode-map "C" 'dired-do-copy)
638 (define-key dired-mode-map "B" 'dired-do-byte-compile)
639 (define-key dired-mode-map "D" 'dired-do-delete)
640 (define-key dired-mode-map "G" 'dired-do-chgrp)
641 (define-key dired-mode-map "H" 'dired-do-hardlink)
642 (define-key dired-mode-map "L" 'dired-do-load)
643 (define-key dired-mode-map "M" 'dired-do-chmod)
644 (define-key dired-mode-map "O" 'dired-do-chown)
645 (define-key dired-mode-map "P" 'dired-do-print)
646 (define-key dired-mode-map "R" 'dired-do-rename)
647 (define-key dired-mode-map "S" 'dired-do-symlink)
648 (define-key dired-mode-map "X" 'dired-do-shell-command)
649 (define-key dired-mode-map "Z" 'dired-do-compress)
650 (define-key dired-mode-map "!" 'dired-do-shell-command)
651 ;; Comparison commands
652 (define-key dired-mode-map "=" 'dired-diff)
653 (define-key dired-mode-map "\M-=" 'dired-backup-diff)
654 ;; Tree Dired commands
655 (define-key dired-mode-map "\M-\C-?" 'dired-unmark-all-files)
656 (define-key dired-mode-map "\M-\C-d" 'dired-tree-down)
657 (define-key dired-mode-map "\M-\C-u" 'dired-tree-up)
658 (define-key dired-mode-map "\M-\C-n" 'dired-next-subdir)
659 (define-key dired-mode-map "\M-\C-p" 'dired-prev-subdir)
660 ;; move to marked files
661 (define-key dired-mode-map "\M-{" 'dired-prev-marked-file)
662 (define-key dired-mode-map "\M-}" 'dired-next-marked-file)
663 ;; kill marked files
664 (define-key dired-mode-map "\M-k" 'dired-do-kill-lines)
665 ;; Make all regexp commands share a `%' prefix:
666 (fset 'dired-regexp-prefix (make-sparse-keymap))
667 (define-key dired-mode-map "%" 'dired-regexp-prefix)
668 (define-key dired-mode-map "%u" 'dired-upcase)
669 (define-key dired-mode-map "%l" 'dired-downcase)
670 (define-key dired-mode-map "%d" 'dired-flag-files-regexp)
671 (define-key dired-mode-map "%m" 'dired-mark-files-regexp)
672 (define-key dired-mode-map "%r" 'dired-do-rename-regexp)
673 (define-key dired-mode-map "%C" 'dired-do-copy-regexp)
674 (define-key dired-mode-map "%H" 'dired-do-hardlink-regexp)
675 (define-key dired-mode-map "%R" 'dired-do-rename-regexp)
676 (define-key dired-mode-map "%S" 'dired-do-symlink-regexp)
677 ;; Lower keys for commands not operating on all the marked files
678 (define-key dired-mode-map "d" 'dired-flag-file-deletion)
679 (define-key dired-mode-map "e" 'dired-find-file)
680 (define-key dired-mode-map "f" 'dired-advertised-find-file)
681 (define-key dired-mode-map "g" 'revert-buffer)
84fc2cfa 682 (define-key dired-mode-map "h" 'describe-mode)
492d2437
RS
683 (define-key dired-mode-map "i" 'dired-maybe-insert-subdir)
684 (define-key dired-mode-map "k" 'dired-kill-line-or-subdir)
685 (define-key dired-mode-map "l" 'dired-do-redisplay)
686 (define-key dired-mode-map "m" 'dired-mark)
687 (define-key dired-mode-map "n" 'dired-next-line)
688 (define-key dired-mode-map "o" 'dired-find-file-other-window)
689 (define-key dired-mode-map "p" 'dired-previous-line)
690 (define-key dired-mode-map "q" 'dired-quit)
691 (define-key dired-mode-map "s" 'dired-sort-toggle-or-edit)
692 (define-key dired-mode-map "u" 'dired-unmark)
693 (define-key dired-mode-map "v" 'dired-view-file)
694 (define-key dired-mode-map "x" 'dired-do-flagged-delete)
695 (define-key dired-mode-map "+" 'dired-create-directory)
696 ;; moving
697 (define-key dired-mode-map "<" 'dired-prev-dirline)
698 (define-key dired-mode-map ">" 'dired-next-dirline)
699 (define-key dired-mode-map "^" 'dired-up-directory)
84fc2cfa
ER
700 (define-key dired-mode-map " " 'dired-next-line)
701 (define-key dired-mode-map "\C-n" 'dired-next-line)
702 (define-key dired-mode-map "\C-p" 'dired-previous-line)
492d2437
RS
703 ;; hiding
704 (define-key dired-mode-map "$" 'dired-hide-subdir)
705 (define-key dired-mode-map "\M-$" 'dired-hide-all)
706 ;; misc
707 (define-key dired-mode-map "?" 'dired-summary)
708 (define-key dired-mode-map "\177" 'dired-unmark-backward)
709 (define-key dired-mode-map "\C-_" 'dired-undo)
710 (define-key dired-mode-map "\C-xu" 'dired-undo)
711 )
84fc2cfa 712
492d2437
RS
713(or (member '(dired-sort-mode dired-sort-mode) minor-mode-alist)
714 ;; Test whether this has already been done in case dired is reloaded
715 ;; There may be several elements with dired-sort-mode as car.
716 (setq minor-mode-alist
717 (cons '(dired-sort-mode dired-sort-mode)
718 ;; dired-sort-mode is nil outside dired
719 minor-mode-alist)))
720\f
84fc2cfa
ER
721;; Dired mode is suitable only for specially formatted data.
722(put 'dired-mode 'mode-class 'special)
723
492d2437
RS
724(defun dired-mode (&optional dirname switches)
725 "\
726Mode for \"editing\" directory listings.
727In dired, you are \"editing\" a list of the files in a directory and
728 \(optionally) its subdirectories, in the format of `ls -lR'.
729 Each directory is a page: use \\[backward-page] and \\[forward-page] to move pagewise.
730\"Editing\" means that you can run shell commands on files, visit,
731 compress, load or byte-compile them, change their file attributes
732 and insert subdirectories into the same buffer. You can \"mark\"
733 files for later commands or \"flag\" them for deletion, either file
734 by file or all files matching certain criteria.
735You can move using the usual cursor motion commands.\\<dired-mode-map>
736Letters no longer insert themselves. Digits are prefix arguments.
737Instead, type \\[dired-flag-file-deletion] to flag a file for Deletion.
738Type \\[dired-mark] to Mark a file or subdirectory for later commands.
739 Most commands operate on the marked files and use the current file
740 if no files are marked. Use a numeric prefix argument to operate on
741 the next ARG (or previous -ARG if ARG<0) files, or just `1'
742 to operate on the current file only. Prefix arguments override marks.
743 Mark-using commands display a list of failures afterwards. Type \\[dired-summary]
744 to see why something went wrong.
745Type \\[dired-unmark] to Unmark a file or all files of a subdirectory.
746Type \\[dired-unmark-backward] to back up one line and unflag.
747Type \\[dired-do-flagged-delete] to eXecute the deletions requested.
748Type \\[dired-advertised-find-file] to Find the current line's file
749 (or dired it in another buffer, if it is a directory).
750Type \\[dired-find-file-other-window] to find file or dired directory in Other window.
751Type \\[dired-maybe-insert-subdir] to Insert a subdirectory in this buffer.
752Type \\[dired-do-rename] to Rename a file or move the marked files to another directory.
753Type \\[dired-do-copy] to Copy files.
754Type \\[dired-sort-toggle-or-edit] to toggle sorting by name/date or change the `ls' switches.
755Type \\[revert-buffer] to read all currently expanded directories again.
756 This retains all marks and hides subdirs again that were hidden before.
757SPC and DEL can be used to move down and up by lines.
758
759If dired ever gets confused, you can either type \\[revert-buffer] \
760to read the
761directories again, type \\[dired-do-redisplay] \
762to relist a single or the marked files or a
763subdirectory, or type \\[dired-build-subdir-alist] to parse the buffer
764again for the directory tree.
765
766Customization variables (rename this buffer and type \\[describe-variable] on each line
767for more info):
768
769 dired-listing-switches
770 dired-trivial-filenames
771 dired-shrink-to-fit
772 dired-marker-char
773 dired-del-marker
774 dired-keep-marker-rename
775 dired-keep-marker-copy
776 dired-keep-marker-hardlink
777 dired-keep-marker-symlink
778
779Hooks (use \\[describe-variable] to see their documentation):
780
781 dired-before-readin-hook
782 dired-after-readin-hook
783 dired-mode-hook
784 dired-load-hook
785
786Keybindings:
84fc2cfa 787\\{dired-mode-map}"
492d2437
RS
788 ;; Not to be called interactively (e.g. dired-directory will be set
789 ;; to default-directory, which is wrong with wildcards).
84fc2cfa 790 (kill-all-local-variables)
84fc2cfa 791 (use-local-map dired-mode-map)
492d2437
RS
792 (dired-advertise) ; default-directory is already set
793 (setq major-mode 'dired-mode
794 mode-name "Dired"
795 case-fold-search nil
796 buffer-read-only t
797 selective-display t ; for subdirectory hiding
798 mode-line-buffer-identification '("Dired: %17b"))
799 (set (make-local-variable 'revert-buffer-function)
800 (function dired-revert))
801 (set (make-local-variable 'page-delimiter)
802 "\n\n")
803 (set (make-local-variable 'dired-directory)
804 (or dirname default-directory))
805 ;; list-buffers uses this to display the dir being edited in this buffer.
806 (set (make-local-variable 'list-buffers-directory)
807 dired-directory)
808 (set (make-local-variable 'dired-actual-switches)
809 (or switches dired-listing-switches))
810 (make-local-variable 'dired-sort-mode)
811 (dired-sort-other dired-actual-switches t)
84fc2cfa
ER
812 (run-hooks 'dired-mode-hook))
813\f
492d2437 814;; Ideosyncratic dired commands that don't deal with marks.
84fc2cfa 815
492d2437
RS
816(defun dired-quit ()
817 "Bury the current dired buffer."
818 (interactive)
819 (bury-buffer))
84fc2cfa
ER
820
821(defun dired-summary ()
492d2437 822 "Summarize basic Dired commands and show recent Dired errors."
84fc2cfa 823 (interactive)
492d2437 824 (dired-why)
84fc2cfa
ER
825 ;>> this should check the key-bindings and use substitute-command-keys if non-standard
826 (message
492d2437 827 "d-elete, u-ndelete, x-punge, f-ind, o-ther window, r-ename, C-opy, h-elp"))
84fc2cfa 828
492d2437
RS
829(defun dired-undo ()
830 "Undo in a dired buffer.
831This doesn't recover lost files, it just undoes changes in the buffer itself.
832You can use it to recover marks, killed lines or subdirs.
833In the latter case, you have to do \\[dired-build-subdir-alist] to
834parse the buffer again."
835 (interactive)
836 (let (buffer-read-only)
837 (undo)))
84fc2cfa
ER
838
839(defun dired-next-line (arg)
840 "Move down lines then position at filename.
841Optional prefix ARG says how many lines to move; default is one line."
842 (interactive "p")
843 (next-line arg)
844 (dired-move-to-filename))
845
846(defun dired-previous-line (arg)
847 "Move up lines then position at filename.
848Optional prefix ARG says how many lines to move; default is one line."
849 (interactive "p")
850 (previous-line arg)
851 (dired-move-to-filename))
852
492d2437
RS
853(defun dired-next-dirline (arg &optional opoint)
854 "Goto ARG'th next directory file line."
855 (interactive "p")
856 (or opoint (setq opoint (point)))
857 (if (if (> arg 0)
858 (re-search-forward dired-re-dir nil t arg)
859 (beginning-of-line)
860 (re-search-backward dired-re-dir nil t (- arg)))
861 (dired-move-to-filename) ; user may type `i' or `f'
862 (goto-char opoint)
863 (error "No more subdirectories")))
864
865(defun dired-prev-dirline (arg)
866 "Goto ARG'th previous directory file line."
867 (interactive "p")
868 (dired-next-dirline (- arg)))
869
84fc2cfa 870(defun dired-up-directory ()
492d2437
RS
871 "Run dired on parent directory of current directory.
872Find the parent directory either in this buffer or another buffer.
873Creates a buffer if necessary."
84fc2cfa 874 (interactive)
492d2437
RS
875 (let* ((dir (dired-current-directory))
876 (up (file-name-directory (directory-file-name dir))))
877 (or (dired-goto-file (directory-file-name dir))
878 (and dired-subdir-alist
879 (dired-goto-subdir up))
880 (progn
881 (dired up)
882 (dired-goto-file dir)))))
84fc2cfa
ER
883
884(defun dired-find-file ()
885 "In dired, visit the file or directory named on this line."
886 (interactive)
887 (find-file (dired-get-filename)))
888
889(defun dired-view-file ()
492d2437
RS
890 "In dired, examine a file in view mode, returning to dired when done.
891When file is a directory, show it in this buffer if it is inserted;
892otherwise, display it in another buffer."
84fc2cfa
ER
893 (interactive)
894 (if (file-directory-p (dired-get-filename))
492d2437
RS
895 (or (and dired-subdir-alist (dired-goto-subdir (dired-get-filename)))
896 (dired (dired-get-filename)))
84fc2cfa
ER
897 (view-file (dired-get-filename))))
898
899(defun dired-find-file-other-window ()
900 "In dired, visit this file or directory in another window."
901 (interactive)
902 (find-file-other-window (dired-get-filename)))
492d2437
RS
903\f
904;;; Functions for extracting and manipulating file names in dired buffers.
84fc2cfa
ER
905
906(defun dired-get-filename (&optional localp no-error-if-not-filep)
907 "In dired, return name of file mentioned on this line.
908Value returned normally includes the directory name.
492d2437
RS
909Optional arg LOCALP with value `no-dir' means don't include directory
910 name in result. A value of t means construct name relative to
911 `default-directory', which still may contain slashes if in a subdirectory.
912Optional arg NO-ERROR-IF-NOT-FILEP means return nil if no filename on
913 this line, otherwise an error occurs."
914 (let (case-fold-search file p1 p2)
84fc2cfa 915 (save-excursion
492d2437
RS
916 (if (setq p1 (dired-move-to-filename (not no-error-if-not-filep)))
917 (setq p2 (dired-move-to-end-of-filename no-error-if-not-filep))))
918 ;; nil if no file on this line, but no-error-if-not-filep is t:
919 (if (setq file (and p1 p2 (buffer-substring p1 p2)))
920 ;; Check if ls quoted the names, and unquote them.
921 ;; Using read to unquote is much faster than substituting
922 ;; \007 (4 chars) -> ^G (1 char) etc. in a lisp loop.
923 (cond ((string-match "b" dired-actual-switches) ; System V ls
924 ;; This case is about 20% slower than without -b.
925 (setq file
926 (read
927 (concat "\""
928 ;; some ls -b don't escape quotes, argh!
929 ;; This is not needed for GNU ls, though.
930 (or (dired-string-replace-match
931 "\\([^\\]\\)\"" file "\\1\\\\\"")
932 file)
933 "\""))))
934 ;; If you do this, update dired-insert-subdir-validate too
935 ;; ((string-match "Q" dired-actual-switches) ; GNU ls
936 ;; (setq file (read file)))
937 ))
938 (if (eq localp 'no-dir)
939 file
940 (and file (concat (dired-current-directory localp) file)))))
941
942(defun dired-make-absolute (file &optional dir)
943 ;;"Convert FILE (a pathname relative to DIR) to an absolute pathname."
944 ;; We can't always use expand-file-name as this would get rid of `.'
945 ;; or expand in / instead default-directory if DIR=="".
946 ;; This should be good enough for ange-ftp, but might easily be
947 ;; redefined (for VMS?).
948 ;; It should be reasonably fast, though, as it is called in
949 ;; dired-get-filename.
950 (concat (or dir default-directory) file))
951
952(defun dired-make-relative (file &optional dir no-error)
953 ;;"Convert FILE (an absolute pathname) to a pathname relative to DIR.
954 ;; Else error (unless NO-ERROR is non-nil, then FILE is returned unchanged)
955 ;;DIR defaults to default-directory."
956 ;; DIR must be file-name-as-directory, as with all directory args in
52041219 957 ;; Emacs Lisp code.
492d2437
RS
958 (or dir (setq dir default-directory))
959 (if (string-match (concat "^" (regexp-quote dir)) file)
960 (substring file (match-end 0))
961 (if no-error
962 file
963 (error "%s: not in directory tree growing at %s" file dir))))
964\f
965;;; Functions for finding the file name in a dired buffer line.
966
967;; Move to first char of filename on this line.
968;; Returns position (point) or nil if no filename on this line."
969(defun dired-move-to-filename (&optional raise-error eol)
970 ;; This is the UNIX version.
971 (or eol (setq eol (progn (end-of-line) (point))))
972 (beginning-of-line)
973 (if (re-search-forward
974 "\\(Jan\\|Feb\\|Mar\\|Apr\\|May\\|Jun\\|Jul\\|Aug\\|Sep\\|Oct\\|Nov\\|Dec\\)[ ]+[0-9]+"
975 eol t)
976 (progn
977 (skip-chars-forward " ") ; there is one SPC after day of month
978 (skip-chars-forward "^ " eol) ; move after time of day (or year)
979 (skip-chars-forward " " eol) ; there is space before the file name
980 ;; Actually, if the year instead of clock time is displayed,
981 ;; there are (only for some ls programs?) two spaces instead
982 ;; of one before the name.
983 ;; If we could depend on ls inserting exactly one SPC we
984 ;; would not bomb on names _starting_ with SPC.
985 (point))
986 (if raise-error
987 (error "No file on this line")
988 nil)))
989
990(defun dired-move-to-end-of-filename (&optional no-error)
991 ;; Assumes point is at beginning of filename,
992 ;; thus the rwx bit re-search-backward below will succeed in *this*
993 ;; line if at all. So, it should be called only after
994 ;; (dired-move-to-filename t).
995 ;; On failure, signals an error (with non-nil NO-ERROR just returns nil).
996 ;; This is the UNIX version.
997 (let (opoint file-type executable symlink hidden case-fold-search used-F eol)
998 ;; case-fold-search is nil now, so we can test for capital F:
999 (setq used-F (string-match "F" dired-actual-switches)
1000 opoint (point)
1001 eol (save-excursion (end-of-line) (point))
1002 hidden (and selective-display
1003 (save-excursion (search-forward "\r" eol t))))
1004 (if hidden
1005 nil
1006 (save-excursion;; Find out what kind of file this is:
1007 ;; Restrict perm bits to be non-blank,
1008 ;; otherwise this matches one char to early (looking backward):
1009 ;; "l---------" (some systems make symlinks that way)
1010 ;; "----------" (plain file with zero perms)
1011 (if (re-search-backward
1012 "\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)"
1013 nil t)
1014 (setq file-type (char-after (match-beginning 1))
1015 symlink (eq file-type ?l)
1016 ;; Only with -F we need to know whether it's an executable
1017 executable (and
1018 used-F
1019 (string-match
1020 "[xst]";; execute bit set anywhere?
1021 (concat
1022 (buffer-substring (match-beginning 2)
1023 (match-end 2))
1024 (buffer-substring (match-beginning 3)
1025 (match-end 3))
1026 (buffer-substring (match-beginning 4)
1027 (match-end 4))))))
1028 (or no-error (error "No file on this line"))))
1029 ;; Move point to end of name:
1030 (if symlink
1031 (if (search-forward " ->" eol t)
1032 (progn
1033 (forward-char -3)
1034 (and used-F
1035 dired-ls-F-marks-symlinks
1036 (eq (preceding-char) ?@);; did ls really mark the link?
1037 (forward-char -1))))
1038 (goto-char eol);; else not a symbolic link
1039 ;; ls -lF marks dirs, sockets and executables with exactly one
1040 ;; trailing character. (Executable bits on symlinks ain't mean
1041 ;; a thing, even to ls, but we know it's not a symlink.)
1042 (and used-F
1043 (or (memq file-type '(?d ?s))
1044 executable)
1045 (forward-char -1))))
1046 (or no-error
1047 (not (eq opoint (point)))
1048 (error (if hidden
1049 (substitute-command-keys
1050 "File line is hidden, type \\[dired-hide-subdir] to unhide")
1051 "No file on this line")))
1052 (if (eq opoint (point))
1053 nil
1054 (point))))
1055
1056\f
1057;; Keeping Dired buffers in sync with the filesystem and with each other
1058
1059(defvar dired-buffers nil
1060 ;; Enlarged by dired-advertise
1061 ;; Queried by function dired-buffers-for-dir. When this detects a
1062 ;; killed buffer, it is removed from this list.
1063 "Alist of directories and their associated dired buffers.")
1064
1065(defun dired-buffers-for-dir (dir)
1066;; Return a list of buffers that dired DIR (top level or in-situ subdir).
1067;; The list is in reverse order of buffer creation, most recent last.
1068;; As a side effect, killed dired buffers for DIR are removed from
1069;; dired-buffers.
1070 (setq dir (file-name-as-directory dir))
1071 (let ((alist dired-buffers) result elt)
1072 (while alist
1073 (setq elt (car alist))
1074 (if (dired-in-this-tree dir (car elt))
1075 (let ((buf (cdr elt)))
1076 (if (buffer-name buf)
1077 (if (assoc dir (save-excursion
1078 (set-buffer buf)
1079 dired-subdir-alist))
1080 (setq result (cons buf result)))
1081 ;; else buffer is killed - clean up:
1082 (setq dired-buffers (delq elt dired-buffers)))))
1083 (setq alist (cdr alist)))
1084 result))
1085
1086(defun dired-advertise ()
1087 ;;"Advertise in variable `dired-buffers' that we dired `default-directory'."
1088 ;; With wildcards we actually advertise too much.
1089 (if (memq (current-buffer) (dired-buffers-for-dir default-directory))
1090 t ; we have already advertised ourselves
1091 (setq dired-buffers
1092 (cons (cons default-directory (current-buffer))
1093 dired-buffers))))
1094
1095(defun dired-unadvertise (dir)
1096 ;; Remove DIR from the buffer alist in variable dired-buffers.
1097 ;; This has the effect of removing any buffer whose main directory is DIR.
1098 ;; It does not affect buffers in which DIR is a subdir.
1099 ;; Removing is also done as a side-effect in dired-buffer-for-dir.
1100 (setq dired-buffers
1101 (delq (assoc dir dired-buffers) dired-buffers)))
1102\f
1103;; Tree Dired
1104
1105;;; utility functions
1106
1107(defun dired-in-this-tree (file dir)
1108 ;;"Is FILE part of the directory tree starting at DIR?"
1109 (let (case-fold-search)
1110 (string-match (concat "^" (regexp-quote dir)) file)))
1111
1112(defun dired-normalize-subdir (dir)
1113 ;; Prepend default-directory to DIR if relative path name.
1114 ;; dired-get-filename must be able to make a valid filename from a
1115 ;; file and its directory DIR.
1116 (file-name-as-directory
1117 (if (file-name-absolute-p dir)
1118 dir
1119 (expand-file-name dir default-directory))))
1120
1121(defun dired-get-subdir ()
1122 ;;"Return the subdir name on this line, or nil if not on a headerline."
1123 ;; Look up in the alist whether this is a headerline.
1124 (save-excursion
1125 (let ((cur-dir (dired-current-directory)))
1126 (beginning-of-line) ; alist stores b-o-l positions
1127 (and (zerop (- (point)
1128 (dired-get-subdir-min (assoc cur-dir
1129 dired-subdir-alist))))
1130 cur-dir))))
1131
1132;(defun dired-get-subdir-min (elt)
1133; (cdr elt))
1134;; can't use macro, must be redefinable for other alist format in dired-nstd.
1135(fset 'dired-get-subdir-min 'cdr)
1136
1137(defun dired-get-subdir-max (elt)
84fc2cfa 1138 (save-excursion
492d2437
RS
1139 (goto-char (dired-get-subdir-min elt))
1140 (dired-subdir-max)))
1141
1142(defun dired-clear-alist ()
1143 (while dired-subdir-alist
1144 (set-marker (dired-get-subdir-min (car dired-subdir-alist)) nil)
1145 (setq dired-subdir-alist (cdr dired-subdir-alist))))
1146
1147(defun dired-build-subdir-alist ()
1148 "Build `dired-subdir-alist' by parsing the buffer.
1149Returns the new value of the alist."
1150 (interactive)
1151 (dired-clear-alist)
1152 (save-excursion
1153 (let ((count 0))
84fc2cfa 1154 (goto-char (point-min))
492d2437
RS
1155 (setq dired-subdir-alist nil)
1156 (while (re-search-forward dired-subdir-regexp nil t)
1157 (setq count (1+ count))
1158 (dired-alist-add-1 (buffer-substring (match-beginning 1)
1159 (match-end 1))
1160 ;; Put subdir boundary between lines:
1161 (save-excursion
1162 (goto-char (match-beginning 0))
1163 (beginning-of-line)
1164 (point-marker)))
1165 (message "%d" count))
1166 (message "%d director%s" count (if (= 1 count) "y" "ies"))
1167 ;; We don't need to sort it because it is in buffer order per
1168 ;; constructionem. Return new alist:
1169 dired-subdir-alist)))
1170
1171(defun dired-alist-add-1 (dir new-marker)
1172 ;; Add new DIR at NEW-MARKER. Don't sort.
1173 (setq dired-subdir-alist
1174 (cons (cons (dired-normalize-subdir dir) new-marker)
1175 dired-subdir-alist)))
1176
1177(defun dired-goto-next-nontrivial-file ()
1178 ;; Position point on first nontrivial file after point.
1179 (dired-goto-next-file);; so there is a file to compare with
1180 (if (stringp dired-trivial-filenames)
1181 (while (and (not (eobp))
1182 (string-match dired-trivial-filenames
1183 (file-name-nondirectory
1184 (or (dired-get-filename nil t) ""))))
1185 (forward-line 1)
1186 (dired-move-to-filename))))
1187
1188(defun dired-goto-next-file ()
1189 (let ((max (1- (dired-subdir-max))))
1190 (while (and (not (dired-move-to-filename)) (< (point) max))
1191 (forward-line 1))))
1192
1193(defun dired-goto-file (file)
1194 "Go to file line of FILE in this dired buffer."
1195 ;; Return value of point on success, else nil.
1196 ;; FILE must be an absolute pathname.
1197 ;; Loses if FILE contains control chars like "\007" for which ls
1198 ;; either inserts "?" or "\\007" into the buffer, so we won't find
1199 ;; it in the buffer.
1200 (interactive
1201 (prog1 ; let push-mark display its message
1202 (list (expand-file-name
1203 (read-file-name "Goto file: "
1204 (dired-current-directory))))
1205 (push-mark)))
1206 (setq file (directory-file-name file)) ; does no harm if no directory
1207 (let (found case-fold-search dir)
1208 (setq dir (or (file-name-directory file)
1209 (error "Need absolute pathname for %s" file)))
1210 (save-excursion
1211 ;; The hair here is to get the result of dired-goto-subdir
1212 ;; without really calling it if we don't have any subdirs.
1213 (if (if (string= dir default-directory)
1214 (goto-char (point-min))
1215 (and dired-subdir-alist
1216 (dired-goto-subdir dir)))
1217 (let ((base (file-name-nondirectory file))
1218 (boundary (dired-subdir-max)))
1219 (while (and (not found)
1220 ;; filenames are preceded by SPC, this makes
1221 ;; the search faster (e.g. for the filename "-"!).
1222 (search-forward (concat " " base) boundary 'move))
1223 ;; Match could have BASE just as initial substring or
1224 ;; or in permission bits or date or
1225 ;; not be a proper filename at all:
1226 (if (equal base (dired-get-filename 'no-dir t))
1227 ;; Must move to filename since an (actually
1228 ;; correct) match could have been elsewhere on the
1229 ;; ;; line (e.g. "-" would match somewhere in the
1230 ;; permission bits).
1231 (setq found (dired-move-to-filename)))))))
1232 (and found
1233 ;; return value of point (i.e., FOUND):
1234 (goto-char found))))
1235
1236(defun dired-initial-position (dirname)
1237 ;; Where point should go in a new listing of DIRNAME.
1238 ;; Point assumed at beginning of new subdir line.
1239 ;; You may redefine this function as you wish, e.g. like in dired-x.el.
1240 (end-of-line)
1241 (if dired-trivial-filenames (dired-goto-next-nontrivial-file)))
1242\f
1243;; These are hooks which make tree dired work.
1244;; They are in this file because other parts of dired need to call them.
1245;; But they don't call the rest of tree dired unless there are subdirs loaded.
1246
1247;; This function is called for each retrieved filename.
1248;; It could stand to be faster, though it's mostly function call
1249;; overhead. Avoiding the function call seems to save about 10% in
1250;; dired-get-filename. Make it a defsubst?
1251(defun dired-current-directory (&optional localp)
1252 "Return the name of the subdirectory to which this line belongs.
1253This returns a string with trailing slash, like `default-directory'.
1254Optional argument means return a file name relative to `default-directory'."
1255 (let ((here (point))
1256 (alist (or dired-subdir-alist
1257 ;; probably because called in a non-dired buffer
1258 (error "No subdir-alist in %s" (current-buffer))))
1259 elt dir)
1260 (while alist
1261 (setq elt (car alist)
1262 dir (car elt)
1263 ;; use `<=' (not `<') as subdir line is part of subdir
1264 alist (if (<= (dired-get-subdir-min elt) here)
1265 nil ; found
1266 (cdr alist))))
1267 (if localp
1268 (dired-make-relative dir default-directory)
1269 dir)))
1270
1271;; Subdirs start at the beginning of their header lines and end just
1272;; before the beginning of the next header line (or end of buffer).
1273
1274(defun dired-subdir-max ()
1275 (save-excursion
1276 (if (or (null dired-subdir-alist) (not (dired-next-subdir 1 t t)))
1277 (point-max)
1278 (point))))
1279\f
1280;; Deleting files
1281
1282(defun dired-do-flagged-delete ()
1283 "In dired, delete the files flagged for deletion."
1284 (interactive)
1285 (let* ((dired-marker-char dired-del-marker)
1286 (regexp (dired-marker-regexp))
1287 case-fold-search)
1288 (if (save-excursion (goto-char (point-min))
1289 (re-search-forward regexp nil t))
1290 (dired-internal-do-deletions
1291 ;; this can't move point since ARG is nil
1292 (dired-map-over-marks (cons (dired-get-filename) (point))
1293 nil)
1294 nil)
1295 (message "(No deletions requested)"))))
1296
1297(defun dired-do-delete (&optional arg)
1298 "Delete all marked (or next ARG) files."
1299 ;; This is more consistent with the file marking feature than
1300 ;; dired-do-flagged-delete.
1301 (interactive "P")
1302 (dired-internal-do-deletions
1303 ;; this may move point if ARG is an integer
1304 (dired-map-over-marks (cons (dired-get-filename) (point))
1305 arg)
1306 arg))
1307
1308(defvar dired-deletion-confirmer 'yes-or-no-p) ; or y-or-n-p?
1309
1310(defun dired-internal-do-deletions (l arg)
1311 ;; L is an alist of files to delete, with their buffer positions.
1312 ;; ARG is the prefix arg.
1313 ;; Filenames are absolute (VMS needs this for logical search paths).
1314 ;; (car L) *must* be the *last* (bottommost) file in the dired buffer.
1315 ;; That way as changes are made in the buffer they do not shift the
1316 ;; lines still to be changed, so the (point) values in L stay valid.
1317 ;; Also, for subdirs in natural order, a subdir's files are deleted
1318 ;; before the subdir itself - the other way around would not work.
1319 (let ((files (mapcar (function car) l))
1320 (count (length l))
1321 (succ 0))
1322 ;; canonicalize file list for pop up
1323 (setq files (nreverse (mapcar (function dired-make-relative) files)))
1324 (if (dired-mark-pop-up
1325 " *Deletions*" 'delete files dired-deletion-confirmer
1326 (format "Delete %s " (dired-mark-prompt arg files)))
84fc2cfa 1327 (save-excursion
492d2437
RS
1328 (let (failures);; files better be in reverse order for this loop!
1329 (while l
1330 (goto-char (cdr (car l)))
1331 (let (buffer-read-only)
1332 (condition-case err
1333 (let ((fn (car (car l))))
1334 ;; This test is equivalent to
1335 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
1336 ;; but more efficient
1337 (if (eq t (car (file-attributes fn)))
1338 (remove-directory fn)
1339 (delete-file fn))
1340 ;; if we get here, removing worked
1341 (setq succ (1+ succ))
1342 (message "%s of %s deletions" succ count)
1343 (delete-region (progn (beginning-of-line) (point))
1344 (progn (forward-line 1) (point)))
1345 (dired-clean-up-after-deletion fn))
1346 (error;; catch errors from failed deletions
1347 (dired-log "%s\n" err)
1348 (setq failures (cons (car (car l)) failures)))))
1349 (setq l (cdr l)))
1350 (if (not failures)
1351 (message "%d deletion%s done" count (dired-plural-s count))
1352 (dired-log-summary
1353 (format "%d of %d deletion%s failed"
1354 (length failures) count
1355 (dired-plural-s count))
1356 failures))))
1357 (message "(No deletions performed)")))
1358 (dired-move-to-filename))
1359
1360;; This is a separate function for the sake of dired-x.el.
1361(defun dired-clean-up-after-deletion (fn)
1362 ;; Clean up after a deleted file or directory FN.
1363 (save-excursion (and (dired-goto-subdir fn)
1364 (dired-kill-subdir))))
1365\f
1366;; Confirmation
1367
1368(defun dired-marker-regexp ()
1369 (concat "^" (regexp-quote (char-to-string dired-marker-char))))
1370
1371(defun dired-plural-s (count)
1372 (if (= 1 count) "" "s"))
1373
1374(defun dired-mark-prompt (arg files)
1375 ;; Return a string for use in a prompt, either the current file
1376 ;; name, or the marker and a count of marked files.
1377 (let ((count (length files)))
1378 (if (= count 1)
1379 (car files)
1380 ;; more than 1 file:
1381 (if (integerp arg)
1382 ;; abs(arg) = count
1383 ;; Perhaps this is nicer, but it also takes more screen space:
1384 ;;(format "[%s %d files]" (if (> arg 0) "next" "previous")
1385 ;; count)
1386 (format "[next %d files]" arg)
1387 (format "%c [%d files]" dired-marker-char count)))))
1388
1389(defun dired-pop-to-buffer (buf)
1390 ;; Pop up buffer BUF.
1391 ;; If dired-shrink-to-fit is t, make its window fit its contents.
1392 (if (not dired-shrink-to-fit)
1393 (pop-to-buffer (get-buffer-create buf))
1394 ;; let window shrink to fit:
1395 (let ((window (selected-window))
1396 target-lines w2)
1397 (cond ;; if split-window-threshold is enabled, use the largest window
1398 ((and (> (window-height (setq w2 (get-largest-window)))
1399 split-height-threshold)
f98955ea 1400 (= (frame-width) (window-width w2)))
492d2437
RS
1401 (setq window w2))
1402 ;; if the least-recently-used window is big enough, use it
1403 ((and (> (window-height (setq w2 (get-lru-window)))
1404 (* 2 window-min-height))
f98955ea 1405 (= (frame-width) (window-width w2)))
492d2437
RS
1406 (setq window w2)))
1407 (save-excursion
1408 (set-buffer buf)
1409 (goto-char (point-max))
1410 (skip-chars-backward "\n\r\t ")
1411 (setq target-lines (count-lines (point-min) (point))))
1412 (if (<= (window-height window) (* 2 window-min-height))
f98955ea 1413 ;; At this point, every window on the frame is too small to split.
492d2437
RS
1414 (setq w2 (display-buffer buf))
1415 (setq w2 (split-window window
1416 (max window-min-height
1417 (- (window-height window)
1418 (1+ (max window-min-height target-lines)))))))
1419 (set-window-buffer w2 buf)
1420 (if (< (1- (window-height w2)) target-lines)
1421 (progn
1422 (select-window w2)
1423 (enlarge-window (- target-lines (1- (window-height w2))))))
1424 (set-window-start w2 1)
1425 )))
1426
1427(defvar dired-no-confirm nil
1428;; "If non-nil, list of symbols for commands dired should not confirm.
1429;;It can be a sublist of
1430;;
1431;; '(byte-compile chgrp chmod chown compress copy delete hardlink load
1432;; move print shell symlink uncompress)"
1433 )
1434
1435(defun dired-mark-pop-up (bufname op-symbol files function &rest args)
1436 ;;"Args BUFNAME OP-SYMBOL FILES FUNCTION &rest ARGS.
1437 ;;Return FUNCTION's result on ARGS after popping up a window (in a buffer
1438 ;;named BUFNAME, nil gives \" *Marked Files*\") showing the marked
1439 ;;files. Uses function `dired-pop-to-buffer' to do that.
1440 ;; FUNCTION should not manipulate files.
1441 ;; It should only read input (an argument or confirmation).
1442 ;;The window is not shown if there is just one file or
1443 ;; OP-SYMBOL is a member of the list in `dired-no-confirm'.
1444 ;;FILES is the list of marked files."
1445 (or bufname (setq bufname " *Marked Files*"))
1446 (if (or (memq op-symbol dired-no-confirm)
1447 (= (length files) 1))
1448 (apply function args)
1449 (save-excursion
1450 (set-buffer (get-buffer-create bufname))
1451 (erase-buffer)
1452 (dired-format-columns-of-files files))
1453 (save-window-excursion
1454 (dired-pop-to-buffer bufname)
1455 (apply function args))))
1456
1457(defun dired-format-columns-of-files (files)
1458 ;; Files should be in forward order for this loop.
1459 ;; i.e., (car files) = first file in buffer.
1460 ;; Returns the number of lines used.
1461 (let* ((maxlen (+ 2 (apply 'max (mapcar 'length files))))
1462 (width (- (window-width (selected-window)) 2))
1463 (columns (max 1 (/ width maxlen)))
1464 (nfiles (length files))
1465 (rows (+ (/ nfiles columns)
1466 (if (zerop (% nfiles columns)) 0 1)))
1467 (i 0)
1468 (j 0))
1469 (setq files (nconc (copy-sequence files) ; fill up with empty fns
1470 (make-list (- (* columns rows) nfiles) "")))
1471 (setcdr (nthcdr (1- (length files)) files) files) ; make circular
1472 (while (< j rows)
1473 (while (< i columns)
1474 (indent-to (* i maxlen))
1475 (insert (car files))
1476 (setq files (nthcdr rows files)
1477 i (1+ i)))
1478 (insert "\n")
1479 (setq i 0
1480 j (1+ j)
1481 files (cdr files)))
1482 rows))
1483\f
1484;; Commands to mark or flag file(s) at or near current line.
1485
1486(defun dired-repeat-over-lines (arg function)
1487 ;; This version skips non-file lines.
1488 (beginning-of-line)
1489 (while (and (> arg 0) (not (eobp)))
1490 (setq arg (1- arg))
1491 (beginning-of-line)
1492 (while (and (not (eobp)) (dired-between-files)) (forward-line 1))
1493 (save-excursion (funcall function))
1494 (forward-line 1))
1495 (while (and (< arg 0) (not (bobp)))
1496 (setq arg (1+ arg))
1497 (forward-line -1)
1498 (while (and (not (bobp)) (dired-between-files)) (forward-line -1))
1499 (beginning-of-line)
1500 (save-excursion (funcall function))
1501 (dired-move-to-filename))
1502 (dired-move-to-filename))
1503
1504(defun dired-between-files ()
1505 ;; Point must be at beginning of line
1506 ;; Should be equivalent to (save-excursion (not (dired-move-to-filename)))
1507 ;; but is about 1.5..2.0 times as fast. (Actually that's not worth it)
1508 (or (looking-at "^$\\|^. *$\\|^. total\\|^. wildcard")
1509 (looking-at dired-subdir-regexp)))
1510
1511(defun dired-next-marked-file (arg &optional wrap opoint)
1512 "Move to the next marked file, wrapping around the end of the buffer."
1513 (interactive "p\np")
1514 (or opoint (setq opoint (point)));; return to where interactively started
1515 (if (if (> arg 0)
1516 (re-search-forward dired-re-mark nil t arg)
1517 (beginning-of-line)
1518 (re-search-backward dired-re-mark nil t (- arg)))
1519 (dired-move-to-filename)
1520 (if (null wrap)
1521 (progn
1522 (goto-char opoint)
1523 (error "No next marked file"))
1524 (message "(Wraparound for next marked file)")
1525 (goto-char (if (> arg 0) (point-min) (point-max)))
1526 (dired-next-marked-file arg nil opoint))))
1527
1528(defun dired-prev-marked-file (arg &optional wrap)
1529 "Move to the previous marked file, wrapping around the end of the buffer."
1530 (interactive "p\np")
1531 (dired-next-marked-file (- arg) wrap))
1532
1533(defun dired-file-marker (file)
1534 ;; Return FILE's marker, or nil if unmarked.
1535 (save-excursion
1536 (and (dired-goto-file file)
1537 (progn
1538 (beginning-of-line)
1539 (if (not (equal ?\040 (following-char)))
1540 (following-char))))))
1541
1542(defun dired-mark-files-in-region (start end)
1543 (let (buffer-read-only)
1544 (if (> start end)
1545 (error "start > end"))
1546 (goto-char start) ; assumed at beginning of line
1547 (while (< (point) end)
1548 ;; Skip subdir line and following garbage like the `total' line:
1549 (while (and (< (point) end) (dired-between-files))
1550 (forward-line 1))
1551 (if (and (not (looking-at dired-re-dot))
1552 (dired-get-filename nil t))
1553 (progn
1554 (delete-char 1)
1555 (insert dired-marker-char)))
1556 (forward-line 1))))
1557
1558(defun dired-mark (arg)
1559 "Mark the current (or next ARG) files.
1560If on a subdir headerline, mark all its files except `.' and `..'.
1561
1562Use \\[dired-unmark-all-files] to remove all marks
1563and \\[dired-unmark] on a subdir to remove the marks in
1564this subdir."
1565 (interactive "P")
1566 (if (and dired-subdir-alist (dired-get-subdir))
1567 (save-excursion (dired-mark-subdir-files))
1568 (let (buffer-read-only)
1569 (dired-repeat-over-lines
52041219 1570 (prefix-numeric-value arg)
492d2437
RS
1571 (function (lambda () (delete-char 1) (insert dired-marker-char)))))))
1572
1573(defun dired-unmark (arg)
1574 "Unmark the current (or next ARG) files.
1575If looking at a subdir, unmark all its files except `.' and `..'."
1576 (interactive "P")
1577 (let ((dired-marker-char ?\040))
1578 (dired-mark arg)))
1579
1580(defun dired-flag-file-deletion (arg)
1581 "In dired, flag the current line's file for deletion.
1582With prefix arg, repeat over several lines.
1583
1584If on a subdir headerline, mark all its files except `.' and `..'."
1585 (interactive "P")
1586 (let ((dired-marker-char dired-del-marker))
1587 (dired-mark arg)))
1588
1589(defun dired-unmark-backward (arg)
1590 "In dired, move up lines and remove deletion flag there.
1591Optional prefix ARG says how many lines to unflag; default is one line."
1592 (interactive "p")
1593 (dired-unmark (- arg)))
84fc2cfa 1594\f
492d2437
RS
1595;;; Commands to mark or flag files based on their characteristics or names.
1596
1597(defun dired-read-regexp (prompt &optional initial)
1598;; This is an extra function so that gmhist can redefine it.
1599 (setq dired-flagging-regexp
1600 (read-string prompt (or initial dired-flagging-regexp))))
1601
1602(defun dired-mark-files-regexp (regexp &optional marker-char)
1603 "Mark all files matching REGEXP for use in later commands.
1604A prefix argument means to unmark them instead.
1605`.' and `..' are never marked.
1606
1607REGEXP is an Emacs regexp, not a shell wildcard. Thus, use `\\.o$' for
1608object files--just `.o' will mark more than you might think."
1609 (interactive
1610 (list (dired-read-regexp (concat (if current-prefix-arg "Unmark" "Mark")
1611 " files (regexp): "))
1612 (if current-prefix-arg ?\040)))
1613 (let ((dired-marker-char (or marker-char dired-marker-char)))
1614 (dired-mark-if
1615 (and (not (looking-at dired-re-dot))
1616 (not (eolp)) ; empty line
1617 (let ((fn (dired-get-filename nil t)))
1618 (and fn (string-match regexp (file-name-nondirectory fn)))))
1619 "matching file")))
1620
1621(defun dired-flag-files-regexp (regexp)
1622 "In dired, flag all files containing the specified REGEXP for deletion.
1623The match is against the non-directory part of the filename. Use `^'
1624 and `$' to anchor matches. Exclude subdirs by hiding them.
1625`.' and `..' are never flagged."
1626 (interactive (list (dired-read-regexp "Flag for deletion (regexp): ")))
1627 (dired-mark-files-regexp regexp dired-del-marker))
1628
1629(defun dired-mark-symlinks (unflag-p)
1630 "Mark all symbolic links.
1631With prefix argument, unflag all those files."
1632 (interactive "P")
1633 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
1634 (dired-mark-if (looking-at dired-re-sym) "symbolic link")))
1635
1636(defun dired-mark-directories (unflag-p)
1637 "Mark all directory file lines except `.' and `..'.
1638With prefix argument, unflag all those files."
1639 (interactive "P")
1640 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
1641 (dired-mark-if (and (looking-at dired-re-dir)
1642 (not (looking-at dired-re-dot)))
1643 "directory file")))
1644
1645(defun dired-mark-executables (unflag-p)
1646 "Mark all executable files.
1647With prefix argument, unflag all those files."
1648 (interactive "P")
1649 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
1650 (dired-mark-if (looking-at dired-re-exe) "executable file")))
1651
1652;; dired-x.el has a dired-mark-sexp interactive command: mark
1653;; files for which PREDICATE returns non-nil.
1654
1655(defun dired-flag-auto-save-files (&optional unflag-p)
84fc2cfa
ER
1656 "Flag for deletion files whose names suggest they are auto save files.
1657A prefix argument says to unflag those files instead."
1658 (interactive "P")
492d2437
RS
1659 (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
1660 (dired-mark-if
1661 (and (not (looking-at dired-re-dir))
1662 (let ((fn (dired-get-filename t t)))
1663 (if fn (auto-save-file-name-p
1664 (file-name-nondirectory fn)))))
1665 "auto save file")))
1666
1667(defun dired-flag-backup-files (&optional unflag-p)
1668 "Flag all backup files (names ending with `~') for deletion.
1669With prefix argument, unflag these files."
1670 (interactive "P")
1671 (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
1672 (dired-mark-if
1673 (and (not (looking-at dired-re-dir))
1674 (let ((fn (dired-get-filename t t)))
1675 (if fn (backup-file-name-p fn))))
1676 "backup file")))
1677
1678(defun dired-unmark-all-files (flag &optional arg)
1679 "Remove a specific mark or any mark from every file.
1680With an arg, queries for each marked file.
1681Type \\[help-command] at that time for help."
1682 (interactive "sRemove mark: (default: all marks) \nP")
1683 (let ((count 0)
1684 (re (if (zerop (length flag)) dired-re-mark
1685 (concat "^" (regexp-quote flag)))))
1686 (save-excursion
1687 (let (buffer-read-only case-fold-search query
1688 (help-form "\
1689Type SPC or `y' to unflag one file, DEL or `n' to skip to next,
1690`!' to unflag all remaining files with no more questions."))
1691 (goto-char (point-min))
1692 (while (re-search-forward re nil t)
1693 (if (or (not arg)
1694 (dired-query 'query "Unmark file `%s'? "
1695 (dired-get-filename t)))
1696 (progn (delete-char -1) (insert " ") (setq count (1+ count))))
1697 (forward-line 1))))
1698 (message "%s" (format "Flags removed: %d %s" count flag) )))
1699\f
1700;;; Cleaning a directory: flagging some backups for deletion.
84fc2cfa
ER
1701
1702(defun dired-clean-directory (keep)
1703 "Flag numerical backups for deletion.
1704Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
1705Positive prefix arg KEEP overrides `dired-kept-versions';
1706Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
1707
1708To clear the flags on these files, you can use \\[dired-flag-backup-files]
1709with a prefix argument."
1710 (interactive "P")
1711 (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
1712 (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
1713 (late-retention (if (<= keep 0) dired-kept-versions keep))
1714 (file-version-assoc-list ()))
492d2437
RS
1715 (message "Cleaning numerical backups (keeping %d late, %d old)..."
1716 late-retention early-retention)
84fc2cfa
ER
1717 ;; Look at each file.
1718 ;; If the file has numeric backup versions,
1719 ;; put on file-version-assoc-list an element of the form
1720 ;; (FILENAME . VERSION-NUMBER-LIST)
492d2437 1721 (dired-map-dired-file-lines (function dired-collect-file-versions))
84fc2cfa
ER
1722 ;; Sort each VERSION-NUMBER-LIST,
1723 ;; and remove the versions not to be deleted.
1724 (let ((fval file-version-assoc-list))
1725 (while fval
1726 (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
1727 (v-count (length sorted-v-list)))
1728 (if (> v-count (+ early-retention late-retention))
1729 (rplacd (nthcdr early-retention sorted-v-list)
1730 (nthcdr (- v-count late-retention)
1731 sorted-v-list)))
1732 (rplacd (car fval)
1733 (cdr sorted-v-list)))
1734 (setq fval (cdr fval))))
1735 ;; Look at each file. If it is a numeric backup file,
1736 ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
492d2437
RS
1737 (dired-map-dired-file-lines (function dired-trample-file-versions))
1738 (message "Cleaning numerical backups...done")))
1739
1740;;; Subroutines of dired-clean-directory.
84fc2cfa 1741
492d2437
RS
1742(defun dired-map-dired-file-lines (fun)
1743 ;; Perform FUN with point at the end of each non-directory line.
1744 ;; FUN takes one argument, the filename (complete pathname).
1745 (save-excursion
1746 (let (file buffer-read-only)
1747 (goto-char (point-min))
1748 (while (not (eobp))
1749 (save-excursion
1750 (and (not (looking-at dired-re-dir))
1751 (not (eolp))
1752 (setq file (dired-get-filename nil t)) ; nil on non-file
1753 (progn (end-of-line)
1754 (funcall fun file))))
1755 (forward-line 1)))))
1756
1757(defun dired-collect-file-versions (fn)
1758 ;; "If it looks like file FN has versions, return a list of the versions.
1759 ;;That is a list of strings which are file names.
1760 ;;The caller may want to flag some of these files for deletion."
84fc2cfa
ER
1761 (let* ((base-versions
1762 (concat (file-name-nondirectory fn) ".~"))
1763 (bv-length (length base-versions))
1764 (possibilities (file-name-all-completions
1765 base-versions
1766 (file-name-directory fn)))
1767 (versions (mapcar 'backup-extract-version possibilities)))
1768 (if versions
1769 (setq file-version-assoc-list (cons (cons fn versions)
1770 file-version-assoc-list)))))
1771
492d2437 1772(defun dired-trample-file-versions (fn)
84fc2cfa
ER
1773 (let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
1774 base-version-list)
1775 (and start-vn
1776 (setq base-version-list ; there was a base version to which
1777 (assoc (substring fn 0 start-vn) ; this looks like a
1778 file-version-assoc-list)) ; subversion
1779 (not (memq (string-to-int (substring fn (+ 2 start-vn)))
1780 base-version-list)) ; this one doesn't make the cut
492d2437
RS
1781 (progn (beginning-of-line)
1782 (delete-char 1)
1783 (insert dired-del-marker)))))
1784\f
1785;; Logging failures operating on files, and showing the results.
84fc2cfa 1786
492d2437 1787(defvar dired-log-buffer "*Dired log*")
84fc2cfa 1788
492d2437
RS
1789(defun dired-why ()
1790 "Pop up a buffer with error log output from Dired.
1791A group of errors from a single command ends with a formfeed.
1792Thus, use \\[backward-page] to find the beginning of a group of errors."
1793 (interactive)
1794 (if (get-buffer dired-log-buffer)
1795 (let ((owindow (selected-window))
1796 (window (display-buffer (get-buffer dired-log-buffer))))
1797 (unwind-protect
1798 (save-excursion
1799 (select-window window)
1800 (goto-char (point-max))
1801 (recenter -1))
1802 (select-window owindow)))))
1803
1804(defun dired-log (log &rest args)
1805 ;; Log a message or the contents of a buffer.
1806 ;; If LOG is a string and there are more args, it is formatted with
1807 ;; those ARGS. Usually the LOG string ends with a \n.
1808 ;; End each bunch of errors with (dired-log t): this inserts
1809 ;; current time and buffer, and a \f (formfeed).
1810 (let ((obuf (current-buffer)))
1811 (unwind-protect ; want to move point
1812 (progn
1813 (set-buffer (get-buffer-create dired-log-buffer))
1814 (goto-char (point-max))
1815 (let (buffer-read-only)
1816 (cond ((stringp log)
1817 (insert (if args
1818 (apply (function format) log args)
1819 log)))
1820 ((bufferp log)
1821 (insert-buffer log))
1822 ((eq t log)
1823 (insert "\n\t" (current-time-string)
1824 "\tBuffer `" (buffer-name obuf) "'\n\f\n")))))
1825 (set-buffer obuf))))
1826
1827(defun dired-log-summary (string failures)
1828 (message (if failures "%s--type ? for details (%s)"
1829 "%s--type ? for details")
1830 string failures)
1831 ;; Log a summary describing a bunch of errors.
1832 (dired-log (concat "\n" string))
1833 (dired-log t))
1834\f
1835;;; Sorting
1836
1837;; Most ls can only sort by name or by date (with -t), nothing else.
1838;; GNU ls sorts on size with -S, on extension with -X, and unsorted with -U.
1839;; So anything that does not contain these is sort "by name".
1840
1841(defvar dired-ls-sorting-switches "SXU"
1842 "String of `ls' switches (single letters) except `t' that influence sorting.")
1843
1844(defvar dired-sort-by-date-regexp
1845 (concat "^-[^" dired-ls-sorting-switches
1846 "]*t[^" dired-ls-sorting-switches "]*$")
1847 "Regexp recognized by dired to set `by date' mode.")
1848
1849(defvar dired-sort-by-name-regexp
1850 (concat "^-[^t" dired-ls-sorting-switches "]+$")
1851 "Regexp recognized by dired to set `by name' mode.")
1852
1853(defvar dired-sort-mode nil
1854 "Whether Dired sorts by name, date etc. (buffer-local).")
1855;; This is nil outside dired buffers so it can be used in the modeline
1856
1857(defun dired-sort-set-modeline ()
1858 ;; Set modeline display according to dired-actual-switches.
1859 ;; Modeline display of "by name" or "by date" guarantees the user a
1860 ;; match with the corresponding regexps. Non-matching switches are
1861 ;; shown literally.
1862 (setq dired-sort-mode
1863 (let (case-fold-search)
1864 (cond ((string-match dired-sort-by-name-regexp dired-actual-switches)
1865 " by name")
1866 ((string-match dired-sort-by-date-regexp dired-actual-switches)
1867 " by date")
1868 (t
1869 (concat " " dired-actual-switches)))))
1870 ;; update mode line:
1871 (set-buffer-modified-p (buffer-modified-p)))
1872
1873(defun dired-sort-toggle-or-edit (&optional arg)
1874 "Toggle between sort by date/name and refresh the dired buffer.
1875With a prefix argument you can edit the current listing switches instead."
84fc2cfa 1876 (interactive "P")
492d2437
RS
1877 (if arg
1878 (dired-sort-other
1879 (read-string "ls switches (must contain -l): " dired-actual-switches))
1880 (dired-sort-toggle)))
1881
1882(defun dired-sort-toggle ()
1883 ;; Toggle between sort by date/name. Reverts the buffer.
1884 (setq dired-actual-switches
1885 (let (case-fold-search)
1886 (concat
1887 "-l"
1888 (dired-replace-in-string (concat "[---lt"
1889 dired-ls-sorting-switches "]")
1890 ""
1891 dired-actual-switches)
1892 (if (string-match (concat "[t" dired-ls-sorting-switches "]")
1893 dired-actual-switches)
1894 ""
1895 "t"))))
1896 (dired-sort-set-modeline)
1897 (revert-buffer))
1898
1899(defun dired-replace-in-string (regexp newtext string)
1900 ;; Replace REGEXP with NEWTEXT everywhere in STRING and return result.
1901 ;; NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
1902 (let ((result "") (start 0) mb me)
1903 (while (string-match regexp string start)
1904 (setq mb (match-beginning 0)
1905 me (match-end 0)
1906 result (concat result (substring string start mb) newtext)
1907 start me))
1908 (concat result (substring string start))))
1909
1910(defun dired-sort-other (switches &optional no-revert)
1911 ;; Specify new ls SWITCHES for current dired buffer. Values matching
1912 ;; `dired-sort-by-date-regexp' or `dired-sort-by-name-regexp' set the
1913 ;; minor mode accordingly, others appear literally in the mode line.
1914 ;; With optional second arg NO-REVERT, don't refresh the listing afterwards.
1915 (setq dired-actual-switches switches)
1916 (dired-sort-set-modeline)
1917 (or no-revert (revert-buffer)))
84fc2cfa 1918\f
492d2437
RS
1919;; To make this file smaller, the less common commands
1920;; go in a separate file. But autoload them here
1921;; to make the separation invisible.
1922
1923(autoload 'dired-diff "dired-aux"
1924 "Compare file at point with file FILE using `diff'.
1925FILE defaults to the file at the mark.
1926The prompted-for file is the first file given to `diff'.
1927Prefix arg lets you edit the diff switches. See the command `diff'."
1928 t)
1929
1930(autoload 'dired-backup-diff "dired-aux"
1931 "Diff this file with its backup file or vice versa.
1932Uses the latest backup, if there are several numerical backups.
1933If this file is a backup, diff it with its original.
1934The backup file is the first file given to `diff'.
1935Prefix arg lets you edit the diff switches. See the command `diff'."
1936 t)
1937
1938(autoload 'dired-do-chmod "dired-aux"
1939 "Change the mode of the marked (or next ARG) files.
1940This calls chmod, thus symbolic modes like `g+w' are allowed."
1941 t)
1942
1943(autoload 'dired-do-chgrp "dired-aux"
1944 "Change the group of the marked (or next ARG) files."
1945 t)
1946
1947(autoload 'dired-do-chown "dired-aux"
1948 "Change the owner of the marked (or next ARG) files."
1949 t)
1950
1951(autoload 'dired-do-print "dired-aux"
1952 "Print the marked (or next ARG) files.
1953Uses the shell command coming from variables `lpr-command' and
1954`lpr-switches' as default."
1955 t)
1956
1957(autoload 'dired-do-shell-command "dired-aux"
1958 "Run a shell command on the marked files.
1959If there is output, it goes to a separate buffer.
1960Normally the command is run on each file individually.
1961However, if there is a `*' in the command then it is run
1962just once with the entire file list substituted there.
1963
1964If no files are marked or a specific numeric prefix arg is given,
1965the next ARG files are used. Just \\[universal-argument] means the current file.
1966The prompt mentions the file(s) or the marker, as appropriate.
1967
1968No automatic redisplay is attempted, as the file names may have
1969changed. Type \\[dired-do-redisplay] to redisplay the marked files.
1970
1971The shell command has the top level directory as working directory, so
1972output files usually are created there instead of in a subdir."
1973 t)
1974
1975(autoload 'dired-kill-line-or-subdir "dired-aux"
1976 "Kill this line (but don't delete its file).
1977Optional prefix argument is a repeat factor.
1978If file is displayed as in situ subdir, kill that as well.
1979If on a subdir headerline, kill whole subdir."
1980 t)
1981
1982(autoload 'dired-do-kill-lines "dired-aux"
1983 "Kill all marked lines (not the files).
1984With a prefix arg, kill all lines not marked or flagged."
1985 t)
1986
1987(autoload 'dired-do-compress "dired-aux"
1988 "Compress or uncompress marked (or next ARG) files."
1989 t)
1990
1991(autoload 'dired-do-byte-compile "dired-aux"
1992 "Byte compile marked (or next ARG) Emacs Lisp files."
1993 t)
1994
1995(autoload 'dired-do-load "dired-aux"
1996 "Load the marked (or next ARG) Emacs Lisp files."
1997 t)
1998
1999(autoload 'dired-do-redisplay "dired-aux"
2000 "Redisplay all marked (or next ARG) files.
2001If on a subdir line, redisplay that subdirectory. In that case,
2002a prefix arg lets you edit the `ls' switches used for the new listing."
2003 t)
2004
2005(autoload 'dired-string-replace-match "dired-aux"
2006 "Replace first match of REGEXP in STRING with NEWTEXT.
2007If it does not match, nil is returned instead of the new string.
2008Optional arg LITERAL means to take NEWTEXT literally.
2009Optional arg GLOBAL means to replace all matches."
2010 t)
2011
2012(autoload 'dired-create-directory "dired-aux"
84fc2cfa 2013 "Create a directory called DIRECTORY."
492d2437 2014 t)
84fc2cfa 2015
492d2437
RS
2016(autoload 'dired-do-copy "dired-aux"
2017 "Copy all marked (or next ARG) files, or copy the current file.
2018Thus, a zero prefix argument copies nothing. But it toggles the
2019variable `dired-copy-preserve-time' (which see)."
2020 t)
2021
2022(autoload 'dired-do-symlink "dired-aux"
2023 "Make symbolic links to current file or all marked (or next ARG) files.
2024When operating on just the current file, you specify the new name.
2025When operating on multiple or marked files, you specify a directory
2026and new symbolic links are made in that directory
2027with the same names that the files currently have."
2028 t)
2029
2030(autoload 'dired-do-hardlink "dired-aux"
2031 "Add names (hard links) current file or all marked (or next ARG) files.
2032When operating on just the current file, you specify the new name.
2033When operating on multiple or marked files, you specify a directory
2034and new hard links are made in that directory
2035with the same names that the files currently have."
2036 t)
2037
2038(autoload 'dired-do-rename "dired-aux"
2039 "Rename current file or all marked (or next ARG) files.
2040When renaming just the current file, you specify the new name.
2041When renaming multiple or marked files, you specify a directory."
2042 t)
2043
2044(autoload 'dired-do-rename-regexp "dired-aux"
2045 "Rename marked files containing REGEXP to NEWNAME.
2046As each match is found, the user must type a character saying
2047 what to do with it. For directions, type \\[help-command] at that time.
2048NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
2049REGEXP defaults to the last regexp used.
2050With a zero prefix arg, renaming by regexp affects the complete
2051 pathname - usually only the non-directory part of file names is used
2052 and changed."
2053 t)
2054
2055(autoload 'dired-do-copy-regexp "dired-aux"
2056 "Copy all marked files containing REGEXP to NEWNAME.
2057See function `dired-rename-regexp' for more info."
2058 t)
2059
2060(autoload 'dired-do-hardlink-regexp "dired-aux"
2061 "Hardlink all marked files containing REGEXP to NEWNAME.
2062See function `dired-rename-regexp' for more info."
2063 t)
2064
2065(autoload 'dired-do-symlink-regexp "dired-aux"
2066 "Symlink all marked files containing REGEXP to NEWNAME.
2067See function `dired-rename-regexp' for more info."
2068 t)
2069
2070(autoload 'dired-upcase "dired-aux"
2071 "Rename all marked (or next ARG) files to upper case."
2072 t)
2073
2074(autoload 'dired-downcase "dired-aux"
2075 "Rename all marked (or next ARG) files to lower case."
2076 t)
2077
2078(autoload 'dired-maybe-insert-subdir "dired-aux"
2079 "Insert this subdirectory into the same dired buffer.
2080If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
2081 else inserts it at its natural place (as `ls -lR' would have done).
2082With a prefix arg, you may edit the ls switches used for this listing.
2083 You can add `R' to the switches to expand the whole tree starting at
2084 this subdirectory.
2085This function takes some pains to conform to `ls -lR' output."
2086 t)
2087
2088(autoload 'dired-next-subdir "dired-aux"
2089 "Go to next subdirectory, regardless of level."
2090 t)
2091
2092(autoload 'dired-prev-subdir "dired-aux"
2093 "Go to previous subdirectory, regardless of level.
2094When called interactively and not on a subdir line, go to this subdir's line."
2095 t)
2096
2097(autoload 'dired-goto-subdir "dired-aux"
2098 "Go to end of header line of DIR in this dired buffer.
2099Return value of point on success, otherwise return nil.
2100The next char is either \\n, or \\r if DIR is hidden."
2101 t)
2102
2103(autoload 'dired-mark-subdir-files "dired-aux"
2104 "Mark all files except `.' and `..'."
2105 t)
2106
2107(autoload 'dired-kill-subdir "dired-aux"
2108 "Remove all lines of current subdirectory.
2109Lower levels are unaffected."
2110 t)
2111
2112(autoload 'dired-tree-up "dired-aux"
2113 "Go up ARG levels in the dired tree."
2114 t)
2115
2116(autoload 'dired-tree-down "dired-aux"
2117 "Go down in the dired tree."
2118 t)
2119
2120(autoload 'dired-hide-subdir "dired-aux"
2121 "Hide or unhide the current subdirectory and move to next directory.
2122Optional prefix arg is a repeat factor.
2123Use \\[dired-hide-all] to (un)hide all directories."
2124 t)
2125
2126(autoload 'dired-hide-all "dired-aux"
2127 "Hide all subdirectories, leaving only their header lines.
2128If there is already something hidden, make everything visible again.
2129Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2130 t)
84fc2cfa 2131\f
492d2437
RS
2132(if (eq system-type 'vax-vms)
2133 (load "dired-vms"))
84fc2cfa 2134
492d2437 2135(run-hooks 'dired-load-hook) ; for your customizations
84fc2cfa 2136
52041219
RS
2137(provide 'dired)
2138
2139;;; dired.el ends here