dired-aux.el 124 KB
Newer Older
1
;;; dired-aux.el --- less commonly used parts of dired -*- lexical-binding: t -*-
Richard M. Stallman's avatar
Richard M. Stallman committed
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1985-1986, 1992, 1994, 1998, 2000-2020 Free Software
Paul Eggert's avatar
Paul Eggert committed
4
;; Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
5

Eric S. Raymond's avatar
Eric S. Raymond committed
6
;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.
7
;; Maintainer: emacs-devel@gnu.org
Gerd Moellmann's avatar
Gerd Moellmann committed
8
;; Keywords: files
9
;; Package: emacs
Eric S. Raymond's avatar
Eric S. Raymond committed
10

Richard M. Stallman's avatar
Richard M. Stallman committed
11 12
;; This file is part of GNU Emacs.

13
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
14
;; it under the terms of the GNU General Public License as published by
15 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
17 18 19 20 21 22 23

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
24
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
25

Eric S. Raymond's avatar
Eric S. Raymond committed
26 27
;;; Commentary:

28 29 30 31
;; The parts of dired mode not normally used.  This is a space-saving hack
;; to avoid having to load a large mode when all that's wanted are a few
;; functions.

Richard M. Stallman's avatar
Richard M. Stallman committed
32 33 34 35
;; Rewritten in 1990/1991 to add tree features, file marking and
;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
;; Finished up by rms in 1992.

Eric S. Raymond's avatar
Eric S. Raymond committed
36 37
;;; Code:

38
(require 'cl-lib)
39 40 41
;; We need macros in dired.el to compile properly,
;; and we call subroutines in it too.
(require 'dired)
42

43 44 45 46 47
(defvar dired-create-files-failures nil
  "Variable where `dired-create-files' records failing file names.
Functions that operate recursively can store additional names
into this list; they also should call `dired-log' to log the errors.")

Richard M. Stallman's avatar
Richard M. Stallman committed
48 49 50 51
;;; 15K
;;;###begin dired-cmd.el
;; Diffing and compressing

52 53
(defconst dired-star-subst-regexp "\\(^\\|[ \t]\\)\\*\\([ \t]\\|$\\)")
(defconst dired-quark-subst-regexp "\\(^\\|[ \t]\\)\\?\\([ \t]\\|$\\)")
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
(make-obsolete-variable 'dired-star-subst-regexp nil "26.1")
(make-obsolete-variable 'dired-quark-subst-regexp nil "26.1")

(defun dired-isolated-string-re (string)
  "Return a regexp to match STRING isolated.
Isolated means that STRING is surrounded by spaces or at the beginning/end
of a string followed/prefixed with an space.
The regexp capture the preceding blank, STRING and the following blank as
the groups 1, 2 and 3 respectively."
  (format "\\(\\`\\|[ \t]\\)\\(%s\\)\\([ \t]\\|\\'\\)" string))

(defun dired--star-or-qmark-p (string match &optional keep)
  "Return non-nil if STRING contains isolated MATCH or `\\=`?\\=`'.
MATCH should be the strings \"?\", `\\=`?\\=`', \"*\" or nil.  The latter
means STRING contains either \"?\" or `\\=`?\\=`' or \"*\".
If optional arg KEEP is non-nil, then preserve the match data.  Otherwise,
this function changes it and saves MATCH as the second match group.

Isolated means that MATCH is surrounded by spaces or at the beginning/end
of STRING followed/prefixed with an space.  A match to `\\=`?\\=`',
isolated or not, is also valid."
  (let ((regexps (list (dired-isolated-string-re (if match (regexp-quote match) "[*?]")))))
    (when (or (null match) (equal match "?"))
      (setq regexps (append (list "\\(\\)\\(`\\?`\\)\\(\\)") regexps)))
    (cl-some (lambda (x)
               (funcall (if keep #'string-match-p #'string-match) x string))
             regexps)))
81

Richard M. Stallman's avatar
Richard M. Stallman committed
82 83
;;;###autoload
(defun dired-diff (file &optional switches)
84 85 86 87 88 89 90 91 92 93 94 95 96 97
  "Compare file at point with FILE using `diff'.
If called interactively, prompt for FILE.
If the mark is active in Transient Mark mode, use the file at the mark
as the default for FILE.  (That's the mark set by \\[set-mark-command],
not by Dired's \\[dired-mark] command.)
If the file at point has a backup file, use that as the default FILE.
If the file at point is a backup file, use its original, if that exists
and can be found.  Note that customizations of `backup-directory-alist'
and `make-backup-file-name-function' change where this function searches
for the backup file, and affect its ability to find the original of a
backup file.

FILE is the first argument given to the `diff' function.  The file at
point is the second argument given to `diff'.
Chong Yidong's avatar
Chong Yidong committed
98

99
With prefix arg, prompt for second argument SWITCHES, which is
100
the string of command switches used as the third argument of `diff'."
Richard M. Stallman's avatar
Richard M. Stallman committed
101
  (interactive
102
   (let* ((current (dired-get-filename t))
103 104 105 106
	  ;; Get the latest existing backup file or its original.
	  (oldf (if (backup-file-name-p current)
		    (file-name-sans-versions current)
		  (diff-latest-backup-file current)))
107 108 109 110
	  ;; Get the file at the mark.
	  (file-at-mark (if (and transient-mark-mode mark-active)
			    (save-excursion (goto-char (mark t))
					    (dired-get-filename t t))))
111 112 113
          (separate-dir (and oldf
                             (not (equal (file-name-directory oldf)
                                         (dired-current-directory)))))
114
	  (default-file (or file-at-mark
115 116 117 118 119 120 121 122 123 124
                            ;; If the file with which to compare
                            ;; doesn't exist, or we cannot intuit it,
                            ;; we forget that name and don't show it
                            ;; as the default, as an indication to the
                            ;; user that she should type the file
                            ;; name.
			    (and (if (and oldf (file-readable-p oldf)) oldf)
                                 (if separate-dir
                                     oldf
                                   (file-name-nondirectory oldf)))))
125 126 127 128 129 130 131 132
	  ;; Use it as default if it's not the same as the current file,
	  ;; and the target dir is current or there is a default file.
	  (default (if (and (not (equal default-file current))
			    (or (equal (dired-dwim-target-directory)
				       (dired-current-directory))
				default-file))
		       default-file))
	  (target-dir (if default
133 134 135
                          (if separate-dir
                              (file-name-directory default)
                            (dired-current-directory))
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
			(dired-dwim-target-directory)))
	  (defaults (dired-dwim-target-defaults (list current) target-dir)))
     (list
      (minibuffer-with-setup-hook
	  (lambda ()
	    (set (make-local-variable 'minibuffer-default-add-function) nil)
	    (setq minibuffer-default defaults))
	(read-file-name
	 (format "Diff %s with%s: " current
		 (if default (format " (default %s)" default) ""))
	 target-dir default t))
      (if current-prefix-arg
	  (read-string "Options for diff: "
		       (if (stringp diff-switches)
			   diff-switches
151
			 (mapconcat #'identity diff-switches " ")))))))
152 153 154 155 156 157 158
  (let ((current (dired-get-filename t)))
    (when (or (equal (expand-file-name file)
		     (expand-file-name current))
	      (and (file-directory-p file)
		   (equal (expand-file-name current file)
			  (expand-file-name current))))
      (error "Attempt to compare the file to itself"))
159 160 161 162
    (if (and (backup-file-name-p current)
	     (equal file (file-name-sans-versions current)))
	(diff current file switches)
      (diff file current switches))))
Richard M. Stallman's avatar
Richard M. Stallman committed
163 164 165 166 167 168

;;;###autoload
(defun dired-backup-diff (&optional switches)
  "Diff this file with its backup file or vice versa.
Uses the latest backup, if there are several numerical backups.
If this file is a backup, diff it with its original.
169 170 171 172 173 174 175
The backup file is the first file given to `diff'.
With prefix arg, prompt for argument SWITCHES which is options for `diff'."
  (interactive
    (if current-prefix-arg
	(list (read-string "Options for diff: "
			   (if (stringp diff-switches)
			       diff-switches
176
			     (mapconcat #'identity diff-switches " "))))
177 178
      nil))
  (diff-backup (dired-get-filename) switches))
Richard M. Stallman's avatar
Richard M. Stallman committed
179

180
;;;###autoload
181 182 183 184 185
(defun dired-compare-directories (dir2 predicate)
  "Mark files with different file attributes in two dired buffers.
Compare file attributes of files in the current directory
with file attributes in directory DIR2 using PREDICATE on pairs of files
with the same name.  Mark files for which PREDICATE returns non-nil.
186
Mark files with different names if PREDICATE is nil (or interactively
187
with empty input at the predicate prompt).
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

PREDICATE is a Lisp expression that can refer to the following variables:

    size1, size2   - file size in bytes
    mtime1, mtime2 - last modification time in seconds, as a float
    fa1, fa2       - list of file attributes
                     returned by function `file-attributes'

    where 1 refers to attribute of file in the current dired buffer
    and 2 to attribute of file in second dired buffer.

Examples of PREDICATE:

    (> mtime1 mtime2) - mark newer files
    (not (= size1 size2)) - mark files with different sizes
Paul Eggert's avatar
Paul Eggert committed
203 204 205 206 207
    (not (string= (file-attribute-modes fa1)  - mark files with different modes
                  (file-attribute-modes fa2)))
    (not (and (= (file-attribute-user-id fa1) - mark files with different UID
                 (file-attribute-user-id fa2))
              (= (file-attribute-group-id fa1) - and GID.
208 209 210 211
                 (file-attribute-group-id fa2))))

If the region is active in Transient Mark mode, mark files
only in the active region if `dired-mark-region' is non-nil."
212
  (interactive
213 214 215 216 217 218 219 220 221 222 223
   (list
    (let* ((target-dir (dired-dwim-target-directory))
	   (defaults (dired-dwim-target-defaults nil target-dir)))
      (minibuffer-with-setup-hook
	  (lambda ()
	    (set (make-local-variable 'minibuffer-default-add-function) nil)
	    (setq minibuffer-default defaults))
	(read-directory-name (format "Compare %s with: "
				     (dired-current-directory))
			     target-dir target-dir t)))
    (read-from-minibuffer "Mark if (lisp expr or RET): " nil nil t nil "nil")))
224 225 226
  (let* ((dir1 (dired-current-directory))
         (file-alist1 (dired-files-attributes dir1))
         (file-alist2 (dired-files-attributes dir2))
227 228 229 230 231 232
	 file-list1 file-list2)
    (setq file-alist1 (delq (assoc "." file-alist1) file-alist1))
    (setq file-alist1 (delq (assoc ".." file-alist1) file-alist1))
    (setq file-alist2 (delq (assoc "." file-alist2) file-alist2))
    (setq file-alist2 (delq (assoc ".." file-alist2) file-alist2))
    (setq file-list1 (mapcar
233
		      #'cadr
234 235
                      (dired-file-set-difference
                       file-alist1 file-alist2
236 237
		       predicate))
	  file-list2 (mapcar
238
		      #'cadr
239 240
                      (dired-file-set-difference
                       file-alist2 file-alist1
241
		       predicate)))
242 243 244 245 246 247 248 249 250 251
    (dired-fun-in-all-buffers
     dir1 nil
     (lambda ()
       (dired-mark-if
        (member (dired-get-filename nil t) file-list1) nil)))
    (dired-fun-in-all-buffers
     dir2 nil
     (lambda ()
       (dired-mark-if
        (member (dired-get-filename nil t) file-list2) nil)))
252 253 254 255 256
    (message "Marked in dir1: %s, in dir2: %s"
             (format-message (ngettext "%d file" "%d files" (length file-list1))
                             (length file-list1))
             (format-message (ngettext "%d file" "%d files" (length file-list2))
                             (length file-list2)))))
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

(defun dired-file-set-difference (list1 list2 predicate)
  "Combine LIST1 and LIST2 using a set-difference operation.
The result list contains all file items that appear in LIST1 but not LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
PREDICATE (see `dired-compare-directories') is an additional match
condition.  Two file items are considered to match if they are equal
*and* PREDICATE evaluates to t."
  (if (or (null list1) (null list2))
      list1
    (let (res)
      (dolist (file1 list1)
	(unless (let ((list list2))
		  (while (and list
272 273 274 275 276 277 278 279
			      (let* ((file2 (car list))
                                     (fa1 (car (cddr file1)))
                                     (fa2 (car (cddr file2))))
                                (or
                                 (not (equal (car file1) (car file2)))
                                 (eval predicate
                                       `((fa1 . ,fa1)
                                         (fa2 . ,fa2)
Paul Eggert's avatar
Paul Eggert committed
280 281
                                         (size1 . ,(file-attribute-size fa1))
                                         (size2 . ,(file-attribute-size fa2))
282
                                         (mtime1
Paul Eggert's avatar
Paul Eggert committed
283
                                          . ,(float-time (file-attribute-modification-time fa1)))
284
                                         (mtime2
Paul Eggert's avatar
Paul Eggert committed
285
                                          . ,(float-time (file-attribute-modification-time fa2)))
286
                                         )))))
287 288
		    (setq list (cdr list)))
		  list)
289
	  (push file1 res)))
290 291 292 293
      (nreverse res))))

(defun dired-files-attributes (dir)
  "Return a list of all file names and attributes from DIR.
Juanma Barranquero's avatar
Juanma Barranquero committed
294
List has a form of (file-name full-file-name (attribute-list))."
295 296 297 298 299 300 301 302
  (mapcar
   (lambda (file-name)
     (let ((full-file-name (expand-file-name file-name dir)))
       (list file-name
             full-file-name
             (file-attributes full-file-name))))
   (directory-files dir)))

303
;;; Change file attributes
Juri Linkov's avatar
Juri Linkov committed
304

Richard M. Stallman's avatar
Richard M. Stallman committed
305
(defun dired-do-chxxx (attribute-name program op-symbol arg)
306
  ;; Change file attributes (group, owner, timestamp) of marked files and
Richard M. Stallman's avatar
Richard M. Stallman committed
307 308 309
  ;; refresh their file lines.
  ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
  ;; PROGRAM is the program used to change the attribute.
310 311
  ;; OP-SYMBOL is the type of operation (for use in `dired-mark-pop-up').
  ;; ARG describes which files to use, as in `dired-get-marked-files'.
312
  (let* ((files (dired-get-marked-files t arg nil nil t))
313
	 ;; The source of default file attributes is the file at point.
314
	 (default-file (dired-get-filename t t))
315 316 317 318
	 (default (when default-file
		    (cond ((eq op-symbol 'touch)
			   (format-time-string
			    "%Y%m%d%H%M.%S"
Paul Eggert's avatar
Paul Eggert committed
319 320
			    (file-attribute-modification-time
			     (file-attributes default-file))))
321
			  ((eq op-symbol 'chown)
Paul Eggert's avatar
Paul Eggert committed
322 323
			   (file-attribute-user-id
			    (file-attributes default-file 'string)))
324
			  ((eq op-symbol 'chgrp)
Paul Eggert's avatar
Paul Eggert committed
325 326
			   (file-attribute-group-id
			    (file-attributes default-file 'string))))))
327 328 329 330 331
	 (prompt (concat "Change " attribute-name " of %s to"
			 (if (eq op-symbol 'touch)
			     " (default now): "
			   ": ")))
	 (new-attribute (dired-mark-read-string prompt nil op-symbol
332 333 334 335 336
						arg files default
						(cond ((eq op-symbol 'chown)
						       (system-users))
						      ((eq op-symbol 'chgrp)
						       (system-groups)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
337
	 (operation (concat program " " new-attribute))
338 339 340 341 342 343 344 345
         ;; When file-name-coding-system is set to something different
         ;; from locale-coding-system, leaving the encoding
         ;; determination to call-process will do the wrong thing,
         ;; because the arguments in this case are file names, not
         ;; just some arbitrary text.  (This must be bound last, to
         ;; avoid adverse effects on any of the preceding forms.)
         (coding-system-for-write (or file-name-coding-system
                                      default-file-name-coding-system))
Richard M. Stallman's avatar
Richard M. Stallman committed
346 347 348
	 failures)
    (setq failures
	  (dired-bunch-files 10000
349
			     #'dired-check-process
350
			     (append
Juri Linkov's avatar
Juri Linkov committed
351
			      (list operation program)
352 353 354 355
			      (unless (or (string-equal new-attribute "")
					  ;; Use `eq' instead of `equal'
					  ;; to detect empty input (bug#12399).
					  (eq new-attribute default))
356 357 358
				(if (eq op-symbol 'touch)
				    (list "-t" new-attribute)
				  (list new-attribute)))
359
			      (if (string-match-p "gnu" system-configuration)
360
				  '("--") nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
361 362 363 364 365 366 367 368 369 370
			     files))
    (dired-do-redisplay arg);; moves point if ARG is an integer
    (if failures
	(dired-log-summary
	 (format "%s: error" operation)
	 nil))))

;;;###autoload
(defun dired-do-chmod (&optional arg)
  "Change the mode of the marked (or next ARG) files.
371 372 373 374 375 376 377 378 379 380 381
Both octal numeric modes like `644' and symbolic modes like `g+w'
are supported.  Type M-n to pull the file attributes of the file
at point into the minibuffer.

See Info node `(coreutils)File permissions' for more information.
Alternatively, see the man page for \"chmod\", using the command
\\[man] in Emacs.

Note that on MS-Windows only the `w' (write) bit is meaningful:
resetting it makes the file read-only.  Changing any other bit
has no effect on MS-Windows."
Richard M. Stallman's avatar
Richard M. Stallman committed
382
  (interactive "P")
383
  (let* ((files (dired-get-marked-files t arg nil nil t))
384
	 ;; The source of default file attributes is the file at point.
385
	 (default-file (dired-get-filename t t))
386
	 (modestr (when default-file
Paul Eggert's avatar
Paul Eggert committed
387
		    (file-attribute-modes (file-attributes default-file))))
388 389 390 391 392 393 394 395 396
	 (default
	   (and (stringp modestr)
		(string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr)
		(replace-regexp-in-string
		 "-" ""
		 (format "u=%s,g=%s,o=%s"
			 (match-string 1 modestr)
			 (match-string 2 modestr)
			 (match-string 3 modestr)))))
397
	 (modes (dired-mark-read-string
398
		 "Change mode of %s to: "
399
		 nil 'chmod arg files default))
400
	 num-modes)
401 402 403 404
    (cond ((or (equal modes "")
	       ;; Use `eq' instead of `equal'
	       ;; to detect empty input (bug#12399).
	       (eq modes default))
405 406 407
	   ;; We used to treat empty input as DEFAULT, but that is not
	   ;; such a good idea (Bug#9361).
	   (error "No file mode specified"))
408
	  ((string-match-p "^[0-7]+" modes)
409 410
	   (setq num-modes (string-to-number modes 8))))

411 412 413 414
    (dolist (file files)
      (set-file-modes
       file
       (if num-modes num-modes
415 416
	 (file-modes-symbolic-to-number modes (file-modes file 'nofollow)))
       'nofollow))
417
    (dired-do-redisplay arg)))
Richard M. Stallman's avatar
Richard M. Stallman committed
418 419 420

;;;###autoload
(defun dired-do-chgrp (&optional arg)
421 422 423
  "Change the group of the marked (or next ARG) files.
Type M-n to pull the file attributes of the file at point
into the minibuffer."
Richard M. Stallman's avatar
Richard M. Stallman committed
424
  (interactive "P")
425 426
  (if (and (memq system-type '(ms-dos windows-nt))
           (not (file-remote-p default-directory)))
427
      (error "chgrp not supported on this system"))
Richard M. Stallman's avatar
Richard M. Stallman committed
428 429 430 431
  (dired-do-chxxx "Group" "chgrp" 'chgrp arg))

;;;###autoload
(defun dired-do-chown (&optional arg)
432 433 434
  "Change the owner of the marked (or next ARG) files.
Type M-n to pull the file attributes of the file at point
into the minibuffer."
Richard M. Stallman's avatar
Richard M. Stallman committed
435
  (interactive "P")
436 437
  (if (and (memq system-type '(ms-dos windows-nt))
           (not (file-remote-p default-directory)))
438
      (error "chown not supported on this system"))
Richard M. Stallman's avatar
Richard M. Stallman committed
439 440
  (dired-do-chxxx "Owner" dired-chown-program 'chown arg))

441
;;;###autoload
Juri Linkov's avatar
Juri Linkov committed
442 443
(defun dired-do-touch (&optional arg)
  "Change the timestamp of the marked (or next ARG) files.
444 445 446
This calls touch.
Type M-n to pull the file attributes of the file at point
into the minibuffer."
Juri Linkov's avatar
Juri Linkov committed
447 448 449
  (interactive "P")
  (dired-do-chxxx "Timestamp" dired-touch-program 'touch arg))

Richard M. Stallman's avatar
Richard M. Stallman committed
450 451 452 453 454 455
;; Process all the files in FILES in batches of a convenient size,
;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).
;; Batches are chosen to need less than MAX chars for the file names,
;; allowing 3 extra characters of separator per file name.
(defun dired-bunch-files (max function args files)
  (let (pending
456
	past
Richard M. Stallman's avatar
Richard M. Stallman committed
457 458 459 460 461 462 463 464 465 466 467
	(pending-length 0)
	failures)
    ;; Accumulate files as long as they fit in MAX chars,
    ;; then process the ones accumulated so far.
    (while files
      (let* ((thisfile (car files))
	     (thislength (+ (length thisfile) 3))
	     (rest (cdr files)))
	;; If we have at least 1 pending file
	;; and this file won't fit in the length limit, process now.
	(if (and pending (> (+ thislength pending-length) max))
468 469 470 471 472
	    (setq pending (nreverse pending)
		  ;; The elements of PENDING are now in forward order.
		  ;; Do the operation and record failures.
		  failures (nconc (apply function (append args pending))
				  failures)
Paul Eggert's avatar
Paul Eggert committed
473
		  ;; Transfer the elements of PENDING onto PAST
474 475 476
		  ;; and clear it out.  Now PAST contains the first N files
		  ;; specified (for some N), and FILES contains the rest.
		  past (nconc past pending)
Richard M. Stallman's avatar
Richard M. Stallman committed
477 478 479 480 481 482 483 484
		  pending nil
		  pending-length 0))
	;; Do (setq pending (cons thisfile pending))
	;; but reuse the cons that was in `files'.
	(setcdr files pending)
	(setq pending files)
	(setq pending-length (+ thislength pending-length))
	(setq files rest)))
485 486 487 488 489 490
    (setq pending (nreverse pending))
    (prog1
	(nconc (apply function (append args pending))
	       failures)
      ;; Now the original list FILES has been put back as it was.
      (nconc past pending))))
Richard M. Stallman's avatar
Richard M. Stallman committed
491

492 493
(defvar lpr-printer-switch)

Richard M. Stallman's avatar
Richard M. Stallman committed
494 495 496 497 498 499
;;;###autoload
(defun dired-do-print (&optional arg)
  "Print the marked (or next ARG) files.
Uses the shell command coming from variables `lpr-command' and
`lpr-switches' as default."
  (interactive "P")
500
  (require 'lpr)
501
  (let* ((file-list (dired-get-marked-files t arg nil nil t))
502 503 504 505 506 507
	 (lpr-switches
	  (if (and (stringp printer-name)
		   (string< "" printer-name))
	      (cons (concat lpr-printer-switch printer-name)
		    lpr-switches)
	    lpr-switches))
Richard M. Stallman's avatar
Richard M. Stallman committed
508 509
	 (command (dired-mark-read-string
		   "Print %s with: "
510
                   (mapconcat #'identity
511 512 513 514 515
			      (cons lpr-command
				    (if (stringp lpr-switches)
					(list lpr-switches)
				      lpr-switches))
			      " ")
Richard M. Stallman's avatar
Richard M. Stallman committed
516 517 518
		   'print arg file-list)))
    (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))

519
(defun dired-mark-read-string (prompt initial op-symbol arg files
520
			       &optional default-value collection)
521 522 523 524 525
  "Read args for a Dired marked-files command, prompting with PROMPT.
Return the user input (a string).

INITIAL, if non-nil, is the initial minibuffer input.
OP-SYMBOL is an operation symbol (see `dired-no-confirm').
Chong Yidong's avatar
Chong Yidong committed
526 527 528
ARG is normally the prefix argument for the calling command;
it is passed as the first argument to `dired-mark-prompt'.
FILES should be a list of marked files' names.
529

Chong Yidong's avatar
Chong Yidong committed
530 531
Optional arg DEFAULT-VALUE is a default value or list of default
values, passed as the seventh arg to `completing-read'.
532

Chong Yidong's avatar
Chong Yidong committed
533 534
Optional arg COLLECTION is a collection of possible completions,
passed as the second arg to `completing-read'."
535
  (dired-mark-pop-up nil op-symbol files
536
		     'completing-read
537
		     (format prompt (dired-mark-prompt arg files))
538
		     collection nil nil initial nil default-value nil))
Dave Love's avatar
Dave Love committed
539

540 541
;;; Cleaning a directory: flagging some backups for deletion.

542 543
(defvar dired-file-version-alist)

544
;;;###autoload
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
(defun dired-clean-directory (keep)
  "Flag numerical backups for deletion.
Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
Positive prefix arg KEEP overrides `dired-kept-versions';
Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.

To clear the flags on these files, you can use \\[dired-flag-backup-files]
with a prefix argument."
  (interactive "P")
  (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
  (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
	(late-retention (if (<= keep 0) dired-kept-versions keep))
	(dired-file-version-alist ()))
    (message "Cleaning numerical backups (keeping %d late, %d old)..."
	     late-retention early-retention)
    ;; Look at each file.
    ;; If the file has numeric backup versions,
    ;; put on dired-file-version-alist an element of the form
    ;; (FILENAME . VERSION-NUMBER-LIST)
564
    (dired-map-dired-file-lines #'dired-collect-file-versions)
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    ;; Sort each VERSION-NUMBER-LIST,
    ;; and remove the versions not to be deleted.
    (let ((fval dired-file-version-alist))
      (while fval
	(let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
	       (v-count (length sorted-v-list)))
	  (if (> v-count (+ early-retention late-retention))
	      (rplacd (nthcdr early-retention sorted-v-list)
		      (nthcdr (- v-count late-retention)
			      sorted-v-list)))
	  (rplacd (car fval)
		  (cdr sorted-v-list)))
	(setq fval (cdr fval))))
    ;; Look at each file.  If it is a numeric backup file,
    ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
580
    (dired-map-dired-file-lines #'dired-trample-file-versions)
581 582 583 584 585 586
    (message "Cleaning numerical backups...done")))

;;; Subroutines of dired-clean-directory.

(defun dired-map-dired-file-lines (fun)
  ;; Perform FUN with point at the end of each non-directory line.
587
  ;; FUN takes one argument, the absolute filename.
588 589 590 591 592
  (save-excursion
    (let (file buffer-read-only)
      (goto-char (point-min))
      (while (not (eobp))
	(save-excursion
593
	  (and (not (looking-at-p dired-re-dir))
594 595 596 597 598 599
	       (not (eolp))
	       (setq file (dired-get-filename nil t)) ; nil on non-file
	       (progn (end-of-line)
		      (funcall fun file))))
	(forward-line 1)))))

600 601
(defvar backup-extract-version-start)  ; used in backup-extract-version

602
(defun dired-collect-file-versions (fn)
603 604 605 606 607 608
  (let ((fn (file-name-sans-versions fn)))
    ;; Only do work if this file is not already in the alist.
    (if (assoc fn dired-file-version-alist)
	nil
      ;; If it looks like file FN has versions, return a list of the versions.
      ;;That is a list of strings which are file names.
609
      ;;The caller may want to flag some of these files for deletion.
610 611
      (let* ((base-versions
	      (concat (file-name-nondirectory fn) ".~"))
612
	     (backup-extract-version-start (length base-versions))
613 614 615
	     (possibilities (file-name-all-completions
			     base-versions
			     (file-name-directory fn)))
616
	     (versions (mapcar #'backup-extract-version possibilities)))
617 618 619 620
	(if versions
	    (setq dired-file-version-alist
		  (cons (cons fn versions)
			dired-file-version-alist)))))))
621 622

(defun dired-trample-file-versions (fn)
623
  (let* ((start-vn (string-match-p "\\.~[0-9]+~$" fn))
624 625 626 627 628
	 base-version-list)
    (and start-vn
	 (setq base-version-list	; there was a base version to which
	       (assoc (substring fn 0 start-vn)	; this looks like a
		      dired-file-version-alist))	; subversion
629
	 (not (memq (string-to-number (substring fn (+ 2 start-vn)))
630 631 632 633
		    base-version-list))	; this one doesn't make the cut
	 (progn (beginning-of-line)
		(delete-char 1)
		(insert dired-del-marker)))))
Dave Love's avatar
Dave Love committed
634

Richard M. Stallman's avatar
Richard M. Stallman committed
635 636
;;; Shell commands

637 638
(declare-function mailcap-file-default-commands "mailcap" (files))

639 640
(defvar dired-aux-files)

641
(defun minibuffer-default-add-dired-shell-commands ()
642 643
  "Return a list of all commands associated with current dired files.
This function is used to add all related commands retrieved by `mailcap'
644 645
to the end of the list of defaults just after the default value."
  (interactive)
646 647 648
  (let ((commands (and (boundp 'dired-aux-files)
		       (require 'mailcap nil t)
		       (mailcap-file-default-commands dired-aux-files))))
649 650 651
    (if (listp minibuffer-default)
	(append minibuffer-default commands)
      (cons minibuffer-default commands))))
652

653
;; This is an extra function so that you can redefine it, e.g., to use gmhist.
Richard M. Stallman's avatar
Richard M. Stallman committed
654
(defun dired-read-shell-command (prompt arg files)
Chong Yidong's avatar
Chong Yidong committed
655 656 657 658 659 660 661 662 663
  "Read a dired shell command.
PROMPT should be a format string with one \"%s\" format sequence,
which is replaced by the value returned by `dired-mark-prompt',
with ARG and FILES as its arguments.  FILES should be a list of
file names.  The result is used as the prompt.

This normally reads using `read-shell-command', but if the
`dired-x' package is loaded, use `dired-guess-shell-command' to
offer a smarter default choice of shell command."
664 665
  (minibuffer-with-setup-hook
      (lambda ()
666 667 668
	(setq-local dired-aux-files files)
	(setq-local minibuffer-default-add-function
		    #'minibuffer-default-add-dired-shell-commands))
669
    (setq prompt (format prompt (dired-mark-prompt arg files)))
Chong Yidong's avatar
Chong Yidong committed
670
    (if (functionp 'dired-guess-shell-command)
671
	(dired-mark-pop-up nil 'shell files
Chong Yidong's avatar
Chong Yidong committed
672
			   'dired-guess-shell-command prompt files)
673
      (dired-mark-pop-up nil 'shell files
Chong Yidong's avatar
Chong Yidong committed
674
			 'read-shell-command prompt nil nil))))
Richard M. Stallman's avatar
Richard M. Stallman committed
675

676 677 678 679
;;;###autoload
(defun dired-do-async-shell-command (command &optional arg file-list)
  "Run a shell command COMMAND on the marked files asynchronously.

680 681 682 683 684 685 686 687 688 689 690
Like `dired-do-shell-command', but adds `&' at the end of COMMAND
to execute it asynchronously.

When operating on multiple files, asynchronous commands
are executed in the background on each file in parallel.
In shell syntax this means separating the individual commands
with `&'.  However, when COMMAND ends in `;' or `;&' then commands
are executed in the background on each file sequentially waiting
for each command to terminate before running the next command.
In shell syntax this means separating the individual commands with `;'.

691 692
The output appears in the buffer `*Async Shell Command*'."
  (interactive
693
   (let ((files (dired-get-marked-files t current-prefix-arg nil nil t)))
694 695 696 697 698
     (list
      ;; Want to give feedback whether this file or marked files are used:
      (dired-read-shell-command "& on %s: " current-prefix-arg files)
      current-prefix-arg
      files)))
699
  (unless (string-match-p "&[ \t]*\\'" command)
700 701 702
    (setq command (concat command " &")))
  (dired-do-shell-command command arg file-list))

Richard M. Stallman's avatar
Richard M. Stallman committed
703
;;;###autoload
704
(defun dired-do-shell-command (command &optional arg file-list)
705
  "Run a shell command COMMAND on the marked files.
706
If no files are marked or a numeric prefix arg is given,
707 708 709
the next ARG files are used.  Just \\[universal-argument] means the current file.
The prompt mentions the file(s) or the marker, as appropriate.

710 711
If there is a `*' in COMMAND, surrounded by whitespace, this runs
COMMAND just once with the entire file list substituted there.
712

713
If there is no `*', but there is a `?' in COMMAND, surrounded by
714 715
whitespace, or a `\\=`?\\=`' this runs COMMAND on each file
individually with the file name substituted for `?' or `\\=`?\\=`'.
Richard M. Stallman's avatar
Richard M. Stallman committed
716

717 718
Otherwise, this runs COMMAND on each file individually with the
file name added at the end of COMMAND (separated by a space).
719

720
`*' and `?' when not surrounded by whitespace nor `\\=`' have no special
721
significance for `dired-do-shell-command', and are passed through
722 723 724 725 726
normally to the shell, but you must confirm first.

If you want to use `*' as a shell wildcard with whitespace around
it, write `*\"\"' in place of just `*'.  This is equivalent to just
`*' in the shell, but avoids Dired's special handling.
Richard M. Stallman's avatar
Richard M. Stallman committed
727

728 729 730 731 732 733 734 735 736 737 738
If COMMAND ends in `&', `;', or `;&', it is executed in the
background asynchronously, and the output appears in the buffer
`*Async Shell Command*'.  When operating on multiple files and COMMAND
ends in `&', the shell command is executed on each file in parallel.
However, when COMMAND ends in `;' or `;&' then commands are executed
in the background on each file sequentially waiting for each command
to terminate before running the next command.  You can also use
`dired-do-async-shell-command' that automatically adds `&'.

Otherwise, COMMAND is executed synchronously, and the output
appears in the buffer `*Shell Command Output*'.
739 740 741 742 743

This feature does not try to redisplay Dired buffers afterward, as
there's no telling what files COMMAND may have changed.
Type \\[dired-do-redisplay] to redisplay the marked files.

Juanma Barranquero's avatar
Juanma Barranquero committed
744 745 746
When COMMAND runs, its working directory is the top-level directory
of the Dired buffer, so output files usually are created there
instead of in a subdir.
747 748

In a noninteractive call (from Lisp code), you must specify
749
the list of file names explicitly with the FILE-LIST argument, which
750 751 752 753 754
can be produced by `dired-get-marked-files', for example.

`dired-guess-shell-alist-default' and
`dired-guess-shell-alist-user' are consulted when the user is
prompted for the shell command to use interactively."
Richard M. Stallman's avatar
Richard M. Stallman committed
755 756
;;Functions dired-run-shell-command and dired-shell-stuff-it do the
;;actual work and can be redefined for customization.
757
  (interactive
758
   (let ((files (dired-get-marked-files t current-prefix-arg nil nil t)))
759 760
     (list
      ;; Want to give feedback whether this file or marked files are used:
761
      (dired-read-shell-command "! on %s: " current-prefix-arg files)
762 763
      current-prefix-arg
      files)))
764 765 766 767 768 769 770
  (cl-flet ((need-confirm-p
             (cmd str)
             (let ((res cmd)
                   (regexp (regexp-quote str)))
               ;; Drop all ? and * surrounded by spaces and `?`.
               (while (and (string-match regexp res)
                           (dired--star-or-qmark-p res str))
771
                 (setq res (replace-match "" t t res 2)))
772
               (string-match regexp res))))
773 774
  (let* ((on-each (not (dired--star-or-qmark-p command "*" 'keep)))
	 (no-subst (not (dired--star-or-qmark-p command "?" 'keep)))
775 776 777 778
         ;; Get confirmation for wildcards that may have been meant
         ;; to control substitution of a file name or the file name list.
         (ok (cond ((not (or on-each no-subst))
	            (error "You can not combine `*' and `?' substitution marks"))
779
	           ((need-confirm-p command "*")
780 781
	            (y-or-n-p (format-message
			       "Confirm--do you mean to use `*' as a wildcard? ")))
782
	           ((need-confirm-p command "?")
783 784 785
	            (y-or-n-p (format-message
			       "Confirm--do you mean to use `?' as a wildcard? ")))
	           (t))))
786 787 788 789 790 791 792 793 794 795 796
    (cond ((not ok) (message "Command canceled"))
          (t
           (if on-each
	       (dired-bunch-files (- 10000 (length command))
	                          (lambda (&rest files)
	                            (dired-run-shell-command
                                     (dired-shell-stuff-it command files t arg)))
	                          nil file-list)
	     ;; execute the shell command
	     (dired-run-shell-command
	      (dired-shell-stuff-it command file-list nil arg))))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
797 798 799 800 801 802 803 804 805

;; Might use {,} for bash or csh:
(defvar dired-mark-prefix ""
  "Prepended to marked files in dired shell commands.")
(defvar dired-mark-postfix ""
  "Appended to marked files in dired shell commands.")
(defvar dired-mark-separator " "
  "Separates marked files in dired shell commands.")

806
(defun dired-shell-stuff-it (command file-list on-each &optional _raw-arg)
Richard M. Stallman's avatar
Richard M. Stallman committed
807 808 809 810 811 812 813
;; "Make up a shell command line from COMMAND and FILE-LIST.
;; If ON-EACH is t, COMMAND should be applied to each file, else
;; simply concat all files and apply COMMAND to this.
;; FILE-LIST's elements will be quoted for the shell."
;; Might be redefined for smarter things and could then use RAW-ARG
;; (coming from interactive P and currently ignored) to decide what to do.
;; Smart would be a way to access basename or extension of file names.
814 815 816 817 818 819 820 821
  (let* ((in-background (string-match "[ \t]*&[ \t]*\\'" command))
	 (command (if in-background
		      (substring command 0 (match-beginning 0))
		    command))
	 (sequentially (string-match "[ \t]*;[ \t]*\\'" command))
	 (command (if sequentially
		      (substring command 0 (match-beginning 0))
		    command))
822 823 824 825
         (parallel-in-background
          (and in-background (not sequentially) (not (eq system-type 'ms-dos))))
         (w32-shell (and (fboundp 'w32-shell-dos-semantics)
                         (w32-shell-dos-semantics)))
Shuguang Sun's avatar
Shuguang Sun committed
826
         (file-remote (file-remote-p default-directory))
827 828 829
         ;; The way to run a command in background in Windows shells
         ;; is to use the START command.  The /B switch means not to
         ;; create a new window for the command.
Shuguang Sun's avatar
Shuguang Sun committed
830
         (cmd-prefix (if (and w32-shell (not file-remote)) "start /b " ""))
831 832
         ;; Windows shells don't support chaining with ";", they use
         ;; "&" instead.
Shuguang Sun's avatar
Shuguang Sun committed
833 834 835
         (cmd-sep (if (and (or (not w32-shell) file-remote)
			   (not parallel-in-background))
		      ";" "&"))
836
	 (stuff-it
837
	  (if (dired--star-or-qmark-p command nil 'keep)
838
	      (lambda (x)
839
		(let ((retval (concat cmd-prefix command)))
840
		  (while (dired--star-or-qmark-p retval nil)
841 842
		    (setq retval (replace-match x t t retval 2)))
		  retval))
843
	    (lambda (x) (concat cmd-prefix command dired-mark-separator x)))))
844
    (concat
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
     (cond
      (on-each
       (format "%s%s"
               (mapconcat stuff-it (mapcar #'shell-quote-argument file-list)
                          cmd-sep)
               ;; POSIX shells running a list of commands in the background
               ;; (LIST = cmd_1 & [cmd_2 & ... cmd_i & ... cmd_N &])
               ;; return once cmd_N ends, i.e., the shell does not
               ;; wait for cmd_i to finish before executing cmd_i+1.
               ;; That means, running (shell-command LIST) may not show
               ;; the output of all the commands (Bug#23206).
               ;; Add 'wait' to force those POSIX shells to wait until
               ;; all commands finish.
               (or (and parallel-in-background (not w32-shell)
                        "&wait")
                   "")))
      (t
       (let ((files (mapconcat #'shell-quote-argument
                               file-list dired-mark-separator)))
         (when (cdr file-list)
           (setq files (concat dired-mark-prefix files dired-mark-postfix)))
         (funcall stuff-it files))))
867
     (or (and in-background "&") ""))))
Richard M. Stallman's avatar
Richard M. Stallman committed
868 869

;; This is an extra function so that it can be redefined by ange-ftp.
870
;;;###autoload
871
(defun dired-run-shell-command (command)
872 873 874 875 876
  (let ((handler
	 (find-file-name-handler (directory-file-name default-directory)
				 'shell-command)))
    (if handler (apply handler 'shell-command (list command))
      (shell-command command)))
877 878
  ;; Return nil for sake of nconc in dired-bunch-files.
  nil)
Dave Love's avatar
Dave Love committed
879

Richard M. Stallman's avatar
Richard M. Stallman committed
880 881

(defun dired-check-process (msg program &rest arguments)
882 883 884 885 886 887
  "Display MSG while running PROGRAM, and check for output.
Remaining arguments are strings passed as command arguments to PROGRAM.
On error, insert output
in a log buffer and return the offending ARGUMENTS or PROGRAM.
Caller can cons up a list of failed args.
Else returns nil for success."
Richard M. Stallman's avatar
Richard M. Stallman committed
888 889 890 891 892 893 894 895
  (let (err-buffer err (dir default-directory))
    (message "%s..." msg)
    (save-excursion
      ;; Get a clean buffer for error output:
      (setq err-buffer (get-buffer-create " *dired-check-process output*"))
      (set-buffer err-buffer)
      (erase-buffer)
      (setq default-directory dir	; caller's default-directory
896
	    err (not (eq 0 (apply #'process-file program nil t nil arguments))))
Richard M. Stallman's avatar
Richard M. Stallman committed
897 898 899 900 901 902 903 904
      (if err
	  (progn
	    (dired-log (concat program " " (prin1-to-string arguments) "\n"))
	    (dired-log err-buffer)
	    (or arguments program t))
	(kill-buffer err-buffer)
	(message "%s...done" msg)
	nil))))
905 906 907

(defun dired-shell-command (cmd)
  "Run CMD, and check for output.
908 909 910 911
On error, pop up the log buffer.
Return the result of `process-file' - zero for success."
  (let ((out-buffer " *dired-check-process output*")
        (dir default-directory))
912 913
    (with-current-buffer (get-buffer-create out-buffer)
      (erase-buffer)
914 915 916 917 918 919 920 921
      (let* ((default-directory dir)
             (res (process-file
                   shell-file-name
                   nil
                   t
                   nil
                   shell-command-switch
                   cmd)))
922
        (unless (zerop res)
923 924
          (pop-to-buffer out-buffer))
        res))))
Dave Love's avatar
Dave Love committed
925

Richard M. Stallman's avatar
Richard M. Stallman committed
926 927 928
;; Commands that delete or redisplay part of the dired buffer.

(defun dired-kill-line (&optional arg)
929 930 931
  "Kill the current line (not the files).
With a prefix argument, kill that many lines starting with the current line.
\(A negative argument kills backward.)"
Richard M. Stallman's avatar
Richard M. Stallman committed
932 933 934 935 936 937
  (interactive "P")
  (setq arg (prefix-numeric-value arg))
  (let (buffer-read-only file)
    (while (/= 0 arg)
      (setq file (dired-get-filename nil t))
      (if (not file)
938
	  (error "Can only kill file lines")
Richard M. Stallman's avatar
Richard M. Stallman committed
939 940 941
	(save-excursion (and file
			     (dired-goto-subdir file)
			     (dired-kill-subdir)))
942
	(delete-region (line-beginning-position)
Richard M. Stallman's avatar
Richard M. Stallman committed
943 944 945 946 947 948 949 950 951 952
		       (progn (forward-line 1) (point)))
	(if (> arg 0)
	    (setq arg (1- arg))
	  (setq arg (1+ arg))
	  (forward-line -1))))
    (dired-move-to-filename)))

;;;###autoload
(defun dired-do-kill-lines (&optional arg fmt)
  "Kill all marked lines (not the files).
953
With a prefix argument, kill that many lines starting with the current line.
954 955 956 957 958 959 960 961
\(A negative argument kills backward.)
If you use this command with a prefix argument to kill the line
for a file that is a directory, which you have inserted in the
Dired buffer as a subdirectory, then it deletes that subdirectory
from the buffer as well.
To kill an entire subdirectory \(without killing its line in the
parent directory), go to its directory header line and use this
command with a prefix argument (the value does not matter)."
Richard M. Stallman's avatar
Richard M. Stallman committed
962 963
  ;; Returns count of killed lines.  FMT="" suppresses message.
  (interactive "P")
964 965 966 967 968 969
  (if arg
      (if (dired-get-subdir)
	  (dired-kill-subdir)
	(dired-kill-line arg))
    (save-excursion
      (goto-char (point-min))
970 971 972 973 974 975
      (let (buffer-read-only
	    (count 0)
	    (regexp (dired-marker-regexp)))
	(while (and (not (eobp))
		    (re-search-forward regexp nil t))
	  (setq count (1+ count))
976
	  (delete-region (line-beginning-position)
977
			 (progn (forward-line 1) (point))))
978 979 980
	(or (equal "" fmt)
	    (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
	count))))
Richard M. Stallman's avatar
Richard M. Stallman committed
981 982

;;;###end dired-cmd.el
Dave Love's avatar
Dave Love committed
983

Richard M. Stallman's avatar
Richard M. Stallman committed
984 985 986 987 988 989 990
;;; 30K
;;;###begin dired-cp.el

(defun dired-compress ()
  ;; Compress or uncompress the current file.
  ;; Return nil for success, offending filename else.
  (let* (buffer-read-only
991 992 993
	 (from-file (dired-get-filename))
	 (new-file (dired-compress-file from-file)))
    (if new-file
994 995
	(let ((start (point)))
	  ;; Remove any preexisting entry for the name NEW-FILE.
996
	  (ignore-errors (dired-remove-entry new-file))
997 998
	  (goto-char start)
	  ;; Now replace the current line with an entry for NEW-FILE.
999 1000 1001 1002 1003 1004 1005 1006
	  ;; But don't remove the current line if either FROM-FILE or
	  ;; NEW-FILE is a directory, because compressing/uncompressing
          ;; directories doesn't remove the original.
          (if (or (file-directory-p from-file)
                  (file-directory-p new-file))
              (dired-add-entry new-file nil t)
            (dired-update-file-line new-file))
          nil)
1007
      (dired-log (concat "Failed to (un)compress " from-file))
1008 1009
      from-file)))

1010
(defvar dired-compress-file-suffixes
1011
  '(
1012
    ;; "tar -zxf" isn't used because it's not available on the
1013 1014
    ;; Solaris10 version of tar. Solaris10 becomes obsolete in 2021.
    ;; Same thing on AIX 7.1.
1015 1016
    ("\\.tar\\.gz\\'" "" "gzip -dc %i | tar -xf -")
    ("\\.tgz\\'" "" "gzip -dc %i | tar -xf -")
1017
    ("\\.gz\\'" "" "gunzip")
1018
    ("\\.lz\\'" "" "lzip -d")
1019 1020 1021 1022
    ("\\.Z\\'" "" "uncompress")
    ;; For .z, try gunzip.  It might be an old gzip file,
    ;; or it might be from compact? pack? (which?) but gunzip handles both.
    ("\\.z\\'" "" "gunzip")
1023 1024
    ("\\.dz\\'" "" "dictunzip")
    ("\\.tbz\\'" ".tar" "bunzip2")
1025
    ("\\.bz2\\'" "" "bunzip2")
1026
    ("\\.xz\\'" "" "unxz")
1027
    ("\\.zip\\'" "" "unzip -o -d %o %i")
1028 1029 1030
    ("\\.tar\\.zst\\'" "" "unzstd -c %i | tar -xf -")
    ("\\.tzst\\'" "" "unzstd -c %i | tar -xf -")
    ("\\.zst\\'" "" "unzstd --rm")
Oleh Krehel's avatar
Oleh Krehel committed
1031
    ("\\.7z\\'" "" "7z x -aoa -o%o %i")
1032
    ;; This item controls naming for compression.
1033
    ("\\.tar\\'" ".tgz" nil)
1034 1035 1036
    ;; This item controls the compression of directories.  Its REGEXP
    ;; element should never match any valid file name.
    ("\000" ".tar.gz" "tar -cf - %i | gzip -c9 > %o"))
1037 1038
  "Control changes in file name suffixes for compression and uncompression.
Each element specifies one transformation rule, and has the form:
1039
  (REGEXP NEW-SUFFIX PROGRAM)
1040 1041 1042 1043 1044
The rule applies when the old file name matches REGEXP.
The new file name is computed by deleting the part that matches REGEXP
 (as well as anything after that), then adding NEW-SUFFIX in its place.
If PROGRAM is non-nil, the rule is an uncompression rule,
and uncompression is done by running PROGRAM.
1045 1046 1047 1048

Within PROGRAM, %i denotes the input file, and %o denotes the
output file.

1049 1050
Otherwise, the rule is a compression rule, and compression is done with gzip.
ARGS are command switches passed to PROGRAM.")
1051

1052
(defvar dired-compress-files-alist
1053 1054 1055
  '(("\\.tar\\.gz\\'" . "tar -cf - %i | gzip -c9 > %o")
    ("\\.tar\\.bz2\\'" . "tar -cf - %i | bzip2 -c9 > %o")
    ("\\.tar\\.xz\\'" . "tar -cf - %i | xz -c9 > %o")
1056
    ("\\.tar\\.zst\\'" . "tar -cf - %i | zstd -19 -o %o")
1057 1058 1059 1060
    ("\\.zip\\'" . "zip %o -r --filesync %i"))
  "Control the compression shell command for `dired-do-compress-to'.

Each element is (REGEXP . CMD), where REGEXP is the name of the
Glenn Morris's avatar
Glenn Morris committed
1061
archive to which you want to compress, and CMD is the
1062 1063 1064 1065 1066 1067 1068 1069
corresponding command.

Within CMD, %i denotes the input file(s), and %o denotes the
output file. %i path(s) are relative, while %o is absolute.")

;;;###autoload
(defun dired-do-compress-to ()
  "Compress selected files and directories to an archive.
Eli Zaretskii's avatar
Eli Zaretskii committed
1070 1071 1072
Prompt for the archive file name.
Choose the archiving command based on the archive file-name extension
and `dired-compress-files-alist'."
1073
  (interactive)
1074
  (let* ((in-files (dired-get-marked-files nil nil nil nil t))
Eli Zaretskii's avatar
Eli Zaretskii committed
1075
         (out-file (expand-file-name (read-file-name "Compress to: ")))
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
         (rule (cl-find-if
                (lambda (x)
                  (string-match (car x) out-file))
                dired-compress-files-alist)))
    (cond ((not rule)
           (error
            "No compression rule found for %s, see `dired-compress-files-alist'"
            out-file))
          ((and (file-exists-p out-file)
                (not (y-or-n-p
                      (format "%s exists, overwrite?"
                              (abbreviate-file-name out-file)))))
           (message "Compression aborted"))
          (t
           (when (zerop
                  (dired-shell-command
1092
                   (format-spec (cdr rule)
1093 1094 1095 1096 1097 1098
                                `((?o . ,(shell-quote-argument out-file))
                                  (?i . ,(mapconcat
                                          (lambda (in-file)
                                            (shell-quote-argument
                                             (file-name-nondirectory in-file)))
                                          in-files " "))))))
1099 1100 1101
             (message (ngettext "Compressed %d file to %s"
			        "Compressed %d files to %s"
			        (length in-files))
1102 1103 1104
                      (length in-files)
                      (file-name-nondirectory out-file)))))))

Richard M. Stallman's avatar
Richard M. Stallman committed
1105
;;;###autoload
1106
(defun dired-compress-file (file)
1107 1108 1109
  "Compress or uncompress FILE.
Return the name of the compressed or uncompressed file.
Return nil if no change in files."
1110
  (let ((handler (find-file-name-handler file 'dired-compress-file))
1111
        suffix newname
1112 1113
        (suffixes dired-compress-file-suffixes)
        command)
1114 1115 1116
    ;; See if any suffix rule matches this file name.
    (while suffixes
      (let (case-fold-search)
1117 1118 1119
        (if (string-match (car (car suffixes)) file)
            (setq suffix (car suffixes) suffixes nil))
        (setq suffixes (cdr suffixes))))
1120
    ;; If so, compute desired new name.
1121
    (if suffix
1122 1123
        (setq newname (concat (substring file 0 (match-beginning 0))
                              (nth 1 suffix))))
1124
    (cond (handler
1125 1126 1127
           (funcall handler 'dired-compress-file file))
          ((file-symlink-p file)
           nil)
1128 1129 1130 1131 1132
          ((and suffix (setq command (nth 2 suffix)))
           (if (string-match "%[io]" command)
               (prog1 (setq newname (file-name-as-directory newname))
                 (dired-shell-command
                  (replace-regexp-in-string
1133
                   "%o" (shell-quote-argument newname)
1134
                   (replace-regexp-in-string
1135 1136 1137 1138
                    "%i" (shell-quote-argument file)
                    command
                    nil t)
                   nil t)))
1139
             ;; We found an uncompression rule.
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
             (let ((match (string-match " " command))
                   (msg (concat "Uncompressing " file)))
               (unless (if match
                           (dired-check-process msg
                                                (substring command 0 match)
                                                (substring command (1+ match))
                                                file)
                         (dired-check-process msg
                                              command
                                              file))
                 newname))))
1151 1152 1153 1154
          (t
           ;; We don't recognize the file as compressed, so compress it.
           ;; Try gzip; if we don't have that, use compress.
           (condition-case nil
1155 1156
               (if (file-directory-p file)
                   (progn
1157
                     (setq suffix (cdr (assoc "\000" dired-compress-file-suffixes)))
1158 1159 1160 1161 1162
                     (when suffix
                       (let ((out-name (concat file (car suffix)))
                             (default-directory (file-name-directory file)))
                         (dired-shell-command
                          (replace-regexp-in-string
1163
                           "%o" (shell-quote-argument out-name)
1164
                           (replace-regexp-in-string
1165 1166 1167 1168
                            "%i" (shell-quote-argument (file-name-nondirectory file))
                            (cadr suffix)
                            nil t)
                           nil t))
1169 1170 1171 1172 1173 1174 1175
                         out-name)))
                 (let ((out-name (concat file ".gz")))
                   (and (or (not (file-exists-p out-name))
                            (y-or-n-p
                             (format "File %s already exists.  Really compress? "
                                     out-name)))
                        (not
1176
                         (dired-check-process (concat "Compressing " file)
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
                                              "gzip" "-f" file))
                        (or (file-exists-p out-name)
                            (setq out-name (concat file ".z")))
                        ;; Rename the compressed file to NEWNAME
                        ;; if it hasn't got that name already.
                        (if (and newname (not (equal newname out-name)))
                            (progn
                              (rename-file out-name newname t)
                              newname)
                          out-name))))
1187 1188 1189 1190 1191
             (file-error
              (if (not (dired-check-process (concat "Compressing " file)
                                            "compress" "-f" file))
                  ;; Don't use NEWNAME with `compress'.
                  (concat file ".Z"))))))))
Dave Love's avatar
Dave Love committed
1192

Richard M. Stallman's avatar
Richard M. Stallman committed
1193 1194 1195 1196 1197 1198
(defun dired-mark-confirm (op-symbol arg)
  ;; Request confirmation from the user that the operation described
  ;; by OP-SYMBOL is to be performed on the marked files.
  ;; Confirmation consists in a y-or-n question with a file list
  ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
  ;; The files used are determined by ARG (as in dired-get-marked-files).
Simon Marshall's avatar
Simon Marshall committed
1199 1200
  (or (eq dired-no-confirm t)
      (memq op-symbol dired-no-confirm)
Richard M. Stallman's avatar
Richard M. Stallman committed
1201 1202 1203
      ;; Pass t for DISTINGUISH-ONE-MARKED so that a single file which
      ;; is marked pops up a window.  That will help the user see
      ;; it isn't the current line file.
1204
      (let ((files (dired-get-marked-files t arg nil t t))
1205 1206
	    (string (if (eq op-symbol 'compress) "Compress or uncompress"
		      (capitalize (symbol-name op-symbol)))))
1207
	(dired-mark-pop-up nil op-symbol files #'y-or-n-p
1208
			   (concat string " "
Richard M. Stallman's avatar
Richard M. Stallman committed
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
				   (dired-mark-prompt arg files) "? ")))))

(defun dired-map-over-marks-check (fun arg op-symbol &optional show-progress)
;  "Map FUN over marked files (with second ARG like in dired-map-over-marks)
; and display failures.

; FUN takes zero args.  It returns non-nil (the offending object, e.g.
; the short form of the filename) for a failure and probably logs a
; detailed error explanation using function `dired-log'.

; OP-SYMBOL is a symbol describing the operation performed (e.g.
; `compress').  It is used with `dired-mark-pop-up' to prompt the user
; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
; `Failed to compress 1 of 2 files - type W to see why ("foo")')

; SHOW-PROGRESS if non-nil means redisplay dired after each file."
  (if (dired-mark-confirm op-symbol arg)
      (let* ((total-list;; all of FUN's return values
	      (dired-map-over-marks (funcall fun) arg show-progress))
	     (total (length total-list))
	     (failures (delq nil total-list))
1230 1231 1232
	     (count (length failures))
	     (string (if (eq op-symbol 'compress) "Compress or uncompress"
		       (capitalize (symbol-name op-symbol)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1233
	(if (not failures)
1234 1235
	    (message (ngettext "%s: %d file." "%s: %d files." total)
		     string total)
Richard M. Stallman's avatar
Richard M. Stallman committed
1236 1237
	  ;; end this bunch of errors:
	  (dired-log-summary
1238 1239 1240 1241
	   (format (ngettext "Failed to %s %d of %d file"
                             "Failed to %s %d of %d files"
                             total)
		   (downcase string) count total)
Richard M. Stallman's avatar
Richard M. Stallman committed
1242 1243
	   failures)))))

1244
;;;###autoload
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
(defun dired-query (sym prompt &rest args)
  "Format PROMPT with ARGS, query user, and store the result in SYM.
The return value is either nil or t.

The user may type y or SPC to accept once; n or DEL to skip once;
! to accept this and subsequent queries; or q or ESC to decline
this and subsequent queries.

If SYM is already bound to a non-nil value, this function may
return automatically without querying the user.  If SYM is !,
return t; if SYM is q or ESC, return nil."
  (let* ((char (symbol-value sym))
	 (char-choices '(?y ?\s ?n ?\177 ?! ?q ?\e)))
    (cond ((eq char ?!)
	   t)       ; accept, and don't ask again
	  ((memq char '(?q ?\e))
	   nil)     ; skip, and don't ask again
	  (t        ; no previous answer - ask now
	   (setq prompt
1264
		 (concat (apply #'format-message prompt args)