-
Notifications
You must be signed in to change notification settings - Fork 4
/
org-habit-stats.el
1851 lines (1623 loc) · 75.3 KB
/
org-habit-stats.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
;;; org-habit-stats.el --- Display info about habits -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2022 ml729
;;
;; Author: ml729
;; Created: October 22, 2021
;; Version: 0.1
;; Keywords: calendar, org-mode, org-habit, habits, stats, statistics, charts, graphs
;; Homepage: https://github.com/ml729/org-habit-stats/
;; Package-Requires: ((emacs "25.1"))
;;
;; This file is not part of GNU Emacs.
;;
;;; License:
;; 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;; View stats, a calendar, and bar graphs of your org-habits.
;;; Code:
(require 'org-habit)
(require 'org-element)
(require 'cl-lib)
(require 'seq)
(require 'chart)
(defgroup org-habit-stats nil
"Visualize your org-habits."
:group 'org-progress
:prefix "org-habit-stats-")
;;; Defcustoms
(defcustom org-habit-stats-include-uncompleted-today nil
"If a habit is not done today, whether or not to include today."
:group 'org-habit-stats
:type 'boolean)
(defcustom org-habit-stats-graph-colors-list
'("#ef7969"
"#49c029"
"#7090ff"
"#e07fff"
"#70d3f0"
"#ffcf00")
"Colors to use for bars of bar graph.
The default colors are Modus Vivendi's colors for graphs. The original value of
`chart-face-color-list` is unaffected."
:group 'org-habit-stats
:type '(list color))
(defcustom org-habit-stats-graph-width 70
"Width of x-axis of graph (in columns), not including origin."
:group 'org-habit-stats
:type 'integer)
(defcustom org-habit-stats-graph-height 12
"Height of y-axis of graph (in line numbers), not including origin."
:group 'org-habit-stats
:type 'integer)
(defcustom org-habit-stats-graph-left-margin 5
"Number of columns to the left of y-axis."
:group 'org-habit-stats
:type 'integer)
(defcustom org-habit-stats-graph-min-num-bars 3
"How many bars to shift left when the bar graph is truncated."
:group 'org-habit-stats
:type 'integer)
(defcustom org-habit-stats-graph-number-months 5
"How many months to display when graph's x-axis is months."
:group 'org-habit-stats
:type 'integer)
(defcustom org-habit-stats-graph-number-weeks 10
"How many weeks to display when graph's x-axis is weeks."
:group 'org-habit-stats
:type 'integer)
(defcustom org-habit-stats-graph-number-days 15
"How many days to display when graph's x-axis is days."
:group 'org-habit-stats
:type 'integer)
(defcustom org-habit-stats-graph-data-horizontal-char ?-
"Character used to draw horizontal lines for a graph's data."
:group 'org-habit-stats
:type 'character)
(defcustom org-habit-stats-graph-data-vertical-char ?|
"Character used to draw vertical lines for a graph's data."
:group 'org-habit-stats
:type 'character)
(defcustom org-habit-stats-graph-axis-horizontal-char ?-
"Character used to draw horizontal lines for a graph's axes."
:group 'org-habit-stats
:type 'character)
(defcustom org-habit-stats-graph-axis-vertical-char ?|
"Character used to draw vertical lines for a graph's axes."
:group 'org-habit-stats
:type 'character)
(defcustom org-habit-stats-graph-show-values-on-bars t
"Whether or not to show exact values on top of bars in the bar graph."
:group 'org-habit-stats
:type 'boolean)
(defcustom org-habit-stats-graph-command-prefix "g"
"Prefix key for graph commands."
:group 'org-habit-stats
:type 'string)
(defcustom org-habit-stats-months-names-alist
'(("Jan" . 1)
("Feb" . 2)
("Mar" . 3)
("Apr" . 4)
("May" . 5)
("Jun" . 6)
("Jul" . 7)
("Aug" . 8)
("Sep" . 9)
("Oct" . 10)
("Nov" . 11)
("Dec" . 12))
"Month names used in graphs."
:group 'org-habit-stats
:type '(alist :key-type string :value-type integer))
(defcustom org-habit-stats-days-names-alist
'(("Sun" . 1)
("Mon" . 2)
("Tue" . 3)
("Wed" . 4)
("Thu" . 5)
("Fri" . 6)
("Sat" . 7))
"Day names used in graphs."
:group 'org-habit-stats
:type '(alist :key-type string :value-type integer))
(defcustom org-habit-stats-stat-date-format
"%F"
"Date format used in graphs for dates in stats."
:group 'org-habit-stats
:type 'string)
(defcustom org-habit-stats-graph-date-format
"%m/%d"
"Date format used in graphs for dates in graphs."
:group 'org-habit-stats
:type 'string)
(defcustom org-habit-stats-stat-functions-alist
'((org-habit-stats-streak . "Current Streak")
(org-habit-stats-exp-smoothing-list-today . "Habit Strength")
(org-habit-stats-record-streak-days . "Record Streak")
(org-habit-stats-record-streak-date . "Record Date")
(org-habit-stats-unstreak . "Unstreak")
(org-habit-stats-30-day-total . "30 day total")
(org-habit-stats-30-day-percentage . "30 day percentage")
(org-habit-stats-alltime-total . "Total Completions")
(org-habit-stats-alltime-percentage . "Total Percentage"))
"Alist mapping stat functions to a list of their names.
The name is used in the org-habit-stats buffer, and (after
replacing whitespace with underscores) in properties."
:group 'org-habit-stats
:type '(alist :key-type function :value-type string))
(defcustom org-habit-stats-message-functions-list
'(org-habit-stats-streak-message
org-habit-stats-unstreak-message
org-habit-stats-comeback-message)
"List of message functions.
A message function takes in the habit history, reversed habit
history, and parsed habit data, and returns a string."
:group 'org-habit-stats
:type '(list function))
(defcustom org-habit-stats-streak-message-alist
'((10 . "Achieved streak 10! Reward: Study the GNU Emacs manuals")
(20 . "Achieved streak 20! Reward: Configure my .emacs.d")
(30 . "Achieved streak 30! Reward: Read Sacha Chua's Emacs News")
(40 . "Achieved streak 40! Reward: Watch Protesilaos Emacs talks")
(50 . "Achieved streak 50! Reward: Try out the latest (M)ELPA packages"))
"Alist mapping current streak length to messages to be displayed.
Only displays the message when the streak length is exactly that value."
:group 'org-habit-stats
:type '(alist :key-type integer :value-type string))
(defcustom org-habit-stats-unstreak-message-alist
'((10 . "It's never too late to start again."))
"Alist mapping current unstreak length to messages to be displayed.
An unstreak is the sequence of consecutive misses. Only displays
the message when the unstreak length is exactly that value."
:group 'org-habit-stats
:type '(alist :key-type integer :value-type string))
(defcustom org-habit-stats-comeback-message
"Record streak recovered!"
"Message to display when record streak is achieved again."
:group 'org-habit-stats
:type 'string)
(defcustom org-habit-stats-exp-smoothing-alpha 0.052
"Weight of completed days for exponential smoothing."
:group 'org-habit-stats
:type 'number)
(defcustom org-habit-stats-exp-smoothing-beta 0.10
"Weight of missed days for exponential smoothing."
:group 'org-habit-stats
:type 'number)
(defcustom org-habit-stats-graph-functions-alist
'((org-habit-stats-graph-completions-per-month . (:key "m"
:title "Monthly Completions"
:x-label "Months"
:y-label "Completions"
:dir horizontal
:max-bars 5))
(org-habit-stats-graph-completions-per-week . (:key "w"
:title "Weekly Completions"
:x-label "Weeks"
:y-label "Completions"
:dir vertical
:max-bars 10))
(org-habit-stats-graph-completions-per-weekday . (:key "d"
:title "Completions by Day"
:x-label "Day"
:y-label "Completions"
:dir vertical
:max-bars 7))
(org-habit-stats-graph-daily-strength . (:key "s"
:title "Daily Habit Strength"
:x-label "Day"
:y-label "Strength"
:dir vertical
:max-bars 14)))
"Alist mapping graph functions to a list of key value pairs.
This includes the key that invokes the function, the title of the
graph, the name of the x-axis, the name of the y-axis, the graph
direction, and the max number of bars to show at a time."
:group 'org-habit-stats
:type '(alist :key-type function :value-type sexp))
(defcustom org-habit-stats-graph-default-func 'org-habit-stats-graph-completions-per-week
"Current graph function used in org habit stats buffer."
:group 'org-habit-stats
:type 'function)
(defcustom org-habit-stats-show-blank-when-new-habit t
"If t, display new habit message for a habit with 0 completions."
:group 'org-habit-stats
:type 'boolean)
(defcustom org-habit-stats-new-habit-message "A new habit."
"Message to display when habit has 0 completions logged."
:group 'org-habit-stats
:type 'boolean)
(defcustom org-habit-stats-calendar-dont-highlight-whitespace nil
"If t, don't highlight whitespace padding in calendar dates."
:group 'org-habit-stats
:type 'boolean)
;;; Defvars
(defvar org-habit-stats-buffer "*Org-Habit-Stats*"
"Name of the buffer used for displaying stats, calendar, and graphs.")
(defvar org-habit-stats-calendar-buffer "*Org-Habit-Stats Calendar*"
"Name of the buffer used for the calendar.")
(defvar org-habit-stats-displayed-month nil
"Stores displayed-month value for calendar functions.")
(defvar org-habit-stats-displayed-year nil
"Stores displayed-year value for calendar functions.")
(defvar org-habit-stats-graph-current-offset 0
"How many bars to shift left when the bar graph is truncated.")
(defvar org-habit-stats-graph-face-list nil
"Faces used for bars in graphs.
Generated from `org-habit-stats-graph-colors-list'.")
(defvar org-habit-stats-graph-current-func nil
"Current graph function used in org habit stats buffer.")
(defvar-local org-habit-stats-habit-source nil)
(defvar-local org-habit-stats-stat-bounds nil)
(defvar-local org-habit-stats-calendar-bounds nil)
(defvar-local org-habit-stats-message-bounds nil)
(defvar-local org-habit-stats-graph-bounds nil)
(defvar-local org-habit-stats-current-habit-data nil)
(defvar-local org-habit-stats-current-habit-name nil)
(defvar-local org-habit-stats-current-habit-description nil)
(defvar-local org-habit-stats-current-history nil)
(defvar-local org-habit-stats-current-history-rev nil)
(defvar-local org-habit-stats-current-buffer nil)
(defvar-local org-habit-stats-current-calendar-buffer nil)
;;; Faces
(defface org-habit-stats-message-positive
'((t (:foreground "#000000" :background "gold2")))
"Face for positive messages."
:group 'org-habit-stats)
(defface org-habit-stats-message-encouraging
'((t (:foreground "#000000" :background "chocolate1")))
"Face for encouraging messages."
:group 'org-habit-stats)
(defface org-habit-stats-graph-label
'((t (:inherit default)))
"Face for a habit graph's axis labels."
:group 'org-habit-stats)
(defface org-habit-stats-graph-name
'((t (:weight bold)))
"Face for a habit graph's axis name."
:group 'org-habit-stats)
(defface org-habit-stats-graph-title
'((t (:weight bold)))
"Face for a habit graph's title."
:group 'org-habit-stats)
(defface org-habit-stats-calendar-completed
'((t (:foreground "#004c00" :background "#e0a3ff")))
"Face for days in the calendar where the habit was completed."
:group 'org-habit-stats)
(defface org-habit-stats-stat-value
'((t (:foreground "#004c00" :background "#aceaac")))
"Face for statistics value."
:group 'org-habit-stats)
(defface org-habit-stats-stat-name
'((t (:inherit org-agenda-structure-secondary)))
"Face for statistics value."
:group 'org-habit-stats)
(defface org-habit-stats-habit-name
'((t (:inherit org-agenda-structure)))
"Face for habit name."
:group 'org-habit-stats)
(defface org-habit-stats-section-name
'((t (:inherit default)))
"Face for section name in org-habit-stats buffer."
:group 'org-habit-stats)
;; Stats functions
(defun org-habit-stats-get-full-history-old-to-new (history)
"Return the full history of a habit from old to new.
HISTORY is a list of dates of completions. A date here is the
number of days since December 31, 1 BC. The returned value is a
list of dates since the earliest date in history (inclusive)
where each element is a pair of the form (date . 0 or 1),
indicating if there was a completion or not on that day.
If today is marked completed, it is included in the history. If today is
not marked completed, it is included in the history if and only
if `org-habit-stats-include-uncompleted-today` is t."
(let ((today (org-today))
(bin-hist '())
(history (reverse history)))
(seq-reduce ;;replace with reduce
(lambda (a b)
(setq a (1- a))
(while (> a b)
(if (= a today)
(if org-habit-stats-include-uncompleted-today
(push (cons a 0) bin-hist))
(push (cons a 0) bin-hist))
(setq a (1- a)))
(push (cons b 1) bin-hist)
b)
history
(1+ today))
bin-hist))
(defun org-habit-stats-get-full-history-new-to-old (history)
"Return the full history of a habit from old to new.
This returns the reverse of calling
`org-habit-stats-get-full-history-new-to-old` on HISTORY."
(reverse (org-habit-stats-get-full-history-old-to-new history)))
(defun org-habit-stats-get-repeat-history-old-to-new (habit-data)
"Return the history of a habit accounting for the repeat interval.
HABIT-DATA contains the result of calliing
`org-habit-stats-parse-todo' on a habit.
It modifies the full history of a habit (see
`org-habit-stats-get-full-history-new-to-old') by removing
certain days without completions. For ++n or +n style habits,
misses occuring n-1 days after a scheduled date are removed. For
.+n style habits, misses occuring n-1 days after a completed day
are removed."
(let* ((partial-history (nth 4 habit-data))
(repeat-type (nth 5 habit-data))
(repeat-len (nth 1 habit-data))
(next-scheduled (nth 0 habit-data))
(full-history (org-habit-stats-get-full-history-old-to-new partial-history))
(new-history '()))
(cond ((= repeat-len 1) full-history)
((or (string= repeat-type "++")
(string= repeat-type "+"))
(dolist (x full-history (reverse new-history))
;; if a date minus next scheduled is nonzero mod repeat-len, and is incomplete, remove it
(when (not (and (= 0 (cdr x))
(/= 0 (mod (- next-scheduled (car x)) repeat-len))))
(push x new-history))))
((string= repeat-type ".+")
(let ((most-recent-complete (caar full-history)))
(dolist (x full-history (reverse new-history))
(when (= 1 (cdr x))
(setq most-recent-complete (car x)))
;; if incomplete, and difference from prev completion is nonzero mod repeat len, remove it
(when (not (and (= 0 (cdr x))
(/= 0 (mod (- (car x) most-recent-complete) repeat-len))))
(push x new-history)))))
(t (error "Invalid repeat type %s" repeat-type)))))
;; (defun org-habit-stats--streak (h)
;; (if (and h (= (cdr (pop h)) 1))
;; (1+ (org-habit-stats--streak h))
;; 0))
(defun org-habit-stats--streak (h)
"Helper function for `org-habit-stats-streak'.
H must be new-to-old habit history."
(let ((streak 0))
(while (and h (= (cdr (pop h)) 1))
(setq streak (1+ streak)))
streak))
(defun org-habit-stats-streak (_history history-rev _habit-data)
"Return current streak of the habit.
HISTORY contains a list of pairs (date . completed) where date is
represented as the number of days since December 31, 1 BC (as is
used by many `org-mode' functions) and completed is 1 if the
habit was completed that day, and 0 otherwise. It is in order
from oldest to newest. Days are skipped if the repeat interval of
the habit is greater than one. See
`org-habit-stats-get-repeat-history-old-to-new' for more
information.
HISTORY-REV is the reverse of history.
HABIT-DATA is the result of running
`org-habit-parse-todo' on a habit."
(org-habit-stats--streak history-rev))
;; (defun org-habit-stats--unstreak (h)
;; "Helper function for `org-habit-stats-unstreak'.
;; H must be new-to-old habit history."
;; (if (and h (= (cdr (pop h)) 0))
;; (1+ (org-habit-stats--unstreak h))
;; 0))
(defun org-habit-stats--unstreak (h)
"Helper function for `org-habit-stats-unstreak'.
H must be new-to-old habit history."
(let ((unstreak 0))
(while (and h (= (cdr (pop h)) 0))
(setq unstreak (1+ unstreak)))
unstreak))
(defun org-habit-stats-unstreak (_history history-rev _habit-data)
"Return the current unstreak (number of consecutive days missed).
If there is no history, returns 0.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats--unstreak history-rev))
(defun org-habit-stats--record-streak-full (history _history-rev _habit-data)
"Return (record-streak . record-day).
The record-day is the last day of the record streak. If the
record streak occurs on multiple days, return the earliest one.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let ((record-streak 0)
(record-day (org-today))
(curr-streak 0)
(curr-streak-start 0))
(while history
(let* ((next-pair (pop history))
(curr-day (car next-pair))
(curr-completed (cdr next-pair)))
(if (= curr-completed 1)
(progn
(when (= curr-streak 0)
(setq curr-streak-start curr-day))
(setq curr-streak (1+ curr-streak)))
(setq curr-streak 0))
(when (> curr-streak record-streak)
(setq record-streak curr-streak)
(setq record-day (+ curr-streak-start curr-streak -1)))))
(cons record-streak record-day)))
(defun org-habit-stats--single-whitespace-only (s)
"Replace all contiguous whitespace with a single space in S."
(string-join
(seq-filter (lambda (x) (if (> (length x) 0) t))
(split-string s " "))
" "))
(defun org-habit-stats-record-streak-format (history history-rev habit-data)
"Return human readable results from `org-habit-stats--record-streak-full'.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let* ((record-data (org-habit-stats--record-streak-full history history-rev habit-data))
(record-streak (car record-data))
(record-day (cdr record-data)))
(concat (number-to-string record-streak)
", on "
(org-habit-stats--single-whitespace-only (org-agenda-format-date-aligned record-day)))))
(defun org-habit-stats-record-streak-days (history history-rev habit-data)
"Return the record streak length.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(car (org-habit-stats--record-streak-full history history-rev habit-data)))
(defun org-habit-stats-record-streak-date (history history-rev habit-data)
"Return the day the record streak is achieved.
If there are multiple record streaks, this returns the last day
of the latest one.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats-format-absolute-day-string
org-habit-stats-stat-date-format
(cdr (org-habit-stats--record-streak-full history history-rev habit-data))))
(defun org-habit-stats--N-day-total (history history-rev N)
"Return the number of completions in the last N days.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY and HISTORY-REV."
(if (and (> N 0) history-rev)
(if (= (cdr (pop history-rev)) 1)
(1+ (org-habit-stats--N-day-total history history-rev (1- N)))
(org-habit-stats--N-day-total history history-rev (1- N)))
0))
(defun org-habit-stats-percentage-format (x)
"Format real number X as a percent."
(format "%.2f%%" (* 100 x)))
(defun org-habit-stats--N-day-percentage (history history-rev _habit-data N)
"Return the percentage of completions in the last N days.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats-percentage-format
(/ (org-habit-stats--N-day-total history history-rev N) (float N))))
(defun org-habit-stats-30-day-percentage (history history-rev habit-data)
"Return the percentage of completions in the last 30 days.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats--N-day-percentage history history-rev habit-data 30))
(defun org-habit-stats-365-day-percentage (history history-rev habit-data)
"Return the percentage of completions in the last 365 days.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats--N-day-percentage history history-rev habit-data 365))
(defun org-habit-stats-alltime-percentage (history history-rev habit-data)
"Return the percentage of completions since the first completion.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let* ((numerator (org-habit-stats-alltime-total history history-rev habit-data))
(denominator (float (length history))))
(org-habit-stats-percentage-format (if (= denominator 0)
0
(/ numerator denominator)))))
(defun org-habit-stats-30-day-total (history history-rev _habit-data)
"Return the total number of completions in the last 30 days.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats--N-day-total history history-rev 30))
(defun org-habit-stats-365-day-total (history history-rev _habit-data)
"Return the total number of completions in the last 365 days.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats--N-day-total history history-rev 365))
(defun org-habit-stats-alltime-total (_history _history-rev habit-data)
"Return the total number of completions since the first completion.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(length (nth 4 habit-data)))
(defun org-habit-stats--exp-smoothing-list-full (history _history-rev _habit-data)
"Return list of scores for a habit.
The list contains the scores for every day between today and the
first completion inclusive. The score is computed via exponential
smoothing. (Inspired by the GPLv3 Loop Habit Tracker app's
score.).
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(if (not history) nil
(let* ((scores '())
(alpha org-habit-stats-exp-smoothing-alpha)
(beta org-habit-stats-exp-smoothing-beta))
(while history
(let* ((completed (cdr (pop history)))
(coeff (if (= completed 1) alpha beta))
(prev-score (if scores (car scores) 0)))
(push (+ (* (- 1 coeff) prev-score)
(* coeff completed)) scores)))
;; (print scores)
(mapcar (lambda (x) (* 100 x)) scores))))
(defun org-habit-stats-exp-smoothing-list-today (history history-rev habit-data)
"Return today's score for the habit.
See `org-habit-stats--exp-smoothing-list-full' for more details.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(if (not history) 0
(car (org-habit-stats--exp-smoothing-list-full
history history-rev habit-data))))
(defun org-habit-stats-get-freq (seq &optional key-func value-func)
"Return frequencies of elements in SEQ.
If KEY-FUNC, use KEY-FUNC to produce keys for hash table. If
VALUE-FUNC, use VALUE-FUNC to produce values for hash table.
Credit to https://stackoverflow.com/a/6050245"
(let ((h (make-hash-table :test 'equal))
(freqs nil)
(value-func (if value-func value-func (lambda (_) 1))))
(dolist (x seq)
(let ((key (if key-func (funcall key-func x) x)))
(puthash key (+ (gethash key h 0) (funcall value-func x)) h)))
(maphash (lambda (k v) (push (cons k v) freqs)) h)
freqs))
(defun org-habit-stats-calculate-stats (history history-rev habit-data)
"Return a list of cons pairs describing the stats for a habit.
Each pair is of the form (\"name of stat\" . stat).
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let ((statresults '()))
(dolist (x org-habit-stats-stat-functions-alist)
(let* ((statfunc (car x))
(statname (cdr x))
(statresult (if (fboundp statfunc) (funcall statfunc history history-rev habit-data))))
(when statresult
(push (cons statname statresult) statresults))))
(reverse statresults)))
(defun org-habit-stats-transpose-pair-list (a)
"Convert a list of pairs A to a pair of two lists."
(cons (mapcar #'car a) (mapcar #'cdr a)))
;;; Message functions
(defun org-habit-stats-get-messages (history history-rev habit-data)
"Return list of messages to display for the habit.
It does so by calling all functions in
`org-habit-stats-message-functions-list' on the three forms of
the habit's data.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let ((messageslst '()))
(dolist (x org-habit-stats-message-functions-list)
(let ((x-message (funcall x history history-rev habit-data)))
(when x-message
(push x-message messageslst))))
(reverse messageslst)))
(defun org-habit-stats-streak-message (history history-rev habit-data)
"Return a message based on the habit's streak or nil.
When the current streak is equal to the first value in a pair in
`org-habit-stats-streak-message-alist', the second value of that
pair is returned as the message.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let* ((streak (org-habit-stats-streak history history-rev habit-data))
(message (alist-get streak org-habit-stats-streak-message-alist)))
(when message
(propertize message
'face 'org-habit-stats-message-positive))))
(defun org-habit-stats-unstreak-message (history history-rev habit-data)
"Return a message based on the habit's streak or nil.
When the current unstreak is equal to the first value in a pair in
`org-habit-stats-unstreak-message-alist', the second value of that
pair is returned as the message.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let* ((unstreak (org-habit-stats-unstreak history history-rev habit-data))
(message (alist-get unstreak org-habit-stats-unstreak-message-alist)))
(when message
(propertize message
'face 'org-habit-stats-message-encouraging))))
(defun org-habit-stats-comeback-message (history history-rev habit-data)
"Return a message when a comeback happens.
The message is `org-habit-stats-comeback-message'.
A comeback occurs when the user reaches a record streak that they
previously already obtained. It also only applies for streaks of
length at least 5.
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let* ((curr-streak (org-habit-stats-streak history history-rev habit-data))
(record-data (org-habit-stats--record-streak-full history history-rev habit-data))
(record-day (cdr record-data))
(record-streak (car record-data)))
(when (and (= curr-streak record-streak)
(>= curr-streak 5)
(/= record-day (org-today))
(/= record-day (1- (org-today))))
(propertize org-habit-stats-comeback-message
'face 'org-habit-stats-message-positive))))
;;; Calendar functions
(defun org-habit-stats-calendar-mark-habits (habit-data)
"Mark completed habits in the internal calendar buffer.
See the docstring of `org-habit-stats-streak' for a description
of HABIT-DATA."
(let ((completed-dates (nth 4 habit-data))
(calendar-buffer org-habit-stats-calendar-buffer))
(dolist (completed-day completed-dates nil)
(let ((completed-day-gregorian (calendar-gregorian-from-absolute completed-day)))
(when (calendar-date-is-visible-p completed-day-gregorian)
(calendar-mark-visible-date completed-day-gregorian 'org-habit-stats-calendar-completed))))))
(defun org-habit-stats-get-calendar-contents ()
"Return contents of `org-habit-stats-calendar-buffer'."
(with-current-buffer org-habit-stats-calendar-buffer
(buffer-string)))
(defun org-habit-stats-get-calendar-overlays ()
"Return a list of all overlays in `org-habit-stats-calendar-buffer'.
These are overlays corresponding to completed days."
(with-current-buffer org-habit-stats-calendar-buffer
(let ((ol-list (overlay-lists)))
(append (car ol-list) (cdr ol-list)))))
(defun org-habit-stats-apply-overlays (ol-list offset buffer)
"Apply overlays in OL-LIST to BUFFER, by offset OFFSET."
(dolist (ol ol-list)
(let* ((new-start (+ (overlay-start ol) offset))
(new-end (+ (overlay-end ol) offset))
(space-at-new-start (save-excursion
(goto-char new-start)
(eq ? (char-after))))
(new-start-adjusted (if (and org-habit-stats-calendar-dont-highlight-whitespace
space-at-new-start
(< new-start new-end))
(1+ new-start)
new-start)))
(move-overlay (copy-overlay ol)
new-start-adjusted
new-end
buffer))))
;; create calendar buffer, inject text at top, mark custom dates, set so curr month on the right first
(defun org-habit-stats-make-calendar-buffer (habit-data)
"Create a `calendar-mode' buffer displaying completed days.
HABIT-DATA contains the results of `org-habit-parse-todo`."
(with-current-buffer
(get-buffer-create org-habit-stats-calendar-buffer)
(calendar-mode)
(let* ((date (calendar-current-date))
(month (1- (calendar-extract-month date)))
(year (calendar-extract-year date)))
(let (calendar-today-visible-hook calendar-today-invisible-hook)
(calendar-generate-window month year))
(setq org-habit-stats-displayed-month month)
(setq org-habit-stats-displayed-year year)
(org-habit-stats-calendar-mark-habits habit-data))
(run-hooks 'calendar-initial-window-hook)))
(defun org-habit-stats-refresh-calendar-buffer ()
"Delete and re-insert calendar with updated info."
(let* ((month org-habit-stats-displayed-month)
(year org-habit-stats-displayed-year)
(habit-data org-habit-stats-current-habit-data))
(with-current-buffer org-habit-stats-calendar-buffer
(setq buffer-read-only nil)
(let (calendar-today-visible-hook calendar-today-invisible-hook)
(calendar-generate-window month year))
(org-habit-stats-calendar-mark-habits habit-data)
(setq buffer-read-only t))))
;;; Calender commands
(defun org-habit-stats-increment-displayed-month (n)
"Increment displayed month by N.
Adjusts displayed-year accordingly. N can be positive, zero, or
negative."
(if (> n 0)
(while (> n 12)
(setq n (- n 12))
(setq org-habit-stats-displayed-year
(1+ org-habit-stats-displayed-year)))
(while (< n 0)
(setq n (+ n 12))
(setq org-habit-stats-displayed-year
(1- org-habit-stats-displayed-year))))
(let ((sum (+ n org-habit-stats-displayed-month)))
(if (> sum 12)
(progn
(setq org-habit-stats-displayed-month (mod sum 12))
(setq org-habit-stats-displayed-year
(1+ org-habit-stats-displayed-year)))
(setq org-habit-stats-displayed-month sum))))
;; (defun org-habit-stats-send-calendar-command (cal-cmd)
;; (with-current-buffer org-habit-stats-calendar-buffer
;; (let* ((displayed-month org-habit-stats-displayed-month)
;; (displayed-year org-habit-stats-displayed-year))
;; (funcall cal-cmd)
;; (org-habit-stats-calendar-mark-habits org-habit-stats-current-habit-data)))
;; (org-habit-stats-refresh-buffer))
(defun org-habit-stats--calendar-scroll (n)
"Scroll org-habit-stats calendar forward N months.
N can be positive, zero, or negative."
(org-habit-stats-increment-displayed-month n)
(if (not (derived-mode-p 'org-habit-stats-mode))
(user-error "Not in an org-habit-stats-mode buffer")
(org-habit-stats-refresh-calendar-buffer)
(org-habit-stats-refresh-calendar-section)))
(defun org-habit-stats-calendar-scroll-right (arg)
"Move the `org-habit-stats' calendar forward ARG months."
(interactive "p")
(org-habit-stats--calendar-scroll arg))
(defun org-habit-stats-calendar-scroll-left (arg)
"Move the `org-habit-stats' calendar backward ARG months."
(interactive "p")
(org-habit-stats--calendar-scroll (- arg)))
(defun org-habit-stats-calendar-scroll-right-three-months (arg)
"Move the `org-habit-stats' calendar forward 3*ARG months."
(interactive "p")
(org-habit-stats--calendar-scroll (* 3 arg)))
(defun org-habit-stats-calendar-scroll-left-three-months (arg)
"Move the `org-habit-stats' calendar backward 3*ARG months."
(interactive "p")
(org-habit-stats--calendar-scroll (* -3 arg)))
(defun org-habit-stats-calendar-forward-year (arg)
"Move the `org-habit-stats' calendar forward 12*ARG months."
(interactive "p")
(org-habit-stats--calendar-scroll (* 12 arg)))
(defun org-habit-stats-calendar-backward-year (arg)
"Move the `org-habit-stats' calendar backward 12*ARG months."
(interactive "p")
(org-habit-stats--calendar-scroll (* -12 arg)))
;;; Graph data functions
(defun org-habit-stats--unix-from-absolute-time (abs-time)
"Convert time ABS-TIME (from end of 1 BC) to unix time.
Used because `org-habit-parse-todo`, `org-today`, etc. all return
days since the end of 1 BC."
(- abs-time (org-habit-stats-days-to-time (calendar-absolute-from-gregorian '(12 31 1969)))))
(defun org-habit-stats-format-absolute-time-string (format-string &optional time zone)
"Format time string given time TIME since end of 1 BC.
Uses `format-time-string` on FORMAT-STRING."
(format-time-string format-string
(org-habit-stats--unix-from-absolute-time time)
zone))
(defun org-habit-stats-format-absolute-day-string (format-string &optional day zone)
"Format time string given days DAY since end of 1 BC.
Uses `format-time-string` on FORMAT-STRING."
(org-habit-stats-format-absolute-time-string format-string
(org-habit-stats-days-to-time day)
zone))
(defun org-habit-stats-graph-count-per-category (history category-func predicate-func format-func)
"Return counts for each category of days.
For each date in HISTORY, get its category (e.g. which month,
which week, day of the week, etc.) using CATEGORY-FUNC, get
counts per category, sort categories with PREDICATE-FUNC, and
convert categories to readable names with FORMAT-FUNC. Returns a
pair of two lists, the first containing names of the categories,
the second containing the corresponding counts per category."
(org-habit-stats-transpose-pair-list
(mapcar (lambda (x) (cons (funcall format-func (car x)) (cdr x)))
(sort (org-habit-stats-get-freq
(mapcar (lambda (x) (cons (funcall category-func (car x)) (cdr x)))
history)
(lambda (x) (car x))
(lambda (x) (cdr x)))
(lambda (x y) (funcall predicate-func (car x) (car y)))))))
(defun org-habit-stats-graph-completions-per-month (history _history-rev _habit-data)
"Return a pair of lists (months . counts).
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats-graph-count-per-category
history
(lambda (d) (let ((day (calendar-gregorian-from-absolute d)))
(list (car day) (caddr day)))) ;; converts absolute date to list (month year)
(lambda (m1 m2) (cond ((< (nth 1 m1) (nth 1 m2)) t)
((= (nth 1 m1) (nth 1 m2)) (if (< (nth 0 m1) (nth 0 m2)) t nil))
(t nil)))
(lambda (m) (car (rassoc (nth 0 m) org-habit-stats-months-names-alist)))))
(defun org-habit-stats-graph-completions-per-week (history _history-rev _habit-data)
"Return a pair of lists (weeks . counts).
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats-graph-count-per-category
history
(lambda (d) (- d (mod d 7))) ;; converts absolute date to the sunday before or on; (month day year) format
(lambda (d1 d2) (< d1 d2))
(lambda (d) (let ((time (org-habit-stats-days-to-time d)))
(org-habit-stats-format-absolute-time-string org-habit-stats-graph-date-format
time)))))
(defun org-habit-stats--pad-history (history n)
"Pad the habit's HISTORY to length N.
Appends uncompleted days to before the first completion."
(while (< (length history) n)
(let ((prev-day (1- (if history (caar history) (org-today)))))
(push (cons prev-day 0) history)))
history)
(defun org-habit-stats-graph-completions-per-weekday (history _history-rev _habit-data)
"Return a pair of lists (weeks . counts).
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(org-habit-stats-graph-count-per-category
(org-habit-stats--pad-history history 7)
(lambda (d) (mod d 7))
(lambda (d1 d2) (< d1 d2))
(lambda (d) (car (rassoc (1+ d) org-habit-stats-days-names-alist)))))
(defun org-habit-stats-graph-daily-strength (history history-rev habit-data)
"Return a pair of lists (days . habit strengths).
See the docstring of `org-habit-stats-streak' for a description
of HISTORY, HISTORY-REV, HABIT-DATA."
(let* ((dayslst (mapcar (lambda (d) (org-habit-stats-format-absolute-time-string
org-habit-stats-graph-date-format