forked from calancha/dired-du
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dired-du.el
2494 lines (2298 loc) · 110 KB
/
dired-du.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; dired-du.el --- Dired with recursive directory sizes -*- lexical-binding: t -*-
;;
;; Filename: dired-du.el
;; Description: Dired with recursive directory sizes
;; Author: Tino Calancha <[email protected]>
;; Maintainer: Tino Calancha <[email protected]>
;; Copyright (C) 2016-2019, Tino Calancha, all rights reserved.
;; Created: Wed Mar 23 22:54:00 2016
;; Version: 0.5.2
;; Package-Requires: ((emacs "24.4") (cl-lib "0.5"))
;; Last-Updated: Sun Feb 24 19:53:27 JST 2019
;; By: calancha
;; Update #: 344
;; Compatibility: GNU Emacs: 24.4
;; Keywords: files, unix, convenience
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Commentary:
;;
;; -- Display the recursive size of directories in Dired --
;;
;; This file defines a minor mode `dired-du-mode' to show
;; the recursive size of directories in Dired buffers.
;; If `du' program is available, then the directory sizes are
;; obtained with it. Otherwise, the directory sizes are obtained
;; with Lisp. The former is faster and provide a more precise value.
;; For directories where the user doesn't have read permission,
;; the recursive size is not obtained.
;; Once this mode is enabled, every new Dired buffer displays
;; recursive dir sizes.
;;
;; To enable the mode at start up:
;;
;; 1) Store the file in a directory within `load-path'.
;; 2) Add the following into .emacs file:
;;
;; (add-hook 'dired-mode-hook #'dired-du-mode)
;;
;; Note that obtaining the recursive size of all the directories
;; in a Dired buffer might be very slow: it may significantly delay
;; the time to display a new Dired buffer.
;; Instead of enabling `dired-du-mode' by default in all Dired buffers
;; you might prefer to use this mode just as an interfaz to
;; the `du' program: you can enable it in the current Dired buffer,
;; and disable it once you have finished checking the used space.
;;
;; -- Number of marked files and their size --
;;
;; In addition, this library adds a command, `dired-du-count-sizes',
;; to count the number of marked files and how much space
;; they use; the command accepts a particular character mark
;; i.e., '*' or all kind of marks i.e, any character other than ?\s.
;;
;; Bugs
;; ====
;; * Sometimes the progress reporter shows funny things,
;; for instance, percents > 100.
;;
;; * Order by size only works with directory recursive sizes if you use
;; `ls-lisp' with `ls-lisp-use-insert-directory-program' set nil; otherwise,
;; the external ls program is responsible to do the sorting ignoring
;; the recursive dir sizes.
;;
;;
;; Internal variables defined here:
;;
;; `dired-du--user-warned', `dired-du-dir-info',
;; `dired-du-filesp-subdir-header', `dired-du-find-dired-buffer',
;; `dired-du-local-subdir-header', `dired-du-mode',
;; `dired-du-remote-subdir-header'.
;;
;; Coustom variables defined here:
;;
;; `dired-du-bind-count-sizes', `dired-du-bind-human-toggle',
;; `dired-du-bind-mode', `dired-du-on-find-dired-ok',
;; `dired-du-size-format', `dired-du-update-headers',
;; `dired-du-used-space-program'.
;;
;; Macros defined here:
;;
;; `dired-du-map-over-marks', `dired-du-with-saved-marks'.
;;
;; Commands defined here:
;;
;; `dired-du--toggle-human-readable', `dired-du-count-sizes',
;; `dired-du-drop-all-subdirs', `dired-du-insert-marked-dirs',
;; `dired-du-on-find-dired-ok-toggle', `dired-du-recompute-dir-size',
;; `dired-du-update-dir-info'.
;;
;; Non-interactive functions defined here:
;;
;; `dired-du--cache-dir-info', `dired-du--change-human-sizes',
;; `dired-du--count-sizes-1', `dired-du--count-sizes-2',
;; `dired-du--create-or-check-dir-info', `dired-du--delete-entry',
;; `dired-du--drop-unexistent-files', `dired-du--file-in-dir-info-p',
;; `dired-du--find-dired-around', `dired-du--fullname-to-glob-pos',
;; `dired-du--get-all-files-type',
;; `dired-du--get-max-gid-and-size-lengths-for-subdir',
;; `dired-du--get-num-extra-blanks', `dired-du--get-position',
;; `dired-du--get-position-1', `dired-du--get-recursive-dir-size',
;; `dired-du--get-value', `dired-du--global-update-dir-info',
;; `dired-du--initialize', `dired-du--insert-subdir',
;; `dired-du--local-update-dir-info', `dired-du--number-as-string-p',
;; `dired-du--read-size-from-buffer', `dired-du--replace',
;; `dired-du--replace-1', `dired-du--reset',
;; `dired-du--revert', `dired-du--size-sorter',
;; `dired-du--subdir-position', `dired-du--update-subdir-header',
;; `dired-du--update-subdir-header-1', `dired-du-alist-get',
;; `dired-du-directory-at-current-line-p',
;; `dired-du-distinguish-one-marked',
;; `dired-du-filename-relative-to-default-dir',
;; `dired-du-get-all-directories', `dired-du-get-all-files',
;; `dired-du-get-all-marks', `dired-du-get-all-non-directories',
;; `dired-du-get-all-subdir-directories',
;; `dired-du-get-all-subdir-non-directories', `dired-du-get-file-info',
;; `dired-du-get-file-size-local', `dired-du-get-file-size-remote',
;; `dired-du-get-marked-files', `dired-du-get-recursive-dir-size',
;; `dired-du-get-recursive-dir-size-in-parallel',
;; `dired-du-ls-lisp-handle-switches', `dired-du-mark-buffer',
;; `dired-du-mark-subdir-files', `dired-du-marker-regexp',
;; `dired-du-run-in-parallel', `dired-du-string-to-number',
;; `dired-du-unmark-buffer', `dired-du-use-comma-separator'.
;;
;; Inline functions defined here:
;;
;; `dired-du-assert-dired-mode', `dired-du-link-number',
;; `dired-du-modification-time', `dired-du-size'.
;;
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; This file is NOT part of GNU Emacs.
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program 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
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code:
(require 'cl-lib)
(require 'dired)
(require 'find-dired)
(require 'ls-lisp)
(autoload 'dired-subdir-min "dired-aux")
(defgroup dired-du nil
"Dired with recursive size dir."
:prefix "dired-du-"
:group 'dired)
(defvar dired-du-dir-info nil
"Alist of cached (DIRNAME . DIR-INFO) in Dired buffer.
DIRNAME is a subdirectory in the DIRED buffer.
DIR-INFO is one alist with information about each directory
in DIRNAME obtained with `dired-du-get-file-info'. Each
element is an alist:
\(NAME ((nlink . NLINK) (size . SIZE) (time . TIME))).
The size of the directories is the recursive size obtained with
`dired-du-used-space-program'. The size of the entries
'.' and '..' is not changed.")
(make-variable-buffer-local 'dired-du-dir-info)
(defvar dired-du-mode nil
"Variable with the status of the mode.
If this variable evaluates non-nil, then show recursive size
for directories in the Dired buffer. This variable is also used
as default value for INCLUDE-DIRS in `dired-du-count-sizes'.")
(make-variable-buffer-local 'dired-du-mode)
(put 'dired-du-mode 'permanent-local t)
(defcustom dired-du-used-space-program
(purecopy (let ((opts (if (string-prefix-p "gnu" (symbol-name system-type))
"-sb"
"-sk"))) ; -k overestimate used space\
; for files w/ size < 1024.
(cond ((executable-find "du") (list "du" opts))
((file-executable-p "/usr/sbin/du")
(list "/usr/sbin/du" opts))
((file-executable-p "/etc/du") (list "/etc/du" opts)))))
"Program and its options to get recursively the total size of a directory.
We assume the output has the format of `du'.
A value of nil disables this feature."
:type '(choice (const :tag "Unset" nil)
(list (string :tag "Program")
(repeat :tag "Options"
:inline t
(string :format "%v")))))
(defvar dired-du--user-warned (and dired-du-used-space-program t)
"Nil if the user must be warned about \
`dired-du-used-space-program' being nil.")
(defcustom dired-du-size-format nil
"Set the format for file sizes.
If equals t, then `dired-du-count-sizes' displays file
sizes using `file-size-human-readable'.
If equals 'comma, then `dired-du-count-sizes' displays
file sizes using thousands comma separator.
Otherwise display file sizes in default numeric format."
:type '(choice
(const :tag "Use default numeric format" nil)
(const :tag "Use human readable string" t)
(const :tag "Use thousands comma separator" 'comma)))
(defcustom dired-du-on-find-dired-ok nil
"If Non-nil show recursive dir sizes in `find-dired'.
The format to display the file sizes is control by
`dired-du-size-format'."
:type 'boolean)
(defvar dired-du-find-dired-buffer nil
"Non-nil if current buffer is a `find-dired' buffer.
When `dired-du-on-find-dired-ok' evaluates non-nil, then this
buffer show recursive dir sizes with format according with
`dired-du-size-format' if the mode is enabled.")
(make-variable-buffer-local 'dired-du-find-dired-buffer)
(defcustom dired-du-update-headers nil
"If Non-nil, update the subdir headers.
The total used space shown contains the recursive size of the directories."
:type 'boolean)
(defvar dired-du-local-subdir-header
"^ total used in directory \\([,.0-9]+[BkKMGTPEZY]?\\) \
available \\([,.0-9]+[BkKMGTPEZY]?\\)"
"Regexp matching a subdir header in a Dired buffer in the local host.")
(defvar dired-du-remote-subdir-header
"^ total \\([,.0-9]+[BkKMGTPEZY]?\\)"
"Regexp matching a subdir header in a Dired buffer visiting a remote host.")
(defvar dired-du-filesp-subdir-header
"^ *files \\([,0-9]+\\)/\\([,0-9]+\\) space used \
\\([,.0-9]+[BkKMGTPEZY]?\\) available \\([,.0-9]+[BkKMGTPEZY]?\\)"
"Regexp matching a subdir header in a Dired buffer using lib `files+'.")
(defcustom dired-du-bind-mode t
"Non-nil means bind `dired-du-mode' to C-x M-r in `dired-mode-map', otherwise do not."
:type 'boolean
:set (lambda (sym val)
(let ((map dired-mode-map))
(when (set sym val)
(define-key map (kbd "C-x M-r") 'dired-du-mode))))
:group 'dired-keys)
(defcustom dired-du-bind-human-toggle t
"Non-nil means bind `dired-du--toggle-human-readable' to C-x C-h in `dired-mode-map', otherwise do not."
:type 'boolean
:set (lambda (sym val)
(let ((map dired-mode-map))
(when (set sym val)
(define-key map (kbd "C-x C-h") 'dired-du--toggle-human-readable))))
:group 'dired-keys)
(defcustom dired-du-bind-count-sizes t
"Non-nil means bind `dired-du-count-sizes' to *N in `dired-mode-map', otherwise do not."
:type 'boolean
:set (lambda (sym val)
(let ((map dired-mode-map))
(when (set sym val)
(define-key map "*N" 'dired-du-count-sizes))))
:group 'dired-keys)
;;; Macros.
(defmacro dired-du-with-saved-marks (&rest body)
"Save alist of files and their marks; execute BODY; restore the marks.
The value returned is the value of the last form in BODY."
(declare (indent 0) (debug t))
(let ((saved-marks (make-symbol "saved-marks"))
(new-marks (make-symbol "new-marks")))
`(let ((,saved-marks (dired-remember-marks (point-min) (point-max))))
(unwind-protect
(progn ,@body)
(let ((,new-marks (dired-remember-marks (point-min) (point-max))))
(unless (equal ,saved-marks ,new-marks)
(dired-du-unmark-buffer)
(let ((inhibit-read-only t))
(dired-mark-remembered ,saved-marks))))))))
;; As `dired-map-over-marks' but with additional arg ALL-MARKS.
(defmacro dired-du-map-over-marks (body arg &optional show-progress
distinguish-one-marked
marker-char all-marks)
"Eval BODY with point on each marked line. Return a list of BODY's results.
If no marked file could be found, execute BODY on the current
line. ARG, if non-nil, specifies the files to use instead of the
marked files.
If ARG is an integer, use the next ARG (or previous -ARG, if
ARG<0) files. In that case, point is dragged along. This is so
that commands on the next ARG (instead of the marked) files can
be chained easily.
For any other non-nil value of ARG, use the current file.
If optional third arg SHOW-PROGRESS evaluates to non-nil,
redisplay the dired buffer after each file is processed.
No guarantee is made about the position on the marked line.
BODY must ensure this itself if it depends on this.
Search starts at the beginning of the buffer, thus the car of the
list corresponds to the line nearest to the buffer's bottom.
This is also true for (positive and negative) integer values of
ARG.
BODY should not be too long as it is expanded four times.
If DISTINGUISH-ONE-MARKED is non-nil, then if we find just one
marked file, return (t FILENAME) instead of (FILENAME).
If MARKER-CHAR is non-nil, then it is the mark
character to search. Otherwise use `dired-marker-char'.
If ALL-MARKS is non-nil, accept all mark characters. Otherwise use
just MARKER-CHAR."
;;
;;Warning: BODY must not add new lines before point - this may cause an
;;endless loop.
;;This warning should not apply any longer, sk 2-Sep-1991 14:10.
`(prog1
(let ((inhibit-read-only t) case-fold-search found results)
(if ,arg
(if (integerp ,arg)
(progn ;; no save-excursion, want to move point.
(dired-repeat-over-lines
,arg
(function (lambda ()
(if ,show-progress (sit-for 0))
(setq results (cons ,body results)))))
(if (< ,arg 0)
(nreverse results)
results))
;; non-nil, non-integer ARG means use current file:
(list ,body))
(let ((regexp (dired-du-marker-regexp ,marker-char ,all-marks))
next-position)
(save-excursion
(goto-char (point-min))
;; remember position of next marked file before BODY
;; can insert lines before the just found file,
;; confusing us by finding the same marked file again
;; and again and...
(setq next-position (and (re-search-forward regexp nil t)
(point-marker))
found (not (null next-position)))
(while next-position
(goto-char next-position)
(if ,show-progress (sit-for 0))
(setq results (cons ,body results))
;; move after last match
(goto-char next-position)
(forward-line 1)
(set-marker next-position nil)
(setq next-position (and (re-search-forward regexp nil t)
(point-marker)))))
(if (and ,distinguish-one-marked (= (length results) 1))
(setq results (cons t results)))
(if found
results
(list ,body)))))
;; save-excursion loses, again
(dired-move-to-filename)))
;;; Advice `find-dired'.
;; Set buffer local variable `dired-du-find-dired-buffer' non-nil
;; on the output buffer of `find-dired' commands.
;; Substitute recursive dir sizes in those buffers only if
;; `dired-du-on-find-dired-ok' non-nil.
(defun dired-du--find-dired-around (orig-fun &rest args)
"Advice function for `find-dired-sentinel'.
Set `dired-du-find-dired-buffer' non-nil in current buffer
and run `dired-after-readin-hook'.
ORIG-FUN is the original `find-dired-sentinel'.
ARGS are the arguments for `find-dired-sentinel'."
(setq dired-du-find-dired-buffer t)
(let ((res (apply orig-fun args)))
(unless (featurep 'find-dired+)
(run-hooks 'dired-after-readin-hook))
res))
;; As `dired-du-get-marked-files' but with additional arg ALL-MARKS.
(defun dired-du-get-marked-files (&optional localp arg filter
distinguish-one-marked
marker-char all-marks)
"Return the marked files names as a list of strings.
The list is in the same order as the buffer, that is, the car is the
first marked file.
Values returned are normally absolute file names.
Optional arg LOCALP as in `dired-get-filename'.
Optional second argument ARG, if non-nil, specifies files near
point instead of marked files. It usually comes from the prefix
argument.
If ARG is an integer, use the next ARG files.
If ARG is any other non-nil value, return the current file name.
If no files are marked, and ARG is nil, also return the current file name.
Optional third argument FILTER, if non-nil, is a function to select
some of the files--those for which (funcall FILTER FILENAME) is non-nil.
If DISTINGUISH-ONE-MARKED is non-nil, then if we find just one marked file,
return (t FILENAME) instead of (FILENAME).
Don't use that together with FILTER.
Optional arg MARKER-CHAR, if non-nil, then it is the mark
character to search. Otherwise use `dired-marker-char'.
Optional arg ALL-MARKS, if non-nil, then accept all mark characters.
Otherwise use just MARKER-CHAR."
(let ((all-of-them
(save-excursion
(delq nil (dired-du-map-over-marks
(dired-get-filename localp 'no-error-if-not-filep)
arg nil distinguish-one-marked marker-char all-marks))))
result)
(when (equal all-of-them '(t))
(setq all-of-them nil))
(if (not filter)
(if (and distinguish-one-marked (eq (car all-of-them) t))
all-of-them
(nreverse all-of-them))
(dolist (file all-of-them)
(if (funcall filter file)
(push file result)))
result)))
;; As `dired-marker-regexp' but with optional args. MARKER-CHAR and ALL-MARKS.
(defun dired-du-marker-regexp (&optional marker-char all-marks)
"Return a regexp matching `dired-marker-char' at the beginning of line.
If MARKER-CHAR evaluates non-nil, then the regexp matches MARKER-CHAR
instead of `dired-marker-char'.
If optional argument ALL-MARKS evaluates to non-nil, then the regexp
matches any mark character."
(if all-marks
dired-re-mark
(concat "^"
(regexp-quote
(char-to-string (or marker-char dired-marker-char))))))
(defsubst dired-du-link-number (attributes)
"Return the number of links in ATTRIBUTES returned by `file-attributes'."
(nth 1 attributes))
(defsubst dired-du-modification-time (attributes)
"The modification time in ATTRIBUTES returned by `file-attributes'.
This is the time of the last change to the file's contents, and
is a list of integers (HIGH LOW USEC PSEC) in the same style
as (current-time)."
(nth 5 attributes))
(defsubst dired-du-size (attributes)
"The size (in bytes) in ATTRIBUTES returned by `file-attributes'.
This is a floating point number if the size is too large for an integer."
(nth 7 attributes))
;;; Toggle on `dired-du-on-find-dired-ok'.
(defun dired-du-on-find-dired-ok-toggle ()
"Toggle on `dired-du-on-find-dired-ok'."
(interactive)
(setq dired-du-on-find-dired-ok
(not dired-du-on-find-dired-ok))
(if dired-du-on-find-dired-ok
(message "Enabled `dired-du-on-find-dired-ok'")
(message "Disabled `dired-du-on-find-dired-ok'"))
(when dired-du-find-dired-buffer
(cond ((and dired-du-on-find-dired-ok
dired-du-mode)
(dired-du--replace))
((not dired-du-on-find-dired-ok)
(revert-buffer)))))
;;; Handle sizes with thousands comma separator.
(defun dired-du-string-to-number (str)
"Like `string-to-number' but recognize a trailing unit prefix.
For example, 2K is expanded to 2048.0. The caller should make
sure that a trailing letter in STR is one of BKkMGTPEZY.
It handles thousands comma separator."
(let* ((str-new (replace-regexp-in-string "," "" str))
(val (string-to-number str-new))
(u (unless (zerop val)
(aref str-new (1- (length str-new))))))
(when (and u (> u ?9))
(when (= u ?k)
(setq u ?K))
(let ((units '(?B ?K ?M ?G ?T ?P ?E ?Z ?Y)))
(while (and units (/= (pop units) u))
(setq val (* 1024.0 val)))))
val))
(defun dired-du-use-comma-separator (num)
"Return number NUM as an string using comma separator."
(replace-regexp-in-string
"^," ""
(apply #'string
(reverse
(string-to-list
(replace-regexp-in-string
",\\." "."
(replace-regexp-in-string
"\\([0-9]\\{3\\}\\)" "\\1,"
(apply #'string
(reverse
(string-to-list
(replace-regexp-in-string
"\\.0$" ""
(number-to-string
num))))))))))))
;;; Functions to obtain recursive dir size.
(defsubst dired-du-assert-dired-mode ()
"Ensure current buffer is in `dired-mode'."
(cl-assert (derived-mode-p 'dired-mode)))
(defun dired-du-directory-at-current-line-p ()
"Return non-nil if there is a directory at current line in the Dired buffer."
(dired-du-assert-dired-mode)
(save-excursion
(goto-char (line-beginning-position)) (looking-at-p dired-re-dir)))
(defun dired-du-filename-relative-to-default-dir (&optional file)
"Return the filename relative to default directory of a file.
Optional arg FILE, if non-nil, then is the file relative or fullname.
Otherwise use the file at the current line in the Dired buffer."
(if (not file)
(dired-get-filename t t)
(let ((basename (file-name-nondirectory file))
(relname (file-relative-name file)))
(cond ((member basename '("." ".."))
(let ((dir (file-name-directory file)))
(cond (dir
(concat
(file-name-as-directory
(file-name-nondirectory
(directory-file-name
dir))) basename))
(t
file))))
(t
relname)))))
(defun dired-du--read-size-from-buffer ()
"Return displayed size for file at current line as a decimal number."
(save-excursion
(when (dired-move-to-filename)
(re-search-backward
directory-listing-before-filename-regexp)
(let ((pos (progn (skip-chars-forward "^ \t") (point))))
(skip-chars-backward "^ \t")
(dired-du-string-to-number
(buffer-substring-no-properties (point) pos))))))
(defun dired-du--get-recursive-dir-size (dir-rel)
"Return recursive directory size for DIR-REL."
(let ((size 0)
(dired-buffer (current-buffer)))
(with-temp-buffer
(if dired-du-used-space-program
(process-file (car dired-du-used-space-program)
nil t nil
(cadr dired-du-used-space-program)
dir-rel)
;; `du' not available: estimate the size with Lisp as
;; the size of all the regular files under this dir. This is
;; an underestimation, but it's OK for most of the cases.
(require 'find-lisp)
(with-no-warnings
(let* ((files (ignore-errors ; Ignore permission denied errors.
(find-lisp-find-files dir-rel "")))
(tmp (if (null files)
(with-current-buffer dired-buffer
(dired-du--read-size-from-buffer))
(apply #'+ (mapcar
(lambda (f)
(dired-du-size
(file-attributes f)))
files)))))
(insert (format "%d" tmp)))))
(goto-char 1)
(while (re-search-forward "^[0-9]+" nil t)
(setq size (+ size (string-to-number (match-string 0))))))
size))
(defun dired-du-get-recursive-dir-size ()
"Return recursive directory size for dir at current line.
If there is not a directory in the current line return nil."
(dired-du-assert-dired-mode)
(when (dired-du-directory-at-current-line-p)
;; remote files need relative name.
(let ((dir-rel (dired-get-filename t 'noerror)))
(dired-du--get-recursive-dir-size dir-rel))))
(defun dired-du-run-in-parallel (command out-buf)
"Run COMMAND for several files in parallel.
Like `dired-run-shell-command' but adding optional arg OUT-BUF and not
displaying the buffer associated to the shell process."
;; prevent showing temp buffer.
(let ((display-buffer-alist (cons '(" \\*temp\\*"
(display-buffer-no-window)
(allow-no-window . t))
display-buffer-alist))
(handler
(find-file-name-handler (directory-file-name default-directory)
'shell-command)))
(if handler (apply handler 'shell-command (list command out-buf))
(shell-command command out-buf))
;; change process sentinel to avoid showing a large command in the echo area.
(let ((sentinel (lambda (process signal)
(when (memq (process-status process) '(exit signal))
(message "collection of recursive dir size: %s."
(substring signal 0 -1))
(message nil)))))
(set-process-sentinel (get-buffer-process out-buf) sentinel)))
;; return nil for sake of nconc in dired-bunch-files.
nil)
(defun dired-du-get-recursive-dir-size-in-parallel (dirs)
"Get recursive directory size for DIRS.
DIRS is a list of directories.
The return value is an alist (DIRNAME . SIZE)."
(dired-du-assert-dired-mode)
(save-excursion
(let ((dirs-rel (mapcar #'file-relative-name dirs))
(command (format "%s %s&" (car dired-du-used-space-program)
(cadr dired-du-used-space-program)))
(prep (make-progress-reporter
"Dired-Du collecting recursive dir sizes, please wait ..."
0 (length dirs)))
result)
(dired-bunch-files
(- 10000 (length command))
(function (lambda (&rest files)
(with-temp-buffer
(let ((buff (current-buffer)))
(dired-du-run-in-parallel
(dired-shell-stuff-it
command files 'on-each)
buff)
(let ((proc (get-buffer-process buff)))
;; wait until all files processed.
(while (eq (process-status proc) 'run)
(let ((completed (count-lines (point-min)
(point-max)))
(old 0))
(unless (= completed old)
(progress-reporter-force-update
prep
completed
(format
"Dired-Du collecting dir sizes ...(%d/%d) "
completed
(length dirs)))
(setq old completed))
(setq completed (count-lines (point-min)
(point-max)))
;; Give a bit of time to the process to end. Initially we
;; were waiting 1 s; it turned out to be too conservative value.
;; TODO: Shouldn't this be run in a sentinel?
(sleep-for 0 10))))
;; collect dir sizes.
(goto-char 1)
(while (re-search-forward "^[0-9]+" nil t)
(let ((size (string-to-number (match-string 0)))
(dir-name (progn
(skip-chars-forward " \t")
(buffer-substring-no-properties
(point)
(line-end-position)))))
(push (cons dir-name size) result)))))))
nil
dirs-rel) result)))
;;; Query functions for `dired-du-dir-info'.
(defun dired-du--get-position-1 (name &optional dir-info)
"Return position of NAME in DIR-INFO."
;; (unless dir-info (setq dir-info (cdar dired-du-dir-info)))
(let ((elt (cond ((hash-table-p dir-info)
(gethash name dir-info))
(t (assoc name dir-info)))))
(when elt
(cl-position elt dir-info :test #'equal))))
(defun dired-du--get-position (name &optional dir-info glob-pos)
"Return position of NAME in DIR-INFO.
Optional arg DIR-INFO, if non-nil, is an alist with same structure as
`dired-du-dir-info'. Otherwise defaults to `dired-du-dir-info'.
Optional arg GLOB-POS, if non-nil, is the global position
in DIR-INFO of the alist containing (KEY . VALUE). Otherwise, it
is obtained inside this function.
Return value is a cons (GLOB-POS . REL-POS); REL-POS is the
position of NAME in the alist.
If NAME is not found in DIR-INFO return nil."
(unless dir-info
(setq dir-info (dired-du--create-or-check-dir-info)))
(let ((info (cl-remove-if-not (lambda (x) (cdr-safe x)) dir-info))
res)
(when info
(cl-labels ((fn (v alist gpos)
(let ((rpos (dired-du--get-position-1 v (cdr alist))))
(when rpos
(setq res
(cons
(or gpos
(dired-du--subdir-position (car alist)))
rpos))))))
(if glob-pos
(let ((local-info (nth glob-pos dir-info)))
(if (not (consp local-info))
(setq res nil)
(fn name local-info glob-pos)))
(catch 'found ; Loop on info.
(dolist (local-info info)
(when (fn name local-info nil)
(throw 'found nil))))))) res))
(defun dired-du-alist-get (key alist &optional default)
"Return the value associated with KEY in ALIST, using `assq'.
If KEY is not found in ALIST, return DEFAULT."
(let ((x (assq key alist)))
(if x (cdr x) default)))
(defun dired-du--get-value (name key &optional dir-info glob-pos)
"Return for file NAME its VALUE in (KEY . VALUE).
KEY is a symbol.
Optional arg DIR-INFO, if non-nil, is an alist with same structure as
`dired-du-dir-info'. Otherwise defaults to
`dired-du-dir-info'.
Optional arg GLOB-POS, if non-nil, is the global position
in DIR-INFO of the alist containing (KEY . VALUE). Otherwise, it
is obtained inside this function.
If name is not found in DIR-INFO return nil."
(unless dir-info
(setq dir-info dired-du-dir-info))
(let ((pos (dired-du--get-position name dir-info glob-pos))
info value)
(when pos
(let ((global-pos (car pos))
(rel-pos (cdr pos)))
(setq info (cdr (nth global-pos dir-info))
value (dired-du-alist-get key (nth rel-pos info)))))
value))
(defun dired-du--subdir-position (subdir)
"Return the position of SUBDIR in `dired-du-dir-info'.
SUBDIR should be a fullname.
If SUBDIR is not found return nil."
(dired-du--create-or-check-dir-info)
(cl-position-if (lambda (x)
(let ((dir (car-safe x)))
(and (stringp dir)
(string= dir subdir))))
dired-du-dir-info))
(defun dired-du--fullname-to-glob-pos (dir)
"Return the global index of DIR in `dired-du-dir-info'."
(let ((rel-name (file-relative-name dir)))
(car (dired-du--get-position rel-name))))
(defun dired-du--file-in-dir-info-p (file &optional dir-info)
"Return non-nil if FILE is included in DIR-INFO."
(let ((relname (dired-du-filename-relative-to-default-dir file))
(glob-pos (dired-du--fullname-to-glob-pos file)))
(dired-du--get-position relname dir-info glob-pos)))
(defun dired-du--create-or-check-dir-info (&optional keep-drop-dirs)
"Initialize `dired-du-dir-info' and return it.
Intial value is just a list with the subdir names included in the
Dired buffer. If there are subdirs not included in `dired-du-dir-info'
then they are added.
Optional arg KEEP-DROP-DIRS, when evaluates non-nil, keep the information of
subdirectories shown before. Otherwise that information is discarded for
performance reasons."
(let* ((subdir-alist dired-subdir-alist)
(num-subdirs (length subdir-alist)))
(cond ((not dired-du-dir-info)
(setq dired-du-dir-info
(mapcar (lambda (x) (cons (car x) nil)) subdir-alist)))
((> num-subdirs ; add missing subdirs.
(length dired-du-dir-info))
(let ((subdirs (mapcar #'car subdir-alist)))
(dolist (dir subdirs)
(unless (assoc-string dir dired-du-dir-info)
(push (list dir) dired-du-dir-info)))))
((and (< num-subdirs ; drop subdirs not shown anymore.
(length dired-du-dir-info))
(not keep-drop-dirs))
(setq dired-du-dir-info
(cl-delete-if
(lambda (x)
(let ((old (car-safe x)))
(and (stringp old)
(not (assoc-string old subdir-alist)))))
dired-du-dir-info))))
dired-du-dir-info))
;;; Get info for file at current line.
(defun dired-du-get-file-info (&optional glob-pos dir-dots dir-size)
"Get file info for file at current line in dired buffer.
Optional arg GLOB-POS, when non-nil, is the position in
`dired-du-dir-info' to look up. Otherwise, look in all positions.
Optional arg DIR-DOTS, if non-nil, then obtain the recursive dir size
for '.' and '..' as well. Otherwise obtain their size from the buffer.
Optional arg DIR-SIZE, if non-nil, is the recursive dir size for the
the file in the current dired line."
;; code for this function is borrowed from dired-x.el::dired-mark-sexp
(let ((remote-dir (file-remote-p default-directory))
nlink gid size time time-mod
name time-cache size-cache nlink-cache change isdir)
(save-excursion
(dired-du--create-or-check-dir-info)
(if (dired-move-to-filename)
(let ((mode-len 10)
(filename (and (null remote-dir)
(dired-get-filename 'local 'noerror)))
;; When the buffer is remote, all information but the recursize
;; dir size, is collected from the buffer for performance
;; reasons; this may cause a lost in the precision
;; if a file has time-cache equals to its modification time.
;; For instance, if the file has a cached time "mar 19 12:46",
;; and it changes its size before "mar 19 12:47", then neither
;; the time-cache nor the size-cache are updated.
;; For local files the file information is collected with
;; `file-attributes',so in the previous example file would
;; update its size on the buffer.
(attributes (and (null remote-dir)
(file-attributes
(dired-get-filename nil 'noerror) 'string)))
(dired-re-inode-size "\\=\\s *\\([0-9]+\\s +\\)?\
\\(?:\\([0-9]+\\(?:\\.[0-9]*\\)?[BkKMGTPEZY]?\\)? ?\\)"))
(beginning-of-line)
(forward-char 2)
(re-search-forward dired-re-inode-size nil t)
(setq isdir (dired-du-directory-at-current-line-p))
(cond (remote-dir ; collect info from buffer
;; xxx might be a size not followed by a unit prefix.
;; we could set s to inode if it were otherwise nil,
;; with a similar reasoning as below for setting gid to uid,
;; but it would be even more whimsical.
;; (setq inode (when (match-string 1)
;; (string-to-number (match-string 1)))
(setq nlink
(progn
(forward-char mode-len)
;; skip any extended attributes marker ("." or "+").
(or (looking-at-p " ")
(forward-char 1))
(read (current-buffer)))
name
(progn
(dired-move-to-filename)
(buffer-substring-no-properties
(point)
(or
(dired-move-to-end-of-filename t)
(point)))))
;; the name stored is the relative name to default-directory.
; In non-remote case, its returned by
(let* ((basename (file-name-nondirectory name))
(fullname
(if (member basename '("." ".."))
(concat
(file-name-as-directory
(dired-current-directory))
basename)
(expand-file-name name default-directory))))
(setq name
(dired-du-filename-relative-to-default-dir
fullname))))
(t
;; collect info from file system
;; gid read from buffer: user may disable gid display;
;; we need the the string in the left of the size,
;; whatever it is (uid/gid).
(setq nlink (dired-du-link-number attributes)
time-mod (dired-du-modification-time attributes)
name filename)))
(setq time-cache (dired-du--get-value name 'time nil glob-pos)
size-cache (dired-du--get-value name 'size nil glob-pos)
nlink-cache (dired-du--get-value name 'nlink nil glob-pos))
(dired-move-to-filename)
(save-excursion
(setq time
(cond (remote-dir
;; the regexp below tries to match from the last
;; digit of the size field through a space after
;; the date. Also, dates may have different
;; formats depending on file age, so the date
;; column need not be aligned to the right.
(buffer-substring-no-properties
(save-excursion
(skip-chars-backward " \t")
(point))
(progn
(re-search-backward
directory-listing-before-filename-regexp)
(skip-chars-forward "^ \t")
(1+ (point)))))
(t ; local file
(progn
(re-search-backward
directory-listing-before-filename-regexp)
(skip-chars-forward "^ \t")
(format "%s" time-mod))))
size (let ((size-on-buffer
(dired-du-string-to-number
(buffer-substring-no-properties
(point)
(progn
(skip-chars-backward "^ \t")
(point))))))
(cond ((member
(file-name-nondirectory name) '("." ".."))
(let* ((size-file size-on-buffer)
(size-human
(file-size-human-readable size-file))
(size-no-human
(format "%d" size-file))
(size-comma
(dired-du-use-comma-separator
size-file))
(fn (lambda (human default size-comma)
(cond ((eq t dired-du-size-format)
human)
((null dired-du-size-format)
default)
(t
size-comma)))))
(cond ((null dir-dots)
(funcall fn size-human size-no-human
size-comma))
(t ; obtain recursive size also\
; for '.' and '..'.
(let* ((size-dir
(or dir-size
(dired-du-get-recursive-dir-size)))
(size-human
(file-size-human-readable
size-dir))
(size-no-human
(format "%d" size-dir))
(size-comma
(dired-du-use-comma-separator
size-dir)))
(funcall fn size-human
size-no-human
size-comma))))))
((and dired-du-mode
(dired-du-directory-at-current-line-p))
(let* ((size-recur
(or (and (string= time time-cache)
(= nlink nlink-cache)
(dired-du-string-to-number
size-cache))
(or
dir-size
(dired-du-get-recursive-dir-size))))
(recursive-size
(cond ((eq t dired-du-size-format)
(file-size-human-readable
size-recur))
((null dired-du-size-format)