Bug fix for vc-dispatcher split.
[bpt/emacs.git] / lisp / dired-aux.el
CommitLineData
f9acc7fb 1;;; dired-aux.el --- less commonly used parts of dired -*-byte-compile-dynamic: t;-*-
dd87891b 2
0d30b337 3;; Copyright (C) 1985, 1986, 1992, 1994, 1998, 2000, 2001, 2002, 2003,
409cc4a3 4;; 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
3a801d0c 5
2f14b48d 6;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.
0acdb863 7;; Maintainer: FSF
565132a3 8;; Keywords: files
e5167999 9
dd87891b
RS
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
b4aa6026 14;; the Free Software Foundation; either version 3, or (at your option)
dd87891b
RS
15;; any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
b578f267 23;; along with GNU Emacs; see the file COPYING. If not, write to the
086add15
LK
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA.
dd87891b 26
2f14b48d
ER
27;;; Commentary:
28
e41b2db1
ER
29;; The parts of dired mode not normally used. This is a space-saving hack
30;; to avoid having to load a large mode when all that's wanted are a few
31;; functions.
32
dd87891b
RS
33;; Rewritten in 1990/1991 to add tree features, file marking and
34;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
35;; Finished up by rms in 1992.
36
2f14b48d
ER
37;;; Code:
38
55d77548
RS
39;; We need macros in dired.el to compile properly,
40;; and we call subroutines in it too.
41(require 'dired)
6482fcac 42
c62a8073
RS
43(defvar dired-create-files-failures nil
44 "Variable where `dired-create-files' records failing file names.
45Functions that operate recursively can store additional names
46into this list; they also should call `dired-log' to log the errors.")
47
dd87891b
RS
48;;; 15K
49;;;###begin dired-cmd.el
50;; Diffing and compressing
51
edb8d73e
FP
52(defconst dired-star-subst-regexp "\\(^\\|[ \t]\\)\\*\\([ \t]\\|$\\)")
53(defconst dired-quark-subst-regexp "\\(^\\|[ \t]\\)\\?\\([ \t]\\|$\\)")
54
dd87891b
RS
55;;;###autoload
56(defun dired-diff (file &optional switches)
57 "Compare file at point with file FILE using `diff'.
a1af8dcf
EZ
58FILE defaults to the file at the mark. (That's the mark set by
59\\[set-mark-command], not by Dired's \\[dired-mark] command.)
fe5e3a2a
RS
60The prompted-for file is the first file given to `diff'.
61With prefix arg, prompt for second argument SWITCHES,
84bf6ad8 62which is options for `diff'."
dd87891b 63 (interactive
84bf6ad8
JL
64 (let ((current (dired-get-filename t))
65 (default (if (mark t)
0d370700 66 (save-excursion (goto-char (mark t))
dd87891b 67 (dired-get-filename t t)))))
84bf6ad8
JL
68 (if (or (equal default current)
69 (and (not (equal (dired-dwim-target-directory)
70 (dired-current-directory)))
71 (not mark-active)))
72 (setq default nil))
231596b2 73 (require 'diff)
5b76833f 74 (list (read-file-name (format "Diff %s with%s: "
84bf6ad8 75 current
dd87891b 76 (if default
5b76833f 77 (concat " (default " default ")")
dd87891b 78 ""))
4ae73f87
JL
79 (if default
80 (dired-current-directory)
81 (dired-dwim-target-directory))
82 default t)
fe5e3a2a
RS
83 (if current-prefix-arg
84 (read-string "Options for diff: "
85 (if (stringp diff-switches)
86 diff-switches
87 (mapconcat 'identity diff-switches " ")))))))
88 (diff file (dired-get-filename t) switches))
dd87891b
RS
89
90;;;###autoload
91(defun dired-backup-diff (&optional switches)
92 "Diff this file with its backup file or vice versa.
93Uses the latest backup, if there are several numerical backups.
94If this file is a backup, diff it with its original.
fe5e3a2a
RS
95The backup file is the first file given to `diff'.
96With prefix arg, prompt for argument SWITCHES which is options for `diff'."
97 (interactive
98 (if current-prefix-arg
99 (list (read-string "Options for diff: "
100 (if (stringp diff-switches)
101 diff-switches
102 (mapconcat 'identity diff-switches " "))))
103 nil))
104 (diff-backup (dired-get-filename) switches))
dd87891b 105
3659a2b8 106;;;###autoload
d1c553c8
RS
107(defun dired-compare-directories (dir2 predicate)
108 "Mark files with different file attributes in two dired buffers.
109Compare file attributes of files in the current directory
110with file attributes in directory DIR2 using PREDICATE on pairs of files
111with the same name. Mark files for which PREDICATE returns non-nil.
999bd52a 112Mark files with different names if PREDICATE is nil (or interactively
3659a2b8 113with empty input at the predicate prompt).
d1c553c8
RS
114
115PREDICATE is a Lisp expression that can refer to the following variables:
116
117 size1, size2 - file size in bytes
118 mtime1, mtime2 - last modification time in seconds, as a float
119 fa1, fa2 - list of file attributes
120 returned by function `file-attributes'
121
122 where 1 refers to attribute of file in the current dired buffer
123 and 2 to attribute of file in second dired buffer.
124
125Examples of PREDICATE:
126
127 (> mtime1 mtime2) - mark newer files
128 (not (= size1 size2)) - mark files with different sizes
129 (not (string= (nth 8 fa1) (nth 8 fa2))) - mark files with different modes
130 (not (and (= (nth 2 fa1) (nth 2 fa2)) - mark files with different UID
131 (= (nth 3 fa1) (nth 3 fa2)))) and GID."
132 (interactive
3659a2b8
JL
133 (list (read-directory-name (format "Compare %s with: "
134 (dired-current-directory))
135 (dired-dwim-target-directory)
136 (dired-dwim-target-directory))
999bd52a 137 (read-from-minibuffer "Mark if (lisp expr or RET): " nil nil t nil "nil")))
d1c553c8
RS
138 (let* ((dir1 (dired-current-directory))
139 (file-alist1 (dired-files-attributes dir1))
140 (file-alist2 (dired-files-attributes dir2))
5176af43
RS
141 file-list1 file-list2)
142 (setq file-alist1 (delq (assoc "." file-alist1) file-alist1))
143 (setq file-alist1 (delq (assoc ".." file-alist1) file-alist1))
144 (setq file-alist2 (delq (assoc "." file-alist2) file-alist2))
145 (setq file-alist2 (delq (assoc ".." file-alist2) file-alist2))
146 (setq file-list1 (mapcar
d1c553c8
RS
147 'cadr
148 (dired-file-set-difference
149 file-alist1 file-alist2
5176af43
RS
150 predicate))
151 file-list2 (mapcar
d1c553c8
RS
152 'cadr
153 (dired-file-set-difference
154 file-alist2 file-alist1
5176af43 155 predicate)))
d1c553c8
RS
156 (dired-fun-in-all-buffers
157 dir1 nil
158 (lambda ()
159 (dired-mark-if
160 (member (dired-get-filename nil t) file-list1) nil)))
161 (dired-fun-in-all-buffers
162 dir2 nil
163 (lambda ()
164 (dired-mark-if
165 (member (dired-get-filename nil t) file-list2) nil)))
166 (message "Marked in dir1: %s files, in dir2: %s files"
167 (length file-list1)
168 (length file-list2))))
169
170(defun dired-file-set-difference (list1 list2 predicate)
171 "Combine LIST1 and LIST2 using a set-difference operation.
172The result list contains all file items that appear in LIST1 but not LIST2.
173This is a non-destructive function; it makes a copy of the data if necessary
174to avoid corrupting the original LIST1 and LIST2.
175PREDICATE (see `dired-compare-directories') is an additional match
176condition. Two file items are considered to match if they are equal
177*and* PREDICATE evaluates to t."
178 (if (or (null list1) (null list2))
179 list1
180 (let (res)
181 (dolist (file1 list1)
182 (unless (let ((list list2))
183 (while (and list
184 (not (let* ((file2 (car list))
9375be01
JPW
185 (fa1 (car (cddr file1)))
186 (fa2 (car (cddr file2)))
d1c553c8
RS
187 (size1 (nth 7 fa1))
188 (size2 (nth 7 fa2))
189 (mtime1 (float-time (nth 5 fa1)))
190 (mtime2 (float-time (nth 5 fa2))))
191 (and
192 (equal (car file1) (car file2))
193 (not (eval predicate))))))
194 (setq list (cdr list)))
195 list)
196 (setq res (cons file1 res))))
197 (nreverse res))))
198
199(defun dired-files-attributes (dir)
200 "Return a list of all file names and attributes from DIR.
201List has a form of (file-name full-file-name (attribute-list))"
202 (mapcar
203 (lambda (file-name)
204 (let ((full-file-name (expand-file-name file-name dir)))
205 (list file-name
206 full-file-name
207 (file-attributes full-file-name))))
208 (directory-files dir)))
209\f
52f134ee
JL
210
211(defun dired-touch-initial (files)
212 "Create initial input value for `touch' command."
213 (let (initial)
214 (while files
215 (let ((current (nth 5 (file-attributes (car files)))))
216 (if (and initial (not (equal initial current)))
217 (setq initial (current-time) files nil)
218 (setq initial current))
219 (setq files (cdr files))))
220 (format-time-string "%Y%m%d%H%M.%S" initial)))
221
dd87891b 222(defun dired-do-chxxx (attribute-name program op-symbol arg)
3ccd3160 223 ;; Change file attributes (mode, group, owner, timestamp) of marked files and
dd87891b
RS
224 ;; refresh their file lines.
225 ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
226 ;; PROGRAM is the program used to change the attribute.
227 ;; OP-SYMBOL is the type of operation (for use in dired-mark-pop-up).
228 ;; ARG describes which files to use, as in dired-get-marked-files.
229 (let* ((files (dired-get-marked-files t arg))
230 (new-attribute
231 (dired-mark-read-string
232 (concat "Change " attribute-name " of %s to: ")
52f134ee
JL
233 (if (eq op-symbol 'touch) (dired-touch-initial files))
234 op-symbol arg files))
dd87891b
RS
235 (operation (concat program " " new-attribute))
236 failures)
237 (setq failures
238 (dired-bunch-files 10000
239 (function dired-check-process)
edb8d73e 240 (append
3ccd3160
JL
241 (list operation program)
242 (if (eq op-symbol 'touch)
243 '("-t") nil)
244 (list new-attribute)
05a455e2
RS
245 (if (string-match "gnu" system-configuration)
246 '("--") nil))
dd87891b
RS
247 files))
248 (dired-do-redisplay arg);; moves point if ARG is an integer
249 (if failures
250 (dired-log-summary
251 (format "%s: error" operation)
252 nil))))
253
254;;;###autoload
255(defun dired-do-chmod (&optional arg)
256 "Change the mode of the marked (or next ARG) files.
822b17d3 257Symbolic modes like `g+w' are allowed."
dd87891b 258 (interactive "P")
822b17d3
MC
259 (let* ((files (dired-get-marked-files t arg))
260 (modes (dired-mark-read-string
261 "Change mode of %s to: " nil
262 'chmod arg files))
263 (num-modes (if (string-match "^[0-7]+" modes)
264 (string-to-number modes 8))))
265 (dolist (file files)
266 (set-file-modes
267 file
268 (if num-modes num-modes
269 (file-modes-symbolic-to-number modes (file-modes file)))))
270 (dired-do-redisplay arg)))
dd87891b
RS
271
272;;;###autoload
273(defun dired-do-chgrp (&optional arg)
274 "Change the group of the marked (or next ARG) files."
275 (interactive "P")
a40dbafc 276 (if (memq system-type '(ms-dos windows-nt))
55535639 277 (error "chgrp not supported on this system"))
dd87891b
RS
278 (dired-do-chxxx "Group" "chgrp" 'chgrp arg))
279
280;;;###autoload
281(defun dired-do-chown (&optional arg)
282 "Change the owner of the marked (or next ARG) files."
283 (interactive "P")
a40dbafc 284 (if (memq system-type '(ms-dos windows-nt))
55535639 285 (error "chown not supported on this system"))
dd87891b
RS
286 (dired-do-chxxx "Owner" dired-chown-program 'chown arg))
287
05dcf18a 288;;;###autoload
3ccd3160
JL
289(defun dired-do-touch (&optional arg)
290 "Change the timestamp of the marked (or next ARG) files.
291This calls touch."
292 (interactive "P")
293 (dired-do-chxxx "Timestamp" dired-touch-program 'touch arg))
294
dd87891b
RS
295;; Process all the files in FILES in batches of a convenient size,
296;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).
297;; Batches are chosen to need less than MAX chars for the file names,
298;; allowing 3 extra characters of separator per file name.
299(defun dired-bunch-files (max function args files)
300 (let (pending
e5369aad 301 past
dd87891b
RS
302 (pending-length 0)
303 failures)
304 ;; Accumulate files as long as they fit in MAX chars,
305 ;; then process the ones accumulated so far.
306 (while files
307 (let* ((thisfile (car files))
308 (thislength (+ (length thisfile) 3))
309 (rest (cdr files)))
310 ;; If we have at least 1 pending file
311 ;; and this file won't fit in the length limit, process now.
312 (if (and pending (> (+ thislength pending-length) max))
e5369aad
RS
313 (setq pending (nreverse pending)
314 ;; The elements of PENDING are now in forward order.
315 ;; Do the operation and record failures.
316 failures (nconc (apply function (append args pending))
317 failures)
318 ;; Transfer the elemens of PENDING onto PAST
319 ;; and clear it out. Now PAST contains the first N files
320 ;; specified (for some N), and FILES contains the rest.
321 past (nconc past pending)
dd87891b
RS
322 pending nil
323 pending-length 0))
324 ;; Do (setq pending (cons thisfile pending))
325 ;; but reuse the cons that was in `files'.
326 (setcdr files pending)
327 (setq pending files)
328 (setq pending-length (+ thislength pending-length))
329 (setq files rest)))
e5369aad
RS
330 (setq pending (nreverse pending))
331 (prog1
332 (nconc (apply function (append args pending))
333 failures)
334 ;; Now the original list FILES has been put back as it was.
335 (nconc past pending))))
dd87891b
RS
336
337;;;###autoload
338(defun dired-do-print (&optional arg)
339 "Print the marked (or next ARG) files.
340Uses the shell command coming from variables `lpr-command' and
341`lpr-switches' as default."
342 (interactive "P")
343 (let* ((file-list (dired-get-marked-files t arg))
344 (command (dired-mark-read-string
345 "Print %s with: "
c572e732
RS
346 (mapconcat 'identity
347 (cons lpr-command
348 (if (stringp lpr-switches)
349 (list lpr-switches)
350 lpr-switches))
351 " ")
dd87891b
RS
352 'print arg file-list)))
353 (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))
354
355;; Read arguments for a marked-files command that wants a string
356;; that is not a file name,
357;; perhaps popping up the list of marked files.
358;; ARG is the prefix arg and indicates whether the files came from
359;; marks (ARG=nil) or a repeat factor (integerp ARG).
360;; If the current file was used, the list has but one element and ARG
361;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
362
363(defun dired-mark-read-string (prompt initial op-symbol arg files)
364 ;; PROMPT for a string, with INITIAL input.
365 ;; Other args are used to give user feedback and pop-up:
366 ;; OP-SYMBOL of command, prefix ARG, marked FILES.
367 (dired-mark-pop-up
368 nil op-symbol files
369 (function read-string)
370 (format prompt (dired-mark-prompt arg files)) initial))
83fadedf 371\f
2d051399
RS
372;;; Cleaning a directory: flagging some backups for deletion.
373
6482fcac
RS
374(defvar dired-file-version-alist)
375
05dcf18a 376;;;###autoload
2d051399
RS
377(defun dired-clean-directory (keep)
378 "Flag numerical backups for deletion.
379Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
380Positive prefix arg KEEP overrides `dired-kept-versions';
381Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
382
383To clear the flags on these files, you can use \\[dired-flag-backup-files]
384with a prefix argument."
385 (interactive "P")
386 (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
387 (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
388 (late-retention (if (<= keep 0) dired-kept-versions keep))
389 (dired-file-version-alist ()))
390 (message "Cleaning numerical backups (keeping %d late, %d old)..."
391 late-retention early-retention)
392 ;; Look at each file.
393 ;; If the file has numeric backup versions,
394 ;; put on dired-file-version-alist an element of the form
395 ;; (FILENAME . VERSION-NUMBER-LIST)
396 (dired-map-dired-file-lines (function dired-collect-file-versions))
397 ;; Sort each VERSION-NUMBER-LIST,
398 ;; and remove the versions not to be deleted.
399 (let ((fval dired-file-version-alist))
400 (while fval
401 (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
402 (v-count (length sorted-v-list)))
403 (if (> v-count (+ early-retention late-retention))
404 (rplacd (nthcdr early-retention sorted-v-list)
405 (nthcdr (- v-count late-retention)
406 sorted-v-list)))
407 (rplacd (car fval)
408 (cdr sorted-v-list)))
409 (setq fval (cdr fval))))
410 ;; Look at each file. If it is a numeric backup file,
411 ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
412 (dired-map-dired-file-lines (function dired-trample-file-versions))
413 (message "Cleaning numerical backups...done")))
414
415;;; Subroutines of dired-clean-directory.
416
417(defun dired-map-dired-file-lines (fun)
418 ;; Perform FUN with point at the end of each non-directory line.
57dabf6b 419 ;; FUN takes one argument, the absolute filename.
2d051399
RS
420 (save-excursion
421 (let (file buffer-read-only)
422 (goto-char (point-min))
423 (while (not (eobp))
424 (save-excursion
425 (and (not (looking-at dired-re-dir))
426 (not (eolp))
427 (setq file (dired-get-filename nil t)) ; nil on non-file
428 (progn (end-of-line)
429 (funcall fun file))))
430 (forward-line 1)))))
431
432(defun dired-collect-file-versions (fn)
61c6f873
RS
433 (let ((fn (file-name-sans-versions fn)))
434 ;; Only do work if this file is not already in the alist.
435 (if (assoc fn dired-file-version-alist)
436 nil
437 ;; If it looks like file FN has versions, return a list of the versions.
438 ;;That is a list of strings which are file names.
f9acc7fb 439 ;;The caller may want to flag some of these files for deletion.
61c6f873
RS
440 (let* ((base-versions
441 (concat (file-name-nondirectory fn) ".~"))
afbd0a53 442 (backup-extract-version-start (length base-versions))
61c6f873
RS
443 (possibilities (file-name-all-completions
444 base-versions
445 (file-name-directory fn)))
446 (versions (mapcar 'backup-extract-version possibilities)))
447 (if versions
448 (setq dired-file-version-alist
449 (cons (cons fn versions)
450 dired-file-version-alist)))))))
2d051399
RS
451
452(defun dired-trample-file-versions (fn)
453 (let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
454 base-version-list)
455 (and start-vn
456 (setq base-version-list ; there was a base version to which
457 (assoc (substring fn 0 start-vn) ; this looks like a
458 dired-file-version-alist)) ; subversion
027a4b6b 459 (not (memq (string-to-number (substring fn (+ 2 start-vn)))
2d051399
RS
460 base-version-list)) ; this one doesn't make the cut
461 (progn (beginning-of-line)
462 (delete-char 1)
463 (insert dired-del-marker)))))
83fadedf 464\f
dd87891b 465;;; Shell commands
dd87891b 466
905eb9ff
JL
467(declare-function mailcap-file-default-commands "mailcap" (files))
468
469(defun minibuffer-default-add-dired-shell-commands ()
470 "Return a list of all commands associted with current dired files.
471This function is used to add all related commands retieved by `mailcap'
472to the end of the list of defaults just after the default value."
473 (interactive)
474 (let ((commands (and (boundp 'files) (require 'mailcap nil t)
475 (mailcap-file-default-commands files))))
476 (if (listp minibuffer-default)
477 (append minibuffer-default commands)
478 (cons minibuffer-default commands))))
2f8a5963 479
1906dec4 480;; This is an extra function so that you can redefine it, e.g., to use gmhist.
dd87891b 481(defun dired-read-shell-command (prompt arg files)
905eb9ff 482 "Read a dired shell command prompting with PROMPT (using read-shell-command).
1906dec4
SM
483ARG is the prefix arg and may be used to indicate in the prompt which
484FILES are affected."
905eb9ff
JL
485 (minibuffer-with-setup-hook
486 (lambda ()
487 (set (make-local-variable 'minibuffer-default-add-function)
488 'minibuffer-default-add-dired-shell-commands))
489 (dired-mark-pop-up
490 nil 'shell files
491 #'read-shell-command
492 (format prompt (dired-mark-prompt arg files))
493 nil nil)))
dd87891b
RS
494
495;; The in-background argument is only needed in Emacs 18 where
496;; shell-command doesn't understand an appended ampersand `&'.
497;;;###autoload
01db6210 498(defun dired-do-shell-command (command &optional arg file-list)
6482fcac
RS
499 "Run a shell command COMMAND on the marked files.
500If no files are marked or a specific numeric prefix arg is given,
501the next ARG files are used. Just \\[universal-argument] means the current file.
502The prompt mentions the file(s) or the marker, as appropriate.
503
eab9ed67
RS
504If there is a `*' in COMMAND, surrounded by whitespace, this runs
505COMMAND just once with the entire file list substituted there.
6482fcac 506
eab9ed67
RS
507If there is no `*', but there is a `?' in COMMAND, surrounded by
508whitespace, this runs COMMAND on each file individually with the
509file name substituted for `?'.
dd87891b 510
eab9ed67
RS
511Otherwise, this runs COMMAND on each file individually with the
512file name added at the end of COMMAND (separated by a space).
d984dbc1 513
eab9ed67
RS
514`*' and `?' when not surrounded by whitespace have no special
515significance for `dired-do-shell-command', and are passed through
516normally to the shell, but you must confirm first. To pass `*' by
b544496d 517itself to the shell as a wildcard, type `*\"\"'.
dd87891b 518
eab9ed67
RS
519If COMMAND produces output, it goes to a separate buffer.
520
521This feature does not try to redisplay Dired buffers afterward, as
522there's no telling what files COMMAND may have changed.
523Type \\[dired-do-redisplay] to redisplay the marked files.
524
525When COMMAND runs, its working directory is the top-level directory of
526the Dired buffer, so output files usually are created there instead of
527in a subdir.
9e545350
KH
528
529In a noninteractive call (from Lisp code), you must specify
40c50be3
EZ
530the list of file names explicitly with the FILE-LIST argument, which
531can be produced by `dired-get-marked-files', for example."
dd87891b
RS
532;;Functions dired-run-shell-command and dired-shell-stuff-it do the
533;;actual work and can be redefined for customization.
01db6210
RS
534 (interactive
535 (let ((files (dired-get-marked-files t current-prefix-arg)))
536 (list
537 ;; Want to give feedback whether this file or marked files are used:
538 (dired-read-shell-command (concat "! on "
539 "%s: ")
540 current-prefix-arg
541 files)
542 current-prefix-arg
543 files)))
edb8d73e
FP
544 (let* ((on-each (not (string-match dired-star-subst-regexp command)))
545 (subst (not (string-match dired-quark-subst-regexp command)))
eab9ed67
RS
546 (star (not (string-match "\\*" command)))
547 (qmark (not (string-match "\\?" command))))
548 ;; Get confirmation for wildcards that may have been meant
549 ;; to control substitution of a file name or the file name list.
edb8d73e
FP
550 (if (cond ((not (or on-each subst))
551 (error "You can not combine `*' and `?' substitution marks"))
552 ((and star (not on-each))
eab9ed67
RS
553 (y-or-n-p "Confirm--do you mean to use `*' as a wildcard? "))
554 ((and qmark (not subst))
555 (y-or-n-p "Confirm--do you mean to use `?' as a wildcard? "))
556 (t))
557 (if on-each
558 (dired-bunch-files
559 (- 10000 (length command))
560 (function (lambda (&rest files)
561 (dired-run-shell-command
562 (dired-shell-stuff-it command files t arg))))
563 nil
564 file-list)
565 ;; execute the shell command
566 (dired-run-shell-command
567 (dired-shell-stuff-it command file-list nil arg))))))
dd87891b
RS
568
569;; Might use {,} for bash or csh:
570(defvar dired-mark-prefix ""
571 "Prepended to marked files in dired shell commands.")
572(defvar dired-mark-postfix ""
573 "Appended to marked files in dired shell commands.")
574(defvar dired-mark-separator " "
575 "Separates marked files in dired shell commands.")
576
577(defun dired-shell-stuff-it (command file-list on-each &optional raw-arg)
578;; "Make up a shell command line from COMMAND and FILE-LIST.
579;; If ON-EACH is t, COMMAND should be applied to each file, else
580;; simply concat all files and apply COMMAND to this.
581;; FILE-LIST's elements will be quoted for the shell."
582;; Might be redefined for smarter things and could then use RAW-ARG
583;; (coming from interactive P and currently ignored) to decide what to do.
584;; Smart would be a way to access basename or extension of file names.
dd87891b 585 (let ((stuff-it
edb8d73e
FP
586 (if (or (string-match dired-star-subst-regexp command)
587 (string-match dired-quark-subst-regexp command))
588 (lambda (x)
589 (let ((retval command))
590 (while (string-match
591 "\\(^\\|[ \t]\\)\\([*?]\\)\\([ \t]\\|$\\)" retval)
592 (setq retval (replace-match x t t retval 2)))
593 retval))
594 (lambda (x) (concat command dired-mark-separator x)))))
dd87891b 595 (if on-each
9a79e9ae 596 (mapconcat stuff-it (mapcar 'shell-quote-argument file-list) ";")
eab9ed67
RS
597 (let ((files (mapconcat 'shell-quote-argument
598 file-list dired-mark-separator)))
dd87891b 599 (if (> (length file-list) 1)
eab9ed67
RS
600 (setq files (concat dired-mark-prefix files dired-mark-postfix)))
601 (funcall stuff-it files)))))
dd87891b
RS
602
603;; This is an extra function so that it can be redefined by ange-ftp.
05dcf18a 604;;;###autoload
6482fcac 605(defun dired-run-shell-command (command)
95ffcc7f
DL
606 (let ((handler
607 (find-file-name-handler (directory-file-name default-directory)
608 'shell-command)))
609 (if handler (apply handler 'shell-command (list command))
610 (shell-command command)))
6482fcac
RS
611 ;; Return nil for sake of nconc in dired-bunch-files.
612 nil)
83fadedf 613\f
dd87891b
RS
614
615(defun dired-check-process (msg program &rest arguments)
616; "Display MSG while running PROGRAM, and check for output.
617;Remaining arguments are strings passed as command arguments to PROGRAM.
618; On error, insert output
619; in a log buffer and return the offending ARGUMENTS or PROGRAM.
620; Caller can cons up a list of failed args.
621;Else returns nil for success."
622 (let (err-buffer err (dir default-directory))
623 (message "%s..." msg)
624 (save-excursion
625 ;; Get a clean buffer for error output:
626 (setq err-buffer (get-buffer-create " *dired-check-process output*"))
627 (set-buffer err-buffer)
628 (erase-buffer)
629 (setq default-directory dir ; caller's default-directory
4a725859 630 err (not (eq 0 (apply 'process-file program nil t nil arguments))))
dd87891b
RS
631 (if err
632 (progn
633 (dired-log (concat program " " (prin1-to-string arguments) "\n"))
634 (dired-log err-buffer)
635 (or arguments program t))
636 (kill-buffer err-buffer)
637 (message "%s...done" msg)
638 nil))))
83fadedf 639\f
dd87891b
RS
640;; Commands that delete or redisplay part of the dired buffer.
641
dd87891b
RS
642(defun dired-kill-line (&optional arg)
643 (interactive "P")
644 (setq arg (prefix-numeric-value arg))
645 (let (buffer-read-only file)
646 (while (/= 0 arg)
647 (setq file (dired-get-filename nil t))
648 (if (not file)
55535639 649 (error "Can only kill file lines")
dd87891b
RS
650 (save-excursion (and file
651 (dired-goto-subdir file)
652 (dired-kill-subdir)))
653 (delete-region (progn (beginning-of-line) (point))
654 (progn (forward-line 1) (point)))
655 (if (> arg 0)
656 (setq arg (1- arg))
657 (setq arg (1+ arg))
658 (forward-line -1))))
659 (dired-move-to-filename)))
660
661;;;###autoload
662(defun dired-do-kill-lines (&optional arg fmt)
663 "Kill all marked lines (not the files).
6482fcac 664With a prefix argument, kill that many lines starting with the current line.
769d9ed6
LT
665\(A negative argument kills backward.)
666If you use this command with a prefix argument to kill the line
667for a file that is a directory, which you have inserted in the
668Dired buffer as a subdirectory, then it deletes that subdirectory
669from the buffer as well.
670To kill an entire subdirectory \(without killing its line in the
671parent directory), go to its directory header line and use this
672command with a prefix argument (the value does not matter)."
dd87891b
RS
673 ;; Returns count of killed lines. FMT="" suppresses message.
674 (interactive "P")
6482fcac
RS
675 (if arg
676 (if (dired-get-subdir)
677 (dired-kill-subdir)
678 (dired-kill-line arg))
679 (save-excursion
680 (goto-char (point-min))
769d9ed6
LT
681 (let (buffer-read-only
682 (count 0)
683 (regexp (dired-marker-regexp)))
684 (while (and (not (eobp))
685 (re-search-forward regexp nil t))
686 (setq count (1+ count))
687 (delete-region (progn (beginning-of-line) (point))
688 (progn (forward-line 1) (point))))
6482fcac
RS
689 (or (equal "" fmt)
690 (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
691 count))))
dd87891b
RS
692
693;;;###end dired-cmd.el
83fadedf 694\f
dd87891b
RS
695;;; 30K
696;;;###begin dired-cp.el
697
698(defun dired-compress ()
699 ;; Compress or uncompress the current file.
700 ;; Return nil for success, offending filename else.
701 (let* (buffer-read-only
bfe81e78
RS
702 (from-file (dired-get-filename))
703 (new-file (dired-compress-file from-file)))
704 (if new-file
53a05194
RS
705 (let ((start (point)))
706 ;; Remove any preexisting entry for the name NEW-FILE.
707 (condition-case nil
708 (dired-remove-entry new-file)
709 (error nil))
710 (goto-char start)
711 ;; Now replace the current line with an entry for NEW-FILE.
712 (dired-update-file-line new-file) nil)
bfe81e78
RS
713 (dired-log (concat "Failed to compress" from-file))
714 from-file)))
715
077d5283
RS
716(defvar dired-compress-file-suffixes
717 '(("\\.gz\\'" "" "gunzip")
718 ("\\.tgz\\'" ".tar" "gunzip")
719 ("\\.Z\\'" "" "uncompress")
720 ;; For .z, try gunzip. It might be an old gzip file,
721 ;; or it might be from compact? pack? (which?) but gunzip handles both.
722 ("\\.z\\'" "" "gunzip")
999bd52a
JL
723 ("\\.dz\\'" "" "dictunzip")
724 ("\\.tbz\\'" ".tar" "bunzip2")
2d938ce7 725 ("\\.bz2\\'" "" "bunzip2")
077d5283
RS
726 ;; This item controls naming for compression.
727 ("\\.tar\\'" ".tgz" nil))
728 "Control changes in file name suffixes for compression and uncompression.
729Each element specifies one transformation rule, and has the form:
730 (REGEXP NEW-SUFFIX PROGRAM)
731The rule applies when the old file name matches REGEXP.
732The new file name is computed by deleting the part that matches REGEXP
733 (as well as anything after that), then adding NEW-SUFFIX in its place.
734If PROGRAM is non-nil, the rule is an uncompression rule,
735and uncompression is done by running PROGRAM.
736Otherwise, the rule is a compression rule, and compression is done with gzip.")
737
d443f37c 738;;;###autoload
bfe81e78
RS
739(defun dired-compress-file (file)
740 ;; Compress or uncompress FILE.
741 ;; Return the name of the compressed or uncompressed file.
eb8c3be9 742 ;; Return nil if no change in files.
077d5283
RS
743 (let ((handler (find-file-name-handler file 'dired-compress-file))
744 suffix newname
745 (suffixes dired-compress-file-suffixes))
746 ;; See if any suffix rule matches this file name.
747 (while suffixes
748 (let (case-fold-search)
749 (if (string-match (car (car suffixes)) file)
750 (setq suffix (car suffixes) suffixes nil))
751 (setq suffixes (cdr suffixes))))
752 ;; If so, compute desired new name.
edb8d73e 753 (if suffix
077d5283
RS
754 (setq newname (concat (substring file 0 (match-beginning 0))
755 (nth 1 suffix))))
bfe81e78
RS
756 (cond (handler
757 (funcall handler 'dired-compress-file file))
758 ((file-symlink-p file)
759 nil)
077d5283
RS
760 ((and suffix (nth 2 suffix))
761 ;; We found an uncompression rule.
53a05194 762 (if (not (dired-check-process (concat "Uncompressing " file)
077d5283
RS
763 (nth 2 suffix) file))
764 newname))
dd87891b 765 (t
077d5283 766 ;;; We don't recognize the file as compressed, so compress it.
e251a1fd
RS
767 ;;; Try gzip; if we don't have that, use compress.
768 (condition-case nil
c8068734
CY
769 (let ((out-name (concat file ".gz")))
770 (and (or (not (file-exists-p out-name))
771 (y-or-n-p
772 (format "File %s already exists. Really compress? "
773 out-name)))
774 (not (dired-check-process (concat "Compressing " file)
775 "gzip" "-f" file))
776 (or (file-exists-p out-name)
777 (setq out-name (concat file ".z")))
778 ;; Rename the compressed file to NEWNAME
779 ;; if it hasn't got that name already.
780 (if (and newname (not (equal newname out-name)))
781 (progn
782 (rename-file out-name newname t)
783 newname)
784 out-name)))
e251a1fd
RS
785 (file-error
786 (if (not (dired-check-process (concat "Compressing " file)
787 "compress" "-f" file))
077d5283 788 ;; Don't use NEWNAME with `compress'.
e251a1fd 789 (concat file ".Z"))))))))
83fadedf 790\f
dd87891b
RS
791(defun dired-mark-confirm (op-symbol arg)
792 ;; Request confirmation from the user that the operation described
793 ;; by OP-SYMBOL is to be performed on the marked files.
794 ;; Confirmation consists in a y-or-n question with a file list
795 ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
796 ;; The files used are determined by ARG (as in dired-get-marked-files).
7baff557
SM
797 (or (eq dired-no-confirm t)
798 (memq op-symbol dired-no-confirm)
c232fd12
RS
799 ;; Pass t for DISTINGUISH-ONE-MARKED so that a single file which
800 ;; is marked pops up a window. That will help the user see
801 ;; it isn't the current line file.
802 (let ((files (dired-get-marked-files t arg nil t))
2de735de
RS
803 (string (if (eq op-symbol 'compress) "Compress or uncompress"
804 (capitalize (symbol-name op-symbol)))))
dd87891b 805 (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
2de735de 806 (concat string " "
dd87891b
RS
807 (dired-mark-prompt arg files) "? ")))))
808
809(defun dired-map-over-marks-check (fun arg op-symbol &optional show-progress)
810; "Map FUN over marked files (with second ARG like in dired-map-over-marks)
811; and display failures.
812
813; FUN takes zero args. It returns non-nil (the offending object, e.g.
814; the short form of the filename) for a failure and probably logs a
815; detailed error explanation using function `dired-log'.
816
817; OP-SYMBOL is a symbol describing the operation performed (e.g.
818; `compress'). It is used with `dired-mark-pop-up' to prompt the user
819; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
820; `Failed to compress 1 of 2 files - type W to see why ("foo")')
821
822; SHOW-PROGRESS if non-nil means redisplay dired after each file."
823 (if (dired-mark-confirm op-symbol arg)
824 (let* ((total-list;; all of FUN's return values
825 (dired-map-over-marks (funcall fun) arg show-progress))
826 (total (length total-list))
827 (failures (delq nil total-list))
2de735de
RS
828 (count (length failures))
829 (string (if (eq op-symbol 'compress) "Compress or uncompress"
830 (capitalize (symbol-name op-symbol)))))
dd87891b
RS
831 (if (not failures)
832 (message "%s: %d file%s."
2de735de 833 string total (dired-plural-s total))
dd87891b
RS
834 ;; end this bunch of errors:
835 (dired-log-summary
836 (format "Failed to %s %d of %d file%s"
2de735de 837 (downcase string) count total (dired-plural-s total))
dd87891b
RS
838 failures)))))
839
840(defvar dired-query-alist
841 '((?\y . y) (?\040 . y) ; `y' or SPC means accept once
842 (?n . n) (?\177 . n) ; `n' or DEL skips once
843 (?! . yes) ; `!' accepts rest
573743d2 844 (?q . no) (?\e . no) ; `q' or ESC skips rest
dd87891b
RS
845 ;; None of these keys quit - use C-g for that.
846 ))
847
05dcf18a 848;;;###autoload
dd87891b
RS
849(defun dired-query (qs-var qs-prompt &rest qs-args)
850 ;; Query user and return nil or t.
851 ;; Store answer in symbol VAR (which must initially be bound to nil).
852 ;; Format PROMPT with ARGS.
c3aef019 853 ;; Binding variable help-form will help the user who types the help key.
dd87891b
RS
854 (let* ((char (symbol-value qs-var))
855 (action (cdr (assoc char dired-query-alist))))
856 (cond ((eq 'yes action)
857 t) ; accept, and don't ask again
858 ((eq 'no action)
859 nil) ; skip, and don't ask again
860 (t;; no lasting effects from last time we asked - ask now
861 (let ((qprompt (concat qs-prompt
862 (if help-form
863 (format " [Type yn!q or %s] "
864 (key-description
865 (char-to-string help-char)))
866 " [Type y, n, q or !] ")))
867 result elt)
868 ;; Actually it looks nicer without cursor-in-echo-area - you can
869 ;; look at the dired buffer instead of at the prompt to decide.
870 (apply 'message qprompt qs-args)
871 (setq char (set qs-var (read-char)))
872 (while (not (setq elt (assoc char dired-query-alist)))
873 (message "Invalid char - type %c for help." help-char)
874 (ding)
875 (sit-for 1)
876 (apply 'message qprompt qs-args)
877 (setq char (set qs-var (read-char))))
de5544e8 878 ;; Display the question with the answer.
8a26c165 879 (message "%s" (concat (apply 'format qprompt qs-args)
de5544e8 880 (char-to-string char)))
dd87891b 881 (memq (cdr elt) '(t y yes)))))))
83fadedf 882\f
dd87891b
RS
883;;;###autoload
884(defun dired-do-compress (&optional arg)
885 "Compress or uncompress marked (or next ARG) files."
886 (interactive "P")
887 (dired-map-over-marks-check (function dired-compress) arg 'compress t))
888
889;; Commands for Emacs Lisp files - load and byte compile
890
891(defun dired-byte-compile ()
892 ;; Return nil for success, offending file name else.
893 (let* ((filename (dired-get-filename))
123ec94d 894 elc-file buffer-read-only failure)
dd87891b
RS
895 (condition-case err
896 (save-excursion (byte-compile-file filename))
897 (error
898 (setq failure err)))
123ec94d 899 (setq elc-file (byte-compile-dest-file filename))
d5b876ef
RS
900 (or (file-exists-p elc-file)
901 (setq failure t))
dd87891b
RS
902 (if failure
903 (progn
904 (dired-log "Byte compile error for %s:\n%s\n" filename failure)
905 (dired-make-relative filename))
906 (dired-remove-file elc-file)
907 (forward-line) ; insert .elc after its .el file
908 (dired-add-file elc-file)
909 nil)))
910
911;;;###autoload
912(defun dired-do-byte-compile (&optional arg)
913 "Byte compile marked (or next ARG) Emacs Lisp files."
914 (interactive "P")
915 (dired-map-over-marks-check (function dired-byte-compile) arg 'byte-compile t))
916
917(defun dired-load ()
918 ;; Return nil for success, offending file name else.
919 (let ((file (dired-get-filename)) failure)
920 (condition-case err
921 (load file nil nil t)
922 (error (setq failure err)))
923 (if (not failure)
924 nil
925 (dired-log "Load error for %s:\n%s\n" file failure)
926 (dired-make-relative file))))
927
928;;;###autoload
929(defun dired-do-load (&optional arg)
930 "Load the marked (or next ARG) Emacs Lisp files."
931 (interactive "P")
932 (dired-map-over-marks-check (function dired-load) arg 'load t))
933
934;;;###autoload
935(defun dired-do-redisplay (&optional arg test-for-subdir)
936 "Redisplay all marked (or next ARG) files.
937If on a subdir line, redisplay that subdirectory. In that case,
79d123ad
LT
938a prefix arg lets you edit the `ls' switches used for the new listing.
939
940Dired remembers switches specified with a prefix arg, so that reverting
941the buffer will not reset them. However, using `dired-undo' to re-insert
942or delete subdirectories can bypass this machinery. Hence, you sometimes
943may have to reset some subdirectory switches after a `dired-undo'.
944You can reset all subdirectory switches to the default using
fad9e9b4 945\\<dired-mode-map>\\[dired-reset-subdir-switches].
098c61f2 946See Info node `(emacs)Subdir switches' for more details."
dd87891b
RS
947 ;; Moves point if the next ARG files are redisplayed.
948 (interactive "P\np")
949 (if (and test-for-subdir (dired-get-subdir))
f2260f48
LT
950 (let* ((dir (dired-get-subdir))
951 (switches (cdr (assoc-string dir dired-switches-alist))))
952 (dired-insert-subdir
953 dir
954 (when arg
955 (read-string "Switches for listing: "
956 (or switches
957 dired-subdir-switches
958 dired-actual-switches)))))
dd87891b
RS
959 (message "Redisplaying...")
960 ;; message much faster than making dired-map-over-marks show progress
00aa3651
RS
961 (dired-uncache
962 (if (consp dired-directory) (car dired-directory) dired-directory))
dd87891b
RS
963 (dired-map-over-marks (let ((fname (dired-get-filename)))
964 (message "Redisplaying... %s" fname)
965 (dired-update-file-line fname))
966 arg)
967 (dired-move-to-filename)
968 (message "Redisplaying...done")))
79d123ad
LT
969
970(defun dired-reset-subdir-switches ()
971 "Set `dired-switches-alist' to nil and revert dired buffer."
972 (interactive)
973 (setq dired-switches-alist nil)
974 (revert-buffer))
83fadedf 975\f
dd87891b
RS
976(defun dired-update-file-line (file)
977 ;; Delete the current line, and insert an entry for FILE.
978 ;; If FILE is nil, then just delete the current line.
979 ;; Keeps any marks that may be present in column one (doing this
980 ;; here is faster than with dired-add-entry's optional arg).
981 ;; Does not update other dired buffers. Use dired-relist-entry for that.
982 (beginning-of-line)
6482fcac
RS
983 (let ((char (following-char)) (opoint (point))
984 (buffer-read-only))
dd87891b
RS
985 (delete-region (point) (progn (forward-line 1) (point)))
986 (if file
987 (progn
24193f35 988 (dired-add-entry file nil t)
dd87891b
RS
989 ;; Replace space by old marker without moving point.
990 ;; Faster than goto+insdel inside a save-excursion?
991 (subst-char-in-region opoint (1+ opoint) ?\040 char))))
992 (dired-move-to-filename))
993
d443f37c 994;;;###autoload
dd87891b
RS
995(defun dired-add-file (filename &optional marker-char)
996 (dired-fun-in-all-buffers
b2a59df0 997 (file-name-directory filename) (file-name-nondirectory filename)
dd87891b
RS
998 (function dired-add-entry) filename marker-char))
999
24193f35 1000(defun dired-add-entry (filename &optional marker-char relative)
dd87891b
RS
1001 ;; Add a new entry for FILENAME, optionally marking it
1002 ;; with MARKER-CHAR (a character, else dired-marker-char is used).
1003 ;; Note that this adds the entry `out of order' if files sorted by
1004 ;; time, etc.
1005 ;; At least this version inserts in the right subdirectory (if present).
1006 ;; And it skips "." or ".." (see `dired-trivial-filenames').
1007 ;; Hidden subdirs are exposed if a file is added there.
1008 (setq filename (directory-file-name filename))
1009 ;; Entry is always for files, even if they happen to also be directories
24193f35 1010 (let* ((opoint (point))
03679a46
GM
1011 (cur-dir (dired-current-directory))
1012 (orig-file-name filename)
1013 (directory (if relative cur-dir (file-name-directory filename)))
1014 reason)
24193f35
RS
1015 (setq filename
1016 (if relative
1017 (file-relative-name filename directory)
1018 (file-name-nondirectory filename))
dd87891b
RS
1019 reason
1020 (catch 'not-found
1021 (if (string= directory cur-dir)
1022 (progn
1023 (skip-chars-forward "^\r\n")
1024 (if (eq (following-char) ?\r)
1025 (dired-unhide-subdir))
1026 ;; We are already where we should be, except when
e5369aad 1027 ;; point is before the subdir line or its total line.
dd87891b
RS
1028 (let ((p (dired-after-subdir-garbage cur-dir)))
1029 (if (< (point) p)
1030 (goto-char p))))
1031 ;; else try to find correct place to insert
1032 (if (dired-goto-subdir directory)
03679a46
GM
1033 (progn ;; unhide if necessary
1034 (if (looking-at "\r") ;; point is at end of subdir line
dd87891b
RS
1035 (dired-unhide-subdir))
1036 ;; found - skip subdir and `total' line
1037 ;; and uninteresting files like . and ..
1038 ;; This better not moves into the next subdir!
1039 (dired-goto-next-nontrivial-file))
1040 ;; not found
1041 (throw 'not-found "Subdir not found")))
225feba2 1042 (let (buffer-read-only opoint)
dd87891b 1043 (beginning-of-line)
225feba2 1044 (setq opoint (point))
e5369aad 1045 ;; Don't expand `.'. Show just the file name within directory.
60e4eb54 1046 (let ((default-directory directory))
e5369aad
RS
1047 (dired-insert-directory directory
1048 (concat dired-actual-switches "d")
1049 (list filename)))
416f1c6f 1050 (goto-char opoint)
e5369aad
RS
1051 ;; Put in desired marker char.
1052 (when marker-char
1053 (let ((dired-marker-char
1054 (if (integerp marker-char) marker-char dired-marker-char)))
ac28c6ca 1055 (dired-mark nil)))
cb79b372
RS
1056 ;; Compensate for a bug in ange-ftp.
1057 ;; It inserts the file's absolute name, rather than
1058 ;; the relative one. That may be hard to fix since it
1059 ;; is probably controlled by something in ftp.
edb8d73e 1060 (goto-char opoint)
0c713b6f 1061 (let ((inserted-name (dired-get-filename 'verbatim)))
cb79b372 1062 (if (file-name-directory inserted-name)
e5369aad 1063 (let (props)
cb79b372 1064 (end-of-line)
e5369aad
RS
1065 (forward-char (- (length inserted-name)))
1066 (setq props (text-properties-at (point)))
1067 (delete-char (length inserted-name))
1068 (let ((pt (point)))
1069 (insert filename)
1070 (set-text-properties pt (point) props))
cb79b372
RS
1071 (forward-char 1))
1072 (forward-line 1)))
dd87891b 1073 (forward-line -1)
03679a46
GM
1074 (if dired-after-readin-hook ;; the subdir-alist is not affected...
1075 (save-excursion ;; ...so we can run it right now:
dd87891b
RS
1076 (save-restriction
1077 (beginning-of-line)
1078 (narrow-to-region (point) (save-excursion
1079 (forward-line 1) (point)))
1080 (run-hooks 'dired-after-readin-hook))))
1081 (dired-move-to-filename))
1082 ;; return nil if all went well
1083 nil))
03679a46 1084 (if reason ; don't move away on failure
dd87891b 1085 (goto-char opoint))
03679a46 1086 (not reason))) ; return t on success, nil else
dd87891b 1087
dd87891b
RS
1088(defun dired-after-subdir-garbage (dir)
1089 ;; Return pos of first file line of DIR, skipping header and total
1090 ;; or wildcard lines.
1091 ;; Important: never moves into the next subdir.
1092 ;; DIR is assumed to be unhidden.
1093 ;; Will probably be redefined for VMS etc.
1094 (save-excursion
1095 (or (dired-goto-subdir dir) (error "This cannot happen"))
1096 (forward-line 1)
1097 (while (and (not (eolp)) ; don't cross subdir boundary
1098 (not (dired-move-to-filename)))
1099 (forward-line 1))
1100 (point)))
1101
d443f37c 1102;;;###autoload
dd87891b
RS
1103(defun dired-remove-file (file)
1104 (dired-fun-in-all-buffers
b2a59df0
RS
1105 (file-name-directory file) (file-name-nondirectory file)
1106 (function dired-remove-entry) file))
dd87891b
RS
1107
1108(defun dired-remove-entry (file)
1109 (save-excursion
1110 (and (dired-goto-file file)
1111 (let (buffer-read-only)
1112 (delete-region (progn (beginning-of-line) (point))
1113 (save-excursion (forward-line 1) (point)))))))
1114
d443f37c 1115;;;###autoload
dd87891b 1116(defun dired-relist-file (file)
e5369aad 1117 "Create or update the line for FILE in all Dired buffers it would belong in."
dd87891b 1118 (dired-fun-in-all-buffers (file-name-directory file)
b2a59df0 1119 (file-name-nondirectory file)
dd87891b
RS
1120 (function dired-relist-entry) file))
1121
1122(defun dired-relist-entry (file)
1123 ;; Relist the line for FILE, or just add it if it did not exist.
57dabf6b 1124 ;; FILE must be an absolute file name.
dd87891b
RS
1125 (let (buffer-read-only marker)
1126 ;; If cursor is already on FILE's line delete-region will cause
1127 ;; save-excursion to fail because of floating makers,
1128 ;; moving point to beginning of line. Sigh.
1129 (save-excursion
1130 (and (dired-goto-file file)
1131 (delete-region (progn (beginning-of-line)
1132 (setq marker (following-char))
1133 (point))
1134 (save-excursion (forward-line 1) (point))))
1135 (setq file (directory-file-name file))
1136 (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
83fadedf 1137\f
dd87891b
RS
1138;;; Copy, move/rename, making hard and symbolic links
1139
91a7e829 1140(defcustom dired-backup-overwrite nil
dd87891b 1141 "*Non-nil if Dired should ask about making backups before overwriting files.
91a7e829
RS
1142Special value `always' suppresses confirmation."
1143 :type '(choice (const :tag "off" nil)
1144 (const :tag "suppress" always)
a9e9b8fa 1145 (other :tag "ask" t))
91a7e829 1146 :group 'dired)
dd87891b 1147
bf0de14d
CY
1148;; This is a fluid var used in dired-handle-overwrite. It should be
1149;; let-bound whenever dired-copy-file etc are called. See
1150;; dired-create-files for an example.
1151(defvar dired-overwrite-confirmed)
6482fcac 1152
dd87891b 1153(defun dired-handle-overwrite (to)
e5369aad 1154 ;; Save old version of file TO that is to be overwritten.
6482fcac 1155 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
dd87891b 1156 ;; from dired-create-files.
d63a6ae0 1157 (let (backup)
bbfe2308
CY
1158 (when (and dired-backup-overwrite
1159 dired-overwrite-confirmed
1160 (setq backup (car (find-backup-file-name to)))
1161 (or (eq 'always dired-backup-overwrite)
1162 (dired-query 'overwrite-backup-query
1163 "Make backup for existing file `%s'? "
1164 to)))
1165 (rename-file to backup 0) ; confirm overwrite of old backup
1166 (dired-relist-entry backup))))
dd87891b 1167
d443f37c 1168;;;###autoload
dd87891b
RS
1169(defun dired-copy-file (from to ok-flag)
1170 (dired-handle-overwrite to)
c62a8073
RS
1171 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1172 dired-recursive-copies))
dd87891b 1173
8e845e23
JB
1174(declare-function make-symbolic-link "fileio.c")
1175
ba1acd68
RS
1176(defun dired-copy-file-recursive (from to ok-flag &optional
1177 preserve-time top recursive)
c62a8073
RS
1178 (let ((attrs (file-attributes from))
1179 dirfailed)
3b68c506
RS
1180 (if (and recursive
1181 (eq t (car attrs))
1182 (or (eq recursive 'always)
ce5a3ac0 1183 (yes-or-no-p (format "Recursive copies of %s? " from))))
3b68c506 1184 ;; This is a directory.
89242dda
JB
1185 (let ((mode (file-modes from))
1186 (files
c62a8073
RS
1187 (condition-case err
1188 (directory-files from nil dired-re-no-dot)
1189 (file-error
1190 (push (dired-make-relative from)
1191 dired-create-files-failures)
1192 (dired-log "Copying error for %s:\n%s\n" from err)
1193 (setq dirfailed t)
1194 nil))))
3b68c506 1195 (if (eq recursive 'top) (setq recursive 'always)) ; Don't ask any more.
c62a8073
RS
1196 (unless dirfailed
1197 (if (file-exists-p to)
1198 (or top (dired-handle-overwrite to))
1199 (condition-case err
89242dda
JB
1200 (progn
1201 (make-directory to)
1202 (set-file-modes to #o700))
c62a8073
RS
1203 (file-error
1204 (push (dired-make-relative from)
1205 dired-create-files-failures)
1206 (setq files nil)
1207 (dired-log "Copying error for %s:\n%s\n" from err)))))
7a547817
RS
1208 (dolist (file files)
1209 (let ((thisfrom (expand-file-name file from))
1210 (thisto (expand-file-name file to)))
1211 ;; Catch errors copying within a directory,
1212 ;; and report them through the dired log mechanism
1213 ;; just as our caller will do for the top level files.
1214 (condition-case err
1215 (dired-copy-file-recursive
1216 thisfrom thisto
1217 ok-flag preserve-time nil recursive)
1218 (file-error
1219 (push (dired-make-relative thisfrom)
1220 dired-create-files-failures)
89242dda
JB
1221 (dired-log "Copying error for %s:\n%s\n" thisfrom err)))))
1222 (when (file-directory-p to)
1223 (set-file-modes to mode)))
3b68c506
RS
1224 ;; Not a directory.
1225 (or top (dired-handle-overwrite to))
c62a8073
RS
1226 (condition-case err
1227 (if (stringp (car attrs))
1228 ;; It is a symlink
1229 (make-symbolic-link (car attrs) to ok-flag)
1230 (copy-file from to ok-flag dired-copy-preserve-time))
4a725859 1231 (file-date-error
c62a8073
RS
1232 (push (dired-make-relative from)
1233 dired-create-files-failures)
7a547817 1234 (dired-log "Can't set date on %s:\n%s\n" from err))))))
ba1acd68 1235
d443f37c 1236;;;###autoload
e5369aad
RS
1237(defun dired-rename-file (file newname ok-if-already-exists)
1238 (dired-handle-overwrite newname)
1239 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
dd87891b 1240 ;; Silently rename the visited file of any buffer visiting this file.
e5369aad
RS
1241 (and (get-file-buffer file)
1242 (with-current-buffer (get-file-buffer file)
1243 (set-visited-file-name newname nil t)))
1244 (dired-remove-file file)
dd87891b 1245 ;; See if it's an inserted subdir, and rename that, too.
e5369aad 1246 (dired-rename-subdir file newname))
dd87891b
RS
1247
1248(defun dired-rename-subdir (from-dir to-dir)
1249 (setq from-dir (file-name-as-directory from-dir)
1250 to-dir (file-name-as-directory to-dir))
b2a59df0 1251 (dired-fun-in-all-buffers from-dir nil
dd87891b
RS
1252 (function dired-rename-subdir-1) from-dir to-dir)
1253 ;; Update visited file name of all affected buffers
9df38cef
RS
1254 (let ((expanded-from-dir (expand-file-name from-dir))
1255 (blist (buffer-list)))
dd87891b
RS
1256 (while blist
1257 (save-excursion
9df38cef 1258 (set-buffer (car blist))
dd87891b 1259 (if (and buffer-file-name
9df38cef 1260 (dired-in-this-tree buffer-file-name expanded-from-dir))
dd87891b 1261 (let ((modflag (buffer-modified-p))
83fadedf 1262 (to-file (dired-replace-in-string
dd87891b
RS
1263 (concat "^" (regexp-quote from-dir))
1264 to-dir
1265 buffer-file-name)))
1266 (set-visited-file-name to-file)
1267 (set-buffer-modified-p modflag))))
1268 (setq blist (cdr blist)))))
1269
1270(defun dired-rename-subdir-1 (dir to)
1271 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1272 ;; one of its subdirectories is expanded in this buffer.
9df38cef
RS
1273 (let ((expanded-dir (expand-file-name dir))
1274 (alist dired-subdir-alist)
dd87891b
RS
1275 (elt nil))
1276 (while alist
1277 (setq elt (car alist)
1278 alist (cdr alist))
9df38cef 1279 (if (dired-in-this-tree (car elt) expanded-dir)
dd87891b
RS
1280 ;; ELT's subdir is affected by the rename
1281 (dired-rename-subdir-2 elt dir to)))
1282 (if (equal dir default-directory)
1283 ;; if top level directory was renamed, lots of things have to be
1284 ;; updated:
1285 (progn
1286 (dired-unadvertise dir) ; we no longer dired DIR...
1287 (setq default-directory to
1288 dired-directory (expand-file-name;; this is correct
1289 ;; with and without wildcards
1290 (file-name-nondirectory dired-directory)
1291 to))
1292 (let ((new-name (file-name-nondirectory
1293 (directory-file-name dired-directory))))
1294 ;; try to rename buffer, but just leave old name if new
1295 ;; name would already exist (don't try appending "<%d>")
1296 (or (get-buffer new-name)
1297 (rename-buffer new-name)))
1298 ;; ... we dired TO now:
1299 (dired-advertise)))))
1300
1301(defun dired-rename-subdir-2 (elt dir to)
f2260f48
LT
1302 ;; Update the headerline and dired-subdir-alist element, as well as
1303 ;; dired-switches-alist element, of directory described by
1304 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1305 ;; describes either DIR itself or a subdir of DIR.
dd87891b
RS
1306 (save-excursion
1307 (let ((regexp (regexp-quote (directory-file-name dir)))
1308 (newtext (directory-file-name to))
1309 buffer-read-only)
1310 (goto-char (dired-get-subdir-min elt))
1311 ;; Update subdir headerline in buffer
1312 (if (not (looking-at dired-subdir-regexp))
1313 (error "%s not found where expected - dired-subdir-alist broken?"
1314 dir)
1315 (goto-char (match-beginning 1))
1316 (if (re-search-forward regexp (match-end 1) t)
1317 (replace-match newtext t t)
1318 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
f2260f48
LT
1319 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1320 (let ((cons (assoc-string (car elt) dired-switches-alist))
1321 (cur-dir (dired-normalize-subdir
1322 (dired-replace-in-string regexp newtext (car elt)))))
1323 (setcar elt cur-dir)
1324 (when cons (setcar cons cur-dir))))))
83fadedf 1325\f
dd87891b
RS
1326;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1327(defun dired-create-files (file-creator operation fn-list name-constructor
1328 &optional marker-char)
1329
1330;; Create a new file for each from a list of existing files. The user
1331;; is queried, dired buffers are updated, and at the end a success or
1332;; failure message is displayed
1333
1334;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
1335
1336;; It is called for each file and must create newfile, the entry of
1337;; which will be added. The user will be queried if the file already
1338;; exists. If oldfile is removed by FILE-CREATOR (i.e, it is a
1339;; rename), it is FILE-CREATOR's responsibility to update dired
a7acbbe4 1340;; buffers. FILE-CREATOR must abort by signaling a file-error if it
dd87891b
RS
1341;; could not create newfile. The error is caught and logged.
1342
1343;; OPERATION (a capitalized string, e.g. `Copy') describes the
1344;; operation performed. It is used for error logging.
1345
57dabf6b 1346;; FN-LIST is the list of files to copy (full absolute file names).
dd87891b
RS
1347
1348;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
1349;; skip. If it skips files for other reasons than a direct user
1350;; query, it is supposed to tell why (using dired-log).
1351
1352;; Optional MARKER-CHAR is a character with which to mark every
1353;; newfile's entry, or t to use the current marker character if the
1354;; oldfile was marked.
1355
c62a8073
RS
1356 (let (dired-create-files-failures failures
1357 skipped (success-count 0) (total (length fn-list)))
dd87891b
RS
1358 (let (to overwrite-query
1359 overwrite-backup-query) ; for dired-handle-overwrite
04509548
SM
1360 (dolist (from fn-list)
1361 (setq to (funcall name-constructor from))
1362 (if (equal to from)
1363 (progn
1364 (setq to nil)
1365 (dired-log "Cannot %s to same file: %s\n"
1366 (downcase operation) from)))
1367 (if (not to)
1368 (setq skipped (cons (dired-make-relative from) skipped))
1369 (let* ((overwrite (file-exists-p to))
1370 (dired-overwrite-confirmed ; for dired-handle-overwrite
1371 (and overwrite
1372 (let ((help-form '(format "\
dd87891b
RS
1373Type SPC or `y' to overwrite file `%s',
1374DEL or `n' to skip to next,
1375ESC or `q' to not overwrite any of the remaining files,
1376`!' to overwrite all remaining files with no more questions." to)))
04509548
SM
1377 (dired-query 'overwrite-query
1378 "Overwrite `%s'?" to))))
1379 ;; must determine if FROM is marked before file-creator
1380 ;; gets a chance to delete it (in case of a move).
1381 (actual-marker-char
1382 (cond ((integerp marker-char) marker-char)
1383 (marker-char (dired-file-marker from)) ; slow
1384 (t nil))))
1385 (condition-case err
1386 (progn
1387 (funcall file-creator from to dired-overwrite-confirmed)
1388 (if overwrite
1389 ;; If we get here, file-creator hasn't been aborted
1390 ;; and the old entry (if any) has to be deleted
1391 ;; before adding the new entry.
1392 (dired-remove-file to))
1393 (setq success-count (1+ success-count))
1394 (message "%s: %d of %d" operation success-count total)
1395 (dired-add-file to actual-marker-char))
1396 (file-error ; FILE-CREATOR aborted
1397 (progn
1398 (push (dired-make-relative from)
1399 failures)
1400 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1401 operation from to err))))))))
dd87891b 1402 (cond
c62a8073
RS
1403 (dired-create-files-failures
1404 (setq failures (nconc failures dired-create-files-failures))
1405 (dired-log-summary
1406 (format "%s failed for %d file%s in %d requests"
1407 operation (length failures)
1408 (dired-plural-s (length failures))
1409 total)
1410 failures))
dd87891b
RS
1411 (failures
1412 (dired-log-summary
1413 (format "%s failed for %d of %d file%s"
c62a8073
RS
1414 operation (length failures)
1415 total (dired-plural-s total))
dd87891b
RS
1416 failures))
1417 (skipped
1418 (dired-log-summary
1419 (format "%s: %d of %d file%s skipped"
1420 operation (length skipped) total
1421 (dired-plural-s total))
1422 skipped))
1423 (t
1424 (message "%s: %s file%s"
1425 operation success-count (dired-plural-s success-count)))))
1426 (dired-move-to-filename))
83fadedf 1427\f
dd87891b 1428(defun dired-do-create-files (op-symbol file-creator operation arg
616e14f4
SM
1429 &optional marker-char op1
1430 how-to)
1431 "Create a new file for each marked file.
1432Prompts user for target, which is a directory in which to create
1433 the new files. Target may be a plain file if only one marked
dcaf31d3
EZ
1434 file exists. The way the default for the target directory is
1435 computed depends on the value of `dired-dwim-target-directory'.
616e14f4
SM
1436OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1437 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1438FILE-CREATOR and OPERATION as in `dired-create-files'.
1439ARG as in `dired-get-marked-files'.
1440Optional arg MARKER-CHAR as in `dired-create-files'.
1441Optional arg OP1 is an alternate form for OPERATION if there is
1442 only one file.
1443Optional arg HOW-TO is used to set the value of the into-dir variable
1444 which determines how to treat target.
1445 If into-dir is set to nil then target is not regarded as a directory,
1446 there must be exactly one marked file, else error.
1447 Else if into-dir is set to a list, then target is a generalized
1448 directory (e.g. some sort of archive). The first element of into-dir
1449 must be a function with at least four arguments:
1450 operation as OPERATION above.
1451 rfn-list a list of the relative names for the marked files.
1452 fn-list a list of the absolute names for the marked files.
1453 target.
1454 The rest of into-dir are optional arguments.
1455 Else into-dir is not a list. Target is a directory.
1456 The marked file(s) are created inside the target directory.
1457
1458 If HOW-TO is not given (or nil), then into-dir is set to true if
1459 target is a directory and otherwise to nil.
1460 Else if HOW-TO is t, then into-dir is set to nil.
1461 Else HOW-TO is assumed to be a function of one argument, target,
1462 that looks at target and returns a value for the into-dir
1463 variable. The function `dired-into-dir-with-symlinks' is provided
1464 for the case (common when creating symlinks) that symbolic
1465 links to directories are not to be considered as directories
1466 (as `file-directory-p' would if HOW-TO had been nil)."
dd87891b
RS
1467 (or op1 (setq op1 operation))
1468 (let* ((fn-list (dired-get-marked-files nil arg))
ba1acd68
RS
1469 (rfn-list (mapcar (function dired-make-relative) fn-list))
1470 (dired-one-file ; fluid variable inside dired-create-files
1471 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
75ab0c79
GM
1472 (target-dir (dired-dwim-target-directory))
1473 (default (and dired-one-file
1474 (expand-file-name (file-name-nondirectory (car fn-list))
1475 target-dir)))
ba1acd68 1476 (target (expand-file-name ; fluid variable inside dired-create-files
dd87891b 1477 (dired-mark-read-file-name
ba1acd68 1478 (concat (if dired-one-file op1 operation) " %s to: ")
75ab0c79 1479 target-dir op-symbol arg rfn-list default)))
325fec3c
EZ
1480 (into-dir (cond ((null how-to)
1481 ;; Allow DOS/Windows users to change the letter
1482 ;; case of a directory. If we don't test these
1483 ;; conditions up front, file-directory-p below
1484 ;; will return t because the filesystem is
1485 ;; case-insensitive, and Emacs will try to move
1486 ;; foo -> foo/foo, which fails.
c60ee5e7 1487 (if (and (memq system-type '(ms-dos windows-nt cygwin))
325fec3c
EZ
1488 (eq op-symbol 'move)
1489 dired-one-file
1490 (string= (downcase
1491 (expand-file-name (car fn-list)))
1492 (downcase
1493 (expand-file-name target)))
1494 (not (string=
1495 (file-name-nondirectory (car fn-list))
1496 (file-name-nondirectory target))))
1497 nil
1498 (file-directory-p target)))
dd87891b
RS
1499 ((eq how-to t) nil)
1500 (t (funcall how-to target)))))
ba1acd68
RS
1501 (if (and (consp into-dir) (functionp (car into-dir)))
1502 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1503 (if (not (or dired-one-file into-dir))
1504 (error "Marked %s: target must be a directory: %s" operation target))
1505 ;; rename-file bombs when moving directories unless we do this:
1506 (or into-dir (setq target (directory-file-name target)))
1507 (dired-create-files
1508 file-creator operation fn-list
1509 (if into-dir ; target is a directory
1510 ;; This function uses fluid variable target when called
1511 ;; inside dired-create-files:
1512 (function
1513 (lambda (from)
1514 (expand-file-name (file-name-nondirectory from) target)))
1515 (function (lambda (from) target)))
1516 marker-char))))
dd87891b
RS
1517
1518;; Read arguments for a marked-files command that wants a file name,
1519;; perhaps popping up the list of marked files.
1520;; ARG is the prefix arg and indicates whether the files came from
1521;; marks (ARG=nil) or a repeat factor (integerp ARG).
1522;; If the current file was used, the list has but one element and ARG
1523;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
64666d2d
MB
1524;; DEFAULT is the default value to return if the user just hits RET;
1525;; if it is omitted or nil, then the name of the directory is used.
dd87891b 1526
64666d2d
MB
1527(defun dired-mark-read-file-name (prompt dir op-symbol arg files
1528 &optional default)
dd87891b
RS
1529 (dired-mark-pop-up
1530 nil op-symbol files
1531 (function read-file-name)
64666d2d 1532 (format prompt (dired-mark-prompt arg files)) dir default))
dd87891b
RS
1533
1534(defun dired-dwim-target-directory ()
1535 ;; Try to guess which target directory the user may want.
1536 ;; If there is a dired buffer displayed in the next window, use
1537 ;; its current subdir, else use current subdir of this dired buffer.
1538 (let ((this-dir (and (eq major-mode 'dired-mode)
1539 (dired-current-directory))))
1540 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1541 (if dired-dwim-target
1542 (let* ((other-buf (window-buffer (next-window)))
1543 (other-dir (save-excursion
1544 (set-buffer other-buf)
1545 (and (eq major-mode 'dired-mode)
1546 (dired-current-directory)))))
1547 (or other-dir this-dir))
1548 this-dir)))
83fadedf 1549\f
dd87891b
RS
1550;;;###autoload
1551(defun dired-create-directory (directory)
1552 "Create a directory called DIRECTORY."
1553 (interactive
1554 (list (read-file-name "Create directory: " (dired-current-directory))))
934b4968
JL
1555 (let* ((expanded (directory-file-name (expand-file-name directory)))
1556 (try expanded) new)
1557 ;; Find the topmost nonexistent parent dir (variable `new')
1558 (while (and try (not (file-exists-p try)) (not (equal new try)))
1559 (setq new try
1560 try (directory-file-name (file-name-directory try))))
1561 (make-directory expanded t)
1562 (when new
1563 (dired-add-file new)
1564 (dired-move-to-filename))))
dd87891b
RS
1565
1566(defun dired-into-dir-with-symlinks (target)
1567 (and (file-directory-p target)
1568 (not (file-symlink-p target))))
1569;; This may not always be what you want, especially if target is your
1570;; home directory and it happens to be a symbolic link, as is often the
1571;; case with NFS and automounters. Or if you want to make symlinks
1572;; into directories that themselves are only symlinks, also quite
1573;; common.
1574
1575;; So we don't use this function as value for HOW-TO in
1576;; dired-do-symlink, which has the minor disadvantage of
1577;; making links *into* a symlinked-dir, when you really wanted to
1578;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1579;; just have to remove that symlink by hand before making your marked
1580;; symlinks.
1581
ba1acd68 1582(defvar dired-copy-how-to-fn nil
0ff9b955 1583 "nil or a function used by `dired-do-copy' to determine target.
ba1acd68
RS
1584See HOW-TO argument for `dired-do-create-files'.")
1585
dd87891b
RS
1586;;;###autoload
1587(defun dired-do-copy (&optional arg)
1588 "Copy all marked (or next ARG) files, or copy the current file.
1589This normally preserves the last-modified date when copying.
1590When operating on just the current file, you specify the new name.
b5458fc2
RS
1591When operating on multiple or marked files, you specify a directory,
1592and new copies of these files are made in that directory
dcaf31d3
EZ
1593with the same names that the files currently have. The default
1594suggested for the target directory depends on the value of
ec9581d5
RS
1595`dired-dwim-target', which see.
1596
1597This command copies symbolic links by creating new ones,
1598like `cp -d'."
dd87891b 1599 (interactive "P")
ea185644 1600 (let ((dired-recursive-copies dired-recursive-copies))
ba1acd68 1601 (dired-do-create-files 'copy (function dired-copy-file)
de97d5e8 1602 "Copy"
ea185644
GM
1603 arg dired-keep-marker-copy
1604 nil dired-copy-how-to-fn)))
dd87891b
RS
1605
1606;;;###autoload
1607(defun dired-do-symlink (&optional arg)
1608 "Make symbolic links to current file or all marked (or next ARG) files.
1609When operating on just the current file, you specify the new name.
1610When operating on multiple or marked files, you specify a directory
1611and new symbolic links are made in that directory
dcaf31d3
EZ
1612with the same names that the files currently have. The default
1613suggested for the target directory depends on the value of
806f34d6
EZ
1614`dired-dwim-target', which see.
1615
1616For relative symlinks, use \\[dired-do-relsymlink]."
dd87891b
RS
1617 (interactive "P")
1618 (dired-do-create-files 'symlink (function make-symbolic-link)
1619 "Symlink" arg dired-keep-marker-symlink))
1620
1621;;;###autoload
1622(defun dired-do-hardlink (&optional arg)
1623 "Add names (hard links) current file or all marked (or next ARG) files.
1624When operating on just the current file, you specify the new name.
1625When operating on multiple or marked files, you specify a directory
1626and new hard links are made in that directory
dcaf31d3
EZ
1627with the same names that the files currently have. The default
1628suggested for the target directory depends on the value of
1629`dired-dwim-target', which see."
dd87891b 1630 (interactive "P")
e5369aad 1631 (dired-do-create-files 'hardlink (function dired-hardlink)
dd87891b
RS
1632 "Hardlink" arg dired-keep-marker-hardlink))
1633
e5369aad
RS
1634(defun dired-hardlink (file newname &optional ok-if-already-exists)
1635 (dired-handle-overwrite newname)
1636 ;; error is caught in -create-files
1637 (add-name-to-file file newname ok-if-already-exists)
1638 ;; Update the link count
1639 (dired-relist-file file))
1640
dd87891b
RS
1641;;;###autoload
1642(defun dired-do-rename (&optional arg)
1643 "Rename current file or all marked (or next ARG) files.
1644When renaming just the current file, you specify the new name.
dcaf31d3 1645When renaming multiple or marked files, you specify a directory.
e5369aad 1646This command also renames any buffers that are visiting the files.
dcaf31d3
EZ
1647The default suggested for the target directory depends on the value
1648of `dired-dwim-target', which see."
dd87891b
RS
1649 (interactive "P")
1650 (dired-do-create-files 'move (function dired-rename-file)
1651 "Move" arg dired-keep-marker-rename "Rename"))
1652;;;###end dired-cp.el
83fadedf 1653\f
dd87891b
RS
1654;;; 5K
1655;;;###begin dired-re.el
1656(defun dired-do-create-files-regexp
731ffbd9 1657 (file-creator operation arg regexp newname &optional whole-name marker-char)
dd87891b
RS
1658 ;; Create a new file for each marked file using regexps.
1659 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1660 ;; ARG as in dired-get-marked-files.
1661 ;; Matches each marked file against REGEXP and constructs the new
1662 ;; filename from NEWNAME (like in function replace-match).
731ffbd9 1663 ;; Optional arg WHOLE-NAME means match/replace the whole file name
dd87891b
RS
1664 ;; instead of only the non-directory part of the file.
1665 ;; Optional arg MARKER-CHAR as in dired-create-files.
1666 (let* ((fn-list (dired-get-marked-files nil arg))
1667 (fn-count (length fn-list))
1668 (operation-prompt (concat operation " `%s' to `%s'?"))
1669 (rename-regexp-help-form (format "\
1670Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1671`!' to %s all remaining matches with no more questions."
1672 (downcase operation)
1673 (downcase operation)))
1674 (regexp-name-constructor
1675 ;; Function to construct new filename using REGEXP and NEWNAME:
731ffbd9 1676 (if whole-name ; easy (but rare) case
dd87891b
RS
1677 (function
1678 (lambda (from)
1679 (let ((to (dired-string-replace-match regexp from newname))
1680 ;; must bind help-form directly around call to
1681 ;; dired-query
1682 (help-form rename-regexp-help-form))
1683 (if to
1684 (and (dired-query 'rename-regexp-query
1685 operation-prompt
1686 from
1687 to)
1688 to)
1689 (dired-log "%s: %s did not match regexp %s\n"
1690 operation from regexp)))))
731ffbd9 1691 ;; not whole-name, replace non-directory part only
dd87891b
RS
1692 (function
1693 (lambda (from)
1694 (let* ((new (dired-string-replace-match
1695 regexp (file-name-nondirectory from) newname))
1696 (to (and new ; nil means there was no match
1697 (expand-file-name new
1698 (file-name-directory from))))
1699 (help-form rename-regexp-help-form))
1700 (if to
1701 (and (dired-query 'rename-regexp-query
1702 operation-prompt
1703 (dired-make-relative from)
1704 (dired-make-relative to))
1705 to)
1706 (dired-log "%s: %s did not match regexp %s\n"
1707 operation (file-name-nondirectory from) regexp)))))))
1708 rename-regexp-query)
1709 (dired-create-files
1710 file-creator operation fn-list regexp-name-constructor marker-char)))
1711
1712(defun dired-mark-read-regexp (operation)
1713 ;; Prompt user about performing OPERATION.
731ffbd9
KS
1714 ;; Read and return list of: regexp newname arg whole-name.
1715 (let* ((whole-name
dd87891b
RS
1716 (equal 0 (prefix-numeric-value current-prefix-arg)))
1717 (arg
731ffbd9 1718 (if whole-name nil current-prefix-arg))
dd87891b
RS
1719 (regexp
1720 (dired-read-regexp
731ffbd9 1721 (concat (if whole-name "Abs. " "") operation " from (regexp): ")))
dd87891b
RS
1722 (newname
1723 (read-string
731ffbd9
KS
1724 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
1725 (list regexp newname arg whole-name)))
dd87891b
RS
1726
1727;;;###autoload
731ffbd9 1728(defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
2b3e941a
EZ
1729 "Rename selected files whose names match REGEXP to NEWNAME.
1730
1731With non-zero prefix argument ARG, the command operates on the next ARG
1732files. Otherwise, it operates on all the marked files, or the current
1733file if none are marked.
1734
dd87891b
RS
1735As each match is found, the user must type a character saying
1736 what to do with it. For directions, type \\[help-command] at that time.
1737NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1738REGEXP defaults to the last regexp used.
57dabf6b
RS
1739
1740With a zero prefix arg, renaming by regexp affects the absolute file name.
1741Normally, only the non-directory part of the file name is used and changed."
dd87891b
RS
1742 (interactive (dired-mark-read-regexp "Rename"))
1743 (dired-do-create-files-regexp
1744 (function dired-rename-file)
731ffbd9 1745 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
dd87891b
RS
1746
1747;;;###autoload
731ffbd9 1748(defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
2b3e941a 1749 "Copy selected files whose names match REGEXP to NEWNAME.
99c364e4 1750See function `dired-do-rename-regexp' for more info."
dd87891b 1751 (interactive (dired-mark-read-regexp "Copy"))
ba1acd68
RS
1752 (let ((dired-recursive-copies nil)) ; No recursive copies.
1753 (dired-do-create-files-regexp
1754 (function dired-copy-file)
1755 (if dired-copy-preserve-time "Copy [-p]" "Copy")
731ffbd9 1756 arg regexp newname whole-name dired-keep-marker-copy)))
dd87891b
RS
1757
1758;;;###autoload
731ffbd9 1759(defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1760 "Hardlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1761See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1762 (interactive (dired-mark-read-regexp "HardLink"))
1763 (dired-do-create-files-regexp
1764 (function add-name-to-file)
731ffbd9 1765 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
dd87891b
RS
1766
1767;;;###autoload
731ffbd9 1768(defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1769 "Symlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1770See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1771 (interactive (dired-mark-read-regexp "SymLink"))
1772 (dired-do-create-files-regexp
1773 (function make-symbolic-link)
731ffbd9 1774 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
dd87891b
RS
1775
1776(defun dired-create-files-non-directory
1777 (file-creator basename-constructor operation arg)
1778 ;; Perform FILE-CREATOR on the non-directory part of marked files
1779 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1780 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1781 (let (rename-non-directory-query)
1782 (dired-create-files
1783 file-creator
1784 operation
1785 (dired-get-marked-files nil arg)
1786 (function
1787 (lambda (from)
1788 (let ((to (concat (file-name-directory from)
1789 (funcall basename-constructor
1790 (file-name-nondirectory from)))))
1791 (and (let ((help-form (format "\
1792Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1793`!' to %s all remaining matches with no more questions."
1794 (downcase operation)
1795 (downcase operation))))
1796 (dired-query 'rename-non-directory-query
1797 (concat operation " `%s' to `%s'")
1798 (dired-make-relative from)
1799 (dired-make-relative to)))
1800 to))))
1801 dired-keep-marker-rename)))
1802
1803(defun dired-rename-non-directory (basename-constructor operation arg)
1804 (dired-create-files-non-directory
1805 (function dired-rename-file)
1806 basename-constructor operation arg))
1807
1808;;;###autoload
1809(defun dired-upcase (&optional arg)
1810 "Rename all marked (or next ARG) files to upper case."
1811 (interactive "P")
1812 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
1813
1814;;;###autoload
1815(defun dired-downcase (&optional arg)
1816 "Rename all marked (or next ARG) files to lower case."
1817 (interactive "P")
1818 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
1819
1820;;;###end dired-re.el
83fadedf 1821\f
dd87891b
RS
1822;;; 13K
1823;;;###begin dired-ins.el
1824
1825;;;###autoload
1826(defun dired-maybe-insert-subdir (dirname &optional
1827 switches no-error-if-not-dir-p)
1828 "Insert this subdirectory into the same dired buffer.
1829If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1830 else inserts it at its natural place (as `ls -lR' would have done).
1831With a prefix arg, you may edit the ls switches used for this listing.
1832 You can add `R' to the switches to expand the whole tree starting at
1833 this subdirectory.
79d123ad
LT
1834This function takes some pains to conform to `ls -lR' output.
1835
1836Dired remembers switches specified with a prefix arg, so that reverting
1837the buffer will not reset them. However, using `dired-undo' to re-insert
1838or delete subdirectories can bypass this machinery. Hence, you sometimes
1839may have to reset some subdirectory switches after a `dired-undo'.
1840You can reset all subdirectory switches to the default using
fad9e9b4 1841\\<dired-mode-map>\\[dired-reset-subdir-switches].
098c61f2 1842See Info node `(emacs)Subdir switches' for more details."
dd87891b
RS
1843 (interactive
1844 (list (dired-get-filename)
1845 (if current-prefix-arg
f2260f48
LT
1846 (read-string "Switches for listing: "
1847 (or dired-subdir-switches dired-actual-switches)))))
dd87891b
RS
1848 (let ((opoint (point)))
1849 ;; We don't need a marker for opoint as the subdir is always
1850 ;; inserted *after* opoint.
1851 (setq dirname (file-name-as-directory dirname))
1852 (or (and (not switches)
1853 (dired-goto-subdir dirname))
1854 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
1855 ;; Push mark so that it's easy to find back. Do this after the
1856 ;; insert message so that the user sees the `Mark set' message.
1857 (push-mark opoint)))
1858
72af9867 1859;;;###autoload
dd87891b
RS
1860(defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
1861 "Insert this subdirectory into the same dired buffer.
1862If it is already present, overwrites previous entry,
1863 else inserts it at its natural place (as `ls -lR' would have done).
1864With a prefix arg, you may edit the `ls' switches used for this listing.
1865 You can add `R' to the switches to expand the whole tree starting at
1866 this subdirectory.
1867This function takes some pains to conform to `ls -lR' output."
1868 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
1869 ;; Prospero where dired-ls does the right thing, but
1870 ;; file-directory-p has not been redefined.
1871 (interactive
1872 (list (dired-get-filename)
1873 (if current-prefix-arg
f2260f48
LT
1874 (read-string "Switches for listing: "
1875 (or dired-subdir-switches dired-actual-switches)))))
dd87891b 1876 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
1877 (or no-error-if-not-dir-p
1878 (file-directory-p dirname)
1879 (error "Attempt to insert a non-directory: %s" dirname))
1880 (let ((elt (assoc dirname dired-subdir-alist))
f2260f48
LT
1881 (cons (assoc-string dirname dired-switches-alist))
1882 (modflag (buffer-modified-p))
1883 (old-switches switches)
1884 switches-have-R mark-alist case-fold-search buffer-read-only)
1885 (and (not switches) cons (setq switches (cdr cons)))
1886 (dired-insert-subdir-validate dirname switches)
dd87891b
RS
1887 ;; case-fold-search is nil now, so we can test for capital `R':
1888 (if (setq switches-have-R (and switches (string-match "R" switches)))
1889 ;; avoid duplicated subdirs
1890 (setq mark-alist (dired-kill-tree dirname t)))
1891 (if elt
1892 ;; If subdir is already present, remove it and remember its marks
1893 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
1894 (dired-insert-subdir-newpos dirname)) ; else compute new position
1895 (dired-insert-subdir-doupdate
1896 dirname elt (dired-insert-subdir-doinsert dirname switches))
f2260f48
LT
1897 (when old-switches
1898 (if cons
1899 (setcdr cons switches)
1900 (push (cons dirname switches) dired-switches-alist)))
1901 (when switches-have-R
1902 (dired-build-subdir-alist switches)
081e4397 1903 (setq switches (dired-replace-in-string "R" "" switches))
f2260f48
LT
1904 (dolist (cur-ass dired-subdir-alist)
1905 (let ((cur-dir (car cur-ass)))
1906 (and (dired-in-this-tree cur-dir dirname)
f2260f48
LT
1907 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
1908 (if cur-cons
1909 (setcdr cur-cons switches)
1910 (push (cons cur-dir switches) dired-switches-alist)))))))
dd87891b 1911 (dired-initial-position dirname)
f2260f48
LT
1912 (save-excursion (dired-mark-remembered mark-alist))
1913 (restore-buffer-modified-p modflag)))
dd87891b
RS
1914
1915;; This is a separate function for dired-vms.
1916(defun dired-insert-subdir-validate (dirname &optional switches)
1917 ;; Check that it is valid to insert DIRNAME with SWITCHES.
1918 ;; Signal an error if invalid (e.g. user typed `i' on `..').
d443f37c 1919 (or (dired-in-this-tree dirname (expand-file-name default-directory))
dd87891b 1920 (error "%s: not in this directory tree" dirname))
f2260f48
LT
1921 (let ((real-switches (or switches dired-subdir-switches)))
1922 (when real-switches
dd87891b
RS
1923 (let (case-fold-search)
1924 (mapcar
1925 (function
1926 (lambda (x)
f2260f48 1927 (or (eq (null (string-match x real-switches))
dd87891b 1928 (null (string-match x dired-actual-switches)))
f2260f48
LT
1929 (error
1930 "Can't have dirs with and without -%s switches together" x))))
dd87891b 1931 ;; all switches that make a difference to dired-get-filename:
f2260f48 1932 '("F" "b"))))))
dd87891b
RS
1933
1934(defun dired-alist-add (dir new-marker)
1935 ;; Add new DIR at NEW-MARKER. Sort alist.
1936 (dired-alist-add-1 dir new-marker)
1937 (dired-alist-sort))
1938
1939(defun dired-alist-sort ()
1940 ;; Keep the alist sorted on buffer position.
1941 (setq dired-subdir-alist
1942 (sort dired-subdir-alist
1943 (function (lambda (elt1 elt2)
1944 (> (dired-get-subdir-min elt1)
1945 (dired-get-subdir-min elt2)))))))
1946
0a07c3a9 1947(defun dired-kill-tree (dirname &optional remember-marks kill-root)
616e14f4 1948 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
0a07c3a9
LT
1949Interactively, you can kill DIRNAME as well by using a prefix argument.
1950In interactive use, the command prompts for DIRNAME.
1951
1952When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
1953of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
1954 (interactive "DKill tree below directory: \ni\nP")
1955 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
1956 (let ((s-alist dired-subdir-alist) dir m-alist)
1957 (while s-alist
1958 (setq dir (car (car s-alist))
1959 s-alist (cdr s-alist))
0a07c3a9
LT
1960 (and (or kill-root (not (string-equal dir dirname)))
1961 (dired-in-this-tree dir dirname)
1962 (dired-goto-subdir dir)
1963 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
dd87891b
RS
1964 m-alist))
1965
1966(defun dired-insert-subdir-newpos (new-dir)
1967 ;; Find pos for new subdir, according to tree order.
1968 ;;(goto-char (point-max))
1969 (let ((alist dired-subdir-alist) elt dir pos new-pos)
1970 (while alist
1971 (setq elt (car alist)
1972 alist (cdr alist)
1973 dir (car elt)
1974 pos (dired-get-subdir-min elt))
1975 (if (dired-tree-lessp dir new-dir)
1976 ;; Insert NEW-DIR after DIR
1977 (setq new-pos (dired-get-subdir-max elt)
1978 alist nil)))
1979 (goto-char new-pos))
1980 ;; want a separating newline between subdirs
1981 (or (eobp)
1982 (forward-line -1))
1983 (insert "\n")
1984 (point))
1985
1986(defun dired-insert-subdir-del (element)
1987 ;; Erase an already present subdir (given by ELEMENT) from buffer.
1988 ;; Move to that buffer position. Return a mark-alist.
1989 (let ((begin-marker (dired-get-subdir-min element)))
1990 (goto-char begin-marker)
1991 ;; Are at beginning of subdir (and inside it!). Now determine its end:
1992 (goto-char (dired-subdir-max))
1993 (or (eobp);; want a separating newline _between_ subdirs:
1994 (forward-char -1))
1995 (prog1
1996 (dired-remember-marks begin-marker (point))
1997 (delete-region begin-marker (point)))))
1998
1999(defun dired-insert-subdir-doinsert (dirname switches)
e5369aad 2000 ;; Insert ls output after point.
dd87891b 2001 ;; Return the boundary of the inserted text (as list of BEG and END).
349254d3
AS
2002 (save-excursion
2003 (let ((begin (point)))
349254d3
AS
2004 (let ((dired-actual-switches
2005 (or switches
f2260f48 2006 dired-subdir-switches
349254d3
AS
2007 (dired-replace-in-string "R" "" dired-actual-switches))))
2008 (if (equal dirname (car (car (last dired-subdir-alist))))
2009 ;; If doing the top level directory of the buffer,
2010 ;; redo it as specified in dired-directory.
2011 (dired-readin-insert)
2012 (dired-insert-directory dirname dired-actual-switches nil nil t)))
349254d3 2013 (list begin (point)))))
dd87891b
RS
2014
2015(defun dired-insert-subdir-doupdate (dirname elt beg-end)
2016 ;; Point is at the correct subdir alist position for ELT,
2017 ;; BEG-END is the subdir-region (as list of begin and end).
2018 (if elt ; subdir was already present
2019 ;; update its position (should actually be unchanged)
2020 (set-marker (dired-get-subdir-min elt) (point-marker))
2021 (dired-alist-add dirname (point-marker)))
2022 ;; The hook may depend on the subdir-alist containing the just
2023 ;; inserted subdir, so run it after dired-alist-add:
2024 (if dired-after-readin-hook
2025 (save-excursion
2026 (let ((begin (nth 0 beg-end))
2027 (end (nth 1 beg-end)))
2028 (goto-char begin)
2029 (save-restriction
2030 (narrow-to-region begin end)
2031 ;; hook may add or delete lines, but the subdir boundary
2032 ;; marker floats
2033 (run-hooks 'dired-after-readin-hook))))))
2034
2035(defun dired-tree-lessp (dir1 dir2)
57dabf6b 2036 ;; Lexicographic order on file name components, like `ls -lR':
4837b516
GM
2037 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2038 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
dd87891b
RS
2039 ;; or DIR1 and DIR2 are in the same parentdir and their last
2040 ;; components are string-lessp.
2041 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2042 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2043 ;; if dired-actual-switches contained `t'.
2044 (setq dir1 (file-name-as-directory dir1)
2045 dir2 (file-name-as-directory dir2))
2046 (let ((components-1 (dired-split "/" dir1))
2047 (components-2 (dired-split "/" dir2)))
2048 (while (and components-1
2049 components-2
2050 (equal (car components-1) (car components-2)))
2051 (setq components-1 (cdr components-1)
2052 components-2 (cdr components-2)))
2053 (let ((c1 (car components-1))
2054 (c2 (car components-2)))
2055
2056 (cond ((and c1 c2)
2057 (string-lessp c1 c2))
2058 ((and (null c1) (null c2))
2059 nil) ; they are equal, not lessp
2060 ((null c1) ; c2 is a subdir of c1: c1<c2
2061 t)
2062 ((null c2) ; c1 is a subdir of c2: c1>c2
2063 nil)
2064 (t (error "This can't happen"))))))
2065
2066;; There should be a builtin split function - inverse to mapconcat.
2067(defun dired-split (pat str &optional limit)
2068 "Splitting on regexp PAT, turn string STR into a list of substrings.
2069Optional third arg LIMIT (>= 1) is a limit to the length of the
2070resulting list.
2071Thus, if SEP is a regexp that only matches itself,
2072
2073 (mapconcat 'identity (dired-split SEP STRING) SEP)
2074
2075is always equal to STRING."
2076 (let* ((start (string-match pat str))
2077 (result (list (substring str 0 start)))
2078 (count 1)
2079 (end (if start (match-end 0))))
2080 (if end ; else nothing left
2081 (while (and (or (not (integerp limit))
2082 (< count limit))
2083 (string-match pat str end))
2084 (setq start (match-beginning 0)
2085 count (1+ count)
2086 result (cons (substring str end start) result)
2087 end (match-end 0)
2088 start end)
2089 ))
2090 (if (and (or (not (integerp limit))
2091 (< count limit))
2092 end) ; else nothing left
2093 (setq result
2094 (cons (substring str end) result)))
2095 (nreverse result)))
83fadedf 2096\f
dd87891b
RS
2097;;; moving by subdirectories
2098
dd87891b
RS
2099;;;###autoload
2100(defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2101 "Go to previous subdirectory, regardless of level.
2102When called interactively and not on a subdir line, go to this subdir's line."
2103 ;;(interactive "p")
2104 (interactive
2105 (list (if current-prefix-arg
2106 (prefix-numeric-value current-prefix-arg)
2107 ;; if on subdir start already, don't stay there!
2108 (if (dired-get-subdir) 1 0))))
2109 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2110
2111(defun dired-subdir-min ()
2112 (save-excursion
2113 (if (not (dired-prev-subdir 0 t t))
2114 (error "Not in a subdir!")
2115 (point))))
2116
2117;;;###autoload
2118(defun dired-goto-subdir (dir)
2119 "Go to end of header line of DIR in this dired buffer.
2120Return value of point on success, otherwise return nil.
2121The next char is either \\n, or \\r if DIR is hidden."
2122 (interactive
2123 (prog1 ; let push-mark display its message
2124 (list (expand-file-name
2125 (completing-read "Goto in situ directory: " ; prompt
2126 dired-subdir-alist ; table
2127 nil ; predicate
2128 t ; require-match
2129 (dired-current-directory))))
2130 (push-mark)))
2131 (setq dir (file-name-as-directory dir))
2132 (let ((elt (assoc dir dired-subdir-alist)))
2133 (and elt
2134 (goto-char (dired-get-subdir-min elt))
2135 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2136 ;; at either \r or \n after this function succeeds.
2137 (progn (skip-chars-forward "^\r\n")
2138 (point)))))
83fadedf 2139\f
dd87891b
RS
2140;;;###autoload
2141(defun dired-mark-subdir-files ()
472974e9
RS
2142 "Mark all files except `.' and `..' in current subdirectory.
2143If the Dired buffer shows multiple directories, this command
2144marks the files listed in the subdirectory that point is in."
96149b57 2145 (interactive)
dd87891b
RS
2146 (let ((p-min (dired-subdir-min)))
2147 (dired-mark-files-in-region p-min (dired-subdir-max))))
2148
2149;;;###autoload
2150(defun dired-kill-subdir (&optional remember-marks)
2151 "Remove all lines of current subdirectory.
2152Lower levels are unaffected."
2153 ;; With optional REMEMBER-MARKS, return a mark-alist.
2154 (interactive)
f2260f48
LT
2155 (let* ((beg (dired-subdir-min))
2156 (end (dired-subdir-max))
2157 (modflag (buffer-modified-p))
2158 (cur-dir (dired-current-directory))
2159 (cons (assoc-string cur-dir dired-switches-alist))
2160 buffer-read-only)
dd87891b
RS
2161 (if (equal cur-dir default-directory)
2162 (error "Attempt to kill top level directory"))
2163 (prog1
2164 (if remember-marks (dired-remember-marks beg end))
2165 (delete-region beg end)
2166 (if (eobp) ; don't leave final blank line
2167 (delete-char -1))
f2260f48
LT
2168 (dired-unsubdir cur-dir)
2169 (when cons
2170 (setq dired-switches-alist (delete cons dired-switches-alist)))
2171 (restore-buffer-modified-p modflag))))
dd87891b
RS
2172
2173(defun dired-unsubdir (dir)
2174 ;; Remove DIR from the alist
2175 (setq dired-subdir-alist
2176 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2177
2178;;;###autoload
2179(defun dired-tree-up (arg)
2180 "Go up ARG levels in the dired tree."
2181 (interactive "p")
2182 (let ((dir (dired-current-directory)))
2183 (while (>= arg 1)
2184 (setq arg (1- arg)
2185 dir (file-name-directory (directory-file-name dir))))
2186 ;;(setq dir (expand-file-name dir))
2187 (or (dired-goto-subdir dir)
55535639 2188 (error "Cannot go up to %s - not in this tree" dir))))
dd87891b
RS
2189
2190;;;###autoload
2191(defun dired-tree-down ()
2192 "Go down in the dired tree."
2193 (interactive)
2194 (let ((dir (dired-current-directory)) ; has slash
2195 pos case-fold-search) ; filenames are case sensitive
2196 (let ((rest (reverse dired-subdir-alist)) elt)
2197 (while rest
2198 (setq elt (car rest)
2199 rest (cdr rest))
2200 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2201 (setq rest nil
2202 pos (dired-goto-subdir (car elt))))))
2203 (if pos
2204 (goto-char pos)
2205 (error "At the bottom"))))
83fadedf 2206\f
dd87891b
RS
2207;;; hiding
2208
2209(defun dired-unhide-subdir ()
2210 (let (buffer-read-only)
2211 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2212
2213(defun dired-hide-check ()
2214 (or selective-display
2215 (error "selective-display must be t for subdir hiding to work!")))
2216
2217(defun dired-subdir-hidden-p (dir)
2218 (and selective-display
2219 (save-excursion
2220 (dired-goto-subdir dir)
2221 (looking-at "\r"))))
2222
2223;;;###autoload
2224(defun dired-hide-subdir (arg)
2225 "Hide or unhide the current subdirectory and move to next directory.
2226Optional prefix arg is a repeat factor.
2227Use \\[dired-hide-all] to (un)hide all directories."
2228 (interactive "p")
2229 (dired-hide-check)
f2260f48
LT
2230 (let ((modflag (buffer-modified-p)))
2231 (while (>= (setq arg (1- arg)) 0)
2232 (let* ((cur-dir (dired-current-directory))
2233 (hidden-p (dired-subdir-hidden-p cur-dir))
2234 (elt (assoc cur-dir dired-subdir-alist))
2235 (end-pos (1- (dired-get-subdir-max elt)))
2236 buffer-read-only)
2237 ;; keep header line visible, hide rest
2238 (goto-char (dired-get-subdir-min elt))
2239 (skip-chars-forward "^\n\r")
2240 (if hidden-p
2241 (subst-char-in-region (point) end-pos ?\r ?\n)
2242 (subst-char-in-region (point) end-pos ?\n ?\r)))
2243 (dired-next-subdir 1 t))
2244 (restore-buffer-modified-p modflag)))
dd87891b
RS
2245
2246;;;###autoload
2247(defun dired-hide-all (arg)
2248 "Hide all subdirectories, leaving only their header lines.
2249If there is already something hidden, make everything visible again.
2250Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2251 (interactive "P")
2252 (dired-hide-check)
f2260f48
LT
2253 (let ((modflag (buffer-modified-p))
2254 buffer-read-only)
dd87891b
RS
2255 (if (save-excursion
2256 (goto-char (point-min))
2257 (search-forward "\r" nil t))
2258 ;; unhide - bombs on \r in filenames
2259 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2260 ;; hide
2261 (let ((pos (point-max)) ; pos of end of last directory
2262 (alist dired-subdir-alist))
f2260f48 2263 (while alist ; while there are dirs before pos
dd87891b
RS
2264 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2265 (save-excursion
2266 (goto-char pos) ; current dir
2267 ;; we're somewhere on current dir's line
2268 (forward-line -1)
2269 (point))
2270 ?\n ?\r)
2271 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
f2260f48
LT
2272 (setq alist (cdr alist)))))
2273 (restore-buffer-modified-p modflag)))
dd87891b
RS
2274
2275;;;###end dired-ins.el
2f14b48d 2276
83fadedf 2277\f
2297e912
RM
2278;; Functions for searching in tags style among marked files.
2279
2280;;;###autoload
5c0b696b 2281(defun dired-do-search (regexp)
2297e912
RM
2282 "Search through all marked files for a match for REGEXP.
2283Stops when a match is found.
2284To continue searching for next match, use command \\[tags-loop-continue]."
2285 (interactive "sSearch marked files (regexp): ")
5e514c27 2286 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2297e912
RM
2287
2288;;;###autoload
be3981a8 2289(defun dired-do-query-replace-regexp (from to &optional delimited)
5c0b696b 2290 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2297e912 2291Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
e5374284 2292If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2297e912
RM
2293with the command \\[tags-loop-continue]."
2294 (interactive
0751a704
JL
2295 (let ((common
2296 (query-replace-read-args
2297 "Query replace regexp in marked files" t t)))
2298 (list (nth 0 common) (nth 1 common) (nth 2 common))))
d1c553c8
RS
2299 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2300 (let ((buffer (get-file-buffer file)))
2301 (if (and buffer (with-current-buffer buffer
2302 buffer-read-only))
60a8f928 2303 (error "File `%s' is visited read-only" file))))
5e514c27
RS
2304 (tags-query-replace from to delimited
2305 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2306
2307(defun dired-nondirectory-p (file)
2308 (not (file-directory-p file)))
83fadedf 2309\f
ee6be958
MB
2310;;;###autoload
2311(defun dired-show-file-type (file &optional deref-symlinks)
2312 "Print the type of FILE, according to the `file' command.
2313If FILE is a symbolic link and the optional argument DEREF-SYMLINKS is
edb8d73e 2314true then the type of the file linked to by FILE is printed instead."
ee6be958 2315 (interactive (list (dired-get-filename t) current-prefix-arg))
edb8d73e 2316 (with-temp-buffer
ee6be958 2317 (if deref-symlinks
384bcc64
RS
2318 (call-process "file" nil t t "-L" "--" file)
2319 (call-process "file" nil t t "--" file))
ee6be958
MB
2320 (when (bolp)
2321 (backward-delete-char 1))
6de40a0c 2322 (message "%s" (buffer-string))))
2297e912 2323
80ec9ac5
RS
2324(provide 'dired-aux)
2325
cbee283d 2326;; arch-tag: 4b508de9-a153-423d-8d3f-a1bbd86f4f60
e5167999 2327;;; dired-aux.el ends here