dired-aux.el 101 KB
Newer Older
1
;;; dired-aux.el --- less commonly used parts of dired
Richard M. Stallman's avatar
Richard M. Stallman committed
2

3
;; Copyright (C) 1985-1986, 1992, 1994, 1998, 2000-2012
Glenn Morris's avatar
Glenn Morris committed
4
;;   Free Software 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>.
Richard M. Stallman's avatar
Richard M. Stallman committed
7
;; Maintainer: FSF
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 <http://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 39 40
;; We need macros in dired.el to compile properly,
;; and we call subroutines in it too.
(require 'dired)
41

42 43 44 45 46
(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
47 48 49 50
;;; 15K
;;;###begin dired-cmd.el
;; Diffing and compressing

51 52 53
(defconst dired-star-subst-regexp "\\(^\\|[ \t]\\)\\*\\([ \t]\\|$\\)")
(defconst dired-quark-subst-regexp "\\(^\\|[ \t]\\)\\?\\([ \t]\\|$\\)")

54 55
(declare-function diff-latest-backup-file "diff" (fn)) ; actually belongs into files.el

Richard M. Stallman's avatar
Richard M. Stallman committed
56 57 58
;;;###autoload
(defun dired-diff (file &optional switches)
  "Compare file at point with file FILE using `diff'.
59 60 61 62 63 64 65 66
If called interactively, prompt for FILE.  If the file at point
has a backup file, use that as the default.  If the mark is active
in Transient Mark mode, use the file at the mark as the default.
\(That's the mark set by \\[set-mark-command], not by Dired's
\\[dired-mark] command.)

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

68 69
With prefix arg, prompt for second argument SWITCHES, which is
the string of command switches for the third argument of `diff'."
Richard M. Stallman's avatar
Richard M. Stallman committed
70
  (interactive
71
   (let* ((current (dired-get-filename t))
72
	  ;; Get the latest existing backup file.
73
	  (oldf (progn (require 'diff) (diff-latest-backup-file current)))
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
	  ;; 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))))
	  (default-file (or file-at-mark
			    (and oldf (file-name-nondirectory oldf))))
	  ;; 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
			  (dired-current-directory)
			(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
			 (mapconcat 'identity diff-switches " ")))))))
105 106 107 108 109 110 111 112
  (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"))
    (diff file current switches)))
Richard M. Stallman's avatar
Richard M. Stallman committed
113 114 115 116 117 118

;;;###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.
119 120 121 122 123 124 125 126 127 128
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
			     (mapconcat 'identity diff-switches " "))))
      nil))
  (diff-backup (dired-get-filename) switches))
Richard M. Stallman's avatar
Richard M. Stallman committed
129

130
;;;###autoload
131 132 133 134 135
(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.
136
Mark files with different names if PREDICATE is nil (or interactively
137
with empty input at the predicate prompt).
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

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
    (not (string= (nth 8 fa1) (nth 8 fa2))) - mark files with different modes
    (not (and (= (nth 2 fa1) (nth 2 fa2))   - mark files with different UID
              (= (nth 3 fa1) (nth 3 fa2))))   and GID."
  (interactive
157 158 159 160 161 162 163 164 165 166 167
   (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")))
168 169 170
  (let* ((dir1 (dired-current-directory))
         (file-alist1 (dired-files-attributes dir1))
         (file-alist2 (dired-files-attributes dir2))
171 172 173 174 175 176
	 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
177 178 179
		      'cadr
                      (dired-file-set-difference
                       file-alist1 file-alist2
180 181
		       predicate))
	  file-list2 (mapcar
182 183 184
		      'cadr
                      (dired-file-set-difference
                       file-alist2 file-alist1
185
		       predicate)))
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    (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)))
    (message "Marked in dir1: %s files, in dir2: %s files"
             (length file-list1)
             (length file-list2))))

(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
			      (not (let* ((file2 (car list))
215 216
					  (fa1 (car (cddr file1)))
					  (fa2 (car (cddr file2)))
217 218 219 220 221 222 223 224 225 226 227 228 229 230
					  (size1 (nth 7 fa1))
					  (size2 (nth 7 fa2))
					  (mtime1 (float-time (nth 5 fa1)))
					  (mtime2 (float-time (nth 5 fa2))))
				     (and
				      (equal (car file1) (car file2))
				      (not (eval predicate))))))
		    (setq list (cdr list)))
		  list)
	  (setq res (cons file1 res))))
      (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
231
List has a form of (file-name full-file-name (attribute-list))."
232 233 234 235 236 237 238 239
  (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)))

240
;;; Change file attributes
Juri Linkov's avatar
Juri Linkov committed
241

Richard M. Stallman's avatar
Richard M. Stallman committed
242
(defun dired-do-chxxx (attribute-name program op-symbol arg)
243
  ;; Change file attributes (group, owner, timestamp) of marked files and
Richard M. Stallman's avatar
Richard M. Stallman committed
244 245 246
  ;; refresh their file lines.
  ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
  ;; PROGRAM is the program used to change the attribute.
247 248
  ;; 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'.
Richard M. Stallman's avatar
Richard M. Stallman committed
249
  (let* ((files (dired-get-marked-files t arg))
250
	 ;; The source of default file attributes is the file at point.
251
	 (default-file (dired-get-filename t t))
252 253 254 255 256 257 258 259 260
	 (default (when default-file
		    (cond ((eq op-symbol 'touch)
			   (format-time-string
			    "%Y%m%d%H%M.%S"
			    (nth 5 (file-attributes default-file))))
			  ((eq op-symbol 'chown)
			   (nth 2 (file-attributes default-file 'string)))
			  ((eq op-symbol 'chgrp)
			   (nth 3 (file-attributes default-file 'string))))))
261 262 263 264 265
	 (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
266 267 268 269 270
						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
271 272 273 274 275
	 (operation (concat program " " new-attribute))
	 failures)
    (setq failures
	  (dired-bunch-files 10000
			     (function dired-check-process)
276
			     (append
Juri Linkov's avatar
Juri Linkov committed
277
			      (list operation program)
278 279 280 281
			      (unless (or (string-equal new-attribute "")
					  ;; Use `eq' instead of `equal'
					  ;; to detect empty input (bug#12399).
					  (eq new-attribute default))
282 283 284
				(if (eq op-symbol 'touch)
				    (list "-t" new-attribute)
				  (list new-attribute)))
285 286
			      (if (string-match "gnu" system-configuration)
				  '("--") nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
287 288 289 290 291 292 293 294 295 296
			     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.
297 298 299
Symbolic modes like `g+w' are allowed.
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
300
  (interactive "P")
301
  (let* ((files (dired-get-marked-files t arg))
302
	 ;; The source of default file attributes is the file at point.
303
	 (default-file (dired-get-filename t t))
304 305
	 (modestr (when default-file
		    (nth 8 (file-attributes default-file))))
306 307 308 309 310 311 312 313 314
	 (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)))))
315
	 (modes (dired-mark-read-string
316
		 "Change mode of %s to: "
317
		 nil 'chmod arg files default))
318
	 num-modes)
319 320 321 322
    (cond ((or (equal modes "")
	       ;; Use `eq' instead of `equal'
	       ;; to detect empty input (bug#12399).
	       (eq modes default))
323 324 325 326 327 328
	   ;; We used to treat empty input as DEFAULT, but that is not
	   ;; such a good idea (Bug#9361).
	   (error "No file mode specified"))
	  ((string-match "^[0-7]+" modes)
	   (setq num-modes (string-to-number modes 8))))

329 330 331 332 333 334
    (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
335 336 337

;;;###autoload
(defun dired-do-chgrp (&optional arg)
338 339 340
  "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
341
  (interactive "P")
342
  (if (memq system-type '(ms-dos windows-nt))
343
      (error "chgrp not supported on this system"))
Richard M. Stallman's avatar
Richard M. Stallman committed
344 345 346 347
  (dired-do-chxxx "Group" "chgrp" 'chgrp arg))

;;;###autoload
(defun dired-do-chown (&optional arg)
348 349 350
  "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
351
  (interactive "P")
352
  (if (memq system-type '(ms-dos windows-nt))
353
      (error "chown not supported on this system"))
Richard M. Stallman's avatar
Richard M. Stallman committed
354 355
  (dired-do-chxxx "Owner" dired-chown-program 'chown arg))

356
;;;###autoload
Juri Linkov's avatar
Juri Linkov committed
357 358
(defun dired-do-touch (&optional arg)
  "Change the timestamp of the marked (or next ARG) files.
359 360 361
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
362 363 364
  (interactive "P")
  (dired-do-chxxx "Timestamp" dired-touch-program 'touch arg))

Richard M. Stallman's avatar
Richard M. Stallman committed
365 366 367 368 369 370
;; 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
371
	past
Richard M. Stallman's avatar
Richard M. Stallman committed
372 373 374 375 376 377 378 379 380 381 382
	(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))
383 384 385 386 387
	    (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
388
		  ;; Transfer the elements of PENDING onto PAST
389 390 391
		  ;; 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
392 393 394 395 396 397 398 399
		  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)))
400 401 402 403 404 405
    (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
406 407 408 409 410 411 412 413 414 415

;;;###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")
  (let* ((file-list (dired-get-marked-files t arg))
	 (command (dired-mark-read-string
		   "Print %s with: "
416 417 418 419 420 421
 		   (mapconcat 'identity
			      (cons lpr-command
				    (if (stringp lpr-switches)
					(list lpr-switches)
				      lpr-switches))
			      " ")
Richard M. Stallman's avatar
Richard M. Stallman committed
422 423 424
		   'print arg file-list)))
    (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))

425
(defun dired-mark-read-string (prompt initial op-symbol arg files
426
			       &optional default-value collection)
427 428 429 430 431
  "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
432 433 434
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.
435

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

Chong Yidong's avatar
Chong Yidong committed
439 440
Optional arg COLLECTION is a collection of possible completions,
passed as the second arg to `completing-read'."
441
  (dired-mark-pop-up nil op-symbol files
442
		     'completing-read
443
		     (format prompt (dired-mark-prompt arg files))
444
		     collection nil nil initial nil default-value nil))
Dave Love's avatar
Dave Love committed
445

446 447
;;; Cleaning a directory: flagging some backups for deletion.

448 449
(defvar dired-file-version-alist)

450
;;;###autoload
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
(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)
    (dired-map-dired-file-lines (function dired-collect-file-versions))
    ;; 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.
    (dired-map-dired-file-lines (function dired-trample-file-versions))
    (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.
493
  ;; FUN takes one argument, the absolute filename.
494 495 496 497 498 499 500 501 502 503 504 505
  (save-excursion
    (let (file buffer-read-only)
      (goto-char (point-min))
      (while (not (eobp))
	(save-excursion
	  (and (not (looking-at dired-re-dir))
	       (not (eolp))
	       (setq file (dired-get-filename nil t)) ; nil on non-file
	       (progn (end-of-line)
		      (funcall fun file))))
	(forward-line 1)))))

506 507
(defvar backup-extract-version-start)  ; used in backup-extract-version

508
(defun dired-collect-file-versions (fn)
509 510 511 512 513 514
  (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.
515
      ;;The caller may want to flag some of these files for deletion.
516 517
      (let* ((base-versions
	      (concat (file-name-nondirectory fn) ".~"))
518
	     (backup-extract-version-start (length base-versions))
519 520 521 522 523 524 525 526
	     (possibilities (file-name-all-completions
			     base-versions
			     (file-name-directory fn)))
	     (versions (mapcar 'backup-extract-version possibilities)))
	(if versions
	    (setq dired-file-version-alist
		  (cons (cons fn versions)
			dired-file-version-alist)))))))
527 528 529 530 531 532 533 534

(defun dired-trample-file-versions (fn)
  (let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
	 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
535
	 (not (memq (string-to-number (substring fn (+ 2 start-vn)))
536 537 538 539
		    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
540

Richard M. Stallman's avatar
Richard M. Stallman committed
541 542
;;; Shell commands

543 544 545
(declare-function mailcap-file-default-commands "mailcap" (files))

(defun minibuffer-default-add-dired-shell-commands ()
546 547
  "Return a list of all commands associated with current dired files.
This function is used to add all related commands retrieved by `mailcap'
548 549 550 551 552 553 554
to the end of the list of defaults just after the default value."
  (interactive)
  (let ((commands (and (boundp 'files) (require 'mailcap nil t)
		       (mailcap-file-default-commands files))))
    (if (listp minibuffer-default)
	(append minibuffer-default commands)
      (cons minibuffer-default commands))))
555

556
;; 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
557
(defun dired-read-shell-command (prompt arg files)
Chong Yidong's avatar
Chong Yidong committed
558 559 560 561 562 563 564 565 566
  "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."
567 568 569 570
  (minibuffer-with-setup-hook
      (lambda ()
	(set (make-local-variable 'minibuffer-default-add-function)
	     'minibuffer-default-add-dired-shell-commands))
571
    (setq prompt (format prompt (dired-mark-prompt arg files)))
Chong Yidong's avatar
Chong Yidong committed
572
    (if (functionp 'dired-guess-shell-command)
573
	(dired-mark-pop-up nil 'shell files
Chong Yidong's avatar
Chong Yidong committed
574
			   'dired-guess-shell-command prompt files)
575
      (dired-mark-pop-up nil 'shell files
Chong Yidong's avatar
Chong Yidong committed
576
			 'read-shell-command prompt nil nil))))
Richard M. Stallman's avatar
Richard M. Stallman committed
577

578 579 580 581
;;;###autoload
(defun dired-do-async-shell-command (command &optional arg file-list)
  "Run a shell command COMMAND on the marked files asynchronously.

582 583 584 585 586 587 588 589 590 591 592
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 `;'.

593 594 595 596 597 598 599 600 601 602 603 604
The output appears in the buffer `*Async Shell Command*'."
  (interactive
   (let ((files (dired-get-marked-files t current-prefix-arg)))
     (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)))
  (unless (string-match "&[ \t]*\\'" command)
    (setq command (concat command " &")))
  (dired-do-shell-command command arg file-list))

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

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

615 616 617
If there is no `*', but there is a `?' in COMMAND, surrounded by
whitespace, this runs COMMAND on each file individually with the
file name substituted for `?'.
Richard M. Stallman's avatar
Richard M. Stallman committed
618

619 620
Otherwise, this runs COMMAND on each file individually with the
file name added at the end of COMMAND (separated by a space).
621

622 623
`*' and `?' when not surrounded by whitespace have no special
significance for `dired-do-shell-command', and are passed through
624 625 626 627 628
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
629

630 631 632 633 634 635 636 637 638 639 640
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*'.
641 642 643 644 645

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
646 647 648
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.
649 650

In a noninteractive call (from Lisp code), you must specify
651 652
the list of file names explicitly with the FILE-LIST argument, which
can be produced by `dired-get-marked-files', for example."
Richard M. Stallman's avatar
Richard M. Stallman committed
653 654
;;Functions dired-run-shell-command and dired-shell-stuff-it do the
;;actual work and can be redefined for customization.
655 656 657 658
  (interactive
   (let ((files (dired-get-marked-files t current-prefix-arg)))
     (list
      ;; Want to give feedback whether this file or marked files are used:
659
      (dired-read-shell-command "! on %s: " current-prefix-arg files)
660 661
      current-prefix-arg
      files)))
662
  (let* ((on-each (not (string-match dired-star-subst-regexp command)))
663 664 665
	 (no-subst (not (string-match dired-quark-subst-regexp command)))
	 (star (string-match "\\*" command))
	 (qmark (string-match "\\?" command)))
666 667
    ;; Get confirmation for wildcards that may have been meant
    ;; to control substitution of a file name or the file name list.
668
    (if (cond ((not (or on-each no-subst))
669
	       (error "You can not combine `*' and `?' substitution marks"))
670
	      ((and star on-each)
671
	       (y-or-n-p "Confirm--do you mean to use `*' as a wildcard? "))
672
	      ((and qmark no-subst)
673 674 675 676 677 678 679 680 681 682 683 684 685
	       (y-or-n-p "Confirm--do you mean to use `?' as a wildcard? "))
	      (t))
	(if on-each
	    (dired-bunch-files
	     (- 10000 (length command))
	     (function (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
686 687 688 689 690 691 692 693 694

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

695
(defun dired-shell-stuff-it (command file-list on-each &optional _raw-arg)
Richard M. Stallman's avatar
Richard M. Stallman committed
696 697 698 699 700 701 702
;; "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.
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
  (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))
	 (stuff-it
	  (if (or (string-match dired-star-subst-regexp command)
		  (string-match dired-quark-subst-regexp command))
	      (lambda (x)
		(let ((retval command))
		  (while (string-match
			  "\\(^\\|[ \t]\\)\\([*?]\\)\\([ \t]\\|$\\)" retval)
		    (setq retval (replace-match x t t retval 2)))
		  retval))
	    (lambda (x) (concat command dired-mark-separator x)))))
    (concat
     (if on-each
	 (mapconcat stuff-it (mapcar 'shell-quote-argument file-list)
		    (if (and in-background (not sequentially)) "&" ";"))
       (let ((files (mapconcat 'shell-quote-argument
			       file-list dired-mark-separator)))
	 (if (> (length file-list) 1)
	     (setq files (concat dired-mark-prefix files dired-mark-postfix)))
	 (funcall stuff-it files)))
     (if in-background "&" ""))))
Richard M. Stallman's avatar
Richard M. Stallman committed
731 732

;; This is an extra function so that it can be redefined by ange-ftp.
733
;;;###autoload
734
(defun dired-run-shell-command (command)
735 736 737 738 739
  (let ((handler
	 (find-file-name-handler (directory-file-name default-directory)
				 'shell-command)))
    (if handler (apply handler 'shell-command (list command))
      (shell-command command)))
740 741
  ;; Return nil for sake of nconc in dired-bunch-files.
  nil)
Dave Love's avatar
Dave Love committed
742

Richard M. Stallman's avatar
Richard M. Stallman committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758

(defun dired-check-process (msg program &rest arguments)
;  "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."
  (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
759
	    err (not (eq 0 (apply 'process-file program nil t nil arguments))))
Richard M. Stallman's avatar
Richard M. Stallman committed
760 761 762 763 764 765 766 767
      (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))))
Dave Love's avatar
Dave Love committed
768

Richard M. Stallman's avatar
Richard M. Stallman committed
769 770 771
;; Commands that delete or redisplay part of the dired buffer.

(defun dired-kill-line (&optional arg)
772 773 774
  "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
775 776 777 778 779 780
  (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)
781
	  (error "Can only kill file lines")
Richard M. Stallman's avatar
Richard M. Stallman committed
782 783 784
	(save-excursion (and file
			     (dired-goto-subdir file)
			     (dired-kill-subdir)))
785
	(delete-region (line-beginning-position)
Richard M. Stallman's avatar
Richard M. Stallman committed
786 787 788 789 790 791 792 793 794 795
		       (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).
796
With a prefix argument, kill that many lines starting with the current line.
797 798 799 800 801 802 803 804
\(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
805 806
  ;; Returns count of killed lines.  FMT="" suppresses message.
  (interactive "P")
807 808 809 810 811 812
  (if arg
      (if (dired-get-subdir)
	  (dired-kill-subdir)
	(dired-kill-line arg))
    (save-excursion
      (goto-char (point-min))
813 814 815 816 817 818
      (let (buffer-read-only
	    (count 0)
	    (regexp (dired-marker-regexp)))
	(while (and (not (eobp))
		    (re-search-forward regexp nil t))
	  (setq count (1+ count))
819
	  (delete-region (line-beginning-position)
820
			 (progn (forward-line 1) (point))))
821 822 823
	(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
824 825

;;;###end dired-cmd.el
Dave Love's avatar
Dave Love committed
826

Richard M. Stallman's avatar
Richard M. Stallman committed
827 828 829 830 831 832 833
;;; 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
834 835 836
	 (from-file (dired-get-filename))
	 (new-file (dired-compress-file from-file)))
    (if new-file
837 838 839 840 841 842 843 844
	(let ((start (point)))
	  ;; Remove any preexisting entry for the name NEW-FILE.
	  (condition-case nil
	      (dired-remove-entry new-file)
	    (error nil))
	  (goto-char start)
	  ;; Now replace the current line with an entry for NEW-FILE.
	  (dired-update-file-line new-file) nil)
845 846 847
      (dired-log (concat "Failed to compress" from-file))
      from-file)))

848 849 850 851 852 853 854
(defvar dired-compress-file-suffixes
  '(("\\.gz\\'" "" "gunzip")
    ("\\.tgz\\'" ".tar" "gunzip")
    ("\\.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")
855 856
    ("\\.dz\\'" "" "dictunzip")
    ("\\.tbz\\'" ".tar" "bunzip2")
857
    ("\\.bz2\\'" "" "bunzip2")
858
    ("\\.xz\\'" "" "unxz")
859 860 861 862 863 864 865 866 867 868 869 870
    ;; This item controls naming for compression.
    ("\\.tar\\'" ".tgz" nil))
  "Control changes in file name suffixes for compression and uncompression.
Each element specifies one transformation rule, and has the form:
  (REGEXP NEW-SUFFIX PROGRAM)
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.
Otherwise, the rule is a compression rule, and compression is done with gzip.")

Richard M. Stallman's avatar
Richard M. Stallman committed
871
;;;###autoload
872 873 874
(defun dired-compress-file (file)
  ;; Compress or uncompress FILE.
  ;; Return the name of the compressed or uncompressed file.
875
  ;; Return nil if no change in files.
876 877 878 879 880 881 882 883 884 885
  (let ((handler (find-file-name-handler file 'dired-compress-file))
	suffix newname
	(suffixes dired-compress-file-suffixes))
    ;; See if any suffix rule matches this file name.
    (while suffixes
      (let (case-fold-search)
	(if (string-match (car (car suffixes)) file)
	    (setq suffix (car suffixes) suffixes nil))
	(setq suffixes (cdr suffixes))))
    ;; If so, compute desired new name.
886
    (if suffix
887 888
	(setq newname (concat (substring file 0 (match-beginning 0))
			      (nth 1 suffix))))
889 890 891 892
    (cond (handler
	   (funcall handler 'dired-compress-file file))
	  ((file-symlink-p file)
	   nil)
893 894
	  ((and suffix (nth 2 suffix))
	   ;; We found an uncompression rule.
895
	   (if (not (dired-check-process (concat "Uncompressing " file)
896 897
					 (nth 2 suffix) file))
	       newname))
Richard M. Stallman's avatar
Richard M. Stallman committed
898
	  (t
899
	   ;;; We don't recognize the file as compressed, so compress it.
900 901
	   ;;; Try gzip; if we don't have that, use compress.
	   (condition-case nil
902 903 904
	       (let ((out-name (concat file ".gz")))
		 (and (or (not (file-exists-p out-name))
			  (y-or-n-p
905 906
			   (format "File %s already exists.  Really compress? "
				   out-name)))
907 908 909 910 911 912 913 914 915 916 917
		      (not (dired-check-process (concat "Compressing " file)
						"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)))
918 919 920
	     (file-error
	      (if (not (dired-check-process (concat "Compressing " file)
					    "compress" "-f" file))
921
		  ;; Don't use NEWNAME with `compress'.
922
		  (concat file ".Z"))))))))
Dave Love's avatar
Dave Love committed
923

Richard M. Stallman's avatar
Richard M. Stallman committed
924 925 926 927 928 929
(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
930 931
  (or (eq dired-no-confirm t)
      (memq op-symbol dired-no-confirm)
Richard M. Stallman's avatar
Richard M. Stallman committed
932 933 934 935
      ;; 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.
      (let ((files (dired-get-marked-files t arg nil t))
936 937
	    (string (if (eq op-symbol 'compress) "Compress or uncompress"
		      (capitalize (symbol-name op-symbol)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
938
	(dired-mark-pop-up nil op-symbol files (function y-or-n-p)
939
			   (concat string " "
Richard M. Stallman's avatar
Richard M. Stallman committed
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
				   (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))
961 962 963
	     (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
964 965
	(if (not failures)
	    (message "%s: %d file%s."
966
		     string total (dired-plural-s total))
Richard M. Stallman's avatar
Richard M. Stallman committed
967 968 969
	  ;; end this bunch of errors:
	  (dired-log-summary
	   (format "Failed to %s %d of %d file%s"
970
		   (downcase string) count total (dired-plural-s total))
Richard M. Stallman's avatar
Richard M. Stallman committed
971 972
	   failures)))))

973
;;;###autoload
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
(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
		 (concat (apply 'format prompt args)
			 (if help-form
			     (format " [Type yn!q or %s] "
996
				     (key-description (vector help-char)))
997 998 999 1000
			   " [Type y, n, q or !] ")))
	   (set sym (setq char (read-char-choice prompt char-choices)))
	   (if (memq char '(?y ?\s ?!)) t)))))

Dave Love's avatar
Dave Love committed
1001

Richard M. Stallman's avatar
Richard M. Stallman committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
;;;###autoload
(defun dired-do-compress (&optional arg)
  "Compress or uncompress marked (or next ARG) files."
  (interactive "P")
  (dired-map-over-marks-check (function dired-compress) arg 'compress t))

;; Commands for Emacs Lisp files - load and byte compile

(defun dired-byte-compile ()
  ;; Return nil for success, offending file name else.
  (let* ((filename (dired-get-filename))
1013
	 elc-file buffer-read-only failure)
Richard M. Stallman's avatar
Richard M. Stallman committed
1014 1015 1016 1017
    (condition-case err
	(save-excursion (byte-compile-file filename))
      (error
       (setq failure err)))
1018
    (setq elc-file (byte-compile-dest-file filename))
1019 1020
    (or (file-exists-p elc-file)
	(setq failure t))
Richard M. Stallman's avatar
Richard M. Stallman committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    (if failure
	(progn
	  (dired-log "Byte compile error for %s:\n%s\n" filename failure)
	  (dired-make-relative filename))
      (dired-remove-file elc-file)
      (forward-line)			; insert .elc after its .el file
      (dired-add-file elc-file)
      nil)))

;;;###autoload
(defun dired-do-byte-compile (&optional arg)
  "Byte compile marked (or next ARG) Emacs Lisp files."
  (interactive "P")
  (dired-map-over-marks-check (function dired-byte-compile) arg 'byte-compile t))

(defun dired-load ()
  ;; Return nil for success, offending file name else.
  (let ((file (dired-get-filename)) failure)
    (condition-case err
      (load file nil nil t)
      (error (setq failure err)))
    (if (not failure)
	nil
      (dired-log "Load error for %s:\n%s\n" file failure)
      (dired-make-relative file))))

;;;###autoload
(defun dired-do-load (&optional arg)
  "Load the marked (or next ARG) Emacs Lisp files."
  (interactive "P")
  (dired-map-over-marks-check (function dired-load) arg 'load t))

;;;###autoload
(defun dired-do-redisplay (&optional arg test-for-subdir)
  "Redisplay all marked (or next ARG) files.
If on a subdir line, redisplay that subdirectory.  In that case,
1057 1058 1059 1060 1061 1062 1063
a prefix arg lets you edit the `ls' switches used for the new listing.

Dired remembers switches specified with a prefix arg, so that reverting
the buffer will not reset them.  However, using `dired-undo' to re-insert
or delete subdirectories can bypass this machinery.  Hence, you sometimes
may have to reset some subdirectory switches after a `dired-undo'.
You can reset all subdirectory switches to the default using
1064
\\<dired-mode-map>\\[dired-reset-subdir-switches].
1065
See Info node `(emacs)Subdir switches' for more details."
Richard M. Stallman's avatar
Richard M. Stallman committed
1066 1067 1068
  ;; Moves point if the next ARG files are redisplayed.
  (interactive "P\np")
  (if (and test-for-subdir (dired-get-subdir))
1069 1070 1071 1072 1073 1074 1075 1076 1077
      (let* ((dir (dired-get-subdir))
	     (switches (cdr (assoc-string dir dired-switches-alist))))
	(dired-insert-subdir
	 dir
	 (when arg
	   (read-string "Switches for listing: "
			(or switches
			    dired-subdir-switches
			    dired-actual-switches)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1078 1079
    (message "Redisplaying...")
    ;; message much faster than making dired-map-over-marks show progress
1080 1081
    (dired-uncache
     (if (consp dired-directory) (car dired-directory) dired-directory))
1082
    (dired-map-over-marks (let ((fname (dired-get-filename))
Juanma Barranquero's avatar
Juanma Barranquero committed
1083
				;; Postpone readin hook till we map
1084 1085
				;; over all marked files (Bug#6810).
				(dired-after-readin-hook nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
1086 1087 1088
			    (message "Redisplaying... %s" fname)
			    (dired-update-file-line fname))
			  arg)
1089
    (run-hooks 'dired-after-readin-hook)
Richard M. Stallman's avatar
Richard M. Stallman committed
1090 1091
    (dired-move-to-filename)
    (message "Redisplaying...done")))
1092 1093 1094 1095 1096 1097

(defun dired-reset-subdir-switches ()
  "Set `dired-switches-alist' to nil and revert dired buffer."
  (interactive)
  (setq dired-switches-alist nil)
  (revert-buffer))
Dave Love's avatar
Dave Love committed
1098

Richard M. Stallman's avatar
Richard M. Stallman committed
1099 1100 1101 1102 1103 1104
(defun dired-update-file-line (file)
  ;; Delete the current line, and insert an entry for FILE.
  ;; If FILE is nil, then just delete the current line.
  ;; Keeps any marks that may be present in column one (doing this
  ;; here is faster than with dired-add-entry's optional arg).
  ;; Does not update other dired buffers.  Use dired-relist-entry for that.
Stephen Berman's avatar
Stephen Berman committed
1105 1106 1107
  (let* ((opoint (line-beginning-position))
	 (char (char-after opoint))
	 (buffer-read-only))
1108
    (delete-region opoint (progn (forward-line 1) (point)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1109 1110
    (if file
	(progn
1111
	  (dired-add-entry file nil t)
Richard M. Stallman's avatar
Richard M. Stallman committed
1112 1113 1114 1115 1116
	  ;; Replace space by old marker without moving point.
	  ;; Faster than goto+insdel inside a save-excursion?
	  (subst-char-in-region opoint (1+ opoint) ?\040 char))))
  (dired-move-to-filename))

Richard M. Stallman's avatar
Richard M. Stallman committed
1117
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
1118 1119
(defun dired-add-file (filename &optional marker-char)
  (dired-fun-in-all-buffers
1120
   (file-name-directory filename) (file-name-nondirectory filename)
Richard M. Stallman's avatar
Richard M. Stallman committed
1121 1122
   (function dired-add-entry) filename marker-char))

1123 1124 1125 1126
(defvar dired-omit-mode)
(declare-function dired-omit-regexp "dired-x" ())
(defvar dired-omit-localp)

1127
(defun dired-add-entry (filename &optional marker-char relative)
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146