dired-aux.el 121 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 208
    (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.
                 (file-attribute-group-id fa2))))"
209
  (interactive
210 211 212 213 214 215 216 217 218 219 220
   (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")))
221 222 223
  (let* ((dir1 (dired-current-directory))
         (file-alist1 (dired-files-attributes dir1))
         (file-alist2 (dired-files-attributes dir2))
224 225 226 227 228 229
	 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
230
		      #'cadr
231 232
                      (dired-file-set-difference
                       file-alist1 file-alist2
233 234
		       predicate))
	  file-list2 (mapcar
235
		      #'cadr
236 237
                      (dired-file-set-difference
                       file-alist2 file-alist1
238
		       predicate)))
239 240 241 242 243 244 245 246 247 248
    (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)))
249 250 251 252 253
    (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)))))
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

(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
269 270 271 272 273 274 275 276
			      (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
277 278
                                         (size1 . ,(file-attribute-size fa1))
                                         (size2 . ,(file-attribute-size fa2))
279
                                         (mtime1
Paul Eggert's avatar
Paul Eggert committed
280
                                          . ,(float-time (file-attribute-modification-time fa1)))
281
                                         (mtime2
Paul Eggert's avatar
Paul Eggert committed
282
                                          . ,(float-time (file-attribute-modification-time fa2)))
283
                                         )))))
284 285
		    (setq list (cdr list)))
		  list)
286
	  (push file1 res)))
287 288 289 290
      (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
291
List has a form of (file-name full-file-name (attribute-list))."
292 293 294 295 296 297 298 299
  (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)))

300
;;; Change file attributes
301

Richard M. Stallman's avatar
Richard M. Stallman committed
302
(defun dired-do-chxxx (attribute-name program op-symbol arg)
303
  ;; Change file attributes (group, owner, timestamp) of marked files and
Richard M. Stallman's avatar
Richard M. Stallman committed
304 305 306
  ;; refresh their file lines.
  ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
  ;; PROGRAM is the program used to change the attribute.
307 308
  ;; 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'.
309
  (let* ((files (dired-get-marked-files t arg nil nil t))
310
	 ;; The source of default file attributes is the file at point.
311
	 (default-file (dired-get-filename t t))
312 313 314 315
	 (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
316 317
			    (file-attribute-modification-time
			     (file-attributes default-file))))
318
			  ((eq op-symbol 'chown)
Paul Eggert's avatar
Paul Eggert committed
319 320
			   (file-attribute-user-id
			    (file-attributes default-file 'string)))
321
			  ((eq op-symbol 'chgrp)
Paul Eggert's avatar
Paul Eggert committed
322 323
			   (file-attribute-group-id
			    (file-attributes default-file 'string))))))
324 325 326 327 328
	 (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
329 330 331 332 333
						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
334
	 (operation (concat program " " new-attribute))
335 336 337 338 339 340 341 342
         ;; 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
343 344 345
	 failures)
    (setq failures
	  (dired-bunch-files 10000
346
			     #'dired-check-process
347
			     (append
Juri Linkov's avatar
Juri Linkov committed
348
			      (list operation program)
349 350 351 352
			      (unless (or (string-equal new-attribute "")
					  ;; Use `eq' instead of `equal'
					  ;; to detect empty input (bug#12399).
					  (eq new-attribute default))
353 354 355
				(if (eq op-symbol 'touch)
				    (list "-t" new-attribute)
				  (list new-attribute)))
356
			      (if (string-match-p "gnu" system-configuration)
357
				  '("--") nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
358 359 360 361 362 363 364 365 366 367
			     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.
368 369 370 371 372 373 374 375 376 377 378
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
379
  (interactive "P")
380
  (let* ((files (dired-get-marked-files t arg nil nil t))
381
	 ;; The source of default file attributes is the file at point.
382
	 (default-file (dired-get-filename t t))
383
	 (modestr (when default-file
Paul Eggert's avatar
Paul Eggert committed
384
		    (file-attribute-modes (file-attributes default-file))))
385 386 387 388 389 390 391 392 393
	 (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)))))
394
	 (modes (dired-mark-read-string
395
		 "Change mode of %s to: "
396
		 nil 'chmod arg files default))
397
	 num-modes)
398 399 400 401
    (cond ((or (equal modes "")
	       ;; Use `eq' instead of `equal'
	       ;; to detect empty input (bug#12399).
	       (eq modes default))
402 403 404
	   ;; We used to treat empty input as DEFAULT, but that is not
	   ;; such a good idea (Bug#9361).
	   (error "No file mode specified"))
405
	  ((string-match-p "^[0-7]+" modes)
406 407
	   (setq num-modes (string-to-number modes 8))))

408 409 410 411 412 413
    (dolist (file files)
      (set-file-modes
       file
       (if num-modes num-modes
	 (file-modes-symbolic-to-number modes (file-modes file)))))
    (dired-do-redisplay arg)))
Richard M. Stallman's avatar
Richard M. Stallman committed
414 415 416

;;;###autoload
(defun dired-do-chgrp (&optional arg)
417 418 419
  "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
420
  (interactive "P")
421 422
  (if (and (memq system-type '(ms-dos windows-nt))
           (not (file-remote-p default-directory)))
423
      (error "chgrp not supported on this system"))
Richard M. Stallman's avatar
Richard M. Stallman committed
424 425 426 427
  (dired-do-chxxx "Group" "chgrp" 'chgrp arg))

;;;###autoload
(defun dired-do-chown (&optional arg)
428 429 430
  "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
431
  (interactive "P")
432 433
  (if (and (memq system-type '(ms-dos windows-nt))
           (not (file-remote-p default-directory)))
434
      (error "chown not supported on this system"))
Richard M. Stallman's avatar
Richard M. Stallman committed
435 436
  (dired-do-chxxx "Owner" dired-chown-program 'chown arg))

437
;;;###autoload
Juri Linkov's avatar
Juri Linkov committed
438 439
(defun dired-do-touch (&optional arg)
  "Change the timestamp of the marked (or next ARG) files.
440 441 442
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
443 444 445
  (interactive "P")
  (dired-do-chxxx "Timestamp" dired-touch-program 'touch arg))

Richard M. Stallman's avatar
Richard M. Stallman committed
446 447 448 449 450 451
;; 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
452
	past
Richard M. Stallman's avatar
Richard M. Stallman committed
453 454 455 456 457 458 459 460 461 462 463
	(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))
464 465 466 467 468
	    (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
469
		  ;; Transfer the elements of PENDING onto PAST
470 471 472
		  ;; 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
473 474 475 476 477 478 479 480
		  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)))
481 482 483 484 485 486
    (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
487

488 489
(defvar lpr-printer-switch)

Richard M. Stallman's avatar
Richard M. Stallman committed
490 491 492 493 494 495
;;;###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")
496
  (require 'lpr)
497
  (let* ((file-list (dired-get-marked-files t arg nil nil t))
498 499 500 501 502 503
	 (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
504 505
	 (command (dired-mark-read-string
		   "Print %s with: "
506
                   (mapconcat #'identity
507 508 509 510 511
			      (cons lpr-command
				    (if (stringp lpr-switches)
					(list lpr-switches)
				      lpr-switches))
			      " ")
Richard M. Stallman's avatar
Richard M. Stallman committed
512 513 514
		   'print arg file-list)))
    (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))

515
(defun dired-mark-read-string (prompt initial op-symbol arg files
516
			       &optional default-value collection)
517 518 519 520 521
  "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
522 523 524
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.
525

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

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

538 539
(defvar dired-file-version-alist)

540
;;;###autoload
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
(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)
560
    (dired-map-dired-file-lines #'dired-collect-file-versions)
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    ;; 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.
576
    (dired-map-dired-file-lines #'dired-trample-file-versions)
577 578 579 580 581 582
    (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.
583
  ;; FUN takes one argument, the absolute filename.
584 585 586 587 588
  (save-excursion
    (let (file buffer-read-only)
      (goto-char (point-min))
      (while (not (eobp))
	(save-excursion
589
	  (and (not (looking-at-p dired-re-dir))
590 591 592 593 594 595
	       (not (eolp))
	       (setq file (dired-get-filename nil t)) ; nil on non-file
	       (progn (end-of-line)
		      (funcall fun file))))
	(forward-line 1)))))

596 597
(defvar backup-extract-version-start)  ; used in backup-extract-version

598
(defun dired-collect-file-versions (fn)
599 600 601 602 603 604
  (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.
605
      ;;The caller may want to flag some of these files for deletion.
606 607
      (let* ((base-versions
	      (concat (file-name-nondirectory fn) ".~"))
608
	     (backup-extract-version-start (length base-versions))
609 610 611
	     (possibilities (file-name-all-completions
			     base-versions
			     (file-name-directory fn)))
612
	     (versions (mapcar #'backup-extract-version possibilities)))
613 614 615 616
	(if versions
	    (setq dired-file-version-alist
		  (cons (cons fn versions)
			dired-file-version-alist)))))))
617 618

(defun dired-trample-file-versions (fn)
619
  (let* ((start-vn (string-match-p "\\.~[0-9]+~$" fn))
620 621 622 623 624
	 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
625
	 (not (memq (string-to-number (substring fn (+ 2 start-vn)))
626 627 628 629
		    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
630

Richard M. Stallman's avatar
Richard M. Stallman committed
631 632
;;; Shell commands

633 634
(declare-function mailcap-file-default-commands "mailcap" (files))

635 636
(defvar dired-aux-files)

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

649
;; 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
650
(defun dired-read-shell-command (prompt arg files)
Chong Yidong's avatar
Chong Yidong committed
651 652 653 654 655 656 657 658 659
  "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."
660 661
  (minibuffer-with-setup-hook
      (lambda ()
662 663 664
	(setq-local dired-aux-files files)
	(setq-local minibuffer-default-add-function
		    #'minibuffer-default-add-dired-shell-commands))
665
    (setq prompt (format prompt (dired-mark-prompt arg files)))
Chong Yidong's avatar
Chong Yidong committed
666
    (if (functionp 'dired-guess-shell-command)
667
	(dired-mark-pop-up nil 'shell files
Chong Yidong's avatar
Chong Yidong committed
668
			   'dired-guess-shell-command prompt files)
669
      (dired-mark-pop-up nil 'shell files
Chong Yidong's avatar
Chong Yidong committed
670
			 'read-shell-command prompt nil nil))))
Richard M. Stallman's avatar
Richard M. Stallman committed
671

672 673 674 675
;;;###autoload
(defun dired-do-async-shell-command (command &optional arg file-list)
  "Run a shell command COMMAND on the marked files asynchronously.

676 677 678 679 680 681 682 683 684 685 686
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 `;'.

687 688
The output appears in the buffer `*Async Shell Command*'."
  (interactive
689
   (let ((files (dired-get-marked-files t current-prefix-arg nil nil t)))
690 691 692 693 694
     (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)))
695
  (unless (string-match-p "&[ \t]*\\'" command)
696 697 698
    (setq command (concat command " &")))
  (dired-do-shell-command command arg file-list))

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

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

709
If there is no `*', but there is a `?' in COMMAND, surrounded by
710 711
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
712

713 714
Otherwise, this runs COMMAND on each file individually with the
file name added at the end of COMMAND (separated by a space).
715

716
`*' and `?' when not surrounded by whitespace nor `\\=`' have no special
717
significance for `dired-do-shell-command', and are passed through
718 719 720 721 722
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
723

724 725 726 727 728 729 730 731 732 733 734
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*'.
735 736 737 738 739

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
740 741 742
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.
743 744

In a noninteractive call (from Lisp code), you must specify
745
the list of file names explicitly with the FILE-LIST argument, which
746 747 748 749 750
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
751 752
;;Functions dired-run-shell-command and dired-shell-stuff-it do the
;;actual work and can be redefined for customization.
753
  (interactive
754
   (let ((files (dired-get-marked-files t current-prefix-arg nil nil t)))
755 756
     (list
      ;; Want to give feedback whether this file or marked files are used:
757
      (dired-read-shell-command "! on %s: " current-prefix-arg files)
758 759
      current-prefix-arg
      files)))
760 761 762 763 764 765 766
  (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))
767
                 (setq res (replace-match "" t t res 2)))
768
               (string-match regexp res))))
769 770
  (let* ((on-each (not (dired--star-or-qmark-p command "*" 'keep)))
	 (no-subst (not (dired--star-or-qmark-p command "?" 'keep)))
771 772 773 774
         ;; 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"))
775
	           ((need-confirm-p command "*")
776 777
	            (y-or-n-p (format-message
			       "Confirm--do you mean to use `*' as a wildcard? ")))
778
	           ((need-confirm-p command "?")
779 780 781
	            (y-or-n-p (format-message
			       "Confirm--do you mean to use `?' as a wildcard? ")))
	           (t))))
782 783 784 785 786 787 788 789 790 791 792
    (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
793 794 795 796 797 798 799 800 801

;; 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.")

802
(defun dired-shell-stuff-it (command file-list on-each &optional _raw-arg)
Richard M. Stallman's avatar
Richard M. Stallman committed
803 804 805 806 807 808 809
;; "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.
810 811 812 813 814 815 816 817
  (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))
818 819 820 821
         (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
822
         (file-remote (file-remote-p default-directory))
823 824 825
         ;; 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
826
         (cmd-prefix (if (and w32-shell (not file-remote)) "start /b " ""))
827 828
         ;; Windows shells don't support chaining with ";", they use
         ;; "&" instead.
Shuguang Sun's avatar
Shuguang Sun committed
829 830 831
         (cmd-sep (if (and (or (not w32-shell) file-remote)
			   (not parallel-in-background))
		      ";" "&"))
832
	 (stuff-it
833
	  (if (dired--star-or-qmark-p command nil 'keep)
834
	      (lambda (x)
835
		(let ((retval (concat cmd-prefix command)))
836
		  (while (dired--star-or-qmark-p retval nil)
837 838
		    (setq retval (replace-match x t t retval 2)))
		  retval))
839
	    (lambda (x) (concat cmd-prefix command dired-mark-separator x)))))
840
    (concat
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
     (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))))
863
     (or (and in-background "&") ""))))
Richard M. Stallman's avatar
Richard M. Stallman committed
864 865

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

(defun dired-check-process (msg program &rest arguments)
878 879 880 881 882 883
  "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
884 885 886 887 888 889 890 891
  (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
892
	    err (not (eq 0 (apply #'process-file program nil t nil arguments))))
Richard M. Stallman's avatar
Richard M. Stallman committed
893 894 895 896 897 898 899 900
      (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))))
901 902 903

(defun dired-shell-command (cmd)
  "Run CMD, and check for output.
904 905 906 907
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))
908 909
    (with-current-buffer (get-buffer-create out-buffer)
      (erase-buffer)
910 911 912 913 914 915 916 917
      (let* ((default-directory dir)
             (res (process-file
                   shell-file-name
                   nil
                   t
                   nil
                   shell-command-switch
                   cmd)))
918
        (unless (zerop res)
919 920
          (pop-to-buffer out-buffer))
        res))))
Dave Love's avatar
Dave Love committed
921

Richard M. Stallman's avatar
Richard M. Stallman committed
922 923 924
;; Commands that delete or redisplay part of the dired buffer.

(defun dired-kill-line (&optional arg)
925 926 927
  "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
928 929 930 931 932 933
  (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)
934
	  (error "Can only kill file lines")
Richard M. Stallman's avatar
Richard M. Stallman committed
935 936 937
	(save-excursion (and file
			     (dired-goto-subdir file)
			     (dired-kill-subdir)))
938
	(delete-region (line-beginning-position)
Richard M. Stallman's avatar
Richard M. Stallman committed
939 940 941 942 943 944 945 946 947 948
		       (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).
949
With a prefix argument, kill that many lines starting with the current line.
950 951 952 953 954 955 956 957
\(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
958 959
  ;; Returns count of killed lines.  FMT="" suppresses message.
  (interactive "P")
960 961 962 963 964 965
  (if arg
      (if (dired-get-subdir)
	  (dired-kill-subdir)
	(dired-kill-line arg))
    (save-excursion
      (goto-char (point-min))
966 967 968 969 970 971
      (let (buffer-read-only
	    (count 0)
	    (regexp (dired-marker-regexp)))
	(while (and (not (eobp))
		    (re-search-forward regexp nil t))
	  (setq count (1+ count))
972
	  (delete-region (line-beginning-position)
973
			 (progn (forward-line 1) (point))))
974 975 976
	(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
977 978

;;;###end dired-cmd.el
Dave Love's avatar
Dave Love committed
979

Richard M. Stallman's avatar
Richard M. Stallman committed
980 981 982 983 984 985 986
;;; 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
987 988 989
	 (from-file (dired-get-filename))
	 (new-file (dired-compress-file from-file)))
    (if new-file
990 991
	(let ((start (point)))
	  ;; Remove any preexisting entry for the name NEW-FILE.
992
	  (ignore-errors (dired-remove-entry new-file))
993 994
	  (goto-char start)
	  ;; Now replace the current line with an entry for NEW-FILE.
995 996 997 998 999 1000 1001 1002
	  ;; 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)
1003
      (dired-log (concat "Failed to (un)compress " from-file))
1004 1005
      from-file)))

1006
(defvar dired-compress-file-suffixes
1007
  '(
1008
    ;; "tar -zxf" isn't used because it's not available on the
1009 1010
    ;; Solaris10 version of tar. Solaris10 becomes obsolete in 2021.
    ;; Same thing on AIX 7.1.
1011 1012
    ("\\.tar\\.gz\\'" "" "gzip -dc %i | tar -xf -")
    ("\\.tgz\\'" "" "gzip -dc %i | tar -xf -")
1013
    ("\\.gz\\'" "" "gunzip")
1014
    ("\\.lz\\'" "" "lzip -d")
1015 1016 1017 1018
    ("\\.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")
1019 1020
    ("\\.dz\\'" "" "dictunzip")
    ("\\.tbz\\'" ".tar" "bunzip2")
1021
    ("\\.bz2\\'" "" "bunzip2")
1022
    ("\\.xz\\'" "" "unxz")
1023
    ("\\.zip\\'" "" "unzip -o -d %o %i")
1024 1025 1026
    ("\\.tar\\.zst\\'" "" "unzstd -c %i | tar -xf -")
    ("\\.tzst\\'" "" "unzstd -c %i | tar -xf -")
    ("\\.zst\\'" "" "unzstd --rm")
Oleh Krehel's avatar
Oleh Krehel committed
1027
    ("\\.7z\\'" "" "7z x -aoa -o%o %i")
1028
    ;; This item controls naming for compression.
1029
    ("\\.tar\\'" ".tgz" nil)
1030 1031 1032
    ;; 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"))
1033 1034
  "Control changes in file name suffixes for compression and uncompression.
Each element specifies one transformation rule, and has the form:
1035
  (REGEXP NEW-SUFFIX PROGRAM)
1036 1037 1038 1039 1040
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.
1041 1042 1043 1044

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

1045 1046
Otherwise, the rule is a compression rule, and compression is done with gzip.
ARGS are command switches passed to PROGRAM.")
1047

1048
(defvar dired-compress-files-alist
1049 1050 1051
  '(("\\.tar\\.gz\\'" . "tar -cf - %i | gzip -c9 > %o")
    ("\\.tar\\.bz2\\'" . "tar -cf - %i | bzip2 -c9 > %o")
    ("\\.tar\\.xz\\'" . "tar -cf - %i | xz -c9 > %o")
1052
    ("\\.tar\\.zst\\'" . "tar -cf - %i | zstd -19 -o %o")
1053 1054 1055 1056
    ("\\.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
1057
archive to which you want to compress, and CMD is the
1058 1059 1060 1061 1062
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.")

1063 1064
(declare-function format-spec "format-spec.el" (format specification))

1065 1066 1067
;;;###autoload
(defun dired-do-compress-to ()
  "Compress selected files and directories to an archive.
Eli Zaretskii's avatar
Eli Zaretskii committed
1068 1069 1070
Prompt for the archive file name.
Choose the archiving command based on the archive file-name extension
and `dired-compress-files-alist'."
1071
  (interactive)
1072
  (require 'format-spec)
1073
  (let* ((in-files (dired-get-marked-files nil nil nil nil t))
Eli Zaretskii's avatar
Eli Zaretskii committed
1074
         (out-file (expand-file-name (read-file-name "Compress to: ")))
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
         (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
1091 1092 1093 1094 1095 1096 1097
                   (format-spec (cdr rule)
                                `((?\o . ,(shell-quote-argument out-file))
                                  (?\i . ,(mapconcat
                                           (lambda (file-desc)
                                             (shell-quote-argument (file-name-nondirectory
                                                                    file-desc)))
                                           in-files " "))))))
1098 1099 1100
             (message (ngettext "Compressed %d file to %s"
			        "Compressed %d files to %s"
			        (length in-files))
1101 1102 1103
                      (length in-files)
                      (file-name-nondirectory out-file)))))))

1104
;;;###autoload
1105
(defun dired-compress-file (file)
1106 1107 1108
  "Compress or uncompress FILE.
Return the name of the compressed or uncompressed file.
Return nil if no change in files."
1109
  (let ((handler (find-file-name-handler file 'dired-compress-file))
1110
        suffix newname
1111 1112
        (suffixes dired-compress-file-suffixes)
        command)
1113 1114 1115
    ;; See if any suffix rule matches this file name.
    (while suffixes
      (let (case-fold-search)
1116 1117 1118
        (if (string-match (car (car suffixes)) file)
            (setq suffix (car suffixes) suffixes nil))
        (setq suffixes (cdr suffixes))))
1119
    ;; If so, compute desired new name.
1120
    (if suffix
1121 1122
        (setq newname (concat (substring file 0 (match-beginning 0))
                              (nth 1 suffix))))
1123
    (cond (handler
1124 1125 1126
           (funcall handler 'dired-compress-file file))
          ((file-symlink-p file)
           nil)
1127 1128 1129 1130 1131
          ((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
1132
                   "%o" (shell-quote-argument newname)
1133
                   (replace-regexp-in-string
1134 1135 1136 1137
                    "%i" (shell-quote-argument file)
                    command
                    nil t)
                   nil t)))
1138
             ;; We found an uncompression rule.
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
             (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))))
1150 1151 1152 1153
          (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
1154 1155
               (if (file-directory-p file)
                   (progn
1156
                     (setq suffix (cdr (assoc "\000" dired-compress-file-suffixes)))
1157 1158 1159 1160 1161
                     (when suffix
                       (let ((out-name (concat file (car suffix)))
                             (default-directory (file-name-directory file)))
                         (dired-shell-command
                          (replace-regexp-in-string
1162
                           "%o" (shell-quote-argument out-name)
1163
                           (replace-regexp-in-string
1164 1165 1166 1167
                            "%i" (shell-quote-argument (file-name-nondirectory file))
                            (cadr suffix)
                            nil t)
                           nil t))
1168 1169 1170 1171 1172 1173 1174
                         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
1175
                         (dired-check-process (concat "Compressing " file)
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
                                              "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))))
1186 1187 1188 1189 1190
             (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
1191

Richard M. Stallman's avatar
Richard M. Stallman committed
1192 1193 1194 1195 1196 1197
(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).
1198 1199
  (or (eq dired-no-confirm t)
      (memq op-symbol dired-no-confirm)
Richard M. Stallman's avatar
Richard M. Stallman committed
1200 1201 1202
      ;; 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.
1203
      (let ((files (dired-get-marked-files t arg nil t t))
1204 1205
	    (string (if (eq op-symbol 'compress) "Compress or uncompress"
		      (capitalize (symbol-name op-symbol)))))
1206
	(dired-mark-pop-up nil op-symbol files #'y-or-n-p
1207
			   (concat string " "
Richard M. Stallman's avatar
Richard M. Stallman committed
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
				   (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))
1229 1230 1231
	     (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
1232
	(if (not failures)
1233 1234
	    (message (ngettext "%s: %d file." "%s: %d files." total)
		     string total)
Richard M. Stallman's avatar
Richard M. Stallman committed
1235 1236
	  ;; end this bunch of errors:
	  (dired-log-summary
1237 1238 1239 1240
	   (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
1241 1242
	   failures)))))

1243
;;;###autoload
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
(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
1263
		 (concat (apply #'format-message prompt args)
1264 1265
			 (if help-form
			     (format " [Type yn!q or %s] "
1266
				     (key-description (vector help-char)))
1267 1268 1269 1270
			   " [Type y, n, q or !] ")))
	   (set sym (setq char (read-char-choice prompt char-choices)))
	   (if (memq char '(?y ?\s ?!)) t)))))</