Set image-mode-text-map when image cannot be displayed.
[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.
1111 ;; Will probably be redefined for VMS etc.
1112 (save-excursion
1113 (or (dired-goto-subdir dir) (error "This cannot happen"))
1114 (forward-line 1)
1115 (while (and (not (eolp)) ; don't cross subdir boundary
1116 (not (dired-move-to-filename)))
1117 (forward-line 1))
1118 (point)))
1119
d443f37c 1120;;;###autoload
dd87891b
RS
1121(defun dired-remove-file (file)
1122 (dired-fun-in-all-buffers
b2a59df0
RS
1123 (file-name-directory file) (file-name-nondirectory file)
1124 (function dired-remove-entry) file))
dd87891b
RS
1125
1126(defun dired-remove-entry (file)
1127 (save-excursion
1128 (and (dired-goto-file file)
1129 (let (buffer-read-only)
1130 (delete-region (progn (beginning-of-line) (point))
1131 (save-excursion (forward-line 1) (point)))))))
1132
d443f37c 1133;;;###autoload
dd87891b 1134(defun dired-relist-file (file)
e5369aad 1135 "Create or update the line for FILE in all Dired buffers it would belong in."
dd87891b 1136 (dired-fun-in-all-buffers (file-name-directory file)
b2a59df0 1137 (file-name-nondirectory file)
dd87891b
RS
1138 (function dired-relist-entry) file))
1139
1140(defun dired-relist-entry (file)
1141 ;; Relist the line for FILE, or just add it if it did not exist.
57dabf6b 1142 ;; FILE must be an absolute file name.
dd87891b
RS
1143 (let (buffer-read-only marker)
1144 ;; If cursor is already on FILE's line delete-region will cause
1145 ;; save-excursion to fail because of floating makers,
1146 ;; moving point to beginning of line. Sigh.
1147 (save-excursion
1148 (and (dired-goto-file file)
1149 (delete-region (progn (beginning-of-line)
1150 (setq marker (following-char))
1151 (point))
1152 (save-excursion (forward-line 1) (point))))
1153 (setq file (directory-file-name file))
1154 (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
83fadedf 1155\f
dd87891b
RS
1156;;; Copy, move/rename, making hard and symbolic links
1157
91a7e829 1158(defcustom dired-backup-overwrite nil
dd87891b 1159 "*Non-nil if Dired should ask about making backups before overwriting files.
91a7e829
RS
1160Special value `always' suppresses confirmation."
1161 :type '(choice (const :tag "off" nil)
1162 (const :tag "suppress" always)
a9e9b8fa 1163 (other :tag "ask" t))
91a7e829 1164 :group 'dired)
dd87891b 1165
bf0de14d
CY
1166;; This is a fluid var used in dired-handle-overwrite. It should be
1167;; let-bound whenever dired-copy-file etc are called. See
1168;; dired-create-files for an example.
1169(defvar dired-overwrite-confirmed)
6482fcac 1170
dd87891b 1171(defun dired-handle-overwrite (to)
e5369aad 1172 ;; Save old version of file TO that is to be overwritten.
6482fcac 1173 ;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars
dd87891b 1174 ;; from dired-create-files.
d63a6ae0 1175 (let (backup)
bbfe2308
CY
1176 (when (and dired-backup-overwrite
1177 dired-overwrite-confirmed
1178 (setq backup (car (find-backup-file-name to)))
1179 (or (eq 'always dired-backup-overwrite)
1180 (dired-query 'overwrite-backup-query
1181 "Make backup for existing file `%s'? "
1182 to)))
1183 (rename-file to backup 0) ; confirm overwrite of old backup
1184 (dired-relist-entry backup))))
dd87891b 1185
d443f37c 1186;;;###autoload
dd87891b
RS
1187(defun dired-copy-file (from to ok-flag)
1188 (dired-handle-overwrite to)
c62a8073
RS
1189 (dired-copy-file-recursive from to ok-flag dired-copy-preserve-time t
1190 dired-recursive-copies))
dd87891b 1191
8e845e23
JB
1192(declare-function make-symbolic-link "fileio.c")
1193
ba1acd68
RS
1194(defun dired-copy-file-recursive (from to ok-flag &optional
1195 preserve-time top recursive)
c62a8073
RS
1196 (let ((attrs (file-attributes from))
1197 dirfailed)
3b68c506
RS
1198 (if (and recursive
1199 (eq t (car attrs))
1200 (or (eq recursive 'always)
ce5a3ac0 1201 (yes-or-no-p (format "Recursive copies of %s? " from))))
3b68c506 1202 ;; This is a directory.
89242dda
JB
1203 (let ((mode (file-modes from))
1204 (files
c62a8073
RS
1205 (condition-case err
1206 (directory-files from nil dired-re-no-dot)
1207 (file-error
1208 (push (dired-make-relative from)
1209 dired-create-files-failures)
1210 (dired-log "Copying error for %s:\n%s\n" from err)
1211 (setq dirfailed t)
1212 nil))))
3b68c506 1213 (if (eq recursive 'top) (setq recursive 'always)) ; Don't ask any more.
c62a8073
RS
1214 (unless dirfailed
1215 (if (file-exists-p to)
1216 (or top (dired-handle-overwrite to))
1217 (condition-case err
7138d3f9
CY
1218 ;; We used to call set-file-modes here, but on some
1219 ;; Linux kernels, that returns an error on vfat
1220 ;; filesystems
e6979d6e
CY
1221 (let ((default-mode (default-file-modes)))
1222 (unwind-protect
1223 (progn
1224 (set-default-file-modes #o700)
1225 (make-directory to))
1226 (set-default-file-modes default-mode)))
c62a8073
RS
1227 (file-error
1228 (push (dired-make-relative from)
1229 dired-create-files-failures)
1230 (setq files nil)
1231 (dired-log "Copying error for %s:\n%s\n" from err)))))
7a547817
RS
1232 (dolist (file files)
1233 (let ((thisfrom (expand-file-name file from))
1234 (thisto (expand-file-name file to)))
1235 ;; Catch errors copying within a directory,
1236 ;; and report them through the dired log mechanism
1237 ;; just as our caller will do for the top level files.
1238 (condition-case err
1239 (dired-copy-file-recursive
1240 thisfrom thisto
1241 ok-flag preserve-time nil recursive)
1242 (file-error
1243 (push (dired-make-relative thisfrom)
1244 dired-create-files-failures)
89242dda
JB
1245 (dired-log "Copying error for %s:\n%s\n" thisfrom err)))))
1246 (when (file-directory-p to)
1247 (set-file-modes to mode)))
3b68c506
RS
1248 ;; Not a directory.
1249 (or top (dired-handle-overwrite to))
c62a8073
RS
1250 (condition-case err
1251 (if (stringp (car attrs))
1252 ;; It is a symlink
1253 (make-symbolic-link (car attrs) to ok-flag)
1254 (copy-file from to ok-flag dired-copy-preserve-time))
4a725859 1255 (file-date-error
c62a8073
RS
1256 (push (dired-make-relative from)
1257 dired-create-files-failures)
7a547817 1258 (dired-log "Can't set date on %s:\n%s\n" from err))))))
ba1acd68 1259
d443f37c 1260;;;###autoload
e5369aad
RS
1261(defun dired-rename-file (file newname ok-if-already-exists)
1262 (dired-handle-overwrite newname)
1263 (rename-file file newname ok-if-already-exists) ; error is caught in -create-files
dd87891b 1264 ;; Silently rename the visited file of any buffer visiting this file.
e5369aad
RS
1265 (and (get-file-buffer file)
1266 (with-current-buffer (get-file-buffer file)
1267 (set-visited-file-name newname nil t)))
1268 (dired-remove-file file)
dd87891b 1269 ;; See if it's an inserted subdir, and rename that, too.
e5369aad 1270 (dired-rename-subdir file newname))
dd87891b
RS
1271
1272(defun dired-rename-subdir (from-dir to-dir)
1273 (setq from-dir (file-name-as-directory from-dir)
1274 to-dir (file-name-as-directory to-dir))
b2a59df0 1275 (dired-fun-in-all-buffers from-dir nil
dd87891b
RS
1276 (function dired-rename-subdir-1) from-dir to-dir)
1277 ;; Update visited file name of all affected buffers
9df38cef
RS
1278 (let ((expanded-from-dir (expand-file-name from-dir))
1279 (blist (buffer-list)))
dd87891b
RS
1280 (while blist
1281 (save-excursion
9df38cef 1282 (set-buffer (car blist))
dd87891b 1283 (if (and buffer-file-name
9df38cef 1284 (dired-in-this-tree buffer-file-name expanded-from-dir))
dd87891b 1285 (let ((modflag (buffer-modified-p))
83fadedf 1286 (to-file (dired-replace-in-string
dd87891b
RS
1287 (concat "^" (regexp-quote from-dir))
1288 to-dir
1289 buffer-file-name)))
1290 (set-visited-file-name to-file)
1291 (set-buffer-modified-p modflag))))
1292 (setq blist (cdr blist)))))
1293
1294(defun dired-rename-subdir-1 (dir to)
1295 ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
1296 ;; one of its subdirectories is expanded in this buffer.
9df38cef
RS
1297 (let ((expanded-dir (expand-file-name dir))
1298 (alist dired-subdir-alist)
dd87891b
RS
1299 (elt nil))
1300 (while alist
1301 (setq elt (car alist)
1302 alist (cdr alist))
9df38cef 1303 (if (dired-in-this-tree (car elt) expanded-dir)
dd87891b
RS
1304 ;; ELT's subdir is affected by the rename
1305 (dired-rename-subdir-2 elt dir to)))
1306 (if (equal dir default-directory)
1307 ;; if top level directory was renamed, lots of things have to be
1308 ;; updated:
1309 (progn
1310 (dired-unadvertise dir) ; we no longer dired DIR...
1311 (setq default-directory to
1312 dired-directory (expand-file-name;; this is correct
1313 ;; with and without wildcards
1314 (file-name-nondirectory dired-directory)
1315 to))
1316 (let ((new-name (file-name-nondirectory
1317 (directory-file-name dired-directory))))
1318 ;; try to rename buffer, but just leave old name if new
1319 ;; name would already exist (don't try appending "<%d>")
1320 (or (get-buffer new-name)
1321 (rename-buffer new-name)))
1322 ;; ... we dired TO now:
1323 (dired-advertise)))))
1324
1325(defun dired-rename-subdir-2 (elt dir to)
f2260f48
LT
1326 ;; Update the headerline and dired-subdir-alist element, as well as
1327 ;; dired-switches-alist element, of directory described by
1328 ;; alist-element ELT to reflect the moving of DIR to TO. Thus, ELT
1329 ;; describes either DIR itself or a subdir of DIR.
dd87891b
RS
1330 (save-excursion
1331 (let ((regexp (regexp-quote (directory-file-name dir)))
1332 (newtext (directory-file-name to))
1333 buffer-read-only)
1334 (goto-char (dired-get-subdir-min elt))
1335 ;; Update subdir headerline in buffer
1336 (if (not (looking-at dired-subdir-regexp))
1337 (error "%s not found where expected - dired-subdir-alist broken?"
1338 dir)
1339 (goto-char (match-beginning 1))
1340 (if (re-search-forward regexp (match-end 1) t)
1341 (replace-match newtext t t)
1342 (error "Expected to find `%s' in headerline of %s" dir (car elt))))
f2260f48
LT
1343 ;; Update buffer-local dired-subdir-alist and dired-switches-alist
1344 (let ((cons (assoc-string (car elt) dired-switches-alist))
1345 (cur-dir (dired-normalize-subdir
1346 (dired-replace-in-string regexp newtext (car elt)))))
1347 (setcar elt cur-dir)
1348 (when cons (setcar cons cur-dir))))))
83fadedf 1349\f
dd87891b
RS
1350;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
1351(defun dired-create-files (file-creator operation fn-list name-constructor
1352 &optional marker-char)
1353
1354;; Create a new file for each from a list of existing files. The user
1355;; is queried, dired buffers are updated, and at the end a success or
1356;; failure message is displayed
1357
1358;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
1359
1360;; It is called for each file and must create newfile, the entry of
1361;; which will be added. The user will be queried if the file already
1362;; exists. If oldfile is removed by FILE-CREATOR (i.e, it is a
1363;; rename), it is FILE-CREATOR's responsibility to update dired
a7acbbe4 1364;; buffers. FILE-CREATOR must abort by signaling a file-error if it
dd87891b
RS
1365;; could not create newfile. The error is caught and logged.
1366
1367;; OPERATION (a capitalized string, e.g. `Copy') describes the
1368;; operation performed. It is used for error logging.
1369
57dabf6b 1370;; FN-LIST is the list of files to copy (full absolute file names).
dd87891b
RS
1371
1372;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
1373;; skip. If it skips files for other reasons than a direct user
1374;; query, it is supposed to tell why (using dired-log).
1375
1376;; Optional MARKER-CHAR is a character with which to mark every
1377;; newfile's entry, or t to use the current marker character if the
1378;; oldfile was marked.
1379
c62a8073
RS
1380 (let (dired-create-files-failures failures
1381 skipped (success-count 0) (total (length fn-list)))
dd87891b
RS
1382 (let (to overwrite-query
1383 overwrite-backup-query) ; for dired-handle-overwrite
04509548
SM
1384 (dolist (from fn-list)
1385 (setq to (funcall name-constructor from))
1386 (if (equal to from)
1387 (progn
1388 (setq to nil)
1389 (dired-log "Cannot %s to same file: %s\n"
1390 (downcase operation) from)))
1391 (if (not to)
1392 (setq skipped (cons (dired-make-relative from) skipped))
1393 (let* ((overwrite (file-exists-p to))
1394 (dired-overwrite-confirmed ; for dired-handle-overwrite
1395 (and overwrite
1396 (let ((help-form '(format "\
dd87891b
RS
1397Type SPC or `y' to overwrite file `%s',
1398DEL or `n' to skip to next,
1399ESC or `q' to not overwrite any of the remaining files,
1400`!' to overwrite all remaining files with no more questions." to)))
04509548
SM
1401 (dired-query 'overwrite-query
1402 "Overwrite `%s'?" to))))
1403 ;; must determine if FROM is marked before file-creator
1404 ;; gets a chance to delete it (in case of a move).
1405 (actual-marker-char
1406 (cond ((integerp marker-char) marker-char)
1407 (marker-char (dired-file-marker from)) ; slow
1408 (t nil))))
1409 (condition-case err
1410 (progn
1411 (funcall file-creator from to dired-overwrite-confirmed)
1412 (if overwrite
1413 ;; If we get here, file-creator hasn't been aborted
1414 ;; and the old entry (if any) has to be deleted
1415 ;; before adding the new entry.
1416 (dired-remove-file to))
1417 (setq success-count (1+ success-count))
1418 (message "%s: %d of %d" operation success-count total)
1419 (dired-add-file to actual-marker-char))
1420 (file-error ; FILE-CREATOR aborted
1421 (progn
1422 (push (dired-make-relative from)
1423 failures)
1424 (dired-log "%s `%s' to `%s' failed:\n%s\n"
1425 operation from to err))))))))
dd87891b 1426 (cond
c62a8073
RS
1427 (dired-create-files-failures
1428 (setq failures (nconc failures dired-create-files-failures))
1429 (dired-log-summary
1430 (format "%s failed for %d file%s in %d requests"
1431 operation (length failures)
1432 (dired-plural-s (length failures))
1433 total)
1434 failures))
dd87891b
RS
1435 (failures
1436 (dired-log-summary
1437 (format "%s failed for %d of %d file%s"
c62a8073
RS
1438 operation (length failures)
1439 total (dired-plural-s total))
dd87891b
RS
1440 failures))
1441 (skipped
1442 (dired-log-summary
1443 (format "%s: %d of %d file%s skipped"
1444 operation (length skipped) total
1445 (dired-plural-s total))
1446 skipped))
1447 (t
1448 (message "%s: %s file%s"
1449 operation success-count (dired-plural-s success-count)))))
1450 (dired-move-to-filename))
83fadedf 1451\f
dd87891b 1452(defun dired-do-create-files (op-symbol file-creator operation arg
616e14f4
SM
1453 &optional marker-char op1
1454 how-to)
1455 "Create a new file for each marked file.
1456Prompts user for target, which is a directory in which to create
1457 the new files. Target may be a plain file if only one marked
dcaf31d3
EZ
1458 file exists. The way the default for the target directory is
1459 computed depends on the value of `dired-dwim-target-directory'.
616e14f4
SM
1460OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up'
1461 will determine whether pop-ups are appropriate for this OP-SYMBOL.
1462FILE-CREATOR and OPERATION as in `dired-create-files'.
1463ARG as in `dired-get-marked-files'.
1464Optional arg MARKER-CHAR as in `dired-create-files'.
1465Optional arg OP1 is an alternate form for OPERATION if there is
1466 only one file.
1467Optional arg HOW-TO is used to set the value of the into-dir variable
1468 which determines how to treat target.
1469 If into-dir is set to nil then target is not regarded as a directory,
1470 there must be exactly one marked file, else error.
1471 Else if into-dir is set to a list, then target is a generalized
1472 directory (e.g. some sort of archive). The first element of into-dir
1473 must be a function with at least four arguments:
1474 operation as OPERATION above.
1475 rfn-list a list of the relative names for the marked files.
1476 fn-list a list of the absolute names for the marked files.
1477 target.
1478 The rest of into-dir are optional arguments.
1479 Else into-dir is not a list. Target is a directory.
1480 The marked file(s) are created inside the target directory.
1481
1482 If HOW-TO is not given (or nil), then into-dir is set to true if
1483 target is a directory and otherwise to nil.
1484 Else if HOW-TO is t, then into-dir is set to nil.
1485 Else HOW-TO is assumed to be a function of one argument, target,
1486 that looks at target and returns a value for the into-dir
1487 variable. The function `dired-into-dir-with-symlinks' is provided
1488 for the case (common when creating symlinks) that symbolic
1489 links to directories are not to be considered as directories
1490 (as `file-directory-p' would if HOW-TO had been nil)."
dd87891b
RS
1491 (or op1 (setq op1 operation))
1492 (let* ((fn-list (dired-get-marked-files nil arg))
ba1acd68
RS
1493 (rfn-list (mapcar (function dired-make-relative) fn-list))
1494 (dired-one-file ; fluid variable inside dired-create-files
1495 (and (consp fn-list) (null (cdr fn-list)) (car fn-list)))
75ab0c79
GM
1496 (target-dir (dired-dwim-target-directory))
1497 (default (and dired-one-file
1498 (expand-file-name (file-name-nondirectory (car fn-list))
1499 target-dir)))
ba1acd68 1500 (target (expand-file-name ; fluid variable inside dired-create-files
dd87891b 1501 (dired-mark-read-file-name
ba1acd68 1502 (concat (if dired-one-file op1 operation) " %s to: ")
75ab0c79 1503 target-dir op-symbol arg rfn-list default)))
325fec3c
EZ
1504 (into-dir (cond ((null how-to)
1505 ;; Allow DOS/Windows users to change the letter
1506 ;; case of a directory. If we don't test these
1507 ;; conditions up front, file-directory-p below
1508 ;; will return t because the filesystem is
1509 ;; case-insensitive, and Emacs will try to move
1510 ;; foo -> foo/foo, which fails.
c60ee5e7 1511 (if (and (memq system-type '(ms-dos windows-nt cygwin))
325fec3c
EZ
1512 (eq op-symbol 'move)
1513 dired-one-file
1514 (string= (downcase
1515 (expand-file-name (car fn-list)))
1516 (downcase
1517 (expand-file-name target)))
1518 (not (string=
1519 (file-name-nondirectory (car fn-list))
1520 (file-name-nondirectory target))))
1521 nil
1522 (file-directory-p target)))
dd87891b
RS
1523 ((eq how-to t) nil)
1524 (t (funcall how-to target)))))
ba1acd68
RS
1525 (if (and (consp into-dir) (functionp (car into-dir)))
1526 (apply (car into-dir) operation rfn-list fn-list target (cdr into-dir))
1527 (if (not (or dired-one-file into-dir))
1528 (error "Marked %s: target must be a directory: %s" operation target))
1529 ;; rename-file bombs when moving directories unless we do this:
1530 (or into-dir (setq target (directory-file-name target)))
1531 (dired-create-files
1532 file-creator operation fn-list
1533 (if into-dir ; target is a directory
1534 ;; This function uses fluid variable target when called
1535 ;; inside dired-create-files:
1536 (function
1537 (lambda (from)
1538 (expand-file-name (file-name-nondirectory from) target)))
1539 (function (lambda (from) target)))
1540 marker-char))))
dd87891b
RS
1541
1542;; Read arguments for a marked-files command that wants a file name,
1543;; perhaps popping up the list of marked files.
1544;; ARG is the prefix arg and indicates whether the files came from
1545;; marks (ARG=nil) or a repeat factor (integerp ARG).
1546;; If the current file was used, the list has but one element and ARG
1547;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
64666d2d
MB
1548;; DEFAULT is the default value to return if the user just hits RET;
1549;; if it is omitted or nil, then the name of the directory is used.
dd87891b 1550
64666d2d
MB
1551(defun dired-mark-read-file-name (prompt dir op-symbol arg files
1552 &optional default)
dd87891b
RS
1553 (dired-mark-pop-up
1554 nil op-symbol files
1555 (function read-file-name)
64666d2d 1556 (format prompt (dired-mark-prompt arg files)) dir default))
dd87891b
RS
1557
1558(defun dired-dwim-target-directory ()
1559 ;; Try to guess which target directory the user may want.
1560 ;; If there is a dired buffer displayed in the next window, use
1561 ;; its current subdir, else use current subdir of this dired buffer.
1562 (let ((this-dir (and (eq major-mode 'dired-mode)
1563 (dired-current-directory))))
1564 ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
1565 (if dired-dwim-target
1566 (let* ((other-buf (window-buffer (next-window)))
1567 (other-dir (save-excursion
1568 (set-buffer other-buf)
1569 (and (eq major-mode 'dired-mode)
1570 (dired-current-directory)))))
1571 (or other-dir this-dir))
1572 this-dir)))
83fadedf 1573\f
dd87891b
RS
1574;;;###autoload
1575(defun dired-create-directory (directory)
1576 "Create a directory called DIRECTORY."
1577 (interactive
1578 (list (read-file-name "Create directory: " (dired-current-directory))))
934b4968
JL
1579 (let* ((expanded (directory-file-name (expand-file-name directory)))
1580 (try expanded) new)
1581 ;; Find the topmost nonexistent parent dir (variable `new')
1582 (while (and try (not (file-exists-p try)) (not (equal new try)))
1583 (setq new try
1584 try (directory-file-name (file-name-directory try))))
1585 (make-directory expanded t)
1586 (when new
1587 (dired-add-file new)
1588 (dired-move-to-filename))))
dd87891b
RS
1589
1590(defun dired-into-dir-with-symlinks (target)
1591 (and (file-directory-p target)
1592 (not (file-symlink-p target))))
1593;; This may not always be what you want, especially if target is your
1594;; home directory and it happens to be a symbolic link, as is often the
1595;; case with NFS and automounters. Or if you want to make symlinks
1596;; into directories that themselves are only symlinks, also quite
1597;; common.
1598
1599;; So we don't use this function as value for HOW-TO in
1600;; dired-do-symlink, which has the minor disadvantage of
1601;; making links *into* a symlinked-dir, when you really wanted to
1602;; *overwrite* that symlink. In that (rare, I guess) case, you'll
1603;; just have to remove that symlink by hand before making your marked
1604;; symlinks.
1605
ba1acd68 1606(defvar dired-copy-how-to-fn nil
0ff9b955 1607 "nil or a function used by `dired-do-copy' to determine target.
ba1acd68
RS
1608See HOW-TO argument for `dired-do-create-files'.")
1609
dd87891b
RS
1610;;;###autoload
1611(defun dired-do-copy (&optional arg)
1612 "Copy all marked (or next ARG) files, or copy the current file.
1613This normally preserves the last-modified date when copying.
1614When operating on just the current file, you specify the new name.
b5458fc2
RS
1615When operating on multiple or marked files, you specify a directory,
1616and new copies of these files are made in that directory
dcaf31d3
EZ
1617with the same names that the files currently have. The default
1618suggested for the target directory depends on the value of
ec9581d5
RS
1619`dired-dwim-target', which see.
1620
1621This command copies symbolic links by creating new ones,
1622like `cp -d'."
dd87891b 1623 (interactive "P")
ea185644 1624 (let ((dired-recursive-copies dired-recursive-copies))
ba1acd68 1625 (dired-do-create-files 'copy (function dired-copy-file)
de97d5e8 1626 "Copy"
ea185644
GM
1627 arg dired-keep-marker-copy
1628 nil dired-copy-how-to-fn)))
dd87891b
RS
1629
1630;;;###autoload
1631(defun dired-do-symlink (&optional arg)
1632 "Make symbolic links to current file or all marked (or next ARG) files.
1633When operating on just the current file, you specify the new name.
1634When operating on multiple or marked files, you specify a directory
1635and new symbolic links are made in that directory
dcaf31d3
EZ
1636with the same names that the files currently have. The default
1637suggested for the target directory depends on the value of
806f34d6
EZ
1638`dired-dwim-target', which see.
1639
1640For relative symlinks, use \\[dired-do-relsymlink]."
dd87891b
RS
1641 (interactive "P")
1642 (dired-do-create-files 'symlink (function make-symbolic-link)
1643 "Symlink" arg dired-keep-marker-symlink))
1644
1645;;;###autoload
1646(defun dired-do-hardlink (&optional arg)
1647 "Add names (hard links) current file or all marked (or next ARG) files.
1648When operating on just the current file, you specify the new name.
1649When operating on multiple or marked files, you specify a directory
1650and new hard links are made in that directory
dcaf31d3
EZ
1651with the same names that the files currently have. The default
1652suggested for the target directory depends on the value of
1653`dired-dwim-target', which see."
dd87891b 1654 (interactive "P")
e5369aad 1655 (dired-do-create-files 'hardlink (function dired-hardlink)
dd87891b
RS
1656 "Hardlink" arg dired-keep-marker-hardlink))
1657
e5369aad
RS
1658(defun dired-hardlink (file newname &optional ok-if-already-exists)
1659 (dired-handle-overwrite newname)
1660 ;; error is caught in -create-files
1661 (add-name-to-file file newname ok-if-already-exists)
1662 ;; Update the link count
1663 (dired-relist-file file))
1664
dd87891b
RS
1665;;;###autoload
1666(defun dired-do-rename (&optional arg)
1667 "Rename current file or all marked (or next ARG) files.
1668When renaming just the current file, you specify the new name.
dcaf31d3 1669When renaming multiple or marked files, you specify a directory.
e5369aad 1670This command also renames any buffers that are visiting the files.
dcaf31d3
EZ
1671The default suggested for the target directory depends on the value
1672of `dired-dwim-target', which see."
dd87891b
RS
1673 (interactive "P")
1674 (dired-do-create-files 'move (function dired-rename-file)
1675 "Move" arg dired-keep-marker-rename "Rename"))
1676;;;###end dired-cp.el
83fadedf 1677\f
dd87891b
RS
1678;;; 5K
1679;;;###begin dired-re.el
1680(defun dired-do-create-files-regexp
731ffbd9 1681 (file-creator operation arg regexp newname &optional whole-name marker-char)
dd87891b
RS
1682 ;; Create a new file for each marked file using regexps.
1683 ;; FILE-CREATOR and OPERATION as in dired-create-files.
1684 ;; ARG as in dired-get-marked-files.
1685 ;; Matches each marked file against REGEXP and constructs the new
1686 ;; filename from NEWNAME (like in function replace-match).
731ffbd9 1687 ;; Optional arg WHOLE-NAME means match/replace the whole file name
dd87891b
RS
1688 ;; instead of only the non-directory part of the file.
1689 ;; Optional arg MARKER-CHAR as in dired-create-files.
1690 (let* ((fn-list (dired-get-marked-files nil arg))
1691 (fn-count (length fn-list))
1692 (operation-prompt (concat operation " `%s' to `%s'?"))
1693 (rename-regexp-help-form (format "\
1694Type SPC or `y' to %s one match, DEL or `n' to skip to next,
1695`!' to %s all remaining matches with no more questions."
1696 (downcase operation)
1697 (downcase operation)))
1698 (regexp-name-constructor
1699 ;; Function to construct new filename using REGEXP and NEWNAME:
731ffbd9 1700 (if whole-name ; easy (but rare) case
dd87891b
RS
1701 (function
1702 (lambda (from)
1703 (let ((to (dired-string-replace-match regexp from newname))
1704 ;; must bind help-form directly around call to
1705 ;; dired-query
1706 (help-form rename-regexp-help-form))
1707 (if to
1708 (and (dired-query 'rename-regexp-query
1709 operation-prompt
1710 from
1711 to)
1712 to)
1713 (dired-log "%s: %s did not match regexp %s\n"
1714 operation from regexp)))))
731ffbd9 1715 ;; not whole-name, replace non-directory part only
dd87891b
RS
1716 (function
1717 (lambda (from)
1718 (let* ((new (dired-string-replace-match
1719 regexp (file-name-nondirectory from) newname))
1720 (to (and new ; nil means there was no match
1721 (expand-file-name new
1722 (file-name-directory from))))
1723 (help-form rename-regexp-help-form))
1724 (if to
1725 (and (dired-query 'rename-regexp-query
1726 operation-prompt
1727 (dired-make-relative from)
1728 (dired-make-relative to))
1729 to)
1730 (dired-log "%s: %s did not match regexp %s\n"
1731 operation (file-name-nondirectory from) regexp)))))))
1732 rename-regexp-query)
1733 (dired-create-files
1734 file-creator operation fn-list regexp-name-constructor marker-char)))
1735
1736(defun dired-mark-read-regexp (operation)
1737 ;; Prompt user about performing OPERATION.
731ffbd9
KS
1738 ;; Read and return list of: regexp newname arg whole-name.
1739 (let* ((whole-name
dd87891b
RS
1740 (equal 0 (prefix-numeric-value current-prefix-arg)))
1741 (arg
731ffbd9 1742 (if whole-name nil current-prefix-arg))
dd87891b
RS
1743 (regexp
1744 (dired-read-regexp
731ffbd9 1745 (concat (if whole-name "Abs. " "") operation " from (regexp): ")))
dd87891b
RS
1746 (newname
1747 (read-string
731ffbd9
KS
1748 (concat (if whole-name "Abs. " "") operation " " regexp " to: "))))
1749 (list regexp newname arg whole-name)))
dd87891b
RS
1750
1751;;;###autoload
731ffbd9 1752(defun dired-do-rename-regexp (regexp newname &optional arg whole-name)
2b3e941a
EZ
1753 "Rename selected files whose names match REGEXP to NEWNAME.
1754
1755With non-zero prefix argument ARG, the command operates on the next ARG
1756files. Otherwise, it operates on all the marked files, or the current
1757file if none are marked.
1758
dd87891b
RS
1759As each match is found, the user must type a character saying
1760 what to do with it. For directions, type \\[help-command] at that time.
1761NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
1762REGEXP defaults to the last regexp used.
57dabf6b
RS
1763
1764With a zero prefix arg, renaming by regexp affects the absolute file name.
1765Normally, only the non-directory part of the file name is used and changed."
dd87891b
RS
1766 (interactive (dired-mark-read-regexp "Rename"))
1767 (dired-do-create-files-regexp
1768 (function dired-rename-file)
731ffbd9 1769 "Rename" arg regexp newname whole-name dired-keep-marker-rename))
dd87891b
RS
1770
1771;;;###autoload
731ffbd9 1772(defun dired-do-copy-regexp (regexp newname &optional arg whole-name)
2b3e941a 1773 "Copy selected files whose names match REGEXP to NEWNAME.
99c364e4 1774See function `dired-do-rename-regexp' for more info."
dd87891b 1775 (interactive (dired-mark-read-regexp "Copy"))
ba1acd68
RS
1776 (let ((dired-recursive-copies nil)) ; No recursive copies.
1777 (dired-do-create-files-regexp
1778 (function dired-copy-file)
1779 (if dired-copy-preserve-time "Copy [-p]" "Copy")
731ffbd9 1780 arg regexp newname whole-name dired-keep-marker-copy)))
dd87891b
RS
1781
1782;;;###autoload
731ffbd9 1783(defun dired-do-hardlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1784 "Hardlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1785See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1786 (interactive (dired-mark-read-regexp "HardLink"))
1787 (dired-do-create-files-regexp
1788 (function add-name-to-file)
731ffbd9 1789 "HardLink" arg regexp newname whole-name dired-keep-marker-hardlink))
dd87891b
RS
1790
1791;;;###autoload
731ffbd9 1792(defun dired-do-symlink-regexp (regexp newname &optional arg whole-name)
2b3e941a 1793 "Symlink selected files whose names match REGEXP to NEWNAME.
99c364e4 1794See function `dired-do-rename-regexp' for more info."
dd87891b
RS
1795 (interactive (dired-mark-read-regexp "SymLink"))
1796 (dired-do-create-files-regexp
1797 (function make-symbolic-link)
731ffbd9 1798 "SymLink" arg regexp newname whole-name dired-keep-marker-symlink))
dd87891b
RS
1799
1800(defun dired-create-files-non-directory
1801 (file-creator basename-constructor operation arg)
1802 ;; Perform FILE-CREATOR on the non-directory part of marked files
1803 ;; using function BASENAME-CONSTRUCTOR, with query for each file.
1804 ;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.
1805 (let (rename-non-directory-query)
1806 (dired-create-files
1807 file-creator
1808 operation
1809 (dired-get-marked-files nil arg)
1810 (function
1811 (lambda (from)
1812 (let ((to (concat (file-name-directory from)
1813 (funcall basename-constructor
1814 (file-name-nondirectory from)))))
1815 (and (let ((help-form (format "\
1816Type SPC or `y' to %s one file, DEL or `n' to skip to next,
1817`!' to %s all remaining matches with no more questions."
1818 (downcase operation)
1819 (downcase operation))))
1820 (dired-query 'rename-non-directory-query
1821 (concat operation " `%s' to `%s'")
1822 (dired-make-relative from)
1823 (dired-make-relative to)))
1824 to))))
1825 dired-keep-marker-rename)))
1826
1827(defun dired-rename-non-directory (basename-constructor operation arg)
1828 (dired-create-files-non-directory
1829 (function dired-rename-file)
1830 basename-constructor operation arg))
1831
1832;;;###autoload
1833(defun dired-upcase (&optional arg)
1834 "Rename all marked (or next ARG) files to upper case."
1835 (interactive "P")
1836 (dired-rename-non-directory (function upcase) "Rename upcase" arg))
1837
1838;;;###autoload
1839(defun dired-downcase (&optional arg)
1840 "Rename all marked (or next ARG) files to lower case."
1841 (interactive "P")
1842 (dired-rename-non-directory (function downcase) "Rename downcase" arg))
1843
1844;;;###end dired-re.el
83fadedf 1845\f
dd87891b
RS
1846;;; 13K
1847;;;###begin dired-ins.el
1848
1849;;;###autoload
1850(defun dired-maybe-insert-subdir (dirname &optional
1851 switches no-error-if-not-dir-p)
1852 "Insert this subdirectory into the same dired buffer.
1853If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
1854 else inserts it at its natural place (as `ls -lR' would have done).
1855With a prefix arg, you may edit the ls switches used for this listing.
1856 You can add `R' to the switches to expand the whole tree starting at
1857 this subdirectory.
79d123ad
LT
1858This function takes some pains to conform to `ls -lR' output.
1859
1860Dired remembers switches specified with a prefix arg, so that reverting
1861the buffer will not reset them. However, using `dired-undo' to re-insert
1862or delete subdirectories can bypass this machinery. Hence, you sometimes
1863may have to reset some subdirectory switches after a `dired-undo'.
1864You can reset all subdirectory switches to the default using
fad9e9b4 1865\\<dired-mode-map>\\[dired-reset-subdir-switches].
098c61f2 1866See Info node `(emacs)Subdir switches' for more details."
dd87891b
RS
1867 (interactive
1868 (list (dired-get-filename)
1869 (if current-prefix-arg
f2260f48
LT
1870 (read-string "Switches for listing: "
1871 (or dired-subdir-switches dired-actual-switches)))))
dd87891b
RS
1872 (let ((opoint (point)))
1873 ;; We don't need a marker for opoint as the subdir is always
1874 ;; inserted *after* opoint.
1875 (setq dirname (file-name-as-directory dirname))
1876 (or (and (not switches)
1877 (dired-goto-subdir dirname))
1878 (dired-insert-subdir dirname switches no-error-if-not-dir-p))
1879 ;; Push mark so that it's easy to find back. Do this after the
1880 ;; insert message so that the user sees the `Mark set' message.
1881 (push-mark opoint)))
1882
72af9867 1883;;;###autoload
dd87891b
RS
1884(defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
1885 "Insert this subdirectory into the same dired buffer.
1886If it is already present, overwrites previous entry,
1887 else inserts it at its natural place (as `ls -lR' would have done).
1888With a prefix arg, you may edit the `ls' switches used for this listing.
1889 You can add `R' to the switches to expand the whole tree starting at
1890 this subdirectory.
1891This function takes some pains to conform to `ls -lR' output."
1892 ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
1893 ;; Prospero where dired-ls does the right thing, but
1894 ;; file-directory-p has not been redefined.
1895 (interactive
1896 (list (dired-get-filename)
1897 (if current-prefix-arg
f2260f48
LT
1898 (read-string "Switches for listing: "
1899 (or dired-subdir-switches dired-actual-switches)))))
dd87891b 1900 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
1901 (or no-error-if-not-dir-p
1902 (file-directory-p dirname)
1903 (error "Attempt to insert a non-directory: %s" dirname))
1904 (let ((elt (assoc dirname dired-subdir-alist))
f2260f48
LT
1905 (cons (assoc-string dirname dired-switches-alist))
1906 (modflag (buffer-modified-p))
1907 (old-switches switches)
1908 switches-have-R mark-alist case-fold-search buffer-read-only)
1909 (and (not switches) cons (setq switches (cdr cons)))
1910 (dired-insert-subdir-validate dirname switches)
dd87891b
RS
1911 ;; case-fold-search is nil now, so we can test for capital `R':
1912 (if (setq switches-have-R (and switches (string-match "R" switches)))
1913 ;; avoid duplicated subdirs
1914 (setq mark-alist (dired-kill-tree dirname t)))
1915 (if elt
1916 ;; If subdir is already present, remove it and remember its marks
1917 (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
1918 (dired-insert-subdir-newpos dirname)) ; else compute new position
1919 (dired-insert-subdir-doupdate
1920 dirname elt (dired-insert-subdir-doinsert dirname switches))
f2260f48
LT
1921 (when old-switches
1922 (if cons
1923 (setcdr cons switches)
1924 (push (cons dirname switches) dired-switches-alist)))
1925 (when switches-have-R
1926 (dired-build-subdir-alist switches)
081e4397 1927 (setq switches (dired-replace-in-string "R" "" switches))
f2260f48
LT
1928 (dolist (cur-ass dired-subdir-alist)
1929 (let ((cur-dir (car cur-ass)))
1930 (and (dired-in-this-tree cur-dir dirname)
f2260f48
LT
1931 (let ((cur-cons (assoc-string cur-dir dired-switches-alist)))
1932 (if cur-cons
1933 (setcdr cur-cons switches)
1934 (push (cons cur-dir switches) dired-switches-alist)))))))
dd87891b 1935 (dired-initial-position dirname)
f2260f48
LT
1936 (save-excursion (dired-mark-remembered mark-alist))
1937 (restore-buffer-modified-p modflag)))
dd87891b
RS
1938
1939;; This is a separate function for dired-vms.
1940(defun dired-insert-subdir-validate (dirname &optional switches)
1941 ;; Check that it is valid to insert DIRNAME with SWITCHES.
1942 ;; Signal an error if invalid (e.g. user typed `i' on `..').
d443f37c 1943 (or (dired-in-this-tree dirname (expand-file-name default-directory))
dd87891b 1944 (error "%s: not in this directory tree" dirname))
f2260f48
LT
1945 (let ((real-switches (or switches dired-subdir-switches)))
1946 (when real-switches
dd87891b
RS
1947 (let (case-fold-search)
1948 (mapcar
1949 (function
1950 (lambda (x)
f2260f48 1951 (or (eq (null (string-match x real-switches))
dd87891b 1952 (null (string-match x dired-actual-switches)))
f2260f48
LT
1953 (error
1954 "Can't have dirs with and without -%s switches together" x))))
dd87891b 1955 ;; all switches that make a difference to dired-get-filename:
f2260f48 1956 '("F" "b"))))))
dd87891b
RS
1957
1958(defun dired-alist-add (dir new-marker)
1959 ;; Add new DIR at NEW-MARKER. Sort alist.
1960 (dired-alist-add-1 dir new-marker)
1961 (dired-alist-sort))
1962
1963(defun dired-alist-sort ()
1964 ;; Keep the alist sorted on buffer position.
1965 (setq dired-subdir-alist
1966 (sort dired-subdir-alist
1967 (function (lambda (elt1 elt2)
1968 (> (dired-get-subdir-min elt1)
1969 (dired-get-subdir-min elt2)))))))
1970
0a07c3a9 1971(defun dired-kill-tree (dirname &optional remember-marks kill-root)
616e14f4 1972 "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
0a07c3a9
LT
1973Interactively, you can kill DIRNAME as well by using a prefix argument.
1974In interactive use, the command prompts for DIRNAME.
1975
1976When called from Lisp, if REMEMBER-MARKS is non-nil, return an alist
1977of marked files. If KILL-ROOT is non-nil, kill DIRNAME as well."
1978 (interactive "DKill tree below directory: \ni\nP")
1979 (setq dirname (file-name-as-directory (expand-file-name dirname)))
dd87891b
RS
1980 (let ((s-alist dired-subdir-alist) dir m-alist)
1981 (while s-alist
1982 (setq dir (car (car s-alist))
1983 s-alist (cdr s-alist))
0a07c3a9
LT
1984 (and (or kill-root (not (string-equal dir dirname)))
1985 (dired-in-this-tree dir dirname)
1986 (dired-goto-subdir dir)
1987 (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
dd87891b
RS
1988 m-alist))
1989
1990(defun dired-insert-subdir-newpos (new-dir)
1991 ;; Find pos for new subdir, according to tree order.
1992 ;;(goto-char (point-max))
1993 (let ((alist dired-subdir-alist) elt dir pos new-pos)
1994 (while alist
1995 (setq elt (car alist)
1996 alist (cdr alist)
1997 dir (car elt)
1998 pos (dired-get-subdir-min elt))
1999 (if (dired-tree-lessp dir new-dir)
2000 ;; Insert NEW-DIR after DIR
2001 (setq new-pos (dired-get-subdir-max elt)
2002 alist nil)))
2003 (goto-char new-pos))
2004 ;; want a separating newline between subdirs
2005 (or (eobp)
2006 (forward-line -1))
2007 (insert "\n")
2008 (point))
2009
2010(defun dired-insert-subdir-del (element)
2011 ;; Erase an already present subdir (given by ELEMENT) from buffer.
2012 ;; Move to that buffer position. Return a mark-alist.
2013 (let ((begin-marker (dired-get-subdir-min element)))
2014 (goto-char begin-marker)
2015 ;; Are at beginning of subdir (and inside it!). Now determine its end:
2016 (goto-char (dired-subdir-max))
2017 (or (eobp);; want a separating newline _between_ subdirs:
2018 (forward-char -1))
2019 (prog1
2020 (dired-remember-marks begin-marker (point))
2021 (delete-region begin-marker (point)))))
2022
2023(defun dired-insert-subdir-doinsert (dirname switches)
e5369aad 2024 ;; Insert ls output after point.
dd87891b 2025 ;; Return the boundary of the inserted text (as list of BEG and END).
349254d3
AS
2026 (save-excursion
2027 (let ((begin (point)))
349254d3
AS
2028 (let ((dired-actual-switches
2029 (or switches
f2260f48 2030 dired-subdir-switches
349254d3
AS
2031 (dired-replace-in-string "R" "" dired-actual-switches))))
2032 (if (equal dirname (car (car (last dired-subdir-alist))))
2033 ;; If doing the top level directory of the buffer,
2034 ;; redo it as specified in dired-directory.
2035 (dired-readin-insert)
2036 (dired-insert-directory dirname dired-actual-switches nil nil t)))
349254d3 2037 (list begin (point)))))
dd87891b
RS
2038
2039(defun dired-insert-subdir-doupdate (dirname elt beg-end)
2040 ;; Point is at the correct subdir alist position for ELT,
2041 ;; BEG-END is the subdir-region (as list of begin and end).
2042 (if elt ; subdir was already present
2043 ;; update its position (should actually be unchanged)
2044 (set-marker (dired-get-subdir-min elt) (point-marker))
2045 (dired-alist-add dirname (point-marker)))
2046 ;; The hook may depend on the subdir-alist containing the just
2047 ;; inserted subdir, so run it after dired-alist-add:
2048 (if dired-after-readin-hook
2049 (save-excursion
2050 (let ((begin (nth 0 beg-end))
2051 (end (nth 1 beg-end)))
2052 (goto-char begin)
2053 (save-restriction
2054 (narrow-to-region begin end)
2055 ;; hook may add or delete lines, but the subdir boundary
2056 ;; marker floats
2057 (run-hooks 'dired-after-readin-hook))))))
2058
2059(defun dired-tree-lessp (dir1 dir2)
57dabf6b 2060 ;; Lexicographic order on file name components, like `ls -lR':
4837b516
GM
2061 ;; DIR1 < DIR2 if DIR1 comes *before* DIR2 in an `ls -lR' listing,
2062 ;; i.e., if DIR1 is a (grand)parent dir of DIR2,
dd87891b
RS
2063 ;; or DIR1 and DIR2 are in the same parentdir and their last
2064 ;; components are string-lessp.
2065 ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
2066 ;; string-lessp could arguably be replaced by file-newer-than-file-p
2067 ;; if dired-actual-switches contained `t'.
2068 (setq dir1 (file-name-as-directory dir1)
2069 dir2 (file-name-as-directory dir2))
2070 (let ((components-1 (dired-split "/" dir1))
2071 (components-2 (dired-split "/" dir2)))
2072 (while (and components-1
2073 components-2
2074 (equal (car components-1) (car components-2)))
2075 (setq components-1 (cdr components-1)
2076 components-2 (cdr components-2)))
2077 (let ((c1 (car components-1))
2078 (c2 (car components-2)))
2079
2080 (cond ((and c1 c2)
2081 (string-lessp c1 c2))
2082 ((and (null c1) (null c2))
2083 nil) ; they are equal, not lessp
2084 ((null c1) ; c2 is a subdir of c1: c1<c2
2085 t)
2086 ((null c2) ; c1 is a subdir of c2: c1>c2
2087 nil)
2088 (t (error "This can't happen"))))))
2089
2090;; There should be a builtin split function - inverse to mapconcat.
2091(defun dired-split (pat str &optional limit)
2092 "Splitting on regexp PAT, turn string STR into a list of substrings.
2093Optional third arg LIMIT (>= 1) is a limit to the length of the
2094resulting list.
2095Thus, if SEP is a regexp that only matches itself,
2096
2097 (mapconcat 'identity (dired-split SEP STRING) SEP)
2098
2099is always equal to STRING."
2100 (let* ((start (string-match pat str))
2101 (result (list (substring str 0 start)))
2102 (count 1)
2103 (end (if start (match-end 0))))
2104 (if end ; else nothing left
2105 (while (and (or (not (integerp limit))
2106 (< count limit))
2107 (string-match pat str end))
2108 (setq start (match-beginning 0)
2109 count (1+ count)
2110 result (cons (substring str end start) result)
2111 end (match-end 0)
2112 start end)
2113 ))
2114 (if (and (or (not (integerp limit))
2115 (< count limit))
2116 end) ; else nothing left
2117 (setq result
2118 (cons (substring str end) result)))
2119 (nreverse result)))
83fadedf 2120\f
dd87891b
RS
2121;;; moving by subdirectories
2122
dd87891b
RS
2123;;;###autoload
2124(defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
2125 "Go to previous subdirectory, regardless of level.
2126When called interactively and not on a subdir line, go to this subdir's line."
2127 ;;(interactive "p")
2128 (interactive
2129 (list (if current-prefix-arg
2130 (prefix-numeric-value current-prefix-arg)
2131 ;; if on subdir start already, don't stay there!
2132 (if (dired-get-subdir) 1 0))))
2133 (dired-next-subdir (- arg) no-error-if-not-found no-skip))
2134
2135(defun dired-subdir-min ()
2136 (save-excursion
2137 (if (not (dired-prev-subdir 0 t t))
2138 (error "Not in a subdir!")
2139 (point))))
2140
2141;;;###autoload
2142(defun dired-goto-subdir (dir)
2143 "Go to end of header line of DIR in this dired buffer.
2144Return value of point on success, otherwise return nil.
2145The next char is either \\n, or \\r if DIR is hidden."
2146 (interactive
2147 (prog1 ; let push-mark display its message
2148 (list (expand-file-name
2149 (completing-read "Goto in situ directory: " ; prompt
2150 dired-subdir-alist ; table
2151 nil ; predicate
2152 t ; require-match
2153 (dired-current-directory))))
2154 (push-mark)))
2155 (setq dir (file-name-as-directory dir))
2156 (let ((elt (assoc dir dired-subdir-alist)))
2157 (and elt
2158 (goto-char (dired-get-subdir-min elt))
2159 ;; dired-subdir-hidden-p and dired-add-entry depend on point being
2160 ;; at either \r or \n after this function succeeds.
2161 (progn (skip-chars-forward "^\r\n")
2162 (point)))))
83fadedf 2163\f
dd87891b
RS
2164;;;###autoload
2165(defun dired-mark-subdir-files ()
472974e9
RS
2166 "Mark all files except `.' and `..' in current subdirectory.
2167If the Dired buffer shows multiple directories, this command
2168marks the files listed in the subdirectory that point is in."
96149b57 2169 (interactive)
dd87891b
RS
2170 (let ((p-min (dired-subdir-min)))
2171 (dired-mark-files-in-region p-min (dired-subdir-max))))
2172
2173;;;###autoload
2174(defun dired-kill-subdir (&optional remember-marks)
2175 "Remove all lines of current subdirectory.
2176Lower levels are unaffected."
2177 ;; With optional REMEMBER-MARKS, return a mark-alist.
2178 (interactive)
f2260f48
LT
2179 (let* ((beg (dired-subdir-min))
2180 (end (dired-subdir-max))
2181 (modflag (buffer-modified-p))
2182 (cur-dir (dired-current-directory))
2183 (cons (assoc-string cur-dir dired-switches-alist))
2184 buffer-read-only)
dd87891b
RS
2185 (if (equal cur-dir default-directory)
2186 (error "Attempt to kill top level directory"))
2187 (prog1
2188 (if remember-marks (dired-remember-marks beg end))
2189 (delete-region beg end)
2190 (if (eobp) ; don't leave final blank line
2191 (delete-char -1))
f2260f48
LT
2192 (dired-unsubdir cur-dir)
2193 (when cons
2194 (setq dired-switches-alist (delete cons dired-switches-alist)))
2195 (restore-buffer-modified-p modflag))))
dd87891b
RS
2196
2197(defun dired-unsubdir (dir)
2198 ;; Remove DIR from the alist
2199 (setq dired-subdir-alist
2200 (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
2201
2202;;;###autoload
2203(defun dired-tree-up (arg)
2204 "Go up ARG levels in the dired tree."
2205 (interactive "p")
2206 (let ((dir (dired-current-directory)))
2207 (while (>= arg 1)
2208 (setq arg (1- arg)
2209 dir (file-name-directory (directory-file-name dir))))
2210 ;;(setq dir (expand-file-name dir))
2211 (or (dired-goto-subdir dir)
55535639 2212 (error "Cannot go up to %s - not in this tree" dir))))
dd87891b
RS
2213
2214;;;###autoload
2215(defun dired-tree-down ()
2216 "Go down in the dired tree."
2217 (interactive)
2218 (let ((dir (dired-current-directory)) ; has slash
2219 pos case-fold-search) ; filenames are case sensitive
2220 (let ((rest (reverse dired-subdir-alist)) elt)
2221 (while rest
2222 (setq elt (car rest)
2223 rest (cdr rest))
2224 (if (dired-in-this-tree (directory-file-name (car elt)) dir)
2225 (setq rest nil
2226 pos (dired-goto-subdir (car elt))))))
2227 (if pos
2228 (goto-char pos)
2229 (error "At the bottom"))))
83fadedf 2230\f
dd87891b
RS
2231;;; hiding
2232
2233(defun dired-unhide-subdir ()
2234 (let (buffer-read-only)
2235 (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
2236
2237(defun dired-hide-check ()
2238 (or selective-display
2239 (error "selective-display must be t for subdir hiding to work!")))
2240
2241(defun dired-subdir-hidden-p (dir)
2242 (and selective-display
2243 (save-excursion
2244 (dired-goto-subdir dir)
2245 (looking-at "\r"))))
2246
2247;;;###autoload
2248(defun dired-hide-subdir (arg)
2249 "Hide or unhide the current subdirectory and move to next directory.
2250Optional prefix arg is a repeat factor.
2251Use \\[dired-hide-all] to (un)hide all directories."
2252 (interactive "p")
2253 (dired-hide-check)
f2260f48
LT
2254 (let ((modflag (buffer-modified-p)))
2255 (while (>= (setq arg (1- arg)) 0)
2256 (let* ((cur-dir (dired-current-directory))
2257 (hidden-p (dired-subdir-hidden-p cur-dir))
2258 (elt (assoc cur-dir dired-subdir-alist))
2259 (end-pos (1- (dired-get-subdir-max elt)))
2260 buffer-read-only)
2261 ;; keep header line visible, hide rest
2262 (goto-char (dired-get-subdir-min elt))
2263 (skip-chars-forward "^\n\r")
2264 (if hidden-p
2265 (subst-char-in-region (point) end-pos ?\r ?\n)
2266 (subst-char-in-region (point) end-pos ?\n ?\r)))
2267 (dired-next-subdir 1 t))
2268 (restore-buffer-modified-p modflag)))
dd87891b
RS
2269
2270;;;###autoload
2271(defun dired-hide-all (arg)
2272 "Hide all subdirectories, leaving only their header lines.
2273If there is already something hidden, make everything visible again.
2274Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
2275 (interactive "P")
2276 (dired-hide-check)
f2260f48
LT
2277 (let ((modflag (buffer-modified-p))
2278 buffer-read-only)
dd87891b
RS
2279 (if (save-excursion
2280 (goto-char (point-min))
2281 (search-forward "\r" nil t))
2282 ;; unhide - bombs on \r in filenames
2283 (subst-char-in-region (point-min) (point-max) ?\r ?\n)
2284 ;; hide
2285 (let ((pos (point-max)) ; pos of end of last directory
2286 (alist dired-subdir-alist))
f2260f48 2287 (while alist ; while there are dirs before pos
dd87891b
RS
2288 (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
2289 (save-excursion
2290 (goto-char pos) ; current dir
2291 ;; we're somewhere on current dir's line
2292 (forward-line -1)
2293 (point))
2294 ?\n ?\r)
2295 (setq pos (dired-get-subdir-min (car alist))) ; prev dir gets current dir
f2260f48
LT
2296 (setq alist (cdr alist)))))
2297 (restore-buffer-modified-p modflag)))
dd87891b
RS
2298
2299;;;###end dired-ins.el
2f14b48d 2300
83fadedf 2301\f
b4b6bda2
JL
2302;; Search only in file names in the Dired buffer.
2303
2304(defcustom dired-isearch-filenames nil
2305 "*If non-nil, Isearch in Dired matches only file names."
2306 :type '(choice (const :tag "No restrictions" nil)
2307 (const :tag "Isearch only in file names" dired-filename))
2308 :group 'dired
2309 :version "23.1")
2310
2311(defvar dired-isearch-orig-success-function nil)
2312
2313(defun dired-isearch-filenames-setup ()
2314 "Set up isearch to search in Dired file names.
2315Intended to be added to `isearch-mode-hook'."
2316 (when dired-isearch-filenames
2317 (setq dired-isearch-orig-success-function
2318 (default-value 'isearch-success-function))
2319 (setq-default isearch-success-function 'dired-isearch-success-function)
2320 (add-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end nil t)))
2321
2322(defun dired-isearch-filenames-end ()
2323 "Clean up the Dired file name search after terminating isearch."
2324 (setq-default isearch-success-function dired-isearch-orig-success-function)
2325 (remove-hook 'isearch-mode-end-hook 'dired-isearch-filenames-end t))
2326
2327(defun dired-isearch-success-function (beg end)
2328 "Match only at visible regions with the text property `dired-filename'."
2329 (and (isearch-success-function-default beg end)
2330 (if dired-isearch-filenames
2331 (text-property-not-all (min beg end) (max beg end)
2332 'dired-filename nil)
2333 t)))
2334
2335;;;###autoload
2336(defun dired-isearch-filenames ()
2337 "Search for a string using Isearch only in file names in the Dired buffer."
2338 (interactive)
2339 (let ((dired-isearch-filenames t))
2340 (isearch-forward)))
2341
2342;;;###autoload
2343(defun dired-isearch-filenames-regexp ()
2344 "Search for a regexp using Isearch only in file names in the Dired buffer."
2345 (interactive)
2346 (let ((dired-isearch-filenames t))
2347 (isearch-forward-regexp)))
2348
2349\f
2297e912
RM
2350;; Functions for searching in tags style among marked files.
2351
160c8be6
JL
2352;;;###autoload
2353(defun dired-do-isearch ()
2354 "Search for a string through all marked files using Isearch."
2355 (interactive)
2356 (multi-isearch-files
2357 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2358
2359;;;###autoload
2360(defun dired-do-isearch-regexp ()
2361 "Search for a regexp through all marked files using Isearch."
2362 (interactive)
2363 (multi-isearch-files-regexp
2364 (dired-get-marked-files nil nil 'dired-nondirectory-p)))
2365
2297e912 2366;;;###autoload
5c0b696b 2367(defun dired-do-search (regexp)
2297e912
RM
2368 "Search through all marked files for a match for REGEXP.
2369Stops when a match is found.
2370To continue searching for next match, use command \\[tags-loop-continue]."
2371 (interactive "sSearch marked files (regexp): ")
5e514c27 2372 (tags-search regexp '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2297e912
RM
2373
2374;;;###autoload
be3981a8 2375(defun dired-do-query-replace-regexp (from to &optional delimited)
5c0b696b 2376 "Do `query-replace-regexp' of FROM with TO, on all marked files.
2297e912 2377Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
e5374284 2378If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
2297e912
RM
2379with the command \\[tags-loop-continue]."
2380 (interactive
0751a704
JL
2381 (let ((common
2382 (query-replace-read-args
2383 "Query replace regexp in marked files" t t)))
2384 (list (nth 0 common) (nth 1 common) (nth 2 common))))
d1c553c8
RS
2385 (dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
2386 (let ((buffer (get-file-buffer file)))
2387 (if (and buffer (with-current-buffer buffer
2388 buffer-read-only))
60a8f928 2389 (error "File `%s' is visited read-only" file))))
5e514c27
RS
2390 (tags-query-replace from to delimited
2391 '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
2392
2393(defun dired-nondirectory-p (file)
2394 (not (file-directory-p file)))
83fadedf 2395\f
ee6be958
MB
2396;;;###autoload
2397(defun dired-show-file-type (file &optional deref-symlinks)
2398 "Print the type of FILE, according to the `file' command.
2399If FILE is a symbolic link and the optional argument DEREF-SYMLINKS is
edb8d73e 2400true then the type of the file linked to by FILE is printed instead."
ee6be958 2401 (interactive (list (dired-get-filename t) current-prefix-arg))
edb8d73e 2402 (with-temp-buffer
ee6be958 2403 (if deref-symlinks
384bcc64
RS
2404 (call-process "file" nil t t "-L" "--" file)
2405 (call-process "file" nil t t "--" file))
ee6be958
MB
2406 (when (bolp)
2407 (backward-delete-char 1))
6de40a0c 2408 (message "%s" (buffer-string))))
2297e912 2409
80ec9ac5
RS
2410(provide 'dired-aux)
2411
cbee283d 2412;; arch-tag: 4b508de9-a153-423d-8d3f-a1bbd86f4f60
e5167999 2413;;; dired-aux.el ends here