-
Notifications
You must be signed in to change notification settings - Fork 31
/
org-fc.el
2238 lines (1964 loc) · 74.3 KB
/
org-fc.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-fc.el --- Spaced Repetition System for Emacs org-mode -*- lexical-binding: t; -*-
;; Copyright (C) 2020 Leon Rische
;; Author: Leon Rische <emacs@leonrische.me>
;; Url: https://www.leonrische.me/pages/org_flashcards.html
;; Package-requires: ((emacs "26.3") (org "9.3"))
;; Version: 0.0.1
;; 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:
;;
;; A Spaced repetition system for Emacs org-mode.
;;
;;; Code:
(require 'cl-lib)
(require 'eieio)
(require 'org-id)
(require 'org-indent)
(require 'org-element)
(require 'outline)
(require 'parse-time)
(require 'subr-x)
(require 'svg)
;;; Customization
(defgroup org-fc nil
"Manage and review flashcards with Emacs."
:group 'external
:group 'text)
(defcustom org-fc-directories '("~/org/")
"Directories to search for flashcards."
:type 'string
:group 'org-fc)
(defvar org-fc-source-path
(file-name-directory
(file-truename (or load-file-name (buffer-file-name))))
"Location of the org-fc sources.
Used to generate absolute paths to the awk scripts.")
(defcustom org-fc-review-history-file (expand-file-name "org-fc-reviews.tsv" user-emacs-directory)
"File to store review results in."
:type 'string
:group 'org-fc)
(defcustom org-fc-shuffle-positions t
"Shuffle positions before review."
:type 'boolean
:group 'org-fc)
(defcustom org-fc-append-failed-cards t
"Add failed cards to the end of the review session."
:type 'boolean
:group 'org-fc)
;;;; Org Tags / Properties
(defcustom org-fc-type-property "FC_TYPE"
"Property used to store the cards type."
:type 'string
:group 'org-fc)
(defcustom org-fc-created-property "FC_CREATED"
"Property used to store the cards creation time."
:type 'string
:group 'org-fc)
(defcustom org-fc-type-cloze-max-hole-property "FC_CLOZE_MAX"
"Name of the property to use for storing the max hole index."
:type 'string
:group 'org-fc)
(defcustom org-fc-type-cloze-type-property "FC_CLOZE_TYPE"
"Name of the property to use for storing the cloze subtype."
:type 'string
:group 'org-fc)
(defcustom org-fc-suspended-tag "suspended"
"Tag for marking suspended cards."
:type 'string
:group 'org-fc)
(defcustom org-fc-flashcard-tag "fc"
"Tag for marking headlines as flashcards."
:type 'string
:group 'org-fc)
(defcustom org-fc-demo-tag "fc-demo"
"Tag for marking headlines as demo flashcards.
When demo flashcards are reviewed, their review data is not
updated. This is used for the `org-fc-demo' and for testing card
types."
:type 'string
:group 'org-fc)
(defcustom org-fc-review-data-drawer "REVIEW_DATA"
"Name of the drawer used to store review data."
:type 'string
:group 'org-fc)
(defcustom org-fc-drawer-whitelist '()
"Drawers that are not hidden during review."
:type 'list
:group 'org-fc)
(defcustom org-fc-stats-review-min-box 0
"Minimum box for reviews to include in the review stats."
:type 'integer
:group 'org-fc)
;;;; Dashboard
(defcustom org-fc-dashboard-bar-chart-width 400
"Width of the svg generated to display review statistics."
:type 'integer
:group 'org-fc)
(defcustom org-fc-dashboard-bar-chart-height 20
"Height of the svg generated to display review statistics."
:type 'integer
:group 'org-fc)
(defcustom org-fc-dashboard-text-bar-chart-width 40
"Width of the text-bar chart used to display review statistics.
This is only used org-fc is run in a non-graphic display
environment without svg support."
:type 'integer
:group 'org-fc)
(defcustom org-fc-dashboard-buffer-name "*org-fc Main*"
"Name of the buffer to use for displaying the dashboard view."
:type 'string
:group 'org-fc)
;;;; Spacing Parameters
(defcustom org-fc-algorithm 'sm2-v1
"Algorithm for spacing reviews of cards."
:type '(choice (const sm2-v1) (const sm2-v2))
:group 'org-fc)
(defcustom org-fc-sm2-changes
'((again . -0.3)
(hard . -0.15)
(good . 0.0)
(easy . 0.15))
"Changes to a cards ease depending on its rating."
:type 'list
:group 'org-fc)
(defcustom org-fc-sm2-fixed-intervals
'(0.0 0.01 1.0 6.0)
"Hard-coded intervals for the first few card boxes.
Values are in days."
:type 'list
:group 'org-fc)
(defcustom org-fc-sm2-ease-min 1.3 "Lower bound for a cards ease."
:type 'float
:group 'org-fc)
(defcustom org-fc-sm2-ease-initial 2.5 "Initial ease."
:type 'float
:group 'org-fc)
(defcustom org-fc-sm2-ease-max 5.0 "Upper bound for a cards ease."
:type 'float
:group 'org-fc)
(defcustom org-fc-sm2-fuzz-min 0.9
"Lower bound for random interval fuzz factor."
:type 'float
:group 'org-fc)
(defcustom org-fc-sm2-fuzz-max 1.1
"Upper bound for random interval fuzz factor."
:type 'float
:group 'org-fc)
;;;; Hooks
(defcustom org-fc-before-setup-hook '()
"Functions run before a card is set up for review."
:type 'hook
:group 'org-fc)
(defcustom org-fc-after-setup-hook '()
"Functions run after a card is set up for review."
:type 'hook
:group 'org-fc)
(defcustom org-fc-before-review-hook '()
"Functions run when a review session is started."
:type 'hook
:group 'org-fc)
(defcustom org-fc-after-review-hook '()
"Functions run when a review session ends / is quit."
:type 'hook
:group 'org-fc)
;;;; Diff
(defcustom org-fc-diff-filler ?-
"Character for filling diffs when the input was too short."
:type 'character
:group 'org-fc)
;;;; Font Faces
(defface org-fc-type-cloze-hole-face
'((t (:bold t)))
"Face for org-fc cloze card holes."
:group 'org-fc)
;; Based on `magit-diff-added'
(defface org-fc-diff-correct
`((((class color) (background light))
:background "#ddffdd"
:foreground "#22aa22")
(((class color) (background dark))
:background "#335533"
:foreground "#ddffdd"))
"Face for correct parts of a diff."
:group 'org-fc)
;; Based on `magit-diff-removed'
(defface org-fc-diff-wrong
`((((class color) (background light))
:background "#ffdddd"
:foreground "#aa2222")
(((class color) (background dark))
:background "#553333"
:foreground "#ffdddd"))
"Face for wrong parts of a diff."
:group 'org-fc)
;;; Variables
;; TODO: Allow customizing this, currently that's not possible because
;; the indexers / filters expect a ISO8601 format.
(defvar org-fc-timestamp-format "%FT%TZ"
"Format to use for storing timestamps.
Defaults to ISO8601")
(defvar org-fc-reviewing-existing-buffer nil
"Track if the current buffer was open before the review.")
(make-variable-buffer-local 'org-fc-reviewing-existing-buffer)
(defvar org-fc-original-header-line-format nil
"`header-line-format' before it was set by org-fc.")
(defvar org-fc-timestamp nil
"Time the last card was flipped.
Used to calculate the time needed for reviewing a card.")
;;; Helper Functions
(defun org-fc-member-p (path)
"Check if PATH is member of one of the `org-fc-directories'."
(setq path (expand-file-name path))
(and (string= (file-name-extension file) "org")
(cl-some
(lambda (dir) (string-prefix-p (expand-file-name dir) path))
org-fc-directories)))
(defun org-fc-noop ()
"Noop-function.")
(defun org-fc-timestamp-now ()
"ISO8601 timestamp of the current time in the UTC timezone."
(format-time-string org-fc-timestamp-format nil "UTC"))
(defun org-fc-days-overdue (ts)
"Number of days between now and the ISO8601 timestamp TS."
(/ (- (time-to-seconds)
(time-to-seconds (date-to-time ts)))
(* 24 60 60)))
(defun org-fc-show-latex ()
"Show latex fragments of heading at point."
(org-latex-preview 4))
(defun org-fc-back-heading-position ()
"Return point at the beginning of an entries 'Back' subheading.
Return nil if there is no such heading.
This is expected to be called on an card entry heading."
(let ((found nil)
(level (cl-first (org-heading-components))))
(org-map-entries
(lambda ()
(when (let ((comps (org-heading-components)))
(and
(string= (cl-fifth comps) "Back")
(= (cl-first comps) (1+ level))))
(setq found (point))))
t 'tree)
found))
(defun org-fc-has-back-heading-p ()
"Check if the entry at point has a 'Back' subheading.
Used to determine if a card uses the compact style."
(not (null (org-fc-back-heading-position))))
(defun org-fc-shuffle (list)
"Randomize the order of elements in LIST.
This mutates / destroys the input list."
(sort list (lambda (_a _b) (< (cl-random 1.0) 0.5))))
(defun org-fc-sorted-random (n)
"Generate a list of N sorted random numbers."
(sort (cl-loop for i below n collect (cl-random 1.0)) #'>))
(defun org-fc-zip (as bs)
"Zip two lists AS and BS."
(cl-loop for a in as for b in bs collect (cons a b)))
;; File-scoped variant of `org-id-goto'
(defun org-fc-id-goto (id file)
"Go to the heading with ID in FILE."
(let ((position (org-id-find-id-in-file id file)))
(if position
(goto-char (cdr position))
(error "ID %s not found in %s" id file))))
(defun org-fc-timestamp-in (interval)
"Generate an `org-mode' timestamp INTERVAL days from now."
(let ((seconds (* interval 60 60 24))
(now (time-to-seconds)))
(format-time-string
org-fc-timestamp-format
(seconds-to-time (+ now seconds))
"UTC0")))
(defun org-fc-deemphasize (string)
"Remove org emphasis markers from STRING.
Returns a pair (marker . body)."
(if (or (string-match org-emph-re string)
(string-match org-verbatim-re string))
(cons (match-string 3 string) (match-string 4 string))
(cons nil string)))
(defun org-fc-emphasize (string)
"Apply org emphasis faces to STRING."
(with-temp-buffer
(insert string)
(goto-char (point-min))
(org-do-emphasis-faces (point-max))
(buffer-string)))
(defun org-fc-indent ()
"Run `org-indent' on the current headline.
Usually org-indent runs with a delay, so when reviewing a card in
a new file, the cards contents jump to the right (are indented)
during the review. We can get around this by synchronously
indenting the current heading."
(if org-indent-mode
(let ((el (org-element-at-point)))
(org-indent-add-properties
(org-element-property :begin el)
(org-element-property :end el)))))
(defmacro org-fc-with-point-at-entry (&rest body)
"Execute BODY with point at the card heading.
If point is not inside a flashcard entry, an error is raised."
`(save-excursion
(org-fc-goto-entry-heading)
,@body))
(defmacro org-fc-with-point-at-back-heading (&rest body)
"Execute BODY with point at the card's back heading.
If point is not inside a flashcard entry, an error is raised."
`(if-let ((pos (org-fc-back-heading-position)))
(save-excursion
(goto-char pos)
,@body)))
;;; Diff
(defun org-fc-diff-subseq (a b start1 start2 end1 end2)
"Find (index-a index-b len) of the longest matching subsequence in A and B.
Only parts of A in the range START1 to END1 and parts of B in the
range START2 to END2 are considered.
If there is no matching subsequence, nil is returned."
(let ((best-length 0) (best-i 0) (best-j 0)
;; Longest matching subsequence starting at index j of B,
;; offset by one to handle the case j = 0
(lengths (make-vector (1+ (length b)) 0)))
(cl-loop for i from start1 to end1 do
(let ((new-lengths (make-vector (1+ (length b)) 0)))
(cl-loop for j from start2 to end2 do
(if (eql (aref a i) (aref b j))
(let ((length (+ 1 (aref lengths j))))
(aset new-lengths (1+ j) length)
(when (> length best-length)
(setq best-length length)
(setq best-i (1+ (- i length)))
(setq best-j (1+ (- j length)))))))
(setq lengths new-lengths)))
(if (> best-length 0)
(list best-i best-j best-length))))
(defun org-fc-diff-matching-blocks (a b start1 start2 end1 end2)
"Find matching blocks of A and B.
Only parts of A in the range START1 to END1 and parts of B in the
range START2 to END2 are considered."
(if-let ((match (org-fc-diff-subseq a b start1 start2 end1 end2)))
(cl-destructuring-bind (i j len) match
(append
(org-fc-diff-matching-blocks a b start1 start2 (1- i) (1- j))
(list match)
(org-fc-diff-matching-blocks a b (+ i len) (+ j len) end1 end2)))))
(defun org-fc-diff--propertize-got (got blocks expected-length)
"Propertize the GOT answer given matching BLOCKS.
If it is shorter than EXPECTED-LENGTH, it is filled using
`org-fc-diff-filler'."
(let ((last 0) res)
;; Prepend filler if text at start is missing
(unless (null blocks)
(cl-destructuring-bind (i j _len) (car blocks)
(if (> j i)
(setq res
(propertize
(make-string (- j i) org-fc-diff-filler)
'face 'org-fc-diff-wrong)))))
(cl-loop for (i _ len) in blocks do
(setq res
(concat
res
(propertize
(cl-subseq got last i)
'face 'org-fc-diff-wrong)
(propertize
(cl-subseq got i (+ i len))
'face 'org-fc-diff-correct)))
(setq last (+ i len)))
(setq res
(concat
res
(propertize (cl-subseq got last) 'face 'org-fc-diff-wrong)))
;; Append filler if result is shorter than expected
(if (< (length res) expected-length)
(concat
res
(propertize
(make-string (- expected-length (length res)) org-fc-diff-filler)
'face 'org-fc-diff-wrong))
res)))
(defun org-fc-diff--propertize-expected (expected blocks)
"Propertize the EXPECTED answer, given matching BLOCKS."
(let ((last 0) res)
(cl-loop for (_ j len) in blocks do
(setq res
(concat
res
(cl-subseq expected last j)
(propertize
(cl-subseq expected j (+ j len))
'face 'org-fc-diff-correct)))
(setq last (+ j len)))
(concat res (cl-subseq expected last))))
(defun org-fc-diff (got expected)
"Generate a colored diff of the strings GOT and EXPECTED."
(if (string= got expected)
(cons (propertize got 'face 'org-fc-diff-correct) nil)
(let ((blocks (org-fc-diff-matching-blocks
got expected
0 0
(1- (length got))
(1- (length expected)))))
(cons
(org-fc-diff--propertize-got got blocks (length expected))
(org-fc-diff--propertize-expected expected blocks)))))
;;; Checking for / going to flashcard headings
(defun org-fc-entry-p ()
"Check if the current heading is a flashcard."
(member org-fc-flashcard-tag (org-get-tags nil 'local)))
(defun org-fc-suspended-entry-p ()
"Check if the current heading is a suspended flashcard."
(let ((tags (org-get-tags nil 'local)))
(and (member org-fc-flashcard-tag tags)
(member org-fc-suspended-tag tags))))
(defun org-fc-part-of-entry-p ()
"Check if the current heading belongs to a flashcard."
(member org-fc-flashcard-tag (org-get-tags nil)))
(defun org-fc-goto-entry-heading ()
"Move up to the parent heading marked as a flashcard."
(unless (org-fc-part-of-entry-p)
(error "Not inside a flashcard entry"))
(unless (org-at-heading-p)
(org-back-to-heading))
(while (not (org-fc-entry-p))
(unless (org-up-heading-safe)
(error "Cannot find a parent heading that is marked as a flashcard"))))
;;; Adding / Removing Tags
(defun org-fc--add-tag (tag)
"Add TAG to the heading at point."
(org-set-tags
(cl-remove-duplicates
(cons tag (org-get-tags nil 'local))
:test #'string=)))
(defun org-fc--remove-tag (tag)
"Add TAG to the heading at point."
(org-set-tags
(remove tag (org-get-tags nil 'local))))
;;; Card Initialization
(defun org-fc--init-card (type)
"Initialize the current card as a flashcard.
Should only be used by the init functions of card TYPEs."
(if (org-fc-part-of-entry-p)
(error "Headline is already a flashcard"))
(org-back-to-heading)
(org-set-property
org-fc-created-property
(org-fc-timestamp-now))
(org-set-property org-fc-type-property type)
(org-id-get-create)
(org-fc--add-tag org-fc-flashcard-tag))
;;; Card Types
;;;; Type Management
(defvar org-fc-types '()
"Alist for registering card types.
Entries should be lists (name handler-fn update-fn).
Use `org-fc-register-type' for adding card types.")
(defun org-fc-register-type (name setup-fn flip-fn update-fn)
"Register a new card type.
Argument NAME Name of the new type.
Argument SETUP-FN Function for initializing a new card of this type.
Argument FLIP-FN Function for flipping a card during review.
Argument UPDATE-FN Function to update a card when it's contents have changed."
(push
(list name setup-fn flip-fn update-fn)
org-fc-types))
(defun org-fc-type-setup-fn (type)
"Get the review function for a card of TYPE."
(let ((entry (alist-get type org-fc-types nil nil #'string=)))
(if entry
(cl-first entry)
(error "No such flashcard type: %s" type))))
(defun org-fc-type-flip-fn (type)
"Get the flip function for a card of TYPE."
(let ((entry (alist-get type org-fc-types nil nil #'string=)))
(if entry
(cl-second entry)
(error "No such flashcard type: %s" type))))
(defun org-fc-type-update-fn (type)
"Get the update function for a card of TYPE."
(let ((entry (alist-get type org-fc-types nil nil #'string=)))
(if entry
(cl-third entry)
(error "No such flashcard type: %s" type))))
;;;; Normal
(defun org-fc-type-normal-init ()
"Mark headline as card of the normal type."
(interactive)
(org-fc--init-card "normal")
(org-fc-review-data-update '("front")))
(defvar org-fc-type-normal--hidden '())
(defun org-fc-type-normal-setup (_position)
"Prepare a normal card for review."
(interactive)
(if (org-fc-has-back-heading-p)
(progn
(org-show-subtree)
(setq org-fc-type-normal--hidden (org-fc-hide-subheading "Back")))
(setq org-fc-type-normal--hidden nil)
(org-flag-subtree t)))
(defun org-fc-type-normal-flip ()
"Flip a normal card."
(interactive)
(org-show-subtree)
(save-excursion
(dolist (pos org-fc-type-normal--hidden)
(goto-char pos)
(org-show-subtree)))
(org-fc-with-point-at-back-heading
(org-fc-show-latex)))
(org-fc-register-type
'normal
'org-fc-type-normal-setup
'org-fc-type-normal-flip
'org-fc-noop)
;;;; Double
(defvar org-fc-type-double--overlay '())
(defun org-fc-type-double-init ()
"Mark headline as card of the double type."
(interactive)
(org-fc--init-card "double")
(org-fc-review-data-update '("front" "back")))
(defun org-fc-type-double-setup (position)
"Prepare POSITION of a double card for review."
(pcase position
("front" (org-fc-type-normal-setup position))
("back"
(org-show-subtree)
(if (org-fc-has-back-heading-p)
(setq org-fc-type-double--overlay (org-fc-hide-content "[...]\n"))
(setq org-fc-type-double--overlay (org-fc-hide-heading "[...]"))))
(_ (error "Invalid double position %s" position))))
(defun org-fc-type-double-flip ()
"Flip a double card."
(if org-fc-type-double--overlay
(delete-overlay org-fc-type-double--overlay))
(org-show-subtree)
(org-fc-with-point-at-back-heading
(org-fc-show-latex)))
(org-fc-register-type
'double
'org-fc-type-double-setup
'org-fc-type-double-flip
'org-fc-noop)
;;;; Text-Input
(defun org-fc-text-input-content ()
"Return the first line of a cards (back) contents.
Returns a pair (pos . string). If the card has a 'Back' heading,
its content is used, otherwise, the main content is used. This
function is expected to be called with point on a heading."
(save-excursion
;; Go to main or "Back" heading
(if-let ((pos (org-fc-back-heading-position)))
(goto-char pos))
;; Skip metadata & drawers
(forward-line)
(while (or (looking-at-p org-scheduled-regexp)
(looking-at-p org-deadline-regexp))
(forward-line))
(while (looking-at org-drawer-regexp)
(if (re-search-forward ":END:" nil t)
(forward-line)
(error "No :END: found for drawer")))
(unless (looking-at-p org-heading-regexp)
(cons
(point)
(buffer-substring-no-properties (point) (point-at-eol))))))
(defun org-fc-type-text-input-init ()
"Mark headline as card of the text-input type."
(interactive)
(unless (org-fc-text-input-content)
(error "Card contains content"))
(org-fc--init-card "text-input")
(org-fc-review-data-update '("front")))
(defvar org-fc-type-text-input--hidden '())
(defun org-fc-type-text-input-setup (_position)
"Prepare a text-input card for review."
(interactive)
;; Hide answer
(if (org-fc-has-back-heading-p)
(progn
(org-show-subtree)
(setq org-fc-type-text-input--hidden (org-fc-hide-subheading "Back")))
(setq org-fc-type-text-input--hidden nil)
(org-flag-subtree t))
;; Prompt user, create diff overlay
(let* ((pos-content (org-fc-text-input-content))
(content (cdr pos-content))
(start (car pos-content))
(end (+ start (length content)))
(deemph (org-fc-deemphasize content))
(diff (org-fc-diff (read-string "Answer: ") (cdr deemph))))
;; Overlay for user input
(when (car deemph)
(setq start (1+ start))
(setq end (1- end)))
(org-fc-hide-region start end (car diff))
;; Overlay for expected answer, using the newline after the answer
(if (cdr diff)
(org-fc-hide-region
end (1+ end)
(concat
" (expected: "
(if (null (car deemph))
(cdr diff)
(org-fc-emphasize
(concat (car deemph) (cdr diff) (car deemph))))
")\n"))))
;; Reveal answer & diff
(save-excursion
(org-show-subtree)
(dolist (pos org-fc-type-text-input--hidden)
(goto-char pos)
(org-show-subtree))))
(org-fc-register-type
'text-input
'org-fc-type-text-input-setup
nil
'org-fc-noop)
;;;; Cloze
;; NOTE: The context type is not implemented yet
(defvar org-fc-type-cloze-types
'(deletion enumeration context single)
"List of valid cloze card subtypes.")
(defvar org-fc-type-cloze--overlays '())
(defcustom org-fc-type-cloze-context 1
"Number of surrounding cards to show for 'context' type cards."
:type 'number
:group 'org-fc)
;;;;; Hole Parsing / Hiding
(defvar org-fc-type-cloze-hole-re
(rx
(seq
"{{"
(group-n 1 (* (or (seq "$" (+ (not (any "$"))) "$")
(not (any "}"))))) "}"
(? (seq "{" (group-n 2 (* (or
(seq "$" (not (any "$")) "$")
(not (any "}"))))) "}"))
(? "@" (group-n 3 (+ digit)))
"}"))
"Regexp for a cloze hole without an id.")
(defvar org-fc-type-cloze-position-hole-re
(rx
(seq
"{{"
(group-n 1 (* (or (seq "$" (+ (not (any "$"))) "$")
(not (any "}"))))) "}"
(? (seq "{" (group-n 2 (* (or
(seq "$" (not (any "$")) "$")
(not (any "}"))))) "}"))
(seq "@" (group-n 3 (+ digit)))
"}"))
"Regexp for a cloze hole with an id.")
(defun org-fc-type-cloze-max-hole-id ()
"Get the max-hole property of the heading at point."
(if-let ((max-id (org-entry-get (point) org-fc-type-cloze-max-hole-property)))
(string-to-number max-id)
-1))
;; NOTE: The way parts of the hole are hidden / revealed is probably
;; unnecessarily complicated. I couldn't get latex / org text emphasis
;; to work otherwise. If the hole has no hint, we can't use any
;; properties of match 2.
(defun org-fc-type-cloze--overlay-current (hole)
"Generate a list of overlays for the current card.
HOLE is the id of the hole being reviewed."
(let ((hole-pos (plist-get hole :hole-pos))
(text-pos (plist-get hole :text-pos))
(hint-pos (plist-get hole :hint-pos)))
(if (car hint-pos)
(list
:before-text
(org-fc-hide-region (car hole-pos) (car text-pos))
:text
(org-fc-hide-region (car text-pos) (cdr text-pos))
:separator
(org-fc-hide-region (cdr text-pos) (car hint-pos)
"[..."
'org-fc-type-cloze-hole-face)
:hint
(org-fc-overlay-region (car hint-pos) (cdr hint-pos)
'org-fc-type-cloze-hole-face)
:after-hint
(org-fc-hide-region (cdr hint-pos) (cdr hole-pos)
"]"
'org-fc-type-cloze-hole-face))
(list
:before-text
(org-fc-hide-region (car hole-pos) (car text-pos))
:text
(org-fc-hide-region (car text-pos) (cdr text-pos))
:hint
(org-fc-hide-region (cdr text-pos) (cdr hole-pos)
"[...]"
'org-fc-type-cloze-hole-face)))))
(defun org-fc-type-cloze--parse-holes (current-position end)
"Starting at point, collect all cloze holes before END.
CURRENT-POSITION is the id of the hole being reviewed. Returns a
pair (holes . current-index) where current-index is the index of
the hole for the current position."
(let ((holes nil)
(current-index nil))
(while (re-search-forward org-fc-type-cloze-position-hole-re end t)
(let ((text (match-string 1))
(hint (match-string 2))
(position (string-to-number (match-string 3))))
(push (list
:text text
:hint hint
:hole-pos (cons (match-beginning 0) (match-end 0))
:text-pos (cons (match-beginning 1) (match-end 1))
:hint-pos (cons (match-beginning 2) (match-end 2)))
holes)
;; Track the position of the current hole in the list of holes
(if (= current-position position) (setq current-index (1- (length holes))))))
(cons (reverse holes) current-index)))
(defun org-fc-type-cloze--tag-holes (type holes current-index)
"Tag HOLES of a card of TYPE in relation to the hole at CURRENT-INDEX."
(cl-loop for i below (length holes)
for hole in holes
collect
(if (= i current-index)
(cons hole :hint)
(cl-case type
('enumeration
(if (< i current-index)
(cons hole :show)
(cons hole :hide)))
('deletion (cons hole :show))
('single (cons hole :hide))
('context
(if (<= (abs (- i current-index)) org-fc-type-cloze-context)
(cons hole :show)
(cons hole :hide)))
(t (error "Org-fc: Unknown cloze card type %s" type))))))
(defun org-fc-type-cloze-hide-holes (current-position type)
"Hide holes of a card of TYPE in relation to the CURRENT-POSITION."
(org-fc-with-point-at-entry
(let* ((el (org-element-at-point))
(overlays nil)
(end (org-element-property :contents-end el))
(holes (org-fc-type-cloze--parse-holes current-position end))
(tagged-holes (org-fc-type-cloze--tag-holes type (car holes) (cdr holes))))
(cl-loop for (hole . tag) in (reverse tagged-holes) do
(cl-case tag
(:show
(org-fc-hide-region
(car (plist-get hole :hole-pos))
(car (plist-get hole :text-pos)))
(org-fc-hide-region
(cdr (plist-get hole :text-pos))
(cdr (plist-get hole :hole-pos))))
(:hide
(org-fc-hide-region
(car (plist-get hole :hole-pos))
(cdr (plist-get hole :hole-pos))
"..."))
(:hint
(setq overlays (org-fc-type-cloze--overlay-current hole)))))
overlays)))
;;;;; Setup / Flipping
(defun org-fc-type-cloze-init (type)
"Initialize the current heading for use as a cloze card of subtype TYPE.
Processes all holes in the card text."
(interactive (list
(intern
(completing-read
"Cloze Type: "
org-fc-type-cloze-types))))
(unless (member type org-fc-type-cloze-types)
(error "Invalid cloze card type: %s" type))
(org-fc--init-card "cloze")
(org-fc-type-cloze-update)
(org-set-property
org-fc-type-cloze-type-property
(format "%s" type)))
(defun org-fc-type-cloze-setup (position)
"Prepare POSITION of a cloze card for review."
(let ((hole (string-to-number position))
(cloze-type (intern (org-entry-get (point) org-fc-type-cloze-type-property))))
(org-show-subtree)
(setq
org-fc-type-cloze--overlays
(org-fc-type-cloze-hide-holes hole cloze-type))))
(defun org-fc-type-cloze-flip ()
"Flip a cloze card."
(if-let ((overlays org-fc-type-cloze--overlays))
(progn
(if (plist-member overlays :separator)
(org-fc-hide-overlay (plist-get overlays :separator)))
(if (plist-member overlays :after-hint)
(org-fc-hide-overlay (plist-get overlays :after-hint)))
(org-fc-hide-overlay (plist-get overlays :hint))
(org-fc-show-overlay
(plist-get overlays :text)
'org-fc-type-cloze-hole-face))))
(defun org-fc-type-cloze-update ()
"Update the review data & deletions of the current heading."
(let* ((el (org-element-at-point))
(end (org-element-property :contents-end el))
(hole-id (1+ (org-fc-type-cloze-max-hole-id)))
ids)
(save-excursion
(while (re-search-forward org-fc-type-cloze-hole-re end t)
(let ((id (match-string 3))
(hole-end (match-end 0)))
(unless id
(setq id hole-id)
(cl-incf hole-id 1)
(let ((id-str (number-to-string id)))
(cl-incf end (+ 1 (length id-str)))
(goto-char hole-end)
(backward-char)
(insert "@" id-str)))
(push (format "%s" id) ids))))
(org-set-property
org-fc-type-cloze-max-hole-property
(format "%s" (1- hole-id)))
(org-fc-review-data-update (reverse ids))))
(org-fc-register-type
'cloze
'org-fc-type-cloze-setup
'org-fc-type-cloze-flip
'org-fc-type-cloze-update)
;;; Working with Overlays / Hiding Text
;;;; Finding Locations in the Buffer
(defun org-fc-point-at-end-of-previous ()
"Value of point at the end of the previous line.
Returns nil if there is no previous line."
(save-excursion
(beginning-of-line)
(if (bobp)
nil
(progn (backward-char)
(point)))))
(defun org-fc-point-after-title ()
"Value of point at the first line after the title keyword.
Returns nil if there is no title keyword."
(org-with-point-at (point-min)
(when (re-search-forward (rx bol "#+TITLE:") nil t)
(point-at-eol))))
;;;; Showing / Hiding Overlays
(defun org-fc-show-all ()
"Remove all org-fc overlays in the current buffer."
(interactive)
(remove-overlays (point-min) (point-max) 'category 'org-fc-hidden)
(remove-overlays (point-min) (point-max) 'category 'org-fc-visible))
;; Based on `outline-flag-region'
(defun org-fc-hide-region (from to &optional text face)
"Hide region FROM ... TO, optionally replacing it with TEXT.
FACE can be used to set the text face of the overlay, e.g. to
make it bold."
;; (remove-overlays from to 'category 'org-fc-hidden)
(let ((o (make-overlay from to nil 'front-advance)))
(overlay-put o 'display-original (overlay-get o 'display))
(overlay-put o 'category 'org-fc-hidden)
(overlay-put o 'evaporate t)