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