1 ;;; dired-aux.el --- less commonly used parts of dired -*-byte-compile-dynamic: t;-*-
3 ;; Copyright (C) 1985, 1986, 1992, 1994 Free Software Foundation, Inc.
5 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; The parts of dired mode not normally used. This is a space-saving hack
28 ;; to avoid having to load a large mode when all that's wanted are a few
31 ;; Rewritten in 1990/1991 to add tree features, file marking and
32 ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
33 ;; Finished up by rms in 1992.
37 ;; We need macros in dired.el to compile properly.
38 (eval-when-compile (require 'dired
))
41 ;;;###begin dired-cmd.el
42 ;; Diffing and compressing
45 (defun dired-diff (file &optional switches
)
46 "Compare file at point with file FILE using `diff'.
47 FILE defaults to the file at the mark.
48 The prompted-for file is the first file given to `diff'.
49 With prefix arg, prompt for second argument SWITCHES,
50 which is options for `diff'."
52 (let ((default (if (mark t
)
53 (save-excursion (goto-char (mark t
))
54 (dired-get-filename t t
)))))
56 (list (read-file-name (format "Diff %s with: %s"
57 (dired-get-filename t
)
59 (concat "(default " default
") ")
61 (dired-current-directory) default t
)
62 (if current-prefix-arg
63 (read-string "Options for diff: "
64 (if (stringp diff-switches
)
66 (mapconcat 'identity diff-switches
" ")))))))
67 (diff file
(dired-get-filename t
) switches
))
70 (defun dired-backup-diff (&optional switches
)
71 "Diff this file with its backup file or vice versa.
72 Uses the latest backup, if there are several numerical backups.
73 If this file is a backup, diff it with its original.
74 The backup file is the first file given to `diff'.
75 With prefix arg, prompt for argument SWITCHES which is options for `diff'."
77 (if current-prefix-arg
78 (list (read-string "Options for diff: "
79 (if (stringp diff-switches
)
81 (mapconcat 'identity diff-switches
" "))))
83 (diff-backup (dired-get-filename) switches
))
85 (defun dired-do-chxxx (attribute-name program op-symbol arg
)
86 ;; Change file attributes (mode, group, owner) of marked files and
87 ;; refresh their file lines.
88 ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
89 ;; PROGRAM is the program used to change the attribute.
90 ;; OP-SYMBOL is the type of operation (for use in dired-mark-pop-up).
91 ;; ARG describes which files to use, as in dired-get-marked-files.
92 (let* ((files (dired-get-marked-files t arg
))
94 (dired-mark-read-string
95 (concat "Change " attribute-name
" of %s to: ")
96 nil op-symbol arg files
))
97 (operation (concat program
" " new-attribute
))
100 (dired-bunch-files 10000
101 (function dired-check-process
)
103 (list operation program new-attribute
)
104 (if (string-match "gnu" system-configuration
)
107 (dired-do-redisplay arg
);; moves point if ARG is an integer
110 (format "%s: error" operation
)
114 (defun dired-do-chmod (&optional arg
)
115 "Change the mode of the marked (or next ARG) files.
116 This calls chmod, thus symbolic modes like `g+w' are allowed."
118 (dired-do-chxxx "Mode" dired-chmod-program
'chmod arg
))
121 (defun dired-do-chgrp (&optional arg
)
122 "Change the group of the marked (or next ARG) files."
124 (if (memq system-type
'(ms-dos windows-nt
))
125 (error "chgrp not supported on this system."))
126 (dired-do-chxxx "Group" "chgrp" 'chgrp arg
))
129 (defun dired-do-chown (&optional arg
)
130 "Change the owner of the marked (or next ARG) files."
132 (if (memq system-type
'(ms-dos windows-nt
))
133 (error "chown not supported on this system."))
134 (dired-do-chxxx "Owner" dired-chown-program
'chown arg
))
136 ;; Process all the files in FILES in batches of a convenient size,
137 ;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).
138 ;; Batches are chosen to need less than MAX chars for the file names,
139 ;; allowing 3 extra characters of separator per file name.
140 (defun dired-bunch-files (max function args files
)
144 ;; Accumulate files as long as they fit in MAX chars,
145 ;; then process the ones accumulated so far.
147 (let* ((thisfile (car files
))
148 (thislength (+ (length thisfile
) 3))
150 ;; If we have at least 1 pending file
151 ;; and this file won't fit in the length limit, process now.
152 (if (and pending
(> (+ thislength pending-length
) max
))
154 (nconc (apply function
(append args pending
))
158 ;; Do (setq pending (cons thisfile pending))
159 ;; but reuse the cons that was in `files'.
160 (setcdr files pending
)
162 (setq pending-length
(+ thislength pending-length
))
164 (nconc (apply function
(append args pending
))
168 (defun dired-do-print (&optional arg
)
169 "Print the marked (or next ARG) files.
170 Uses the shell command coming from variables `lpr-command' and
171 `lpr-switches' as default."
173 (let* ((file-list (dired-get-marked-files t arg
))
174 (command (dired-mark-read-string
178 (if (stringp lpr-switches
)
182 'print arg file-list
)))
183 (dired-run-shell-command (dired-shell-stuff-it command file-list nil
))))
185 ;; Read arguments for a marked-files command that wants a string
186 ;; that is not a file name,
187 ;; perhaps popping up the list of marked files.
188 ;; ARG is the prefix arg and indicates whether the files came from
189 ;; marks (ARG=nil) or a repeat factor (integerp ARG).
190 ;; If the current file was used, the list has but one element and ARG
191 ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
193 (defun dired-mark-read-string (prompt initial op-symbol arg files
)
194 ;; PROMPT for a string, with INITIAL input.
195 ;; Other args are used to give user feedback and pop-up:
196 ;; OP-SYMBOL of command, prefix ARG, marked FILES.
199 (function read-string
)
200 (format prompt
(dired-mark-prompt arg files
)) initial
))
202 ;;; Cleaning a directory: flagging some backups for deletion.
204 (defvar dired-file-version-alist
)
206 (defun dired-clean-directory (keep)
207 "Flag numerical backups for deletion.
208 Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
209 Positive prefix arg KEEP overrides `dired-kept-versions';
210 Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
212 To clear the flags on these files, you can use \\[dired-flag-backup-files]
213 with a prefix argument."
215 (setq keep
(if keep
(prefix-numeric-value keep
) dired-kept-versions
))
216 (let ((early-retention (if (< keep
0) (- keep
) kept-old-versions
))
217 (late-retention (if (<= keep
0) dired-kept-versions keep
))
218 (dired-file-version-alist ()))
219 (message "Cleaning numerical backups (keeping %d late, %d old)..."
220 late-retention early-retention
)
221 ;; Look at each file.
222 ;; If the file has numeric backup versions,
223 ;; put on dired-file-version-alist an element of the form
224 ;; (FILENAME . VERSION-NUMBER-LIST)
225 (dired-map-dired-file-lines (function dired-collect-file-versions
))
226 ;; Sort each VERSION-NUMBER-LIST,
227 ;; and remove the versions not to be deleted.
228 (let ((fval dired-file-version-alist
))
230 (let* ((sorted-v-list (cons 'q
(sort (cdr (car fval
)) '<)))
231 (v-count (length sorted-v-list
)))
232 (if (> v-count
(+ early-retention late-retention
))
233 (rplacd (nthcdr early-retention sorted-v-list
)
234 (nthcdr (- v-count late-retention
)
237 (cdr sorted-v-list
)))
238 (setq fval
(cdr fval
))))
239 ;; Look at each file. If it is a numeric backup file,
240 ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
241 (dired-map-dired-file-lines (function dired-trample-file-versions
))
242 (message "Cleaning numerical backups...done")))
244 ;;; Subroutines of dired-clean-directory.
246 (defun dired-map-dired-file-lines (fun)
247 ;; Perform FUN with point at the end of each non-directory line.
248 ;; FUN takes one argument, the filename (complete pathname).
250 (let (file buffer-read-only
)
251 (goto-char (point-min))
254 (and (not (looking-at dired-re-dir
))
256 (setq file
(dired-get-filename nil t
)) ; nil on non-file
258 (funcall fun file
))))
261 (defun dired-collect-file-versions (fn)
262 (let ((fn (file-name-sans-versions fn
)))
263 ;; Only do work if this file is not already in the alist.
264 (if (assoc fn dired-file-version-alist
)
266 ;; If it looks like file FN has versions, return a list of the versions.
267 ;;That is a list of strings which are file names.
268 ;;The caller may want to flag some of these files for deletion.
269 (let* ((base-versions
270 (concat (file-name-nondirectory fn
) ".~"))
271 (backup-extract-version-start (length base-versions
))
272 (possibilities (file-name-all-completions
274 (file-name-directory fn
)))
275 (versions (mapcar 'backup-extract-version possibilities
)))
277 (setq dired-file-version-alist
278 (cons (cons fn versions
)
279 dired-file-version-alist
)))))))
281 (defun dired-trample-file-versions (fn)
282 (let* ((start-vn (string-match "\\.~[0-9]+~$" fn
))
285 (setq base-version-list
; there was a base version to which
286 (assoc (substring fn
0 start-vn
) ; this looks like a
287 dired-file-version-alist
)) ; subversion
288 (not (memq (string-to-int (substring fn
(+ 2 start-vn
)))
289 base-version-list
)) ; this one doesn't make the cut
290 (progn (beginning-of-line)
292 (insert dired-del-marker
)))))
295 ;;>>> install (move this function into simple.el)
296 (defun dired-shell-quote (filename)
297 "Quote a file name for inferior shell (see variable `shell-file-name')."
298 ;; Quote everything except POSIX filename characters.
299 ;; This should be safe enough even for really weird shells.
300 (let ((result "") (start 0) end
)
301 (while (string-match "[^-0-9a-zA-Z_./]" filename start
)
302 (setq end
(match-beginning 0)
303 result
(concat result
(substring filename start end
)
304 "\\" (substring filename end
(1+ end
)))
306 (concat result
(substring filename start
))))
308 (defun dired-read-shell-command (prompt arg files
)
309 ;; "Read a dired shell command prompting with PROMPT (using read-string).
310 ;;ARG is the prefix arg and may be used to indicate in the prompt which
311 ;; files are affected.
312 ;;This is an extra function so that you can redefine it, e.g., to use gmhist."
315 (function read-string
)
316 (format prompt
(dired-mark-prompt arg files
))
317 nil
'shell-command-history
))
319 ;; The in-background argument is only needed in Emacs 18 where
320 ;; shell-command doesn't understand an appended ampersand `&'.
322 (defun dired-do-shell-command (command &optional arg
)
323 "Run a shell command COMMAND on the marked files.
324 If no files are marked or a specific numeric prefix arg is given,
325 the next ARG files are used. Just \\[universal-argument] means the current file.
326 The prompt mentions the file(s) or the marker, as appropriate.
328 If there is output, it goes to a separate buffer.
330 Normally the command is run on each file individually.
331 However, if there is a `*' in the command then it is run
332 just once with the entire file list substituted there.
334 No automatic redisplay of dired buffers is attempted, as there's no
335 telling what files the command may have changed. Type
336 \\[dired-do-redisplay] to redisplay the marked files.
338 The shell command has the top level directory as working directory, so
339 output files usually are created there instead of in a subdir."
340 ;;Functions dired-run-shell-command and dired-shell-stuff-it do the
341 ;;actual work and can be redefined for customization.
343 ;; Want to give feedback whether this file or marked files are used:
344 (dired-read-shell-command (concat "! on "
347 (dired-get-marked-files
348 t current-prefix-arg
))
350 (let* ((on-each (not (string-match "\\*" command
)))
351 (file-list (dired-get-marked-files t arg
)))
354 (- 10000 (length command
))
355 (function (lambda (&rest files
)
356 (dired-run-shell-command
357 (dired-shell-stuff-it command files t arg
))))
360 ;; execute the shell command
361 (dired-run-shell-command
362 (dired-shell-stuff-it command file-list nil arg
)))))
364 ;; Might use {,} for bash or csh:
365 (defvar dired-mark-prefix
""
366 "Prepended to marked files in dired shell commands.")
367 (defvar dired-mark-postfix
""
368 "Appended to marked files in dired shell commands.")
369 (defvar dired-mark-separator
" "
370 "Separates marked files in dired shell commands.")
372 (defun dired-shell-stuff-it (command file-list on-each
&optional raw-arg
)
373 ;; "Make up a shell command line from COMMAND and FILE-LIST.
374 ;; If ON-EACH is t, COMMAND should be applied to each file, else
375 ;; simply concat all files and apply COMMAND to this.
376 ;; FILE-LIST's elements will be quoted for the shell."
377 ;; Might be redefined for smarter things and could then use RAW-ARG
378 ;; (coming from interactive P and currently ignored) to decide what to do.
379 ;; Smart would be a way to access basename or extension of file names.
380 ;; See dired-trns.el for an approach to this.
381 ;; Bug: There is no way to quote a *
382 ;; On the other hand, you can never accidentally get a * into your cmd.
384 (if (string-match "\\*" command
)
385 (function (lambda (x)
386 (dired-replace-in-string "\\*" x command
)))
387 (function (lambda (x) (concat command
" " x
))))))
389 (mapconcat stuff-it
(mapcar 'dired-shell-quote file-list
) ";")
390 (let ((fns (mapconcat 'dired-shell-quote
391 file-list dired-mark-separator
)))
392 (if (> (length file-list
) 1)
393 (setq fns
(concat dired-mark-prefix fns dired-mark-postfix
)))
394 (funcall stuff-it fns
)))))
396 ;; This is an extra function so that it can be redefined by ange-ftp.
397 (defun dired-run-shell-command (command)
398 (shell-command command
)
399 ;; Return nil for sake of nconc in dired-bunch-files.
402 ;; In Emacs 19 this will return program's exit status.
403 ;; This is a separate function so that ange-ftp can redefine it.
404 (defun dired-call-process (program discard
&rest arguments
)
405 ; "Run PROGRAM with output to current buffer unless DISCARD is t.
406 ;Remaining arguments are strings passed as command arguments to PROGRAM."
407 ;; Look for a handler for default-directory in case it is a remote file name.
409 (find-file-name-handler (directory-file-name default-directory
)
410 'dired-call-process
)))
411 (if handler
(apply handler
'dired-call-process
412 program discard arguments
)
413 (apply 'call-process program nil
(not discard
) nil arguments
))))
415 (defun dired-check-process (msg program
&rest arguments
)
416 ; "Display MSG while running PROGRAM, and check for output.
417 ;Remaining arguments are strings passed as command arguments to PROGRAM.
418 ; On error, insert output
419 ; in a log buffer and return the offending ARGUMENTS or PROGRAM.
420 ; Caller can cons up a list of failed args.
421 ;Else returns nil for success."
422 (let (err-buffer err
(dir default-directory
))
423 (message "%s..." msg
)
425 ;; Get a clean buffer for error output:
426 (setq err-buffer
(get-buffer-create " *dired-check-process output*"))
427 (set-buffer err-buffer
)
429 (setq default-directory dir
; caller's default-directory
431 (apply (function dired-call-process
) program nil arguments
)))
434 (dired-log (concat program
" " (prin1-to-string arguments
) "\n"))
435 (dired-log err-buffer
)
436 (or arguments program t
))
437 (kill-buffer err-buffer
)
438 (message "%s...done" msg
)
441 ;; Commands that delete or redisplay part of the dired buffer.
443 (defun dired-kill-line (&optional arg
)
445 (setq arg
(prefix-numeric-value arg
))
446 (let (buffer-read-only file
)
448 (setq file
(dired-get-filename nil t
))
450 (error "Can only kill file lines.")
451 (save-excursion (and file
452 (dired-goto-subdir file
)
453 (dired-kill-subdir)))
454 (delete-region (progn (beginning-of-line) (point))
455 (progn (forward-line 1) (point)))
460 (dired-move-to-filename)))
463 (defun dired-do-kill-lines (&optional arg fmt
)
464 "Kill all marked lines (not the files).
465 With a prefix argument, kill that many lines starting with the current line.
466 \(A negative argument kills lines before the current line.)
467 To kill an entire subdirectory, go to its directory header line
468 and use this command with a prefix argument (the value does not matter)."
469 ;; Returns count of killed lines. FMT="" suppresses message.
472 (if (dired-get-subdir)
474 (dired-kill-line arg
))
476 (goto-char (point-min))
477 (let (buffer-read-only (count 0))
478 (if (not arg
) ; kill marked lines
479 (let ((regexp (dired-marker-regexp)))
480 (while (and (not (eobp))
481 (re-search-forward regexp nil t
))
482 (setq count
(1+ count
))
483 (delete-region (progn (beginning-of-line) (point))
484 (progn (forward-line 1) (point)))))
485 ;; else kill unmarked lines
487 (if (or (dired-between-files)
488 (not (looking-at "^ ")))
490 (setq count
(1+ count
))
491 (delete-region (point) (save-excursion
495 (message (or fmt
"Killed %d line%s.") count
(dired-plural-s count
)))
498 ;;;###end dired-cmd.el
501 ;;;###begin dired-cp.el
503 (defun dired-compress ()
504 ;; Compress or uncompress the current file.
505 ;; Return nil for success, offending filename else.
506 (let* (buffer-read-only
507 (from-file (dired-get-filename))
508 (new-file (dired-compress-file from-file
)))
510 (let ((start (point)))
511 ;; Remove any preexisting entry for the name NEW-FILE.
513 (dired-remove-entry new-file
)
516 ;; Now replace the current line with an entry for NEW-FILE.
517 (dired-update-file-line new-file
) nil
)
518 (dired-log (concat "Failed to compress" from-file
))
521 (defvar dired-compress-file-suffixes
522 '(("\\.gz\\'" "" "gunzip")
523 ("\\.tgz\\'" ".tar" "gunzip")
524 ("\\.Z\\'" "" "uncompress")
525 ;; For .z, try gunzip. It might be an old gzip file,
526 ;; or it might be from compact? pack? (which?) but gunzip handles both.
527 ("\\.z\\'" "" "gunzip")
528 ;; This item controls naming for compression.
529 ("\\.tar\\'" ".tgz" nil
))
530 "Control changes in file name suffixes for compression and uncompression.
531 Each element specifies one transformation rule, and has the form:
532 (REGEXP NEW-SUFFIX PROGRAM)
533 The rule applies when the old file name matches REGEXP.
534 The new file name is computed by deleting the part that matches REGEXP
535 (as well as anything after that), then adding NEW-SUFFIX in its place.
536 If PROGRAM is non-nil, the rule is an uncompression rule,
537 and uncompression is done by running PROGRAM.
538 Otherwise, the rule is a compression rule, and compression is done with gzip.")
541 (defun dired-compress-file (file)
542 ;; Compress or uncompress FILE.
543 ;; Return the name of the compressed or uncompressed file.
544 ;; Return nil if no change in files.
545 (let ((handler (find-file-name-handler file
'dired-compress-file
))
547 (suffixes dired-compress-file-suffixes
))
548 ;; See if any suffix rule matches this file name.
550 (let (case-fold-search)
551 (if (string-match (car (car suffixes
)) file
)
552 (setq suffix
(car suffixes
) suffixes nil
))
553 (setq suffixes
(cdr suffixes
))))
554 ;; If so, compute desired new name.
556 (setq newname
(concat (substring file
0 (match-beginning 0))
559 (funcall handler
'dired-compress-file file
))
560 ((file-symlink-p file
)
562 ((and suffix
(nth 2 suffix
))
563 ;; We found an uncompression rule.
564 (if (not (dired-check-process (concat "Uncompressing " file
)
565 (nth 2 suffix
) file
))
568 ;;; We don't recognize the file as compressed, so compress it.
569 ;;; Try gzip; if we don't have that, use compress.
571 (if (not (dired-check-process (concat "Compressing " file
)
574 (if (file-exists-p (concat file
".gz"))
576 (concat file
".z"))))
577 ;; Rename the compressed file to NEWNAME
578 ;; if it hasn't got that name already.
579 (if (and newname
(not (equal newname out-name
)))
581 (rename-file out-name newname t
)
585 (if (not (dired-check-process (concat "Compressing " file
)
586 "compress" "-f" file
))
587 ;; Don't use NEWNAME with `compress'.
588 (concat file
".Z"))))))))
590 (defun dired-mark-confirm (op-symbol arg
)
591 ;; Request confirmation from the user that the operation described
592 ;; by OP-SYMBOL is to be performed on the marked files.
593 ;; Confirmation consists in a y-or-n question with a file list
594 ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
595 ;; The files used are determined by ARG (as in dired-get-marked-files).
596 (or (eq dired-no-confirm t
)
597 (memq op-symbol dired-no-confirm
)
598 (let ((files (dired-get-marked-files t arg
))
599 (string (if (eq op-symbol
'compress
) "Compress or uncompress"
600 (capitalize (symbol-name op-symbol
)))))
601 (dired-mark-pop-up nil op-symbol files
(function y-or-n-p
)
603 (dired-mark-prompt arg files
) "? ")))))
605 (defun dired-map-over-marks-check (fun arg op-symbol
&optional show-progress
)
606 ; "Map FUN over marked files (with second ARG like in dired-map-over-marks)
607 ; and display failures.
609 ; FUN takes zero args. It returns non-nil (the offending object, e.g.
610 ; the short form of the filename) for a failure and probably logs a
611 ; detailed error explanation using function `dired-log'.
613 ; OP-SYMBOL is a symbol describing the operation performed (e.g.
614 ; `compress'). It is used with `dired-mark-pop-up' to prompt the user
615 ; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
616 ; `Failed to compress 1 of 2 files - type W to see why ("foo")')
618 ; SHOW-PROGRESS if non-nil means redisplay dired after each file."
619 (if (dired-mark-confirm op-symbol arg
)
620 (let* ((total-list;; all of FUN's return values
621 (dired-map-over-marks (funcall fun
) arg show-progress
))
622 (total (length total-list
))
623 (failures (delq nil total-list
))
624 (count (length failures
))
625 (string (if (eq op-symbol
'compress
) "Compress or uncompress"
626 (capitalize (symbol-name op-symbol
)))))
628 (message "%s: %d file%s."
629 string total
(dired-plural-s total
))
630 ;; end this bunch of errors:
632 (format "Failed to %s %d of %d file%s"
633 (downcase string
) count total
(dired-plural-s total
))
636 (defvar dired-query-alist
637 '((?\y . y
) (?
\040 . y
) ; `y' or SPC means accept once
638 (?n . n
) (?
\177 . n
) ; `n' or DEL skips once
639 (?
! . yes
) ; `!' accepts rest
640 (?q. no
) (?\e . no
) ; `q' or ESC skips rest
641 ;; None of these keys quit - use C-g for that.
644 (defun dired-query (qs-var qs-prompt
&rest qs-args
)
645 ;; Query user and return nil or t.
646 ;; Store answer in symbol VAR (which must initially be bound to nil).
647 ;; Format PROMPT with ARGS.
648 ;; Binding variable help-form will help the user who types the help key.
649 (let* ((char (symbol-value qs-var
))
650 (action (cdr (assoc char dired-query-alist
))))
651 (cond ((eq 'yes action
)
652 t
) ; accept, and don't ask again
654 nil
) ; skip, and don't ask again
655 (t;; no lasting effects from last time we asked - ask now
656 (let ((qprompt (concat qs-prompt
658 (format " [Type yn!q or %s] "
660 (char-to-string help-char
)))
661 " [Type y, n, q or !] ")))
663 ;; Actually it looks nicer without cursor-in-echo-area - you can
664 ;; look at the dired buffer instead of at the prompt to decide.
665 (apply 'message qprompt qs-args
)
666 (setq char
(set qs-var
(read-char)))
667 (while (not (setq elt
(assoc char dired-query-alist
)))
668 (message "Invalid char - type %c for help." help-char
)
671 (apply 'message qprompt qs-args
)
672 (setq char
(set qs-var
(read-char))))
673 (memq (cdr elt
) '(t y yes
)))))))
676 (defun dired-do-compress (&optional arg
)
677 "Compress or uncompress marked (or next ARG) files."
679 (dired-map-over-marks-check (function dired-compress
) arg
'compress t
))
681 ;; Commands for Emacs Lisp files - load and byte compile
683 (defun dired-byte-compile ()
684 ;; Return nil for success, offending file name else.
685 (let* ((filename (dired-get-filename))
686 elc-file buffer-read-only failure
)
688 (save-excursion (byte-compile-file filename
))
691 (setq elc-file
(byte-compile-dest-file filename
))
692 (or (file-exists-p elc-file
)
696 (dired-log "Byte compile error for %s:\n%s\n" filename failure
)
697 (dired-make-relative filename
))
698 (dired-remove-file elc-file
)
699 (forward-line) ; insert .elc after its .el file
700 (dired-add-file elc-file
)
704 (defun dired-do-byte-compile (&optional arg
)
705 "Byte compile marked (or next ARG) Emacs Lisp files."
707 (dired-map-over-marks-check (function dired-byte-compile
) arg
'byte-compile t
))
710 ;; Return nil for success, offending file name else.
711 (let ((file (dired-get-filename)) failure
)
713 (load file nil nil t
)
714 (error (setq failure err
)))
717 (dired-log "Load error for %s:\n%s\n" file failure
)
718 (dired-make-relative file
))))
721 (defun dired-do-load (&optional arg
)
722 "Load the marked (or next ARG) Emacs Lisp files."
724 (dired-map-over-marks-check (function dired-load
) arg
'load t
))
727 (defun dired-do-redisplay (&optional arg test-for-subdir
)
728 "Redisplay all marked (or next ARG) files.
729 If on a subdir line, redisplay that subdirectory. In that case,
730 a prefix arg lets you edit the `ls' switches used for the new listing."
731 ;; Moves point if the next ARG files are redisplayed.
733 (if (and test-for-subdir
(dired-get-subdir))
736 (if arg
(read-string "Switches for listing: " dired-actual-switches
)))
737 (message "Redisplaying...")
738 ;; message much faster than making dired-map-over-marks show progress
740 (if (consp dired-directory
) (car dired-directory
) dired-directory
))
741 (dired-map-over-marks (let ((fname (dired-get-filename)))
742 (message "Redisplaying... %s" fname
)
743 (dired-update-file-line fname
))
745 (dired-move-to-filename)
746 (message "Redisplaying...done")))
748 (defun dired-update-file-line (file)
749 ;; Delete the current line, and insert an entry for FILE.
750 ;; If FILE is nil, then just delete the current line.
751 ;; Keeps any marks that may be present in column one (doing this
752 ;; here is faster than with dired-add-entry's optional arg).
753 ;; Does not update other dired buffers. Use dired-relist-entry for that.
755 (let ((char (following-char)) (opoint (point))
757 (delete-region (point) (progn (forward-line 1) (point)))
760 (dired-add-entry file
)
761 ;; Replace space by old marker without moving point.
762 ;; Faster than goto+insdel inside a save-excursion?
763 (subst-char-in-region opoint
(1+ opoint
) ?
\040 char
))))
764 (dired-move-to-filename))
766 (defun dired-fun-in-all-buffers (directory file fun
&rest args
)
767 ;; In all buffers dired'ing DIRECTORY, run FUN with ARGS.
768 ;; If the buffer has a wildcard pattern, check that it matches FILE.
769 ;; (FILE does not include a directory component.)
770 ;; FILE may be nil, in which case ignore it.
771 ;; Return list of buffers where FUN succeeded (i.e., returned non-nil).
772 (let ((buf-list (dired-buffers-for-dir (expand-file-name directory
)
774 (obuf (current-buffer))
777 (setq buf
(car buf-list
)
778 buf-list
(cdr buf-list
))
783 (setq success-list
(cons (buffer-name buf
) success-list
))))
788 (defun dired-add-file (filename &optional marker-char
)
789 (dired-fun-in-all-buffers
790 (file-name-directory filename
) (file-name-nondirectory filename
)
791 (function dired-add-entry
) filename marker-char
))
793 (defun dired-add-entry (filename &optional marker-char
)
794 ;; Add a new entry for FILENAME, optionally marking it
795 ;; with MARKER-CHAR (a character, else dired-marker-char is used).
796 ;; Note that this adds the entry `out of order' if files sorted by
798 ;; At least this version inserts in the right subdirectory (if present).
799 ;; And it skips "." or ".." (see `dired-trivial-filenames').
800 ;; Hidden subdirs are exposed if a file is added there.
801 (setq filename
(directory-file-name filename
))
802 ;; Entry is always for files, even if they happen to also be directories
803 (let ((opoint (point))
804 (cur-dir (dired-current-directory))
805 (orig-file-name filename
)
806 (directory (file-name-directory filename
))
808 (setq filename
(file-name-nondirectory filename
)
811 (if (string= directory cur-dir
)
813 (skip-chars-forward "^\r\n")
814 (if (eq (following-char) ?
\r)
815 (dired-unhide-subdir))
816 ;; We are already where we should be, except when
817 ;; point is before the subdir line or its total line.
818 (let ((p (dired-after-subdir-garbage cur-dir
)))
821 ;; else try to find correct place to insert
822 (if (dired-goto-subdir directory
)
823 (progn;; unhide if necessary
824 (if (looking-at "\r");; point is at end of subdir line
825 (dired-unhide-subdir))
826 ;; found - skip subdir and `total' line
827 ;; and uninteresting files like . and ..
828 ;; This better not moves into the next subdir!
829 (dired-goto-next-nontrivial-file))
831 (throw 'not-found
"Subdir not found")))
832 (let (buffer-read-only opoint
)
834 (setq opoint
(point))
835 (dired-add-entry-do-indentation marker-char
)
836 ;; don't expand `.'. Show just the file name within directory.
837 (let ((default-directory directory
))
838 (insert-directory filename
839 (concat dired-actual-switches
"d")))
840 ;; Compensate for a bug in ange-ftp.
841 ;; It inserts the file's absolute name, rather than
842 ;; the relative one. That may be hard to fix since it
843 ;; is probably controlled by something in ftp.
845 (let ((inserted-name (dired-get-filename 'no-dir
)))
846 (if (file-name-directory inserted-name
)
849 (delete-char (- (length inserted-name
)))
853 ;; Give each line a text property recording info about it.
854 (dired-insert-set-properties opoint
(point))
856 (if dired-after-readin-hook
;; the subdir-alist is not affected...
857 (save-excursion;; ...so we can run it right now:
860 (narrow-to-region (point) (save-excursion
861 (forward-line 1) (point)))
862 (run-hooks 'dired-after-readin-hook
))))
863 (dired-move-to-filename))
864 ;; return nil if all went well
866 (if reason
; don't move away on failure
868 (not reason
))) ; return t on success, nil else
870 ;; This is a separate function for the sake of nested dired format.
871 (defun dired-add-entry-do-indentation (marker-char)
872 ;; two spaces or a marker plus a space:
873 (insert (if marker-char
874 (if (integerp marker-char
) marker-char dired-marker-char
)
878 (defun dired-after-subdir-garbage (dir)
879 ;; Return pos of first file line of DIR, skipping header and total
880 ;; or wildcard lines.
881 ;; Important: never moves into the next subdir.
882 ;; DIR is assumed to be unhidden.
883 ;; Will probably be redefined for VMS etc.
885 (or (dired-goto-subdir dir
) (error "This cannot happen"))
887 (while (and (not (eolp)) ; don't cross subdir boundary
888 (not (dired-move-to-filename)))
893 (defun dired-remove-file (file)
894 (dired-fun-in-all-buffers
895 (file-name-directory file
) (file-name-nondirectory file
)
896 (function dired-remove-entry
) file
))
898 (defun dired-remove-entry (file)
900 (and (dired-goto-file file
)
901 (let (buffer-read-only)
902 (delete-region (progn (beginning-of-line) (point))
903 (save-excursion (forward-line 1) (point)))))))
906 (defun dired-relist-file (file)
907 (dired-fun-in-all-buffers (file-name-directory file
)
908 (file-name-nondirectory file
)
909 (function dired-relist-entry
) file
))
911 (defun dired-relist-entry (file)
912 ;; Relist the line for FILE, or just add it if it did not exist.
913 ;; FILE must be an absolute pathname.
914 (let (buffer-read-only marker
)
915 ;; If cursor is already on FILE's line delete-region will cause
916 ;; save-excursion to fail because of floating makers,
917 ;; moving point to beginning of line. Sigh.
919 (and (dired-goto-file file
)
920 (delete-region (progn (beginning-of-line)
921 (setq marker
(following-char))
923 (save-excursion (forward-line 1) (point))))
924 (setq file
(directory-file-name file
))
925 (dired-add-entry file
(if (eq ?
\040 marker
) nil marker
)))))
927 ;;; Copy, move/rename, making hard and symbolic links
929 (defcustom dired-backup-overwrite nil
930 "*Non-nil if Dired should ask about making backups before overwriting files.
931 Special value `always' suppresses confirmation."
932 :type
'(choice (const :tag
"off" nil
)
933 (const :tag
"suppress" always
)
934 (sexp :tag
"ask" :format
"%t\n" t
))
937 (defvar dired-overwrite-confirmed
)
939 (defun dired-handle-overwrite (to)
940 ;; Save old version of a to be overwritten file TO.
941 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
942 ;; from dired-create-files.
944 (if (and dired-backup-overwrite
945 dired-overwrite-confirmed
946 (setq backup
(car (find-backup-file-name to
)))
947 (or (eq 'always dired-backup-overwrite
)
948 (dired-query 'overwrite-backup-query
949 (format "Make backup for existing file `%s'? " to
))))
951 (rename-file to backup
0) ; confirm overwrite of old backup
952 (dired-relist-entry backup
)))))
955 (defun dired-copy-file (from to ok-flag
)
956 (dired-handle-overwrite to
)
958 (copy-file from to ok-flag dired-copy-preserve-time
)
959 (file-date-error (message "Can't set date")
963 (defun dired-rename-file (from to ok-flag
)
964 (dired-handle-overwrite to
)
965 (rename-file from to ok-flag
) ; error is caught in -create-files
966 ;; Silently rename the visited file of any buffer visiting this file.
967 (and (get-file-buffer from
)
968 (with-current-buffer (get-file-buffer from
)
969 (set-visited-file-name to nil t
)))
970 (dired-remove-file from
)
971 ;; See if it's an inserted subdir, and rename that, too.
972 (dired-rename-subdir from to
))
974 (defun dired-rename-subdir (from-dir to-dir
)
975 (setq from-dir
(file-name-as-directory from-dir
)
976 to-dir
(file-name-as-directory to-dir
))
977 (dired-fun-in-all-buffers from-dir nil
978 (function dired-rename-subdir-1
) from-dir to-dir
)
979 ;; Update visited file name of all affected buffers
980 (let ((expanded-from-dir (expand-file-name from-dir
))
981 (blist (buffer-list)))
984 (set-buffer (car blist
))
985 (if (and buffer-file-name
986 (dired-in-this-tree buffer-file-name expanded-from-dir
))
987 (let ((modflag (buffer-modified-p))
988 (to-file (dired-replace-in-string
989 (concat "^" (regexp-quote from-dir
))
992 (set-visited-file-name to-file
)
993 (set-buffer-modified-p modflag
))))
994 (setq blist
(cdr blist
)))))
996 (defun dired-rename-subdir-1 (dir to
)
997 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
998 ;; one of its subdirectories is expanded in this buffer.
999 (let ((expanded-dir (expand-file-name dir
))
1000 (alist dired-subdir-alist
)
1003 (setq elt
(car alist
)
1005 (if (dired-in-this-tree (car elt
) expanded-dir
)
1006 ;; ELT's subdir is affected by the rename
1007 (dired-rename-subdir-2 elt dir to
)))
1008 (if (equal dir default-directory
)
1009 ;; if top level directory was renamed, lots of things have to be
1012 (dired-unadvertise dir
) ; we no longer dired DIR...
1013 (setq default-directory to
1014 dired-directory
(expand-file-name;; this is correct
1015 ;; with and without wildcards
1016 (file-name-nondirectory dired-directory
)
1018 (let ((new-name (file-name-nondirectory
1019 (directory-file-name dired-directory
))))
1020 ;; try to rename buffer, but just leave old name if new
1021 ;; name would already exist (don't try appending "<%d>")
1022 (or (get-buffer new-name
)
1023 (rename-buffer new-name
)))
1024 ;; ... we dired TO now:
1025 (dired-advertise)))))
1027 (defun dired-rename-subdir-2 (elt dir to
)
1028 ;; Update the headerline and dired-subdir-alist element of directory
1029 ;; described by alist-element ELT to reflect the moving of DIR to TO.
1030 ;; Thus, ELT describes either DIR itself or a subdir of DIR.
1032 (let ((regexp (regexp-quote (directory-file-name dir
)))
1033 (newtext (directory-file-name to
))
1035 (goto-char (dired-get-subdir-min elt
))
1036 ;; Update subdir headerline in buffer
1037 (if (not (looking-at dired-subdir-regexp
))
1038 (error "%s not found where expected - dired-subdir-alist broken?"
1040 (goto-char (match-beginning 1))
1041 (if (re-search-forward regexp
(match-end 1) t
)
1042 (replace-match newtext t t
)
1043 (error "Expected to find `%s' in headerline of %s" dir
(car elt
))))
1044 ;; Update buffer-local dired-subdir-alist
1046 (dired-normalize-subdir
1047 (dired-replace-in-string regexp newtext
(car elt
)))))))
1049 ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1050 (defun dired-create-files (file-creator operation fn-list name-constructor
1051 &optional marker-char
)
1053 ;; Create a new file for each from a list of existing files. The user
1054 ;; is queried, dired buffers are updated, and at the end a success or
1055 ;; failure message is displayed
1057 ;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
1059 ;; It is called for each file and must create newfile, the entry of
1060 ;; which will be added. The user will be queried if the file already
1061 ;; exists. If oldfile is removed by FILE-CREATOR (i.e, it is a
1062 ;; rename), it is FILE-CREATOR's responsibility to update dired
1063 ;; buffers. FILE-CREATOR must abort by signaling a file-error if it
1064 ;; could not create newfile. The error is caught and logged.
1066 ;; OPERATION (a capitalized string, e.g. `Copy') describes the
1067 ;; operation performed. It is used for error logging.
1069 ;; FN-LIST is the list of files to copy (full absolute pathnames).
1071 ;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
1072 ;; skip. If it skips files for other reasons than a direct user
1073 ;; query, it is supposed to tell why (using dired-log).
1075 ;; Optional MARKER-CHAR is a character with which to mark every
1076 ;; newfile's entry, or t to use the current marker character if the
1077 ;; oldfile was marked.
1079 (let (failures skipped
(success-count 0) (total (length fn-list
)))
1080 (let (to overwrite-query
1081 overwrite-backup-query
) ; for dired-handle-overwrite
1085 (setq to
(funcall name-constructor from
))
1089 (dired-log "Cannot %s to same file: %s\n"
1090 (downcase operation
) from
)))
1092 (setq skipped
(cons (dired-make-relative from
) skipped
))
1093 (let* ((overwrite (file-exists-p to
))
1094 (dired-overwrite-confirmed ; for dired-handle-overwrite
1096 (let ((help-form '(format "\
1097 Type SPC or `y' to overwrite file `%s',
1098 DEL or `n' to skip to next,
1099 ESC or `q' to not overwrite any of the remaining files,
1100 `!' to overwrite all remaining files with no more questions." to
)))
1101 (dired-query 'overwrite-query
1102 "Overwrite `%s'?" to
))))
1103 ;; must determine if FROM is marked before file-creator
1104 ;; gets a chance to delete it (in case of a move).
1106 (cond ((integerp marker-char
) marker-char
)
1107 (marker-char (dired-file-marker from
)) ; slow
1111 (funcall file-creator from to dired-overwrite-confirmed
)
1113 ;; If we get here, file-creator hasn't been aborted
1114 ;; and the old entry (if any) has to be deleted
1115 ;; before adding the new entry.
1116 (dired-remove-file to
))
1117 (setq success-count
(1+ success-count
))
1118 (message "%s: %d of %d" operation success-count total
)
1119 (dired-add-file to actual-marker-char
))
1120 (file-error ; FILE-CREATOR aborted
1122 (setq failures
(cons (dired-make-relative from
) failures
))
1123 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1124 operation from to err
))))))))
1129 (format "%s failed for %d of %d file%s"
1130 operation
(length failures
) total
1131 (dired-plural-s total
))
1135 (format "%s: %d of %d file%s skipped"
1136 operation
(length skipped
) total
1137 (dired-plural-s total
))
1140 (message "%s: %s file%s"
1141 operation success-count
(dired-plural-s success-count
)))))
1142 (dired-move-to-filename))
1144 (defun dired-do-create-files (op-symbol file-creator operation arg
1145 &optional marker-char op1
1147 ;; Create a new file for each marked file.
1148 ;; Prompts user for target, which is a directory in which to create
1149 ;; the new files. Target may be a plain file if only one marked
1151 ;; OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1152 ;; will determine whether pop-ups are appropriate for this OP-SYMBOL.
1153 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1154 ;; ARG as in dired-get-marked-files.
1155 ;; Optional arg OP1 is an alternate form for OPERATION if there is
1157 ;; Optional arg MARKER-CHAR as in dired-create-files.
1158 ;; Optional arg HOW-TO determines how to treat target:
1159 ;; If HOW-TO is not given (or nil), and target is a directory, the
1160 ;; file(s) are created inside the target directory. If target
1161 ;; is not a directory, there must be exactly one marked file,
1163 ;; If HOW-TO is t, then target is not modified. There must be
1164 ;; exactly one marked file, else error.
1165 ;; Else HOW-TO is assumed to be a function of one argument, target,
1166 ;; that looks at target and returns a value for the into-dir
1167 ;; variable. The function dired-into-dir-with-symlinks is provided
1168 ;; for the case (common when creating symlinks) that symbolic
1169 ;; links to directories are not to be considered as directories
1170 ;; (as file-directory-p would if HOW-TO had been nil).
1171 (or op1
(setq op1 operation
))
1172 (let* ((fn-list (dired-get-marked-files nil arg
))
1173 (fn-count (length fn-list
))
1174 (target (expand-file-name
1175 (dired-mark-read-file-name
1176 (concat (if (= 1 fn-count
) op1 operation
) " %s to: ")
1177 (dired-dwim-target-directory)
1178 op-symbol arg
(mapcar (function dired-make-relative
) fn-list
))))
1179 (into-dir (cond ((null how-to
) (file-directory-p target
))
1181 (t (funcall how-to target
)))))
1182 (if (and (> fn-count
1)
1184 (error "Marked %s: target must be a directory: %s" operation target
))
1185 ;; rename-file bombs when moving directories unless we do this:
1186 (or into-dir
(setq target
(directory-file-name target
)))
1188 file-creator operation fn-list
1189 (if into-dir
; target is a directory
1190 ;; This function uses fluid vars into-dir and target when called
1191 ;; inside dired-create-files:
1192 (function (lambda (from)
1193 (expand-file-name (file-name-nondirectory from
) target
)))
1194 (function (lambda (from) target
)))
1197 ;; Read arguments for a marked-files command that wants a file name,
1198 ;; perhaps popping up the list of marked files.
1199 ;; ARG is the prefix arg and indicates whether the files came from
1200 ;; marks (ARG=nil) or a repeat factor (integerp ARG).
1201 ;; If the current file was used, the list has but one element and ARG
1202 ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
1204 (defun dired-mark-read-file-name (prompt dir op-symbol arg files
)
1207 (function read-file-name
)
1208 (format prompt
(dired-mark-prompt arg files
)) dir
))
1210 (defun dired-dwim-target-directory ()
1211 ;; Try to guess which target directory the user may want.
1212 ;; If there is a dired buffer displayed in the next window, use
1213 ;; its current subdir, else use current subdir of this dired buffer.
1214 (let ((this-dir (and (eq major-mode
'dired-mode
)
1215 (dired-current-directory))))
1216 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1217 (if dired-dwim-target
1218 (let* ((other-buf (window-buffer (next-window)))
1219 (other-dir (save-excursion
1220 (set-buffer other-buf
)
1221 (and (eq major-mode
'dired-mode
)
1222 (dired-current-directory)))))
1223 (or other-dir this-dir
))
1227 (defun dired-create-directory (directory)
1228 "Create a directory called DIRECTORY."
1230 (list (read-file-name "Create directory: " (dired-current-directory))))
1231 (let ((expanded (directory-file-name (expand-file-name directory
))))
1232 (make-directory expanded
)
1233 (dired-add-file expanded
)
1234 (dired-move-to-filename)))
1236 (defun dired-into-dir-with-symlinks (target)
1237 (and (file-directory-p target
)
1238 (not (file-symlink-p target
))))
1239 ;; This may not always be what you want, especially if target is your
1240 ;; home directory and it happens to be a symbolic link, as is often the
1241 ;; case with NFS and automounters. Or if you want to make symlinks
1242 ;; into directories that themselves are only symlinks, also quite
1245 ;; So we don't use this function as value for HOW-TO in
1246 ;; dired-do-symlink, which has the minor disadvantage of
1247 ;; making links *into* a symlinked-dir, when you really wanted to
1248 ;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1249 ;; just have to remove that symlink by hand before making your marked
1253 (defun dired-do-copy (&optional arg
)
1254 "Copy all marked (or next ARG) files, or copy the current file.
1255 This normally preserves the last-modified date when copying.
1256 When operating on just the current file, you specify the new name.
1257 When operating on multiple or marked files, you specify a directory,
1258 and new copies of these files are made in that directory
1259 with the same names that the files currently have."
1261 (dired-do-create-files 'copy
(function dired-copy-file
)
1262 (if dired-copy-preserve-time
"Copy [-p]" "Copy")
1263 arg dired-keep-marker-copy
))
1266 (defun dired-do-symlink (&optional arg
)
1267 "Make symbolic links to current file or all marked (or next ARG) files.
1268 When operating on just the current file, you specify the new name.
1269 When operating on multiple or marked files, you specify a directory
1270 and new symbolic links are made in that directory
1271 with the same names that the files currently have."
1273 (dired-do-create-files 'symlink
(function make-symbolic-link
)
1274 "Symlink" arg dired-keep-marker-symlink
))
1277 (defun dired-do-hardlink (&optional arg
)
1278 "Add names (hard links) current file or all marked (or next ARG) files.
1279 When operating on just the current file, you specify the new name.
1280 When operating on multiple or marked files, you specify a directory
1281 and new hard links are made in that directory
1282 with the same names that the files currently have."
1284 (dired-do-create-files 'hardlink
(function add-name-to-file
)
1285 "Hardlink" arg dired-keep-marker-hardlink
))
1288 (defun dired-do-rename (&optional arg
)
1289 "Rename current file or all marked (or next ARG) files.
1290 When renaming just the current file, you specify the new name.
1291 When renaming multiple or marked files, you specify a directory."
1293 (dired-do-create-files 'move
(function dired-rename-file
)
1294 "Move" arg dired-keep-marker-rename
"Rename"))
1295 ;;;###end dired-cp.el
1298 ;;;###begin dired-re.el
1299 (defun dired-do-create-files-regexp
1300 (file-creator operation arg regexp newname
&optional whole-path marker-char
)
1301 ;; Create a new file for each marked file using regexps.
1302 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1303 ;; ARG as in dired-get-marked-files.
1304 ;; Matches each marked file against REGEXP and constructs the new
1305 ;; filename from NEWNAME (like in function replace-match).
1306 ;; Optional arg WHOLE-PATH means match/replace the whole pathname
1307 ;; instead of only the non-directory part of the file.
1308 ;; Optional arg MARKER-CHAR as in dired-create-files.
1309 (let* ((fn-list (dired-get-marked-files nil arg
))
1310 (fn-count (length fn-list
))
1311 (operation-prompt (concat operation
" `%s' to `%s'?"))
1312 (rename-regexp-help-form (format "\
1313 Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1314 `!' to %s all remaining matches with no more questions."
1315 (downcase operation
)
1316 (downcase operation
)))
1317 (regexp-name-constructor
1318 ;; Function to construct new filename using REGEXP and NEWNAME:
1319 (if whole-path
; easy (but rare) case
1322 (let ((to (dired-string-replace-match regexp from newname
))
1323 ;; must bind help-form directly around call to
1325 (help-form rename-regexp-help-form
))
1327 (and (dired-query 'rename-regexp-query
1332 (dired-log "%s: %s did not match regexp %s\n"
1333 operation from regexp
)))))
1334 ;; not whole-path, replace non-directory part only
1337 (let* ((new (dired-string-replace-match
1338 regexp
(file-name-nondirectory from
) newname
))
1339 (to (and new
; nil means there was no match
1340 (expand-file-name new
1341 (file-name-directory from
))))
1342 (help-form rename-regexp-help-form
))
1344 (and (dired-query 'rename-regexp-query
1346 (dired-make-relative from
)
1347 (dired-make-relative to
))
1349 (dired-log "%s: %s did not match regexp %s\n"
1350 operation
(file-name-nondirectory from
) regexp
)))))))
1351 rename-regexp-query
)
1353 file-creator operation fn-list regexp-name-constructor marker-char
)))
1355 (defun dired-mark-read-regexp (operation)
1356 ;; Prompt user about performing OPERATION.
1357 ;; Read and return list of: regexp newname arg whole-path.
1359 (equal 0 (prefix-numeric-value current-prefix-arg
)))
1361 (if whole-path nil current-prefix-arg
))
1364 (concat (if whole-path
"Path " "") operation
" from (regexp): ")))
1367 (concat (if whole-path
"Path " "") operation
" " regexp
" to: "))))
1368 (list regexp newname arg whole-path
)))
1371 (defun dired-do-rename-regexp (regexp newname
&optional arg whole-path
)
1372 "Rename marked files containing REGEXP to NEWNAME.
1373 As each match is found, the user must type a character saying
1374 what to do with it. For directions, type \\[help-command] at that time.
1375 NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1376 REGEXP defaults to the last regexp used.
1377 With a zero prefix arg, renaming by regexp affects the complete
1378 pathname - usually only the non-directory part of file names is used
1380 (interactive (dired-mark-read-regexp "Rename"))
1381 (dired-do-create-files-regexp
1382 (function dired-rename-file
)
1383 "Rename" arg regexp newname whole-path dired-keep-marker-rename
))
1386 (defun dired-do-copy-regexp (regexp newname
&optional arg whole-path
)
1387 "Copy all marked files containing REGEXP to NEWNAME.
1388 See function `dired-rename-regexp' for more info."
1389 (interactive (dired-mark-read-regexp "Copy"))
1390 (dired-do-create-files-regexp
1391 (function dired-copy-file
)
1392 (if dired-copy-preserve-time
"Copy [-p]" "Copy")
1393 arg regexp newname whole-path dired-keep-marker-copy
))
1396 (defun dired-do-hardlink-regexp (regexp newname
&optional arg whole-path
)
1397 "Hardlink all marked files containing REGEXP to NEWNAME.
1398 See function `dired-rename-regexp' for more info."
1399 (interactive (dired-mark-read-regexp "HardLink"))
1400 (dired-do-create-files-regexp
1401 (function add-name-to-file
)
1402 "HardLink" arg regexp newname whole-path dired-keep-marker-hardlink
))
1405 (defun dired-do-symlink-regexp (regexp newname
&optional arg whole-path
)
1406 "Symlink all marked files containing REGEXP to NEWNAME.
1407 See function `dired-rename-regexp' for more info."
1408 (interactive (dired-mark-read-regexp "SymLink"))
1409 (dired-do-create-files-regexp
1410 (function make-symbolic-link
)
1411 "SymLink" arg regexp newname whole-path dired-keep-marker-symlink
))
1413 (defun dired-create-files-non-directory
1414 (file-creator basename-constructor operation arg
)
1415 ;; Perform FILE-CREATOR on the non-directory part of marked files
1416 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1417 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1418 (let (rename-non-directory-query)
1422 (dired-get-marked-files nil arg
)
1425 (let ((to (concat (file-name-directory from
)
1426 (funcall basename-constructor
1427 (file-name-nondirectory from
)))))
1428 (and (let ((help-form (format "\
1429 Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1430 `!' to %s all remaining matches with no more questions."
1431 (downcase operation
)
1432 (downcase operation
))))
1433 (dired-query 'rename-non-directory-query
1434 (concat operation
" `%s' to `%s'")
1435 (dired-make-relative from
)
1436 (dired-make-relative to
)))
1438 dired-keep-marker-rename
)))
1440 (defun dired-rename-non-directory (basename-constructor operation arg
)
1441 (dired-create-files-non-directory
1442 (function dired-rename-file
)
1443 basename-constructor operation arg
))
1446 (defun dired-upcase (&optional arg
)
1447 "Rename all marked (or next ARG) files to upper case."
1449 (dired-rename-non-directory (function upcase
) "Rename upcase" arg
))
1452 (defun dired-downcase (&optional arg
)
1453 "Rename all marked (or next ARG) files to lower case."
1455 (dired-rename-non-directory (function downcase
) "Rename downcase" arg
))
1457 ;;;###end dired-re.el
1460 ;;;###begin dired-ins.el
1463 (defun dired-maybe-insert-subdir (dirname &optional
1464 switches no-error-if-not-dir-p
)
1465 "Insert this subdirectory into the same dired buffer.
1466 If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1467 else inserts it at its natural place (as `ls -lR' would have done).
1468 With a prefix arg, you may edit the ls switches used for this listing.
1469 You can add `R' to the switches to expand the whole tree starting at
1471 This function takes some pains to conform to `ls -lR' output."
1473 (list (dired-get-filename)
1474 (if current-prefix-arg
1475 (read-string "Switches for listing: " dired-actual-switches
))))
1476 (let ((opoint (point)))
1477 ;; We don't need a marker for opoint as the subdir is always
1478 ;; inserted *after* opoint.
1479 (setq dirname
(file-name-as-directory dirname
))
1480 (or (and (not switches
)
1481 (dired-goto-subdir dirname
))
1482 (dired-insert-subdir dirname switches no-error-if-not-dir-p
))
1483 ;; Push mark so that it's easy to find back. Do this after the
1484 ;; insert message so that the user sees the `Mark set' message.
1485 (push-mark opoint
)))
1487 (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p
)
1488 "Insert this subdirectory into the same dired buffer.
1489 If it is already present, overwrites previous entry,
1490 else inserts it at its natural place (as `ls -lR' would have done).
1491 With a prefix arg, you may edit the `ls' switches used for this listing.
1492 You can add `R' to the switches to expand the whole tree starting at
1494 This function takes some pains to conform to `ls -lR' output."
1495 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
1496 ;; Prospero where dired-ls does the right thing, but
1497 ;; file-directory-p has not been redefined.
1499 (list (dired-get-filename)
1500 (if current-prefix-arg
1501 (read-string "Switches for listing: " dired-actual-switches
))))
1502 (setq dirname
(file-name-as-directory (expand-file-name dirname
)))
1503 (dired-insert-subdir-validate dirname switches
)
1504 (or no-error-if-not-dir-p
1505 (file-directory-p dirname
)
1506 (error "Attempt to insert a non-directory: %s" dirname
))
1507 (let ((elt (assoc dirname dired-subdir-alist
))
1508 switches-have-R mark-alist case-fold-search buffer-read-only
)
1509 ;; case-fold-search is nil now, so we can test for capital `R':
1510 (if (setq switches-have-R
(and switches
(string-match "R" switches
)))
1511 ;; avoid duplicated subdirs
1512 (setq mark-alist
(dired-kill-tree dirname t
)))
1514 ;; If subdir is already present, remove it and remember its marks
1515 (setq mark-alist
(nconc (dired-insert-subdir-del elt
) mark-alist
))
1516 (dired-insert-subdir-newpos dirname
)) ; else compute new position
1517 (dired-insert-subdir-doupdate
1518 dirname elt
(dired-insert-subdir-doinsert dirname switches
))
1519 (if switches-have-R
(dired-build-subdir-alist))
1520 (dired-initial-position dirname
)
1521 (save-excursion (dired-mark-remembered mark-alist
))))
1523 ;; This is a separate function for dired-vms.
1524 (defun dired-insert-subdir-validate (dirname &optional switches
)
1525 ;; Check that it is valid to insert DIRNAME with SWITCHES.
1526 ;; Signal an error if invalid (e.g. user typed `i' on `..').
1527 (or (dired-in-this-tree dirname
(expand-file-name default-directory
))
1528 (error "%s: not in this directory tree" dirname
))
1530 (let (case-fold-search)
1534 (or (eq (null (string-match x switches
))
1535 (null (string-match x dired-actual-switches
)))
1536 (error "Can't have dirs with and without -%s switches together"
1538 ;; all switches that make a difference to dired-get-filename:
1541 (defun dired-alist-add (dir new-marker
)
1542 ;; Add new DIR at NEW-MARKER. Sort alist.
1543 (dired-alist-add-1 dir new-marker
)
1546 (defun dired-alist-sort ()
1547 ;; Keep the alist sorted on buffer position.
1548 (setq dired-subdir-alist
1549 (sort dired-subdir-alist
1550 (function (lambda (elt1 elt2
)
1551 (> (dired-get-subdir-min elt1
)
1552 (dired-get-subdir-min elt2
)))))))
1554 (defun dired-kill-tree (dirname &optional remember-marks
)
1555 ;;"Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
1556 ;; With optional arg REMEMBER-MARKS, return an alist of marked files."
1557 (interactive "DKill tree below directory: ")
1558 (setq dirname
(expand-file-name dirname
))
1559 (let ((s-alist dired-subdir-alist
) dir m-alist
)
1561 (setq dir
(car (car s-alist
))
1562 s-alist
(cdr s-alist
))
1563 (if (and (not (string-equal dir dirname
))
1564 (dired-in-this-tree dir dirname
)
1565 (dired-goto-subdir dir
))
1566 (setq m-alist
(nconc (dired-kill-subdir remember-marks
) m-alist
))))
1569 (defun dired-insert-subdir-newpos (new-dir)
1570 ;; Find pos for new subdir, according to tree order.
1571 ;;(goto-char (point-max))
1572 (let ((alist dired-subdir-alist
) elt dir pos new-pos
)
1574 (setq elt
(car alist
)
1577 pos
(dired-get-subdir-min elt
))
1578 (if (dired-tree-lessp dir new-dir
)
1579 ;; Insert NEW-DIR after DIR
1580 (setq new-pos
(dired-get-subdir-max elt
)
1582 (goto-char new-pos
))
1583 ;; want a separating newline between subdirs
1589 (defun dired-insert-subdir-del (element)
1590 ;; Erase an already present subdir (given by ELEMENT) from buffer.
1591 ;; Move to that buffer position. Return a mark-alist.
1592 (let ((begin-marker (dired-get-subdir-min element
)))
1593 (goto-char begin-marker
)
1594 ;; Are at beginning of subdir (and inside it!). Now determine its end:
1595 (goto-char (dired-subdir-max))
1596 (or (eobp);; want a separating newline _between_ subdirs:
1599 (dired-remember-marks begin-marker
(point))
1600 (delete-region begin-marker
(point)))))
1602 (defun dired-insert-subdir-doinsert (dirname switches
)
1603 ;; Insert ls output after point and put point on the correct
1604 ;; position for the subdir alist.
1605 ;; Return the boundary of the inserted text (as list of BEG and END).
1606 (let ((begin (point)) end
)
1607 (message "Reading directory %s..." dirname
)
1608 (let ((dired-actual-switches
1610 (dired-replace-in-string "R" "" dired-actual-switches
))))
1611 (if (equal dirname
(car (car (reverse dired-subdir-alist
))))
1612 ;; top level directory may contain wildcards:
1613 (dired-readin-insert dired-directory
)
1614 (let ((opoint (point)))
1615 (insert-directory dirname dired-actual-switches nil t
)
1616 (dired-insert-set-properties opoint
(point)))))
1617 (message "Reading directory %s...done" dirname
)
1618 (setq end
(point-marker))
1619 (indent-rigidly begin end
2)
1620 ;; call dired-insert-headerline afterwards, as under VMS dired-ls
1621 ;; does insert the headerline itself and the insert function just
1623 ;; Need a marker for END as this inserts text.
1625 (dired-insert-headerline dirname
)
1626 ;; point is now like in dired-build-subdir-alist
1628 (list begin
(marker-position end
))
1629 (set-marker end nil
))))
1631 (defun dired-insert-subdir-doupdate (dirname elt beg-end
)
1632 ;; Point is at the correct subdir alist position for ELT,
1633 ;; BEG-END is the subdir-region (as list of begin and end).
1634 (if elt
; subdir was already present
1635 ;; update its position (should actually be unchanged)
1636 (set-marker (dired-get-subdir-min elt
) (point-marker))
1637 (dired-alist-add dirname
(point-marker)))
1638 ;; The hook may depend on the subdir-alist containing the just
1639 ;; inserted subdir, so run it after dired-alist-add:
1640 (if dired-after-readin-hook
1642 (let ((begin (nth 0 beg-end
))
1643 (end (nth 1 beg-end
)))
1646 (narrow-to-region begin end
)
1647 ;; hook may add or delete lines, but the subdir boundary
1649 (run-hooks 'dired-after-readin-hook
))))))
1651 (defun dired-tree-lessp (dir1 dir2
)
1652 ;; Lexicographic order on pathname components, like `ls -lR':
1653 ;; DIR1 < DIR2 iff DIR1 comes *before* DIR2 in an `ls -lR' listing,
1654 ;; i.e., iff DIR1 is a (grand)parent dir of DIR2,
1655 ;; or DIR1 and DIR2 are in the same parentdir and their last
1656 ;; components are string-lessp.
1657 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
1658 ;; string-lessp could arguably be replaced by file-newer-than-file-p
1659 ;; if dired-actual-switches contained `t'.
1660 (setq dir1
(file-name-as-directory dir1
)
1661 dir2
(file-name-as-directory dir2
))
1662 (let ((components-1 (dired-split "/" dir1
))
1663 (components-2 (dired-split "/" dir2
)))
1664 (while (and components-1
1666 (equal (car components-1
) (car components-2
)))
1667 (setq components-1
(cdr components-1
)
1668 components-2
(cdr components-2
)))
1669 (let ((c1 (car components-1
))
1670 (c2 (car components-2
)))
1673 (string-lessp c1 c2
))
1674 ((and (null c1
) (null c2
))
1675 nil
) ; they are equal, not lessp
1676 ((null c1
) ; c2 is a subdir of c1: c1<c2
1678 ((null c2
) ; c1 is a subdir of c2: c1>c2
1680 (t (error "This can't happen"))))))
1682 ;; There should be a builtin split function - inverse to mapconcat.
1683 (defun dired-split (pat str
&optional limit
)
1684 "Splitting on regexp PAT, turn string STR into a list of substrings.
1685 Optional third arg LIMIT (>= 1) is a limit to the length of the
1687 Thus, if SEP is a regexp that only matches itself,
1689 (mapconcat 'identity (dired-split SEP STRING) SEP)
1691 is always equal to STRING."
1692 (let* ((start (string-match pat str
))
1693 (result (list (substring str
0 start
)))
1695 (end (if start
(match-end 0))))
1696 (if end
; else nothing left
1697 (while (and (or (not (integerp limit
))
1699 (string-match pat str end
))
1700 (setq start
(match-beginning 0)
1702 result
(cons (substring str end start
) result
)
1706 (if (and (or (not (integerp limit
))
1708 end
) ; else nothing left
1710 (cons (substring str end
) result
)))
1713 ;;; moving by subdirectories
1716 (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip
)
1717 "Go to previous subdirectory, regardless of level.
1718 When called interactively and not on a subdir line, go to this subdir's line."
1721 (list (if current-prefix-arg
1722 (prefix-numeric-value current-prefix-arg
)
1723 ;; if on subdir start already, don't stay there!
1724 (if (dired-get-subdir) 1 0))))
1725 (dired-next-subdir (- arg
) no-error-if-not-found no-skip
))
1727 (defun dired-subdir-min ()
1729 (if (not (dired-prev-subdir 0 t t
))
1730 (error "Not in a subdir!")
1734 (defun dired-goto-subdir (dir)
1735 "Go to end of header line of DIR in this dired buffer.
1736 Return value of point on success, otherwise return nil.
1737 The next char is either \\n, or \\r if DIR is hidden."
1739 (prog1 ; let push-mark display its message
1740 (list (expand-file-name
1741 (completing-read "Goto in situ directory: " ; prompt
1742 dired-subdir-alist
; table
1745 (dired-current-directory))))
1747 (setq dir
(file-name-as-directory dir
))
1748 (let ((elt (assoc dir dired-subdir-alist
)))
1750 (goto-char (dired-get-subdir-min elt
))
1751 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
1752 ;; at either \r or \n after this function succeeds.
1753 (progn (skip-chars-forward "^\r\n")
1757 (defun dired-mark-subdir-files ()
1758 "Mark all files except `.' and `..'."
1760 (let ((p-min (dired-subdir-min)))
1761 (dired-mark-files-in-region p-min
(dired-subdir-max))))
1764 (defun dired-kill-subdir (&optional remember-marks
)
1765 "Remove all lines of current subdirectory.
1766 Lower levels are unaffected."
1767 ;; With optional REMEMBER-MARKS, return a mark-alist.
1769 (let ((beg (dired-subdir-min))
1770 (end (dired-subdir-max))
1771 buffer-read-only cur-dir
)
1772 (setq cur-dir
(dired-current-directory))
1773 (if (equal cur-dir default-directory
)
1774 (error "Attempt to kill top level directory"))
1776 (if remember-marks
(dired-remember-marks beg end
))
1777 (delete-region beg end
)
1778 (if (eobp) ; don't leave final blank line
1780 (dired-unsubdir cur-dir
))))
1782 (defun dired-unsubdir (dir)
1783 ;; Remove DIR from the alist
1784 (setq dired-subdir-alist
1785 (delq (assoc dir dired-subdir-alist
) dired-subdir-alist
)))
1788 (defun dired-tree-up (arg)
1789 "Go up ARG levels in the dired tree."
1791 (let ((dir (dired-current-directory)))
1794 dir
(file-name-directory (directory-file-name dir
))))
1795 ;;(setq dir (expand-file-name dir))
1796 (or (dired-goto-subdir dir
)
1797 (error "Cannot go up to %s - not in this tree." dir
))))
1800 (defun dired-tree-down ()
1801 "Go down in the dired tree."
1803 (let ((dir (dired-current-directory)) ; has slash
1804 pos case-fold-search
) ; filenames are case sensitive
1805 (let ((rest (reverse dired-subdir-alist
)) elt
)
1807 (setq elt
(car rest
)
1809 (if (dired-in-this-tree (directory-file-name (car elt
)) dir
)
1811 pos
(dired-goto-subdir (car elt
))))))
1814 (error "At the bottom"))))
1818 (defun dired-unhide-subdir ()
1819 (let (buffer-read-only)
1820 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?
\r ?
\n)))
1822 (defun dired-hide-check ()
1823 (or selective-display
1824 (error "selective-display must be t for subdir hiding to work!")))
1826 (defun dired-subdir-hidden-p (dir)
1827 (and selective-display
1829 (dired-goto-subdir dir
)
1830 (looking-at "\r"))))
1833 (defun dired-hide-subdir (arg)
1834 "Hide or unhide the current subdirectory and move to next directory.
1835 Optional prefix arg is a repeat factor.
1836 Use \\[dired-hide-all] to (un)hide all directories."
1839 (while (>= (setq arg
(1- arg
)) 0)
1840 (let* ((cur-dir (dired-current-directory))
1841 (hidden-p (dired-subdir-hidden-p cur-dir
))
1842 (elt (assoc cur-dir dired-subdir-alist
))
1843 (end-pos (1- (dired-get-subdir-max elt
)))
1845 ;; keep header line visible, hide rest
1846 (goto-char (dired-get-subdir-min elt
))
1847 (skip-chars-forward "^\n\r")
1849 (subst-char-in-region (point) end-pos ?
\r ?
\n)
1850 (subst-char-in-region (point) end-pos ?
\n ?
\r)))
1851 (dired-next-subdir 1 t
)))
1854 (defun dired-hide-all (arg)
1855 "Hide all subdirectories, leaving only their header lines.
1856 If there is already something hidden, make everything visible again.
1857 Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
1860 (let (buffer-read-only)
1862 (goto-char (point-min))
1863 (search-forward "\r" nil t
))
1864 ;; unhide - bombs on \r in filenames
1865 (subst-char-in-region (point-min) (point-max) ?
\r ?
\n)
1867 (let ((pos (point-max)) ; pos of end of last directory
1868 (alist dired-subdir-alist
))
1869 (while alist
; while there are dirs before pos
1870 (subst-char-in-region (dired-get-subdir-min (car alist
)) ; pos of prev dir
1872 (goto-char pos
) ; current dir
1873 ;; we're somewhere on current dir's line
1877 (setq pos
(dired-get-subdir-min (car alist
))) ; prev dir gets current dir
1878 (setq alist
(cdr alist
)))))))
1880 ;;;###end dired-ins.el
1883 ;; Functions for searching in tags style among marked files.
1886 (defun dired-do-search (regexp)
1887 "Search through all marked files for a match for REGEXP.
1888 Stops when a match is found.
1889 To continue searching for next match, use command \\[tags-loop-continue]."
1890 (interactive "sSearch marked files (regexp): ")
1891 (tags-search regexp
'(dired-get-marked-files)))
1894 (defun dired-do-query-replace (from to
&optional delimited
)
1895 "Do `query-replace-regexp' of FROM with TO, on all marked files.
1896 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
1897 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1898 with the command \\[tags-loop-continue]."
1900 "sQuery replace in marked files (regexp): \nsQuery replace %s by: \nP")
1901 (tags-query-replace from to delimited
'(dired-get-marked-files)))
1904 (provide 'dired-aux
)
1906 ;;; dired-aux.el ends here