contrib: Fix error messages.
[org-mode.git] / contrib / lisp / org-drill.el
bloba1422ebe9a9168d5e77c255563f768ecb24eabc2
1 ;;; -*- coding: utf-8-unix -*-
2 ;;; org-drill.el - Self-testing using spaced repetition
3 ;;;
4 ;;; Author: Paul Sexton <eeeickythump@gmail.com>
5 ;;; Version: 2.4.3
6 ;;; Repository at http://bitbucket.org/eeeickythump/org-drill/
7 ;;;
8 ;;;
9 ;;; Synopsis
10 ;;; ========
11 ;;;
12 ;;; Uses the SuperMemo spaced repetition algorithms to conduct interactive
13 ;;; "drill sessions", where the material to be remembered is presented to the
14 ;;; student in random order. The student rates his or her recall of each item,
15 ;;; and this information is used to schedule the item for later revision.
16 ;;;
17 ;;; Each drill session can be restricted to topics in the current buffer
18 ;;; (default), one or several files, all agenda files, or a subtree. A single
19 ;;; topic can also be drilled.
20 ;;;
21 ;;; Different "card types" can be defined, which present their information to
22 ;;; the student in different ways.
23 ;;;
24 ;;; See the file README.org for more detailed documentation.
27 (eval-when-compile (require 'cl))
28 (eval-when-compile (require 'hi-lock))
29 (require 'cl-lib)
30 (require 'hi-lock)
31 (require 'org)
32 (require 'org-id)
33 (require 'org-learn)
36 (defgroup org-drill nil
37 "Options concerning interactive drill sessions in Org mode (org-drill)."
38 :tag "Org-Drill"
39 :group 'org-link)
43 (defcustom org-drill-question-tag
44 "drill"
45 "Tag which topics must possess in order to be identified as review topics
46 by `org-drill'."
47 :group 'org-drill
48 :type 'string)
51 (defcustom org-drill-maximum-items-per-session
53 "Each drill session will present at most this many topics for review.
54 Nil means unlimited."
55 :group 'org-drill
56 :type '(choice integer (const nil)))
60 (defcustom org-drill-maximum-duration
62 "Maximum duration of a drill session, in minutes.
63 Nil means unlimited."
64 :group 'org-drill
65 :type '(choice integer (const nil)))
68 (defcustom org-drill-failure-quality
70 "If the quality of recall for an item is this number or lower,
71 it is regarded as an unambiguous failure, and the repetition
72 interval for the card is reset to 0 days. If the quality is higher
73 than this number, it is regarded as successfully recalled, but the
74 time interval to the next repetition will be lowered if the quality
75 was near to a fail.
77 By default this is 2, for SuperMemo-like behaviour. For
78 Mnemosyne-like behaviour, set it to 1. Other values are not
79 really sensible."
80 :group 'org-drill
81 :type '(choice (const 2) (const 1)))
84 (defcustom org-drill-forgetting-index
86 "What percentage of items do you consider it is 'acceptable' to
87 forget each drill session? The default is 10%. A warning message
88 is displayed at the end of the session if the percentage forgotten
89 climbs above this number."
90 :group 'org-drill
91 :type 'integer)
94 (defcustom org-drill-leech-failure-threshold
96 "If an item is forgotten more than this many times, it is tagged
97 as a 'leech' item."
98 :group 'org-drill
99 :type '(choice integer (const nil)))
102 (defcustom org-drill-leech-method
103 'skip
104 "How should 'leech items' be handled during drill sessions?
105 Possible values:
106 - nil :: Leech items are treated the same as normal items.
107 - skip :: Leech items are not included in drill sessions.
108 - warn :: Leech items are still included in drill sessions,
109 but a warning message is printed when each leech item is
110 presented."
111 :group 'org-drill
112 :type '(choice (const warn) (const skip) (const nil)))
115 (defface org-drill-visible-cloze-face
116 '((t (:foreground "darkseagreen")))
117 "The face used to hide the contents of cloze phrases."
118 :group 'org-drill)
121 (defface org-drill-visible-cloze-hint-face
122 '((t (:foreground "dark slate blue")))
123 "The face used to hide the contents of cloze phrases."
124 :group 'org-drill)
127 (defface org-drill-hidden-cloze-face
128 '((t (:foreground "deep sky blue" :background "blue")))
129 "The face used to hide the contents of cloze phrases."
130 :group 'org-drill)
133 (defcustom org-drill-use-visible-cloze-face-p
135 "Use a special face to highlight cloze-deleted text in org mode
136 buffers?"
137 :group 'org-drill
138 :type 'boolean)
141 (defcustom org-drill-hide-item-headings-p
143 "Conceal the contents of the main heading of each item during drill
144 sessions? You may want to enable this behaviour if item headings or tags
145 contain information that could 'give away' the answer."
146 :group 'org-drill
147 :type 'boolean)
150 (defcustom org-drill-new-count-color
151 "royal blue"
152 "Foreground colour used to display the count of remaining new items
153 during a drill session."
154 :group 'org-drill
155 :type 'color)
157 (defcustom org-drill-mature-count-color
158 "green"
159 "Foreground colour used to display the count of remaining mature items
160 during a drill session. Mature items are due for review, but are not new."
161 :group 'org-drill
162 :type 'color)
164 (defcustom org-drill-failed-count-color
165 "red"
166 "Foreground colour used to display the count of remaining failed items
167 during a drill session."
168 :group 'org-drill
169 :type 'color)
171 (defcustom org-drill-done-count-color
172 "sienna"
173 "Foreground colour used to display the count of reviewed items
174 during a drill session."
175 :group 'org-drill
176 :type 'color)
178 (defcustom org-drill-left-cloze-delimiter
180 "String used within org buffers to delimit cloze deletions."
181 :group 'org-drill
182 :type 'string)
184 (defcustom org-drill-right-cloze-delimiter
186 "String used within org buffers to delimit cloze deletions."
187 :group 'org-drill
188 :type 'string)
191 (setplist 'org-drill-cloze-overlay-defaults
192 `(display ,(format "%s...%s"
193 org-drill-left-cloze-delimiter
194 org-drill-right-cloze-delimiter)
195 face org-drill-hidden-cloze-face
196 window t))
198 (setplist 'org-drill-hidden-text-overlay
199 '(invisible t))
201 (setplist 'org-drill-replaced-text-overlay
202 '(display "Replaced text"
203 face default
204 window t))
207 (defvar org-drill-hint-separator "||"
208 "String which, if it occurs within a cloze expression, signifies that the
209 rest of the expression after the string is a `hint', to be displayed instead of
210 the hidden cloze during a test.")
212 (defun org-drill--compute-cloze-regexp ()
213 (concat "\\("
214 (regexp-quote org-drill-left-cloze-delimiter)
215 "[[:cntrl:][:graph:][:space:]]+?\\)\\(\\|"
216 (regexp-quote org-drill-hint-separator)
217 ".+?\\)\\("
218 (regexp-quote org-drill-right-cloze-delimiter)
219 "\\)"))
221 (defun org-drill--compute-cloze-keywords ()
222 (list (list (org-drill--compute-cloze-regexp)
223 (copy-list '(1 'org-drill-visible-cloze-face nil))
224 (copy-list '(2 'org-drill-visible-cloze-hint-face t))
225 (copy-list '(3 'org-drill-visible-cloze-face nil))
228 (defvar-local org-drill-cloze-regexp
229 (org-drill--compute-cloze-regexp))
232 (defvar-local org-drill-cloze-keywords
233 (org-drill--compute-cloze-keywords))
236 (defcustom org-drill-card-type-alist
237 '((nil org-drill-present-simple-card)
238 ("simple" org-drill-present-simple-card)
239 ("twosided" org-drill-present-two-sided-card nil t)
240 ("multisided" org-drill-present-multi-sided-card nil t)
241 ("hide1cloze" org-drill-present-multicloze-hide1)
242 ("hide2cloze" org-drill-present-multicloze-hide2)
243 ("show1cloze" org-drill-present-multicloze-show1)
244 ("show2cloze" org-drill-present-multicloze-show2)
245 ("multicloze" org-drill-present-multicloze-hide1)
246 ("hidefirst" org-drill-present-multicloze-hide-first)
247 ("hidelast" org-drill-present-multicloze-hide-last)
248 ("hide1_firstmore" org-drill-present-multicloze-hide1-firstmore)
249 ("show1_lastmore" org-drill-present-multicloze-show1-lastmore)
250 ("show1_firstless" org-drill-present-multicloze-show1-firstless)
251 ("conjugate"
252 org-drill-present-verb-conjugation
253 org-drill-show-answer-verb-conjugation)
254 ("decline_noun"
255 org-drill-present-noun-declension
256 org-drill-show-answer-noun-declension)
257 ("spanish_verb" org-drill-present-spanish-verb)
258 ("translate_number" org-drill-present-translate-number))
259 "Alist associating card types with presentation functions. Each
260 entry in the alist takes the form:
262 ;;; (CARDTYPE QUESTION-FN [ANSWER-FN DRILL-EMPTY-P])
264 Where CARDTYPE is a string or nil (for default), and QUESTION-FN
265 is a function which takes no arguments and returns a boolean
266 value.
268 When supplied, ANSWER-FN is a function that takes one argument --
269 that argument is a function of no arguments, which when called,
270 prompts the user to rate their recall and performs rescheduling
271 of the drill item. ANSWER-FN is called with the point on the
272 active item's heading, just prior to displaying the item's
273 'answer'. It can therefore be used to modify the appearance of
274 the answer. ANSWER-FN must call its argument before returning.
276 When supplied, DRILL-EMPTY-P is a boolean value, default nil.
277 When non-nil, cards of this type will be presented during tests
278 even if their bodies are empty."
279 :group 'org-drill
280 :type '(alist :key-type (choice string (const nil))
281 :value-type function))
284 (defcustom org-drill-scope
285 'file
286 "The scope in which to search for drill items when conducting a
287 drill session. This can be any of:
289 file The current buffer, respecting the restriction if any.
290 This is the default.
291 tree The subtree started with the entry at point
292 file-no-restriction The current buffer, without restriction
293 file-with-archives The current buffer, and any archives associated with it.
294 agenda All agenda files
295 agenda-with-archives All agenda files with any archive files associated
296 with them.
297 directory All files with the extension '.org' in the same
298 directory as the current file (includes the current
299 file if it is an .org file.)
300 (FILE1 FILE2 ...) If this is a list, all files in the list will be scanned.
302 ;; Note -- meanings differ slightly from the argument to org-map-entries:
303 ;; 'file' means current file/buffer, respecting any restriction
304 ;; 'file-no-restriction' means current file/buffer, ignoring restrictions
305 ;; 'directory' means all *.org files in current directory
306 :group 'org-drill
307 :type '(choice (const :tag "The current buffer, respecting the restriction if any." file)
308 (const :tag "The subtree started with the entry at point" tree)
309 (const :tag "The current buffer, without restriction" file-no-restriction)
310 (const :tag "The current buffer, and any archives associated with it." file-with-archives)
311 (const :tag "All agenda files" agenda)
312 (const :tag "All agenda files with any archive files associated with them." agenda-with-archives)
313 (const :tag "All files with the extension '.org' in the same directory as the current file (includes the current file if it is an .org file.)" directory)
314 (repeat :tag "List of files to scan for drill items." file)))
317 (defcustom org-drill-match
319 "If non-nil, a string specifying a tags/property/TODO query. During
320 drill sessions, only items that match this query will be considered."
321 :group 'org-drill
322 :type '(choice (const nil) string))
325 (defcustom org-drill-save-buffers-after-drill-sessions-p
327 "If non-nil, prompt to save all modified buffers after a drill session
328 finishes."
329 :group 'org-drill
330 :type 'boolean)
333 (defcustom org-drill-spaced-repetition-algorithm
334 'sm5
335 "Which SuperMemo spaced repetition algorithm to use for scheduling items.
336 Available choices are:
337 - SM2 :: the SM2 algorithm, used in SuperMemo 2.0
338 - SM5 :: the SM5 algorithm, used in SuperMemo 5.0
339 - Simple8 :: a modified version of the SM8 algorithm. SM8 is used in
340 SuperMemo 98. The version implemented here is simplified in that while it
341 'learns' the difficulty of each item using quality grades and number of
342 failures, it does not modify the matrix of values that
343 governs how fast the inter-repetition intervals increase. A method for
344 adjusting intervals when items are reviewed early or late has been taken
345 from SM11, a later version of the algorithm, and included in Simple8."
346 :group 'org-drill
347 :type '(choice (const sm2) (const sm5) (const simple8)))
350 (defcustom org-drill-optimal-factor-matrix
352 "DO NOT CHANGE THE VALUE OF THIS VARIABLE.
354 Persistent matrix of optimal factors, used by the SuperMemo SM5 algorithm.
355 The matrix is saved (using the 'customize' facility) at the end of each
356 drill session.
358 Over time, values in the matrix will adapt to the individual user's
359 pace of learning."
360 :group 'org-drill
361 :type 'sexp)
364 (defcustom org-drill-sm5-initial-interval
366 "In the SM5 algorithm, the initial interval after the first
367 successful presentation of an item is always 4 days. If you wish to change
368 this, you can do so here."
369 :group 'org-drill
370 :type 'float)
373 (defcustom org-drill-add-random-noise-to-intervals-p
375 "If true, the number of days until an item's next repetition
376 will vary slightly from the interval calculated by the SM2
377 algorithm. The variation is very small when the interval is
378 small, but scales up with the interval."
379 :group 'org-drill
380 :type 'boolean)
383 (defcustom org-drill-adjust-intervals-for-early-and-late-repetitions-p
385 "If true, when the student successfully reviews an item 1 or more days
386 before or after the scheduled review date, this will affect that date of
387 the item's next scheduled review, according to the algorithm presented at
388 [[http://www.supermemo.com/english/algsm11.htm#Advanced%20repetitions]].
390 Items that were reviewed early will have their next review date brought
391 forward. Those that were reviewed late will have their next review
392 date postponed further.
394 Note that this option currently has no effect if the SM2 algorithm
395 is used."
396 :group 'org-drill
397 :type 'boolean)
400 (defcustom org-drill-cloze-text-weight
402 "For card types 'hide1_firstmore', 'show1_lastmore' and 'show1_firstless',
403 this number determines how often the 'less favoured' situation
404 should arise. It will occur 1 in every N trials, where N is the
405 value of the variable.
407 For example, with the hide1_firstmore card type, the first piece
408 of clozed text should be hidden more often than the other
409 pieces. If this variable is set to 4 (default), the first item
410 will only be shown 25% of the time (1 in 4 trials). Similarly for
411 show1_lastmore, the last item will be shown 75% of the time, and
412 for show1_firstless, the first item would only be shown 25% of the
413 time.
415 If the value of this variable is NIL, then weighting is disabled, and
416 all weighted card types are treated as their unweighted equivalents."
417 :group 'org-drill
418 :type '(choice integer (const nil)))
421 (defcustom org-drill-cram-hours
423 "When in cram mode, items are considered due for review if
424 they were reviewed at least this many hours ago."
425 :group 'org-drill
426 :type 'integer)
429 ;;; NEW items have never been presented in a drill session before.
430 ;;; MATURE items HAVE been presented at least once before.
431 ;;; - YOUNG mature items were scheduled no more than
432 ;;; ORG-DRILL-DAYS-BEFORE-OLD days after their last
433 ;;; repetition. These items will have been learned 'recently' and will have a
434 ;;; low repetition count.
435 ;;; - OLD mature items have intervals greater than
436 ;;; ORG-DRILL-DAYS-BEFORE-OLD.
437 ;;; - OVERDUE items are past their scheduled review date by more than
438 ;;; LAST-INTERVAL * (ORG-DRILL-OVERDUE-INTERVAL-FACTOR - 1) days,
439 ;;; regardless of young/old status.
442 (defcustom org-drill-days-before-old
444 "When an item's inter-repetition interval rises above this value in days,
445 it is no longer considered a 'young' (recently learned) item."
446 :group 'org-drill
447 :type 'integer)
450 (defcustom org-drill-overdue-interval-factor
452 "An item is considered overdue if its scheduled review date is
453 more than (ORG-DRILL-OVERDUE-INTERVAL-FACTOR - 1) * LAST-INTERVAL
454 days in the past. For example, a value of 1.2 means an additional
455 20% of the last scheduled interval is allowed to elapse before
456 the item is overdue. A value of 1.0 means no extra time is
457 allowed at all - items are immediately considered overdue if
458 there is even one day's delay in reviewing them. This variable
459 should never be less than 1.0."
460 :group 'org-drill
461 :type 'float)
464 (defcustom org-drill-learn-fraction
466 "Fraction between 0 and 1 that governs how quickly the spaces
467 between successive repetitions increase, for all items. The
468 default value is 0.5. Higher values make spaces increase more
469 quickly with each successful repetition. You should only change
470 this in small increments (for example 0.05-0.1) as it has an
471 exponential effect on inter-repetition spacing."
472 :group 'org-drill
473 :type 'float)
476 (defvar drill-answer nil
477 "Global variable that can be bound to a correct answer when an
478 item is being presented. If this variable is non-nil, the default
479 presentation function will show its value instead of the default
480 behaviour of revealing the contents of the drilled item.
482 This variable is useful for card types that compute their answers
483 -- for example, a card type that asks the student to translate a
484 random number to another language. ")
487 (defvar *org-drill-session-qualities* nil)
488 (defvar *org-drill-start-time* 0)
489 (defvar *org-drill-new-entries* nil)
490 (defvar *org-drill-dormant-entry-count* 0)
491 (defvar *org-drill-due-entry-count* 0)
492 (defvar *org-drill-overdue-entry-count* 0)
493 (defvar *org-drill-due-tomorrow-count* 0)
494 (defvar *org-drill-overdue-entries* nil
495 "List of markers for items that are considered 'overdue', based on
496 the value of ORG-DRILL-OVERDUE-INTERVAL-FACTOR.")
497 (defvar *org-drill-young-mature-entries* nil
498 "List of markers for mature entries whose last inter-repetition
499 interval was <= ORG-DRILL-DAYS-BEFORE-OLD days.")
500 (defvar *org-drill-old-mature-entries* nil
501 "List of markers for mature entries whose last inter-repetition
502 interval was greater than ORG-DRILL-DAYS-BEFORE-OLD days.")
503 (defvar *org-drill-failed-entries* nil)
504 (defvar *org-drill-again-entries* nil)
505 (defvar *org-drill-done-entries* nil)
506 (defvar *org-drill-current-item* nil
507 "Set to the marker for the item currently being tested.")
508 (defvar *org-drill-cram-mode* nil
509 "Are we in 'cram mode', where all items are considered due
510 for review unless they were already reviewed in the recent past?")
511 (defvar org-drill-scheduling-properties
512 '("LEARN_DATA" "DRILL_LAST_INTERVAL" "DRILL_REPEATS_SINCE_FAIL"
513 "DRILL_TOTAL_REPEATS" "DRILL_FAILURE_COUNT" "DRILL_AVERAGE_QUALITY"
514 "DRILL_EASE" "DRILL_LAST_QUALITY" "DRILL_LAST_REVIEWED"))
517 ;;; Make the above settings safe as file-local variables.
520 (put 'org-drill-question-tag 'safe-local-variable 'stringp)
521 (put 'org-drill-maximum-items-per-session 'safe-local-variable
522 '(lambda (val) (or (integerp val) (null val))))
523 (put 'org-drill-maximum-duration 'safe-local-variable
524 '(lambda (val) (or (integerp val) (null val))))
525 (put 'org-drill-failure-quality 'safe-local-variable 'integerp)
526 (put 'org-drill-forgetting-index 'safe-local-variable 'integerp)
527 (put 'org-drill-leech-failure-threshold 'safe-local-variable 'integerp)
528 (put 'org-drill-leech-method 'safe-local-variable
529 '(lambda (val) (memq val '(nil skip warn))))
530 (put 'org-drill-use-visible-cloze-face-p 'safe-local-variable 'booleanp)
531 (put 'org-drill-hide-item-headings-p 'safe-local-variable 'booleanp)
532 (put 'org-drill-spaced-repetition-algorithm 'safe-local-variable
533 '(lambda (val) (memq val '(simple8 sm5 sm2))))
534 (put 'org-drill-sm5-initial-interval 'safe-local-variable 'floatp)
535 (put 'org-drill-add-random-noise-to-intervals-p 'safe-local-variable 'booleanp)
536 (put 'org-drill-adjust-intervals-for-early-and-late-repetitions-p
537 'safe-local-variable 'booleanp)
538 (put 'org-drill-cram-hours 'safe-local-variable 'integerp)
539 (put 'org-drill-learn-fraction 'safe-local-variable 'floatp)
540 (put 'org-drill-days-before-old 'safe-local-variable 'integerp)
541 (put 'org-drill-overdue-interval-factor 'safe-local-variable 'floatp)
542 (put 'org-drill-scope 'safe-local-variable
543 '(lambda (val) (or (symbolp val) (listp val))))
544 (put 'org-drill-match 'safe-local-variable
545 '(lambda (val) (or (stringp val) (null val))))
546 (put 'org-drill-save-buffers-after-drill-sessions-p 'safe-local-variable 'booleanp)
547 (put 'org-drill-cloze-text-weight 'safe-local-variable
548 '(lambda (val) (or (null val) (integerp val))))
549 (put 'org-drill-left-cloze-delimiter 'safe-local-variable 'stringp)
550 (put 'org-drill-right-cloze-delimiter 'safe-local-variable 'stringp)
553 ;;;; Utilities ================================================================
556 (defun free-marker (m)
557 (set-marker m nil))
560 (defmacro pop-random (place)
561 (let ((idx (gensym)))
562 `(if (null ,place)
564 (let ((,idx (random* (length ,place))))
565 (prog1 (nth ,idx ,place)
566 (setq ,place (append (subseq ,place 0 ,idx)
567 (subseq ,place (1+ ,idx)))))))))
570 (defmacro push-end (val place)
571 "Add VAL to the end of the sequence stored in PLACE. Return the new
572 value."
573 `(setq ,place (append ,place (list ,val))))
576 (defun shuffle-list (list)
577 "Randomly permute the elements of LIST (all permutations equally likely)."
578 ;; Adapted from 'shuffle-vector' in cookie1.el
579 (let ((i 0)
581 temp
582 (len (length list)))
583 (while (< i len)
584 (setq j (+ i (random* (- len i))))
585 (setq temp (nth i list))
586 (setf (nth i list) (nth j list))
587 (setf (nth j list) temp)
588 (setq i (1+ i))))
589 list)
592 (defun round-float (floatnum fix)
593 "Round the floating point number FLOATNUM to FIX decimal places.
594 Example: (round-float 3.56755765 3) -> 3.568"
595 (let ((n (expt 10 fix)))
596 (/ (float (round (* floatnum n))) n)))
599 (defun command-keybinding-to-string (cmd)
600 "Return a human-readable description of the key/keys to which the command
601 CMD is bound, or nil if it is not bound to a key."
602 (let ((key (where-is-internal cmd overriding-local-map t)))
603 (if key (key-description key))))
606 (defun time-to-inactive-org-timestamp (time)
607 (format-time-string
608 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
609 time))
612 (defun time-to-active-org-timestamp (time)
613 (format-time-string
614 (concat "<" (substring (cdr org-time-stamp-formats) 1 -1) ">")
615 time))
618 (defun org-map-drill-entries (func &optional scope drill-match &rest skip)
619 "Like `org-map-entries', but only drill entries are processed."
620 (let ((org-drill-scope (or scope org-drill-scope))
621 (org-drill-match (or drill-match org-drill-match)))
622 (apply 'org-map-entries func
623 (concat "+" org-drill-question-tag
624 (if (and (stringp org-drill-match)
625 (not (member '(?+ ?- ?|) (elt org-drill-match 0))))
626 "+" "")
627 (or org-drill-match ""))
628 (case org-drill-scope
629 (file nil)
630 (file-no-restriction 'file)
631 (directory
632 (directory-files (file-name-directory (buffer-file-name))
633 t "\\.org$"))
634 (t org-drill-scope))
635 skip)))
638 (defmacro with-hidden-cloze-text (&rest body)
639 `(progn
640 (org-drill-hide-clozed-text)
641 (unwind-protect
642 (progn
643 ,@body)
644 (org-drill-unhide-clozed-text))))
647 (defmacro with-hidden-cloze-hints (&rest body)
648 `(progn
649 (org-drill-hide-cloze-hints)
650 (unwind-protect
651 (progn
652 ,@body)
653 (org-drill-unhide-text))))
656 (defmacro with-hidden-comments (&rest body)
657 `(progn
658 (if org-drill-hide-item-headings-p
659 (org-drill-hide-heading-at-point))
660 (org-drill-hide-comments)
661 (unwind-protect
662 (progn
663 ,@body)
664 (org-drill-unhide-text))))
667 (defun org-drill-days-since-last-review ()
668 "Nil means a last review date has not yet been stored for
669 the item.
670 Zero means it was reviewed today.
671 A positive number means it was reviewed that many days ago.
672 A negative number means the date of last review is in the future --
673 this should never happen."
674 (let ((datestr (org-entry-get (point) "DRILL_LAST_REVIEWED")))
675 (when datestr
676 (- (time-to-days (current-time))
677 (time-to-days (apply 'encode-time
678 (org-parse-time-string datestr)))))))
681 (defun org-drill-hours-since-last-review ()
682 "Like `org-drill-days-since-last-review', but return value is
683 in hours rather than days."
684 (let ((datestr (org-entry-get (point) "DRILL_LAST_REVIEWED")))
685 (when datestr
686 (floor
687 (/ (- (time-to-seconds (current-time))
688 (time-to-seconds (apply 'encode-time
689 (org-parse-time-string datestr))))
690 (* 60 60))))))
693 (defun org-drill-entry-p (&optional marker)
694 "Is MARKER, or the point, in a 'drill item'? This will return nil if
695 the point is inside a subheading of a drill item -- to handle that
696 situation use `org-part-of-drill-entry-p'."
697 (save-excursion
698 (when marker
699 (org-drill-goto-entry marker))
700 (member org-drill-question-tag (org-get-local-tags))))
703 (defun org-drill-goto-entry (marker)
704 (switch-to-buffer (marker-buffer marker))
705 (goto-char marker))
708 (defun org-part-of-drill-entry-p ()
709 "Is the current entry either the main heading of a 'drill item',
710 or a subheading within a drill item?"
711 (or (org-drill-entry-p)
712 ;; Does this heading INHERIT the drill tag
713 (member org-drill-question-tag (org-get-tags-at))))
716 (defun org-drill-goto-drill-entry-heading ()
717 "Move the point to the heading which holds the :drill: tag for this
718 drill entry."
719 (unless (org-at-heading-p)
720 (org-back-to-heading))
721 (unless (org-part-of-drill-entry-p)
722 (error "Point is not inside a drill entry"))
723 (while (not (org-drill-entry-p))
724 (unless (org-up-heading-safe)
725 (error "Cannot find a parent heading that is marked as a drill entry"))))
729 (defun org-drill-entry-leech-p ()
730 "Is the current entry a 'leech item'?"
731 (and (org-drill-entry-p)
732 (member "leech" (org-get-local-tags))))
735 ;; (defun org-drill-entry-due-p ()
736 ;; (cond
737 ;; (*org-drill-cram-mode*
738 ;; (let ((hours (org-drill-hours-since-last-review)))
739 ;; (and (org-drill-entry-p)
740 ;; (or (null hours)
741 ;; (>= hours org-drill-cram-hours)))))
742 ;; (t
743 ;; (let ((item-time (org-get-scheduled-time (point))))
744 ;; (and (org-drill-entry-p)
745 ;; (or (not (eql 'skip org-drill-leech-method))
746 ;; (not (org-drill-entry-leech-p)))
747 ;; (or (null item-time) ; not scheduled
748 ;; (not (minusp ; scheduled for today/in past
749 ;; (- (time-to-days (current-time))
750 ;; (time-to-days item-time))))))))))
753 (defun org-drill-entry-days-overdue ()
754 "Returns:
755 - NIL if the item is not to be regarded as scheduled for review at all.
756 This is the case if it is not a drill item, or if it is a leech item
757 that we wish to skip, or if we are in cram mode and have already reviewed
758 the item within the last few hours.
759 - 0 if the item is new, or if it scheduled for review today.
760 - A negative integer - item is scheduled that many days in the future.
761 - A positive integer - item is scheduled that many days in the past."
762 (cond
763 (*org-drill-cram-mode*
764 (let ((hours (org-drill-hours-since-last-review)))
765 (and (org-drill-entry-p)
766 (or (null hours)
767 (>= hours org-drill-cram-hours))
768 0)))
770 (let ((item-time (org-get-scheduled-time (point))))
771 (cond
772 ((or (not (org-drill-entry-p))
773 (and (eql 'skip org-drill-leech-method)
774 (org-drill-entry-leech-p)))
775 nil)
776 ((null item-time) ; not scheduled -> due now
779 (- (time-to-days (current-time))
780 (time-to-days item-time))))))))
783 (defun org-drill-entry-overdue-p (&optional days-overdue last-interval)
784 "Returns true if entry that is scheduled DAYS-OVERDUE dasy in the past,
785 and whose last inter-repetition interval was LAST-INTERVAL, should be
786 considered 'overdue'. If the arguments are not given they are extracted
787 from the entry at point."
788 (unless days-overdue
789 (setq days-overdue (org-drill-entry-days-overdue)))
790 (unless last-interval
791 (setq last-interval (org-drill-entry-last-interval 1)))
792 (and (numberp days-overdue)
793 (> days-overdue 1) ; enforce a sane minimum 'overdue' gap
794 ;;(> due org-drill-days-before-overdue)
795 (> (/ (+ days-overdue last-interval 1.0) last-interval)
796 org-drill-overdue-interval-factor)))
800 (defun org-drill-entry-due-p ()
801 (let ((due (org-drill-entry-days-overdue)))
802 (and (not (null due))
803 (not (minusp due)))))
806 (defun org-drill-entry-new-p ()
807 (and (org-drill-entry-p)
808 (let ((item-time (org-get-scheduled-time (point))))
809 (null item-time))))
812 (defun org-drill-entry-last-quality (&optional default)
813 (let ((quality (org-entry-get (point) "DRILL_LAST_QUALITY")))
814 (if quality
815 (string-to-number quality)
816 default)))
819 (defun org-drill-entry-failure-count ()
820 (let ((quality (org-entry-get (point) "DRILL_FAILURE_COUNT")))
821 (if quality
822 (string-to-number quality)
823 0)))
826 (defun org-drill-entry-average-quality (&optional default)
827 (let ((val (org-entry-get (point) "DRILL_AVERAGE_QUALITY")))
828 (if val
829 (string-to-number val)
830 (or default nil))))
832 (defun org-drill-entry-last-interval (&optional default)
833 (let ((val (org-entry-get (point) "DRILL_LAST_INTERVAL")))
834 (if val
835 (string-to-number val)
836 (or default 0))))
838 (defun org-drill-entry-repeats-since-fail (&optional default)
839 (let ((val (org-entry-get (point) "DRILL_REPEATS_SINCE_FAIL")))
840 (if val
841 (string-to-number val)
842 (or default 0))))
844 (defun org-drill-entry-total-repeats (&optional default)
845 (let ((val (org-entry-get (point) "DRILL_TOTAL_REPEATS")))
846 (if val
847 (string-to-number val)
848 (or default 0))))
850 (defun org-drill-entry-ease (&optional default)
851 (let ((val (org-entry-get (point) "DRILL_EASE")))
852 (if val
853 (string-to-number val)
854 default)))
857 ;;; From http://www.supermemo.com/english/ol/sm5.htm
858 (defun org-drill-random-dispersal-factor ()
859 "Returns a random number between 0.5 and 1.5."
860 (let ((a 0.047)
861 (b 0.092)
862 (p (- (random* 1.0) 0.5)))
863 (cl-flet ((sign (n)
864 (cond ((zerop n) 0)
865 ((plusp n) 1)
866 (t -1))))
867 (/ (+ 100 (* (* (/ -1 b) (log (- 1 (* (/ b a ) (abs p)))))
868 (sign p)))
869 100.0))))
871 (defun pseudonormal (mean variation)
872 "Random numbers in a pseudo-normal distribution with mean MEAN, range
873 MEAN-VARIATION to MEAN+VARIATION"
874 (+ (random* variation)
875 (random* variation)
876 (- variation)
877 mean))
880 (defun org-drill-early-interval-factor (optimal-factor
881 optimal-interval
882 days-ahead)
883 "Arguments:
884 - OPTIMAL-FACTOR: interval-factor if the item had been tested
885 exactly when it was supposed to be.
886 - OPTIMAL-INTERVAL: interval for next repetition (days) if the item had been
887 tested exactly when it was supposed to be.
888 - DAYS-AHEAD: how many days ahead of time the item was reviewed.
890 Returns an adjusted optimal factor which should be used to
891 calculate the next interval, instead of the optimal factor found
892 in the matrix."
893 (let ((delta-ofmax (* (1- optimal-factor)
894 (/ (+ optimal-interval
895 (* 0.6 optimal-interval) -1) (1- optimal-interval)))))
896 (- optimal-factor
897 (* delta-ofmax (/ days-ahead (+ days-ahead (* 0.6 optimal-interval)))))))
900 (defun org-drill-get-item-data ()
901 "Returns a list of 6 items, containing all the stored recall
902 data for the item at point:
903 - LAST-INTERVAL is the interval in days that was used to schedule the item's
904 current review date.
905 - REPEATS is the number of items the item has been successfully recalled without
906 without any failures. It is reset to 0 upon failure to recall the item.
907 - FAILURES is the total number of times the user has failed to recall the item.
908 - TOTAL-REPEATS includes both successful and unsuccessful repetitions.
909 - AVERAGE-QUALITY is the mean quality of recall of the item over
910 all its repetitions, successful and unsuccessful.
911 - EASE is a number reflecting how easy the item is to learn. Higher is easier.
913 (let ((learn-str (org-entry-get (point) "LEARN_DATA"))
914 (repeats (org-drill-entry-total-repeats :missing)))
915 (cond
916 (learn-str
917 (let ((learn-data (or (and learn-str
918 (read learn-str))
919 (copy-list initial-repetition-state))))
920 (list (nth 0 learn-data) ; last interval
921 (nth 1 learn-data) ; repetitions
922 (org-drill-entry-failure-count)
923 (nth 1 learn-data)
924 (org-drill-entry-last-quality)
925 (nth 2 learn-data) ; EF
927 ((not (eql :missing repeats))
928 (list (org-drill-entry-last-interval)
929 (org-drill-entry-repeats-since-fail)
930 (org-drill-entry-failure-count)
931 (org-drill-entry-total-repeats)
932 (org-drill-entry-average-quality)
933 (org-drill-entry-ease)))
934 (t ; virgin item
935 (list 0 0 0 0 nil nil)))))
938 (defun org-drill-store-item-data (last-interval repeats failures
939 total-repeats meanq
940 ease)
941 "Stores the given data in the item at point."
942 (org-entry-delete (point) "LEARN_DATA")
943 (org-set-property "DRILL_LAST_INTERVAL"
944 (number-to-string (round-float last-interval 4)))
945 (org-set-property "DRILL_REPEATS_SINCE_FAIL" (number-to-string repeats))
946 (org-set-property "DRILL_TOTAL_REPEATS" (number-to-string total-repeats))
947 (org-set-property "DRILL_FAILURE_COUNT" (number-to-string failures))
948 (org-set-property "DRILL_AVERAGE_QUALITY"
949 (number-to-string (round-float meanq 3)))
950 (org-set-property "DRILL_EASE"
951 (number-to-string (round-float ease 3))))
955 ;;; SM2 Algorithm =============================================================
958 (defun determine-next-interval-sm2 (last-interval n ef quality
959 failures meanq total-repeats)
960 "Arguments:
961 - LAST-INTERVAL -- the number of days since the item was last reviewed.
962 - REPEATS -- the number of times the item has been successfully reviewed
963 - EF -- the 'easiness factor'
964 - QUALITY -- 0 to 5
966 Returns a list: (INTERVAL REPEATS EF FAILURES MEAN TOTAL-REPEATS OFMATRIX), where:
967 - INTERVAL is the number of days until the item should next be reviewed
968 - REPEATS is incremented by 1.
969 - EF is modified based on the recall quality for the item.
970 - OF-MATRIX is not modified."
971 (assert (> n 0))
972 (assert (and (>= quality 0) (<= quality 5)))
973 (if (<= quality org-drill-failure-quality)
974 ;; When an item is failed, its interval is reset to 0,
975 ;; but its EF is unchanged
976 (list -1 1 ef (1+ failures) meanq (1+ total-repeats)
977 org-drill-optimal-factor-matrix)
978 ;; else:
979 (let* ((next-ef (modify-e-factor ef quality))
980 (interval
981 (cond
982 ((<= n 1) 1)
983 ((= n 2)
984 (cond
985 (org-drill-add-random-noise-to-intervals-p
986 (case quality
987 (5 6)
988 (4 4)
989 (3 3)
990 (2 1)
991 (t -1)))
992 (t 6)))
993 (t (* last-interval next-ef)))))
994 (list (if org-drill-add-random-noise-to-intervals-p
995 (+ last-interval (* (- interval last-interval)
996 (org-drill-random-dispersal-factor)))
997 interval)
998 (1+ n)
999 next-ef
1000 failures meanq (1+ total-repeats)
1001 org-drill-optimal-factor-matrix))))
1004 ;;; SM5 Algorithm =============================================================
1008 (defun initial-optimal-factor-sm5 (n ef)
1009 (if (= 1 n)
1010 org-drill-sm5-initial-interval
1011 ef))
1013 (defun get-optimal-factor-sm5 (n ef of-matrix)
1014 (let ((factors (assoc n of-matrix)))
1015 (or (and factors
1016 (let ((ef-of (assoc ef (cdr factors))))
1017 (and ef-of (cdr ef-of))))
1018 (initial-optimal-factor-sm5 n ef))))
1021 (defun inter-repetition-interval-sm5 (last-interval n ef &optional of-matrix)
1022 (let ((of (get-optimal-factor-sm5 n ef (or of-matrix
1023 org-drill-optimal-factor-matrix))))
1024 (if (= 1 n)
1026 (* of last-interval))))
1029 (defun determine-next-interval-sm5 (last-interval n ef quality
1030 failures meanq total-repeats
1031 of-matrix &optional delta-days)
1032 (if (zerop n) (setq n 1))
1033 (if (null ef) (setq ef 2.5))
1034 (assert (> n 0))
1035 (assert (and (>= quality 0) (<= quality 5)))
1036 (unless of-matrix
1037 (setq of-matrix org-drill-optimal-factor-matrix))
1038 (setq of-matrix (cl-copy-tree of-matrix))
1040 (setq meanq (if meanq
1041 (/ (+ quality (* meanq total-repeats 1.0))
1042 (1+ total-repeats))
1043 quality))
1045 (let ((next-ef (modify-e-factor ef quality))
1046 (old-ef ef)
1047 (new-of (modify-of (get-optimal-factor-sm5 n ef of-matrix)
1048 quality org-drill-learn-fraction))
1049 (interval nil))
1050 (when (and org-drill-adjust-intervals-for-early-and-late-repetitions-p
1051 delta-days (minusp delta-days))
1052 (setq new-of (org-drill-early-interval-factor
1053 (get-optimal-factor-sm5 n ef of-matrix)
1054 (inter-repetition-interval-sm5
1055 last-interval n ef of-matrix)
1056 delta-days)))
1058 (setq of-matrix
1059 (set-optimal-factor n next-ef of-matrix
1060 (round-float new-of 3))) ; round OF to 3 d.p.
1062 (setq ef next-ef)
1064 (cond
1065 ;; "Failed" -- reset repetitions to 0,
1066 ((<= quality org-drill-failure-quality)
1067 (list -1 1 old-ef (1+ failures) meanq (1+ total-repeats)
1068 of-matrix)) ; Not clear if OF matrix is supposed to be
1069 ; preserved
1070 ;; For a zero-based quality of 4 or 5, don't repeat
1071 ;; ((and (>= quality 4)
1072 ;; (not org-learn-always-reschedule))
1073 ;; (list 0 (1+ n) ef failures meanq
1074 ;; (1+ total-repeats) of-matrix)) ; 0 interval = unschedule
1076 (setq interval (inter-repetition-interval-sm5
1077 last-interval n ef of-matrix))
1078 (if org-drill-add-random-noise-to-intervals-p
1079 (setq interval (* interval (org-drill-random-dispersal-factor))))
1080 (list interval
1081 (1+ n)
1083 failures
1084 meanq
1085 (1+ total-repeats)
1086 of-matrix)))))
1089 ;;; Simple8 Algorithm =========================================================
1092 (defun org-drill-simple8-first-interval (failures)
1093 "Arguments:
1094 - FAILURES: integer >= 0. The total number of times the item has
1095 been forgotten, ever.
1097 Returns the optimal FIRST interval for an item which has previously been
1098 forgotten on FAILURES occasions."
1099 (* 2.4849 (exp (* -0.057 failures))))
1102 (defun org-drill-simple8-interval-factor (ease repetition)
1103 "Arguments:
1104 - EASE: floating point number >= 1.2. Corresponds to `AF' in SM8 algorithm.
1105 - REPETITION: the number of times the item has been tested.
1106 1 is the first repetition (ie the second trial).
1107 Returns:
1108 The factor by which the last interval should be
1109 multiplied to give the next interval. Corresponds to `RF' or `OF'."
1110 (+ 1.2 (* (- ease 1.2) (expt org-drill-learn-fraction (log repetition 2)))))
1113 (defun org-drill-simple8-quality->ease (quality)
1114 "Returns the ease (`AF' in the SM8 algorithm) which corresponds
1115 to a mean item quality of QUALITY."
1116 (+ (* 0.0542 (expt quality 4))
1117 (* -0.4848 (expt quality 3))
1118 (* 1.4916 (expt quality 2))
1119 (* -1.2403 quality)
1120 1.4515))
1123 (defun determine-next-interval-simple8 (last-interval repeats quality
1124 failures meanq totaln
1125 &optional delta-days)
1126 "Arguments:
1127 - LAST-INTERVAL -- the number of days since the item was last reviewed.
1128 - REPEATS -- the number of times the item has been successfully reviewed
1129 - EASE -- the 'easiness factor'
1130 - QUALITY -- 0 to 5
1131 - DELTA-DAYS -- how many days overdue was the item when it was reviewed.
1132 0 = reviewed on the scheduled day. +N = N days overdue.
1133 -N = reviewed N days early.
1135 Returns the new item data, as a list of 6 values:
1136 - NEXT-INTERVAL
1137 - REPEATS
1138 - EASE
1139 - FAILURES
1140 - AVERAGE-QUALITY
1141 - TOTAL-REPEATS.
1142 See the documentation for `org-drill-get-item-data' for a description of these."
1143 (assert (>= repeats 0))
1144 (assert (and (>= quality 0) (<= quality 5)))
1145 (assert (or (null meanq) (and (>= meanq 0) (<= meanq 5))))
1146 (let ((next-interval nil))
1147 (setf meanq (if meanq
1148 (/ (+ quality (* meanq totaln 1.0)) (1+ totaln))
1149 quality))
1150 (cond
1151 ((<= quality org-drill-failure-quality)
1152 (incf failures)
1153 (setf repeats 0
1154 next-interval -1))
1155 ((or (zerop repeats)
1156 (zerop last-interval))
1157 (setf next-interval (org-drill-simple8-first-interval failures))
1158 (incf repeats)
1159 (incf totaln))
1161 (let* ((use-n
1162 (if (and
1163 org-drill-adjust-intervals-for-early-and-late-repetitions-p
1164 (numberp delta-days) (plusp delta-days)
1165 (plusp last-interval))
1166 (+ repeats (min 1 (/ delta-days last-interval 1.0)))
1167 repeats))
1168 (factor (org-drill-simple8-interval-factor
1169 (org-drill-simple8-quality->ease meanq) use-n))
1170 (next-int (* last-interval factor)))
1171 (when (and org-drill-adjust-intervals-for-early-and-late-repetitions-p
1172 (numberp delta-days) (minusp delta-days))
1173 ;; The item was reviewed earlier than scheduled.
1174 (setf factor (org-drill-early-interval-factor
1175 factor next-int (abs delta-days))
1176 next-int (* last-interval factor)))
1177 (setf next-interval next-int)
1178 (incf repeats)
1179 (incf totaln))))
1180 (list
1181 (if (and org-drill-add-random-noise-to-intervals-p
1182 (plusp next-interval))
1183 (* next-interval (org-drill-random-dispersal-factor))
1184 next-interval)
1185 repeats
1186 (org-drill-simple8-quality->ease meanq)
1187 failures
1188 meanq
1189 totaln
1195 ;;; Essentially copied from `org-learn.el', but modified to
1196 ;;; optionally call the SM2 or simple8 functions.
1197 (defun org-drill-smart-reschedule (quality &optional days-ahead)
1198 "If DAYS-AHEAD is supplied it must be a positive integer. The
1199 item will be scheduled exactly this many days into the future."
1200 (let ((delta-days (- (time-to-days (current-time))
1201 (time-to-days (or (org-get-scheduled-time (point))
1202 (current-time)))))
1203 (ofmatrix org-drill-optimal-factor-matrix)
1204 ;; Entries can have weights, 1 by default. Intervals are divided by the
1205 ;; item's weight, so an item with a weight of 2 will have all intervals
1206 ;; halved, meaning you will end up reviewing it twice as often.
1207 ;; Useful for entries which randomly present any of several facts.
1208 (weight (org-entry-get (point) "DRILL_CARD_WEIGHT")))
1209 (if (stringp weight)
1210 (setq weight (read weight)))
1211 (destructuring-bind (last-interval repetitions failures
1212 total-repeats meanq ease)
1213 (org-drill-get-item-data)
1214 (destructuring-bind (next-interval repetitions ease
1215 failures meanq total-repeats
1216 &optional new-ofmatrix)
1217 (case org-drill-spaced-repetition-algorithm
1218 (sm5 (determine-next-interval-sm5 last-interval repetitions
1219 ease quality failures
1220 meanq total-repeats ofmatrix))
1221 (sm2 (determine-next-interval-sm2 last-interval repetitions
1222 ease quality failures
1223 meanq total-repeats))
1224 (simple8 (determine-next-interval-simple8 last-interval repetitions
1225 quality failures meanq
1226 total-repeats
1227 delta-days)))
1228 (if (numberp days-ahead)
1229 (setq next-interval days-ahead))
1231 (if (and (null days-ahead)
1232 (numberp weight) (plusp weight)
1233 (not (minusp next-interval)))
1234 (setq next-interval
1235 (max 1.0 (+ last-interval
1236 (/ (- next-interval last-interval) weight)))))
1238 (org-drill-store-item-data next-interval repetitions failures
1239 total-repeats meanq ease)
1241 (if (eql 'sm5 org-drill-spaced-repetition-algorithm)
1242 (setq org-drill-optimal-factor-matrix new-ofmatrix))
1244 (cond
1245 ((= 0 days-ahead)
1246 (org-schedule '(4)))
1247 ((minusp days-ahead)
1248 (org-schedule nil (current-time)))
1250 (org-schedule nil (time-add (current-time)
1251 (days-to-time
1252 (round next-interval))))))))))
1255 (defun org-drill-hypothetical-next-review-date (quality)
1256 "Returns an integer representing the number of days into the future
1257 that the current item would be scheduled, based on a recall quality
1258 of QUALITY."
1259 (let ((weight (org-entry-get (point) "DRILL_CARD_WEIGHT")))
1260 (destructuring-bind (last-interval repetitions failures
1261 total-repeats meanq ease)
1262 (org-drill-get-item-data)
1263 (if (stringp weight)
1264 (setq weight (read weight)))
1265 (destructuring-bind (next-interval repetitions ease
1266 failures meanq total-repeats
1267 &optional ofmatrix)
1268 (case org-drill-spaced-repetition-algorithm
1269 (sm5 (determine-next-interval-sm5 last-interval repetitions
1270 ease quality failures
1271 meanq total-repeats
1272 org-drill-optimal-factor-matrix))
1273 (sm2 (determine-next-interval-sm2 last-interval repetitions
1274 ease quality failures
1275 meanq total-repeats))
1276 (simple8 (determine-next-interval-simple8 last-interval repetitions
1277 quality failures meanq
1278 total-repeats)))
1279 (cond
1280 ((not (plusp next-interval))
1282 ((and (numberp weight) (plusp weight))
1283 (+ last-interval
1284 (max 1.0 (/ (- next-interval last-interval) weight))))
1286 next-interval))))))
1289 (defun org-drill-hypothetical-next-review-dates ()
1290 (let ((intervals nil))
1291 (dotimes (q 6)
1292 (push (max (or (car intervals) 0)
1293 (org-drill-hypothetical-next-review-date q))
1294 intervals))
1295 (reverse intervals)))
1298 (defun org-drill-reschedule ()
1299 "Returns quality rating (0-5), or nil if the user quit."
1300 (let ((ch nil)
1301 (input nil)
1302 (next-review-dates (org-drill-hypothetical-next-review-dates)))
1303 (save-excursion
1304 (while (not (memq ch '(?q ?e ?0 ?1 ?2 ?3 ?4 ?5)))
1305 (setq input (read-key-sequence
1306 (if (eq ch ??)
1307 (format "0-2 Means you have forgotten the item.
1308 3-5 Means you have remembered the item.
1310 0 - Completely forgot.
1311 1 - Even after seeing the answer, it still took a bit to sink in.
1312 2 - After seeing the answer, you remembered it.
1313 3 - It took you awhile, but you finally remembered. (+%s days)
1314 4 - After a little bit of thought you remembered. (+%s days)
1315 5 - You remembered the item really easily. (+%s days)
1317 How well did you do? (0-5, ?=help, e=edit, t=tags, q=quit)"
1318 (round (nth 3 next-review-dates))
1319 (round (nth 4 next-review-dates))
1320 (round (nth 5 next-review-dates)))
1321 "How well did you do? (0-5, ?=help, e=edit, t=tags, q=quit)")))
1322 (cond
1323 ((stringp input)
1324 (setq ch (elt input 0)))
1325 ((and (vectorp input) (symbolp (elt input 0)))
1326 (case (elt input 0)
1327 (up (ignore-errors (forward-line -1)))
1328 (down (ignore-errors (forward-line 1)))
1329 (left (ignore-errors (backward-char)))
1330 (right (ignore-errors (forward-char)))
1331 (prior (ignore-errors (scroll-down))) ; pgup
1332 (next (ignore-errors (scroll-up))))) ; pgdn
1333 ((and (vectorp input) (listp (elt input 0))
1334 (eventp (elt input 0)))
1335 (case (car (elt input 0))
1336 (wheel-up (ignore-errors (mwheel-scroll (elt input 0))))
1337 (wheel-down (ignore-errors (mwheel-scroll (elt input 0)))))))
1338 (if (eql ch ?t)
1339 (org-set-tags-command))))
1340 (cond
1341 ((and (>= ch ?0) (<= ch ?5))
1342 (let ((quality (- ch ?0))
1343 (failures (org-drill-entry-failure-count)))
1344 (unless *org-drill-cram-mode*
1345 (save-excursion
1346 (let ((quality (if (org-drill--entry-lapsed-p) 2 quality)))
1347 (org-drill-smart-reschedule quality
1348 (nth quality next-review-dates))))
1349 (push quality *org-drill-session-qualities*)
1350 (cond
1351 ((<= quality org-drill-failure-quality)
1352 (when org-drill-leech-failure-threshold
1353 ;;(setq failures (if failures (string-to-number failures) 0))
1354 ;; (org-set-property "DRILL_FAILURE_COUNT"
1355 ;; (format "%d" (1+ failures)))
1356 (if (> (1+ failures) org-drill-leech-failure-threshold)
1357 (org-toggle-tag "leech" 'on))))
1359 (let ((scheduled-time (org-get-scheduled-time (point))))
1360 (when scheduled-time
1361 (message "Next review in %d days"
1362 (- (time-to-days scheduled-time)
1363 (time-to-days (current-time))))
1364 (sit-for 0.5)))))
1365 (org-set-property "DRILL_LAST_QUALITY" (format "%d" quality))
1366 (org-set-property "DRILL_LAST_REVIEWED"
1367 (time-to-inactive-org-timestamp (current-time))))
1368 quality))
1369 ((= ch ?e)
1370 'edit)
1372 nil))))
1375 ;; (defun org-drill-hide-all-subheadings-except (heading-list)
1376 ;; "Returns a list containing the position of each immediate subheading of
1377 ;; the current topic."
1378 ;; (let ((drill-entry-level (org-current-level))
1379 ;; (drill-sections nil)
1380 ;; (drill-heading nil))
1381 ;; (org-show-subtree)
1382 ;; (save-excursion
1383 ;; (org-map-entries
1384 ;; (lambda ()
1385 ;; (when (and (not (outline-invisible-p))
1386 ;; (> (org-current-level) drill-entry-level))
1387 ;; (setq drill-heading (org-get-heading t))
1388 ;; (unless (and (= (org-current-level) (1+ drill-entry-level))
1389 ;; (member drill-heading heading-list))
1390 ;; (hide-subtree))
1391 ;; (push (point) drill-sections)))
1392 ;; "" 'tree))
1393 ;; (reverse drill-sections)))
1397 (defun org-drill-hide-subheadings-if (test)
1398 "TEST is a function taking no arguments. TEST will be called for each
1399 of the immediate subheadings of the current drill item, with the point
1400 on the relevant subheading. TEST should return nil if the subheading is
1401 to be revealed, non-nil if it is to be hidden.
1402 Returns a list containing the position of each immediate subheading of
1403 the current topic."
1404 (let ((drill-entry-level (org-current-level))
1405 (drill-sections nil))
1406 (org-show-subtree)
1407 (save-excursion
1408 (org-map-entries
1409 (lambda ()
1410 (when (and (not (outline-invisible-p))
1411 (> (org-current-level) drill-entry-level))
1412 (when (or (/= (org-current-level) (1+ drill-entry-level))
1413 (funcall test))
1414 (hide-subtree))
1415 (push (point) drill-sections)))
1416 "" 'tree))
1417 (reverse drill-sections)))
1420 (defun org-drill-hide-all-subheadings-except (heading-list)
1421 (org-drill-hide-subheadings-if
1422 (lambda () (let ((drill-heading (org-get-heading t)))
1423 (not (member drill-heading heading-list))))))
1426 (defun org-drill-presentation-prompt (&rest fmt-and-args)
1427 (let* ((item-start-time (current-time))
1428 (input nil)
1429 (ch nil)
1430 (last-second 0)
1431 (mature-entry-count (+ (length *org-drill-young-mature-entries*)
1432 (length *org-drill-old-mature-entries*)
1433 (length *org-drill-overdue-entries*)))
1434 (status (first (org-drill-entry-status)))
1435 (prompt
1436 (if fmt-and-args
1437 (apply 'format
1438 (first fmt-and-args)
1439 (rest fmt-and-args))
1440 (concat "Press key for answer, "
1441 "e=edit, t=tags, s=skip, q=quit."))))
1442 (setq prompt
1443 (format "%s %s %s %s %s %s"
1444 (propertize
1445 (char-to-string
1446 (cond
1447 ((eql status :failed) ?F)
1448 (*org-drill-cram-mode* ?C)
1450 (case status
1451 (:new ?N) (:young ?Y) (:old ?o) (:overdue ?!)
1452 (t ??)))))
1453 'face `(:foreground
1454 ,(case status
1455 (:new org-drill-new-count-color)
1456 ((:young :old) org-drill-mature-count-color)
1457 ((:overdue :failed) org-drill-failed-count-color)
1458 (t org-drill-done-count-color))))
1459 (propertize
1460 (number-to-string (length *org-drill-done-entries*))
1461 'face `(:foreground ,org-drill-done-count-color)
1462 'help-echo "The number of items you have reviewed this session.")
1463 (propertize
1464 (number-to-string (+ (length *org-drill-again-entries*)
1465 (length *org-drill-failed-entries*)))
1466 'face `(:foreground ,org-drill-failed-count-color)
1467 'help-echo (concat "The number of items that you failed, "
1468 "and need to review again."))
1469 (propertize
1470 (number-to-string mature-entry-count)
1471 'face `(:foreground ,org-drill-mature-count-color)
1472 'help-echo "The number of old items due for review.")
1473 (propertize
1474 (number-to-string (length *org-drill-new-entries*))
1475 'face `(:foreground ,org-drill-new-count-color)
1476 'help-echo (concat "The number of new items that you "
1477 "have never reviewed."))
1478 prompt))
1479 (if (and (eql 'warn org-drill-leech-method)
1480 (org-drill-entry-leech-p))
1481 (setq prompt (concat
1482 (propertize "!!! LEECH ITEM !!!
1483 You seem to be having a lot of trouble memorising this item.
1484 Consider reformulating the item to make it easier to remember.\n"
1485 'face '(:foreground "red"))
1486 prompt)))
1487 (while (memq ch '(nil ?t))
1488 (setq ch nil)
1489 (while (not (input-pending-p))
1490 (let ((elapsed (time-subtract (current-time) item-start-time)))
1491 (message (concat (if (>= (time-to-seconds elapsed) (* 60 60))
1492 "++:++ "
1493 (format-time-string "%M:%S " elapsed))
1494 prompt))
1495 (sit-for 1)))
1496 (setq input (read-key-sequence nil))
1497 (if (stringp input) (setq ch (elt input 0)))
1498 (if (eql ch ?t)
1499 (org-set-tags-command)))
1500 (case ch
1501 (?q nil)
1502 (?e 'edit)
1503 (?s 'skip)
1504 (otherwise t))))
1507 (defun org-pos-in-regexp (pos regexp &optional nlines)
1508 (save-excursion
1509 (goto-char pos)
1510 (org-in-regexp regexp nlines)))
1513 (defun org-drill-hide-region (beg end &optional text)
1514 "Hide the buffer region between BEG and END with an 'invisible text'
1515 visual overlay, or with the string TEXT if it is supplied."
1516 (let ((ovl (make-overlay beg end)))
1517 (overlay-put ovl 'category
1518 'org-drill-hidden-text-overlay)
1519 (overlay-put ovl 'priority 9999)
1520 (when (stringp text)
1521 (overlay-put ovl 'invisible nil)
1522 (overlay-put ovl 'face 'default)
1523 (overlay-put ovl 'display text))))
1526 (defun org-drill-hide-heading-at-point (&optional text)
1527 (unless (org-at-heading-p)
1528 (error "Point is not on a heading"))
1529 (save-excursion
1530 (let ((beg (point)))
1531 (end-of-line)
1532 (org-drill-hide-region beg (point) text))))
1535 (defun org-drill-hide-comments ()
1536 (save-excursion
1537 (while (re-search-forward "^#.*$" nil t)
1538 (org-drill-hide-region (match-beginning 0) (match-end 0)))))
1541 (defun org-drill-unhide-text ()
1542 ;; This will also unhide the item's heading.
1543 (save-excursion
1544 (dolist (ovl (overlays-in (point-min) (point-max)))
1545 (when (eql 'org-drill-hidden-text-overlay (overlay-get ovl 'category))
1546 (delete-overlay ovl)))))
1549 (defun org-drill-hide-clozed-text ()
1550 (save-excursion
1551 (while (re-search-forward org-drill-cloze-regexp nil t)
1552 ;; Don't hide:
1553 ;; - org links, partly because they might contain inline
1554 ;; images which we want to keep visible.
1555 ;; - LaTeX math fragments
1556 ;; - the contents of SRC blocks
1557 (unless (save-match-data
1558 (or (org-pos-in-regexp (match-beginning 0)
1559 org-bracket-link-regexp 1)
1560 (org-in-src-block-p)
1561 (org-inside-LaTeX-fragment-p)))
1562 (org-drill-hide-matched-cloze-text)))))
1565 (defun org-drill-hide-matched-cloze-text ()
1566 "Hide the current match with a 'cloze' visual overlay."
1567 (let ((ovl (make-overlay (match-beginning 0) (match-end 0)))
1568 (hint-sep-pos (string-match-p (regexp-quote org-drill-hint-separator)
1569 (match-string 0))))
1570 (overlay-put ovl 'category
1571 'org-drill-cloze-overlay-defaults)
1572 (overlay-put ovl 'priority 9999)
1573 (when (and hint-sep-pos
1574 (> hint-sep-pos 1))
1575 (let ((hint (substring-no-properties
1576 (match-string 0)
1577 (+ hint-sep-pos (length org-drill-hint-separator))
1578 (1- (length (match-string 0))))))
1579 (overlay-put
1580 ovl 'display
1581 ;; If hint is like `X...' then display [X...]
1582 ;; otherwise display [...X]
1583 (format (if (string-match-p (regexp-quote "...") hint) "[%s]" "[%s...]")
1584 hint))))))
1587 (defun org-drill-hide-cloze-hints ()
1588 (save-excursion
1589 (while (re-search-forward org-drill-cloze-regexp nil t)
1590 (unless (or (save-match-data
1591 (org-pos-in-regexp (match-beginning 0)
1592 org-bracket-link-regexp 1))
1593 (null (match-beginning 2))) ; hint subexpression matched
1594 (org-drill-hide-region (match-beginning 2) (match-end 2))))))
1597 (defmacro with-replaced-entry-text (text &rest body)
1598 "During the execution of BODY, the entire text of the current entry is
1599 concealed by an overlay that displays the string TEXT."
1600 `(progn
1601 (org-drill-replace-entry-text ,text)
1602 (unwind-protect
1603 (progn
1604 ,@body)
1605 (org-drill-unreplace-entry-text))))
1608 (defmacro with-replaced-entry-text-multi (replacements &rest body)
1609 "During the execution of BODY, the entire text of the current entry is
1610 concealed by an overlay that displays the overlays in REPLACEMENTS."
1611 `(progn
1612 (org-drill-replace-entry-text ,replacements t)
1613 (unwind-protect
1614 (progn
1615 ,@body)
1616 (org-drill-unreplace-entry-text))))
1619 (defun org-drill-replace-entry-text (text &optional multi-p)
1620 "Make an overlay that conceals the entire text of the item, not
1621 including properties or the contents of subheadings. The overlay shows
1622 the string TEXT.
1623 If MULTI-P is non-nil, TEXT must be a list of values which are legal
1624 for the `display' text property. The text of the item will be temporarily
1625 replaced by all of these items, in the order in which they appear in
1626 the list.
1627 Note: does not actually alter the item."
1628 (cond
1629 ((and multi-p
1630 (listp text))
1631 (org-drill-replace-entry-text-multi text))
1633 (let ((ovl (make-overlay (point-min)
1634 (save-excursion
1635 (outline-next-heading)
1636 (point)))))
1637 (overlay-put ovl 'priority 9999)
1638 (overlay-put ovl 'category
1639 'org-drill-replaced-text-overlay)
1640 (overlay-put ovl 'display text)))))
1643 (defun org-drill-unreplace-entry-text ()
1644 (save-excursion
1645 (dolist (ovl (overlays-in (point-min) (point-max)))
1646 (when (eql 'org-drill-replaced-text-overlay (overlay-get ovl 'category))
1647 (delete-overlay ovl)))))
1650 (defun org-drill-replace-entry-text-multi (replacements)
1651 "Make overlays that conceal the entire text of the item, not
1652 including properties or the contents of subheadings. The overlay shows
1653 the string TEXT.
1654 Note: does not actually alter the item."
1655 (let ((ovl nil)
1656 (p-min (point-min))
1657 (p-max (save-excursion
1658 (outline-next-heading)
1659 (point))))
1660 (assert (>= (- p-max p-min) (length replacements)))
1661 (dotimes (i (length replacements))
1662 (setq ovl (make-overlay (+ p-min (* 2 i))
1663 (if (= i (1- (length replacements)))
1664 p-max
1665 (+ p-min (* 2 i) 1))))
1666 (overlay-put ovl 'priority 9999)
1667 (overlay-put ovl 'category
1668 'org-drill-replaced-text-overlay)
1669 (overlay-put ovl 'display (nth i replacements)))))
1672 (defmacro with-replaced-entry-heading (heading &rest body)
1673 `(progn
1674 (org-drill-replace-entry-heading ,heading)
1675 (unwind-protect
1676 (progn
1677 ,@body)
1678 (org-drill-unhide-text))))
1681 (defun org-drill-replace-entry-heading (heading)
1682 "Make an overlay that conceals the heading of the item. The overlay shows
1683 the string TEXT.
1684 Note: does not actually alter the item."
1685 (org-drill-hide-heading-at-point heading))
1688 (defun org-drill-unhide-clozed-text ()
1689 (save-excursion
1690 (dolist (ovl (overlays-in (point-min) (point-max)))
1691 (when (eql 'org-drill-cloze-overlay-defaults (overlay-get ovl 'category))
1692 (delete-overlay ovl)))))
1695 (defun org-drill-get-entry-text (&optional keep-properties-p)
1696 (let ((text (org-agenda-get-some-entry-text (point-marker) 100)))
1697 (if keep-properties-p
1698 text
1699 (substring-no-properties text))))
1702 ;; (defun org-entry-empty-p ()
1703 ;; (zerop (length (org-drill-get-entry-text))))
1705 ;; This version is about 5x faster than the old version, above.
1706 (defun org-entry-empty-p ()
1707 (save-excursion
1708 (org-back-to-heading t)
1709 (let ((lim (save-excursion
1710 (outline-next-heading) (point))))
1711 (org-end-of-meta-data-and-drawers)
1712 (or (>= (point) lim)
1713 (null (re-search-forward "[[:graph:]]" lim t))))))
1715 (defun org-drill-entry-empty-p () (org-entry-empty-p))
1718 ;;; Presentation functions ====================================================
1720 ;; Each of these is called with point on topic heading. Each needs to show the
1721 ;; topic in the form of a 'question' or with some information 'hidden', as
1722 ;; appropriate for the card type. The user should then be prompted to press a
1723 ;; key. The function should then reveal either the 'answer' or the entire
1724 ;; topic, and should return t if the user chose to see the answer and rate their
1725 ;; recall, nil if they chose to quit.
1728 (defun org-drill-present-simple-card ()
1729 (with-hidden-comments
1730 (with-hidden-cloze-hints
1731 (with-hidden-cloze-text
1732 (org-drill-hide-all-subheadings-except nil)
1733 (org-drill--show-latex-fragments) ; overlay all LaTeX fragments with images
1734 (ignore-errors
1735 (org-display-inline-images t))
1736 (org-cycle-hide-drawers 'all)
1737 (prog1 (org-drill-presentation-prompt)
1738 (org-drill-hide-subheadings-if 'org-drill-entry-p))))))
1741 (defun org-drill-present-default-answer (reschedule-fn)
1742 (cond
1743 (drill-answer
1744 (with-replaced-entry-text
1745 (format "\nAnswer:\n\n %s\n" drill-answer)
1746 (prog1
1747 (funcall reschedule-fn)
1748 (setq drill-answer nil))))
1750 (org-drill-hide-subheadings-if 'org-drill-entry-p)
1751 (org-drill-unhide-clozed-text)
1752 (org-drill--show-latex-fragments)
1753 (ignore-errors
1754 (org-display-inline-images t))
1755 (org-cycle-hide-drawers 'all)
1756 (with-hidden-cloze-hints
1757 (funcall reschedule-fn)))))
1760 (defun org-drill--show-latex-fragments ()
1761 (org-remove-latex-fragment-image-overlays)
1762 (if (fboundp 'org-toggle-latex-fragment)
1763 (org-toggle-latex-fragment '(4))
1764 (org-preview-latex-fragment '(4))))
1767 (defun org-drill-present-two-sided-card ()
1768 (with-hidden-comments
1769 (with-hidden-cloze-hints
1770 (with-hidden-cloze-text
1771 (let ((drill-sections (org-drill-hide-all-subheadings-except nil)))
1772 (when drill-sections
1773 (save-excursion
1774 (goto-char (nth (random* (min 2 (length drill-sections)))
1775 drill-sections))
1776 (org-show-subtree)))
1777 (org-drill--show-latex-fragments)
1778 (ignore-errors
1779 (org-display-inline-images t))
1780 (org-cycle-hide-drawers 'all)
1781 (prog1 (org-drill-presentation-prompt)
1782 (org-drill-hide-subheadings-if 'org-drill-entry-p)))))))
1786 (defun org-drill-present-multi-sided-card ()
1787 (with-hidden-comments
1788 (with-hidden-cloze-hints
1789 (with-hidden-cloze-text
1790 (let ((drill-sections (org-drill-hide-all-subheadings-except nil)))
1791 (when drill-sections
1792 (save-excursion
1793 (goto-char (nth (random* (length drill-sections)) drill-sections))
1794 (org-show-subtree)))
1795 (org-drill--show-latex-fragments)
1796 (ignore-errors
1797 (org-display-inline-images t))
1798 (org-cycle-hide-drawers 'all)
1799 (prog1 (org-drill-presentation-prompt)
1800 (org-drill-hide-subheadings-if 'org-drill-entry-p)))))))
1803 (defun org-drill-present-multicloze-hide-n (number-to-hide
1804 &optional
1805 force-show-first
1806 force-show-last
1807 force-hide-first)
1808 "Hides NUMBER-TO-HIDE pieces of text that are marked for cloze deletion,
1809 chosen at random.
1810 If NUMBER-TO-HIDE is negative, show only (ABS NUMBER-TO-HIDE) pieces,
1811 hiding all the rest.
1812 If FORCE-HIDE-FIRST is non-nil, force the first piece of text to be one of
1813 the hidden items.
1814 If FORCE-SHOW-FIRST is non-nil, never hide the first piece of text.
1815 If FORCE-SHOW-LAST is non-nil, never hide the last piece of text.
1816 If the number of text pieces in the item is less than
1817 NUMBER-TO-HIDE, then all text pieces will be hidden (except the first or last
1818 items if FORCE-SHOW-FIRST or FORCE-SHOW-LAST is non-nil)."
1819 (with-hidden-comments
1820 (with-hidden-cloze-hints
1821 (let ((item-end nil)
1822 (match-count 0)
1823 (body-start (or (cdr (org-get-property-block))
1824 (point))))
1825 (if (and force-hide-first force-show-first)
1826 (error "FORCE-HIDE-FIRST and FORCE-SHOW-FIRST are mutually exclusive"))
1827 (org-drill-hide-all-subheadings-except nil)
1828 (save-excursion
1829 (outline-next-heading)
1830 (setq item-end (point)))
1831 (save-excursion
1832 (goto-char body-start)
1833 (while (re-search-forward org-drill-cloze-regexp item-end t)
1834 (let ((in-regexp? (save-match-data
1835 (org-pos-in-regexp (match-beginning 0)
1836 org-bracket-link-regexp 1))))
1837 (unless (or in-regexp?
1838 (org-inside-LaTeX-fragment-p))
1839 (incf match-count)))))
1840 (if (minusp number-to-hide)
1841 (setq number-to-hide (+ match-count number-to-hide)))
1842 (when (plusp match-count)
1843 (let* ((positions (shuffle-list (loop for i from 1
1844 to match-count
1845 collect i)))
1846 (match-nums nil)
1847 (cnt nil))
1848 (if force-hide-first
1849 ;; Force '1' to be in the list, and to be the first item
1850 ;; in the list.
1851 (setq positions (cons 1 (remove 1 positions))))
1852 (if force-show-first
1853 (setq positions (remove 1 positions)))
1854 (if force-show-last
1855 (setq positions (remove match-count positions)))
1856 (setq match-nums
1857 (subseq positions
1858 0 (min number-to-hide (length positions))))
1859 ;; (dolist (pos-to-hide match-nums)
1860 (save-excursion
1861 (goto-char body-start)
1862 (setq cnt 0)
1863 (while (re-search-forward org-drill-cloze-regexp item-end t)
1864 (unless (save-match-data
1865 (or (org-pos-in-regexp (match-beginning 0)
1866 org-bracket-link-regexp 1)
1867 (org-inside-LaTeX-fragment-p)))
1868 (incf cnt)
1869 (if (memq cnt match-nums)
1870 (org-drill-hide-matched-cloze-text)))))))
1871 ;; (loop
1872 ;; do (re-search-forward org-drill-cloze-regexp
1873 ;; item-end t pos-to-hide)
1874 ;; while (org-pos-in-regexp (match-beginning 0)
1875 ;; org-bracket-link-regexp 1))
1876 ;; (org-drill-hide-matched-cloze-text)))))
1877 (org-drill--show-latex-fragments)
1878 (ignore-errors
1879 (org-display-inline-images t))
1880 (org-cycle-hide-drawers 'all)
1881 (prog1 (org-drill-presentation-prompt)
1882 (org-drill-hide-subheadings-if 'org-drill-entry-p)
1883 (org-drill-unhide-clozed-text))))))
1886 (defun org-drill-present-multicloze-hide-nth (to-hide)
1887 "Hide the TO-HIDE'th piece of clozed text. 1 is the first piece. If
1888 TO-HIDE is negative, count backwards, so -1 means the last item, -2
1889 the second to last, etc."
1890 (with-hidden-comments
1891 (with-hidden-cloze-hints
1892 (let ((item-end nil)
1893 (match-count 0)
1894 (body-start (or (cdr (org-get-property-block))
1895 (point)))
1896 (cnt 0))
1897 (org-drill-hide-all-subheadings-except nil)
1898 (save-excursion
1899 (outline-next-heading)
1900 (setq item-end (point)))
1901 (save-excursion
1902 (goto-char body-start)
1903 (while (re-search-forward org-drill-cloze-regexp item-end t)
1904 (let ((in-regexp? (save-match-data
1905 (org-pos-in-regexp (match-beginning 0)
1906 org-bracket-link-regexp 1))))
1907 (unless (or in-regexp?
1908 (org-inside-LaTeX-fragment-p))
1909 (incf match-count)))))
1910 (if (minusp to-hide)
1911 (setq to-hide (+ 1 to-hide match-count)))
1912 (cond
1913 ((or (not (plusp match-count))
1914 (> to-hide match-count))
1915 nil)
1917 (save-excursion
1918 (goto-char body-start)
1919 (setq cnt 0)
1920 (while (re-search-forward org-drill-cloze-regexp item-end t)
1921 (unless (save-match-data
1922 ;; Don't consider this a cloze region if it is part of an
1923 ;; org link, or if it occurs inside a LaTeX math
1924 ;; fragment
1925 (or (org-pos-in-regexp (match-beginning 0)
1926 org-bracket-link-regexp 1)
1927 (org-inside-LaTeX-fragment-p)))
1928 (incf cnt)
1929 (if (= cnt to-hide)
1930 (org-drill-hide-matched-cloze-text)))))))
1931 (org-drill--show-latex-fragments)
1932 (ignore-errors
1933 (org-display-inline-images t))
1934 (org-cycle-hide-drawers 'all)
1935 (prog1 (org-drill-presentation-prompt)
1936 (org-drill-hide-subheadings-if 'org-drill-entry-p)
1937 (org-drill-unhide-clozed-text))))))
1940 (defun org-drill-present-multicloze-hide1 ()
1941 "Hides one of the pieces of text that are marked for cloze deletion,
1942 chosen at random."
1943 (org-drill-present-multicloze-hide-n 1))
1946 (defun org-drill-present-multicloze-hide2 ()
1947 "Hides two of the pieces of text that are marked for cloze deletion,
1948 chosen at random."
1949 (org-drill-present-multicloze-hide-n 2))
1952 (defun org-drill-present-multicloze-hide-first ()
1953 "Hides the first piece of text that is marked for cloze deletion."
1954 (org-drill-present-multicloze-hide-nth 1))
1957 (defun org-drill-present-multicloze-hide-last ()
1958 "Hides the last piece of text that is marked for cloze deletion."
1959 (org-drill-present-multicloze-hide-nth -1))
1962 (defun org-drill-present-multicloze-hide1-firstmore ()
1963 "Commonly, hides the FIRST piece of text that is marked for
1964 cloze deletion. Uncommonly, hide one of the other pieces of text,
1965 chosen at random.
1967 The definitions of 'commonly' and 'uncommonly' are determined by
1968 the value of `org-drill-cloze-text-weight'."
1969 ;; The 'firstmore' and 'lastmore' functions used to randomly choose whether
1970 ;; to hide the 'favoured' piece of text. However even when the chance of
1971 ;; hiding it was set quite high (80%), the outcome was too unpredictable over
1972 ;; the small number of repetitions where most learning takes place for each
1973 ;; item. In other words, the actual frequency during the first 10 repetitions
1974 ;; was often very different from 80%. Hence we use modulo instead.
1975 (cond
1976 ((null org-drill-cloze-text-weight)
1977 ;; Behave as hide1cloze
1978 (org-drill-present-multicloze-hide1))
1979 ((not (and (integerp org-drill-cloze-text-weight)
1980 (plusp org-drill-cloze-text-weight)))
1981 (error "Illegal value for org-drill-cloze-text-weight: %S"
1982 org-drill-cloze-text-weight))
1983 ((zerop (mod (1+ (org-drill-entry-total-repeats 0))
1984 org-drill-cloze-text-weight))
1985 ;; Uncommonly, hide any item except the first
1986 (org-drill-present-multicloze-hide-n 1 t))
1988 ;; Commonly, hide first item
1989 (org-drill-present-multicloze-hide-first))))
1992 (defun org-drill-present-multicloze-show1-lastmore ()
1993 "Commonly, hides all pieces except the last. Uncommonly, shows
1994 any random piece. The effect is similar to 'show1cloze' except
1995 that the last item is much less likely to be the item that is
1996 visible.
1998 The definitions of 'commonly' and 'uncommonly' are determined by
1999 the value of `org-drill-cloze-text-weight'."
2000 (cond
2001 ((null org-drill-cloze-text-weight)
2002 ;; Behave as show1cloze
2003 (org-drill-present-multicloze-show1))
2004 ((not (and (integerp org-drill-cloze-text-weight)
2005 (plusp org-drill-cloze-text-weight)))
2006 (error "Illegal value for org-drill-cloze-text-weight: %S"
2007 org-drill-cloze-text-weight))
2008 ((zerop (mod (1+ (org-drill-entry-total-repeats 0))
2009 org-drill-cloze-text-weight))
2010 ;; Uncommonly, show any item except the last
2011 (org-drill-present-multicloze-hide-n -1 nil nil t))
2013 ;; Commonly, show the LAST item
2014 (org-drill-present-multicloze-hide-n -1 nil t))))
2017 (defun org-drill-present-multicloze-show1-firstless ()
2018 "Commonly, hides all pieces except one, where the shown piece
2019 is guaranteed NOT to be the first piece. Uncommonly, shows any
2020 random piece. The effect is similar to 'show1cloze' except that
2021 the first item is much less likely to be the item that is
2022 visible.
2024 The definitions of 'commonly' and 'uncommonly' are determined by
2025 the value of `org-drill-cloze-text-weight'."
2026 (cond
2027 ((null org-drill-cloze-text-weight)
2028 ;; Behave as show1cloze
2029 (org-drill-present-multicloze-show1))
2030 ((not (and (integerp org-drill-cloze-text-weight)
2031 (plusp org-drill-cloze-text-weight)))
2032 (error "Illegal value for org-drill-cloze-text-weight: %S"
2033 org-drill-cloze-text-weight))
2034 ((zerop (mod (1+ (org-drill-entry-total-repeats 0))
2035 org-drill-cloze-text-weight))
2036 ;; Uncommonly, show the first item
2037 (org-drill-present-multicloze-hide-n -1 t))
2039 ;; Commonly, show any item, except the first
2040 (org-drill-present-multicloze-hide-n -1 nil nil t))))
2043 (defun org-drill-present-multicloze-show1 ()
2044 "Similar to `org-drill-present-multicloze-hide1', but hides all
2045 the pieces of text that are marked for cloze deletion, except for one
2046 piece which is chosen at random."
2047 (org-drill-present-multicloze-hide-n -1))
2050 (defun org-drill-present-multicloze-show2 ()
2051 "Similar to `org-drill-present-multicloze-show1', but reveals two
2052 pieces rather than one."
2053 (org-drill-present-multicloze-hide-n -2))
2056 (defun org-drill-present-card-using-text (question &optional answer)
2057 "Present the string QUESTION as the only visible content of the card.
2058 If ANSWER is supplied, set the global variable `drill-answer' to its value."
2059 (if answer (setq drill-answer answer))
2060 (with-hidden-comments
2061 (with-replaced-entry-text
2062 (concat "\n" question)
2063 (org-drill-hide-all-subheadings-except nil)
2064 (org-cycle-hide-drawers 'all)
2065 (ignore-errors
2066 (org-display-inline-images t))
2067 (prog1 (org-drill-presentation-prompt)
2068 (org-drill-hide-subheadings-if 'org-drill-entry-p)))))
2071 (defun org-drill-present-card-using-multiple-overlays (replacements &optional answer)
2072 "TEXTS is a list of valid values for the 'display' text property.
2073 Present these overlays, in sequence, as the only
2074 visible content of the card.
2075 If ANSWER is supplied, set the global variable `drill-answer' to its value."
2076 (if answer (setq drill-answer answer))
2077 (with-hidden-comments
2078 (with-replaced-entry-text-multi
2079 replacements
2080 (org-drill-hide-all-subheadings-except nil)
2081 (org-cycle-hide-drawers 'all)
2082 (ignore-errors
2083 (org-display-inline-images t))
2084 (prog1 (org-drill-presentation-prompt)
2085 (org-drill-hide-subheadings-if 'org-drill-entry-p)))))
2088 (defun org-drill-entry ()
2089 "Present the current topic for interactive review, as in `org-drill'.
2090 Review will occur regardless of whether the topic is due for review or whether
2091 it meets the definition of a 'review topic' used by `org-drill'.
2093 Returns a quality rating from 0 to 5, or nil if the user quit, or the symbol
2094 EDIT if the user chose to exit the drill and edit the current item. Choosing
2095 the latter option leaves the drill session suspended; it can be resumed
2096 later using `org-drill-resume'.
2098 See `org-drill' for more details."
2099 (interactive)
2100 (org-drill-goto-drill-entry-heading)
2101 ;;(unless (org-part-of-drill-entry-p)
2102 ;; (error "Point is not inside a drill entry"))
2103 ;;(unless (org-at-heading-p)
2104 ;; (org-back-to-heading))
2105 (let ((card-type (org-entry-get (point) "DRILL_CARD_TYPE" t))
2106 (answer-fn 'org-drill-present-default-answer)
2107 (present-empty-cards nil)
2108 (cont nil)
2109 ;; fontification functions in `outline-view-change-hook' can cause big
2110 ;; slowdowns, so we temporarily bind this variable to nil here.
2111 (outline-view-change-hook nil))
2112 (setq drill-answer nil)
2113 (org-save-outline-visibility t
2114 (save-restriction
2115 (org-narrow-to-subtree)
2116 (org-show-subtree)
2117 (org-cycle-hide-drawers 'all)
2119 (let ((presentation-fn
2120 (cdr (assoc card-type org-drill-card-type-alist))))
2121 (if (listp presentation-fn)
2122 (psetq answer-fn (or (second presentation-fn)
2123 'org-drill-present-default-answer)
2124 present-empty-cards (third presentation-fn)
2125 presentation-fn (first presentation-fn)))
2126 (prog1
2127 (cond
2128 ((null presentation-fn)
2129 (message "%s:%d: Unrecognised card type '%s', skipping..."
2130 (buffer-name) (point) card-type)
2131 (sit-for 0.5)
2132 'skip)
2134 (setq cont (funcall presentation-fn))
2135 (cond
2136 ((not cont)
2137 (message "Quit")
2138 nil)
2139 ((eql cont 'edit)
2140 'edit)
2141 ((eql cont 'skip)
2142 'skip)
2144 (save-excursion
2145 (funcall answer-fn
2146 (lambda () (org-drill-reschedule))))))))
2147 (org-remove-latex-fragment-image-overlays)))))))
2150 (defun org-drill-entries-pending-p ()
2151 (or *org-drill-again-entries*
2152 *org-drill-current-item*
2153 (and (not (org-drill-maximum-item-count-reached-p))
2154 (not (org-drill-maximum-duration-reached-p))
2155 (or *org-drill-new-entries*
2156 *org-drill-failed-entries*
2157 *org-drill-young-mature-entries*
2158 *org-drill-old-mature-entries*
2159 *org-drill-overdue-entries*
2160 *org-drill-again-entries*))))
2163 (defun org-drill-pending-entry-count ()
2164 (+ (if (markerp *org-drill-current-item*) 1 0)
2165 (length *org-drill-new-entries*)
2166 (length *org-drill-failed-entries*)
2167 (length *org-drill-young-mature-entries*)
2168 (length *org-drill-old-mature-entries*)
2169 (length *org-drill-overdue-entries*)
2170 (length *org-drill-again-entries*)))
2173 (defun org-drill-maximum-duration-reached-p ()
2174 "Returns true if the current drill session has continued past its
2175 maximum duration."
2176 (and org-drill-maximum-duration
2177 (not *org-drill-cram-mode*)
2178 *org-drill-start-time*
2179 (> (- (float-time (current-time)) *org-drill-start-time*)
2180 (* org-drill-maximum-duration 60))))
2183 (defun org-drill-maximum-item-count-reached-p ()
2184 "Returns true if the current drill session has reached the
2185 maximum number of items."
2186 (and org-drill-maximum-items-per-session
2187 (not *org-drill-cram-mode*)
2188 (>= (length *org-drill-done-entries*)
2189 org-drill-maximum-items-per-session)))
2192 (defun org-drill-pop-next-pending-entry ()
2193 (block org-drill-pop-next-pending-entry
2194 (let ((m nil))
2195 (while (or (null m)
2196 (not (org-drill-entry-p m)))
2197 (setq
2199 (cond
2200 ;; First priority is items we failed in a prior session.
2201 ((and *org-drill-failed-entries*
2202 (not (org-drill-maximum-item-count-reached-p))
2203 (not (org-drill-maximum-duration-reached-p)))
2204 (pop-random *org-drill-failed-entries*))
2205 ;; Next priority is overdue items.
2206 ((and *org-drill-overdue-entries*
2207 (not (org-drill-maximum-item-count-reached-p))
2208 (not (org-drill-maximum-duration-reached-p)))
2209 ;; We use `pop', not `pop-random', because we have already
2210 ;; sorted overdue items into a random order which takes
2211 ;; number of days overdue into account.
2212 (pop *org-drill-overdue-entries*))
2213 ;; Next priority is 'young' items.
2214 ((and *org-drill-young-mature-entries*
2215 (not (org-drill-maximum-item-count-reached-p))
2216 (not (org-drill-maximum-duration-reached-p)))
2217 (pop-random *org-drill-young-mature-entries*))
2218 ;; Next priority is newly added items, and older entries.
2219 ;; We pool these into a single group.
2220 ((and (or *org-drill-new-entries*
2221 *org-drill-old-mature-entries*)
2222 (not (org-drill-maximum-item-count-reached-p))
2223 (not (org-drill-maximum-duration-reached-p)))
2224 (cond
2225 ((< (random* (+ (length *org-drill-new-entries*)
2226 (length *org-drill-old-mature-entries*)))
2227 (length *org-drill-new-entries*))
2228 (pop-random *org-drill-new-entries*))
2230 (pop-random *org-drill-old-mature-entries*))))
2231 ;; After all the above are done, last priority is items
2232 ;; that were failed earlier THIS SESSION.
2233 (*org-drill-again-entries*
2234 (pop *org-drill-again-entries*))
2235 (t ; nothing left -- return nil
2236 (return-from org-drill-pop-next-pending-entry nil)))))
2237 m)))
2240 (defun org-drill-entries (&optional resuming-p)
2241 "Returns nil, t, or a list of markers representing entries that were
2242 'failed' and need to be presented again before the session ends.
2244 RESUMING-P is true if we are resuming a suspended drill session."
2245 (block org-drill-entries
2246 (while (org-drill-entries-pending-p)
2247 (let ((m (cond
2248 ((or (not resuming-p)
2249 (null *org-drill-current-item*)
2250 (not (org-drill-entry-p *org-drill-current-item*)))
2251 (org-drill-pop-next-pending-entry))
2252 (t ; resuming a suspended session.
2253 (setq resuming-p nil)
2254 *org-drill-current-item*))))
2255 (setq *org-drill-current-item* m)
2256 (unless m
2257 (error "Unexpectedly ran out of pending drill items"))
2258 (save-excursion
2259 (org-drill-goto-entry m)
2260 (cond
2261 ((not (org-drill-entry-due-p))
2262 ;; The entry is not due anymore. This could arise if the user
2263 ;; suspends a drill session, then drills an individual entry,
2264 ;; then resumes the session.
2265 (message "Entry no longer due, skipping...")
2266 (sit-for 0.3)
2267 nil)
2269 (setq result (org-drill-entry))
2270 (cond
2271 ((null result)
2272 (message "Quit")
2273 (setq end-pos :quit)
2274 (return-from org-drill-entries nil))
2275 ((eql result 'edit)
2276 (setq end-pos (point-marker))
2277 (return-from org-drill-entries nil))
2278 ((eql result 'skip)
2279 (setq *org-drill-current-item* nil)
2280 nil) ; skip this item
2282 (cond
2283 ((<= result org-drill-failure-quality)
2284 (if *org-drill-again-entries*
2285 (setq *org-drill-again-entries*
2286 (shuffle-list *org-drill-again-entries*)))
2287 (push-end m *org-drill-again-entries*))
2289 (push m *org-drill-done-entries*)))
2290 (setq *org-drill-current-item* nil))))))))))
2294 (defun org-drill-final-report ()
2295 (let ((pass-percent
2296 (round (* 100 (count-if (lambda (qual)
2297 (> qual org-drill-failure-quality))
2298 *org-drill-session-qualities*))
2299 (max 1 (length *org-drill-session-qualities*))))
2300 (prompt nil)
2301 (max-mini-window-height 0.6))
2302 (setq prompt
2303 (format
2304 "%d items reviewed. Session duration %s.
2305 Recall of reviewed items:
2306 Excellent (5): %3d%% | Near miss (2): %3d%%
2307 Good (4): %3d%% | Failure (1): %3d%%
2308 Hard (3): %3d%% | Abject failure (0): %3d%%
2310 You successfully recalled %d%% of reviewed items (quality > %s)
2311 %d/%d items still await review (%s, %s, %s, %s, %s).
2312 Tomorrow, %d more items will become due for review.
2313 Session finished. Press a key to continue..."
2314 (length *org-drill-done-entries*)
2315 (format-seconds "%h:%.2m:%.2s"
2316 (- (float-time (current-time)) *org-drill-start-time*))
2317 (round (* 100 (count 5 *org-drill-session-qualities*))
2318 (max 1 (length *org-drill-session-qualities*)))
2319 (round (* 100 (count 2 *org-drill-session-qualities*))
2320 (max 1 (length *org-drill-session-qualities*)))
2321 (round (* 100 (count 4 *org-drill-session-qualities*))
2322 (max 1 (length *org-drill-session-qualities*)))
2323 (round (* 100 (count 1 *org-drill-session-qualities*))
2324 (max 1 (length *org-drill-session-qualities*)))
2325 (round (* 100 (count 3 *org-drill-session-qualities*))
2326 (max 1 (length *org-drill-session-qualities*)))
2327 (round (* 100 (count 0 *org-drill-session-qualities*))
2328 (max 1 (length *org-drill-session-qualities*)))
2329 pass-percent
2330 org-drill-failure-quality
2331 (org-drill-pending-entry-count)
2332 (+ (org-drill-pending-entry-count)
2333 *org-drill-dormant-entry-count*)
2334 (propertize
2335 (format "%d failed"
2336 (+ (length *org-drill-failed-entries*)
2337 (length *org-drill-again-entries*)))
2338 'face `(:foreground ,org-drill-failed-count-color))
2339 (propertize
2340 (format "%d overdue"
2341 (length *org-drill-overdue-entries*))
2342 'face `(:foreground ,org-drill-failed-count-color))
2343 (propertize
2344 (format "%d new"
2345 (length *org-drill-new-entries*))
2346 'face `(:foreground ,org-drill-new-count-color))
2347 (propertize
2348 (format "%d young"
2349 (length *org-drill-young-mature-entries*))
2350 'face `(:foreground ,org-drill-mature-count-color))
2351 (propertize
2352 (format "%d old"
2353 (length *org-drill-old-mature-entries*))
2354 'face `(:foreground ,org-drill-mature-count-color))
2355 *org-drill-due-tomorrow-count*
2358 (while (not (input-pending-p))
2359 (message "%s" prompt)
2360 (sit-for 0.5))
2361 (read-char-exclusive)
2363 (if (and *org-drill-session-qualities*
2364 (< pass-percent (- 100 org-drill-forgetting-index)))
2365 (read-char-exclusive
2366 (format
2368 You failed %d%% of the items you reviewed during this session.
2369 %d (%d%%) of all items scanned were overdue.
2371 Are you keeping up with your items, and reviewing them
2372 when they are scheduled? If so, you may want to consider
2373 lowering the value of `org-drill-learn-fraction' slightly in
2374 order to make items appear more frequently over time."
2375 (propertize "WARNING!" 'face 'org-warning)
2376 (- 100 pass-percent)
2377 *org-drill-overdue-entry-count*
2378 (round (* 100 *org-drill-overdue-entry-count*)
2379 (+ *org-drill-dormant-entry-count*
2380 *org-drill-due-entry-count*)))
2381 ))))
2385 (defun org-drill-free-markers (markers)
2386 "MARKERS is a list of markers, all of which will be freed (set to
2387 point nowhere). Alternatively, MARKERS can be 't', in which case
2388 all the markers used by Org-Drill will be freed."
2389 (dolist (m (if (eql t markers)
2390 (append *org-drill-done-entries*
2391 *org-drill-new-entries*
2392 *org-drill-failed-entries*
2393 *org-drill-again-entries*
2394 *org-drill-overdue-entries*
2395 *org-drill-young-mature-entries*
2396 *org-drill-old-mature-entries*)
2397 markers))
2398 (free-marker m)))
2401 ;;; overdue-data is a list of entries, each entry has the form (POS DUE AGE)
2402 ;;; where POS is a marker pointing to the start of the entry, and
2403 ;;; DUE is a number indicating how many days ago the entry was due.
2404 ;;; AGE is the number of days elapsed since item creation (nil if unknown).
2405 ;;; if age > 60, sort by age (oldest first)
2406 ;;; if age < 60, sort by due (biggest first)
2408 ;;; if (age a) <= 60 and (age b) <= 60, sort by due
2409 ;;; else sort by age
2411 (defun org-drill-order-overdue-entries (overdue-data)
2412 (let* ((lapsed-days 60)
2413 (not-lapsed (remove-if (lambda (a) (> (or (second a) 0) lapsed-days))
2414 overdue-data))
2415 (lapsed (remove-if-not (lambda (a) (> (or (second a) 0)
2416 lapsed-days)) overdue-data)))
2417 (setq *org-drill-overdue-entries*
2418 (mapcar 'first
2419 (append
2420 (sort (shuffle-list not-lapsed)
2421 (lambda (a b) (> (second a) (second b))))
2422 (sort lapsed
2423 (lambda (a b) (> (third a) (third b)))))))))
2426 (defun org-drill--entry-lapsed-p ()
2427 (let ((lapsed-days 60))
2428 (> (or (org-drill-entry-days-overdue) 0) lapsed-days)))
2433 (defun org-drill-entry-days-since-creation (&optional use-last-interval-p)
2434 "If USE-LAST-INTERVAL-P is non-nil, and DATE_ADDED is missing, use the
2435 value of DRILL_LAST_INTERVAL instead (as the item's age must be at least
2436 that many days)."
2437 (let ((timestamp (org-entry-get (point) "DATE_ADDED")))
2438 (cond
2439 (timestamp
2440 (- (org-time-stamp-to-now timestamp)))
2441 (use-last-interval-p
2442 (+ (org-drill-entry-days-overdue)
2443 (read (or (org-entry-get (point) "DRILL_LAST_INTERVAL") "0"))))
2444 (t nil))))
2447 (defun org-drill-entry-status ()
2448 "Returns a list (STATUS DUE AGE) where DUE is the number of days overdue,
2449 zero being due today, -1 being scheduled 1 day in the future.
2450 AGE is the number of days elapsed since the item was created (nil if unknown).
2451 STATUS is one of the following values:
2452 - nil, if the item is not a drill entry, or has an empty body
2453 - :unscheduled
2454 - :future
2455 - :new
2456 - :failed
2457 - :overdue
2458 - :young
2459 - :old
2461 (save-excursion
2462 (unless (org-at-heading-p)
2463 (org-back-to-heading))
2464 (let ((due (org-drill-entry-days-overdue))
2465 (age (org-drill-entry-days-since-creation t))
2466 (last-int (org-drill-entry-last-interval 1)))
2467 (list
2468 (cond
2469 ((not (org-drill-entry-p))
2470 nil)
2471 ((and (org-entry-empty-p)
2472 (let* ((card-type (org-entry-get (point) "DRILL_CARD_TYPE" nil))
2473 (dat (cdr (assoc card-type org-drill-card-type-alist))))
2474 (or (null card-type)
2475 (not (third dat)))))
2476 ;; body is empty, and this is not a card type where empty bodies are
2477 ;; meaningful, so skip it.
2478 nil)
2479 ((null due) ; unscheduled - usually a skipped leech
2480 :unscheduled)
2481 ;; ((eql -1 due)
2482 ;; :tomorrow)
2483 ((minusp due) ; scheduled in the future
2484 :future)
2485 ;; The rest of the stati all denote 'due' items ==========================
2486 ((<= (org-drill-entry-last-quality 9999)
2487 org-drill-failure-quality)
2488 ;; Mature entries that were failed last time are
2489 ;; FAILED, regardless of how young, old or overdue
2490 ;; they are.
2491 :failed)
2492 ((org-drill-entry-new-p)
2493 :new)
2494 ((org-drill-entry-overdue-p due last-int)
2495 ;; Overdue status overrides young versus old
2496 ;; distinction.
2497 ;; Store marker + due, for sorting of overdue entries
2498 :overdue)
2499 ((<= (org-drill-entry-last-interval 9999)
2500 org-drill-days-before-old)
2501 :young)
2503 :old))
2504 due age))))
2507 (defun org-drill-progress-message (collected scanned)
2508 (when (zerop (% scanned 50))
2509 (let* ((meter-width 40)
2510 (sym1 (if (oddp (floor scanned (* 50 meter-width))) ?| ?.))
2511 (sym2 (if (eql sym1 ?.) ?| ?.)))
2512 (message "Collecting due drill items:%4d %s%s"
2513 collected
2514 (make-string (% (ceiling scanned 50) meter-width)
2515 sym2)
2516 (make-string (- meter-width (% (ceiling scanned 50) meter-width))
2517 sym1)))))
2520 (defun org-drill (&optional scope drill-match resume-p)
2521 "Begin an interactive 'drill session'. The user is asked to
2522 review a series of topics (headers). Each topic is initially
2523 presented as a 'question', often with part of the topic content
2524 hidden. The user attempts to recall the hidden information or
2525 answer the question, then presses a key to reveal the answer. The
2526 user then rates his or her recall or performance on that
2527 topic. This rating information is used to reschedule the topic
2528 for future review.
2530 Org-drill proceeds by:
2532 - Finding all topics (headings) in SCOPE which have either been
2533 used and rescheduled before, or which have a tag that matches
2534 `org-drill-question-tag'.
2536 - All matching topics which are either unscheduled, or are
2537 scheduled for the current date or a date in the past, are
2538 considered to be candidates for the drill session.
2540 - If `org-drill-maximum-items-per-session' is set, a random
2541 subset of these topics is presented. Otherwise, all of the
2542 eligible topics will be presented.
2544 SCOPE determines the scope in which to search for
2545 questions. It accepts the same values as `org-drill-scope',
2546 which see.
2548 DRILL-MATCH, if supplied, is a string specifying a tags/property/
2549 todo query. Only items matching the query will be considered.
2550 It accepts the same values as `org-drill-match', which see.
2552 If RESUME-P is non-nil, resume a suspended drill session rather
2553 than starting a new one."
2555 (interactive)
2556 ;; Check org version. Org 7.9.3f introduced a backwards-incompatible change
2557 ;; to the arguments accepted by `org-schedule'. At the time of writing there
2558 ;; are still lots of people using versions of org older than this.
2559 (let ((majorv (first (mapcar 'string-to-number (split-string (org-release) "[.]")))))
2560 (if (and (< majorv 8)
2561 (not (string-match-p "universal prefix argument" (documentation 'org-schedule))))
2562 (read-char-exclusive
2563 (format "Warning: org-drill requires org mode 7.9.3f or newer. Scheduling of failed cards will not
2564 work correctly with older versions of org mode. Your org mode version (%s) appears to be older than
2565 7.9.3f. Please consider installing a more recent version of org mode." (org-release)))))
2566 (let ((end-pos nil)
2567 (overdue-data nil)
2568 (cnt 0))
2569 (block org-drill
2570 (unless resume-p
2571 (org-drill-free-markers t)
2572 (setq *org-drill-current-item* nil
2573 *org-drill-done-entries* nil
2574 *org-drill-dormant-entry-count* 0
2575 *org-drill-due-entry-count* 0
2576 *org-drill-due-tomorrow-count* 0
2577 *org-drill-overdue-entry-count* 0
2578 *org-drill-new-entries* nil
2579 *org-drill-overdue-entries* nil
2580 *org-drill-young-mature-entries* nil
2581 *org-drill-old-mature-entries* nil
2582 *org-drill-failed-entries* nil
2583 *org-drill-again-entries* nil)
2584 (setq *org-drill-session-qualities* nil)
2585 (setq *org-drill-start-time* (float-time (current-time))))
2586 (setq *random-state* (make-random-state t)) ; reseed RNG
2587 (unwind-protect
2588 (save-excursion
2589 (unless resume-p
2590 (let ((org-trust-scanner-tags t)
2591 (warned-about-id-creation nil))
2592 (org-map-drill-entries
2593 (lambda ()
2594 (org-drill-progress-message
2595 (+ (length *org-drill-new-entries*)
2596 (length *org-drill-overdue-entries*)
2597 (length *org-drill-young-mature-entries*)
2598 (length *org-drill-old-mature-entries*)
2599 (length *org-drill-failed-entries*))
2600 (incf cnt))
2601 (cond
2602 ((not (org-drill-entry-p))
2603 nil) ; skip
2605 (when (and (not warned-about-id-creation)
2606 (null (org-id-get)))
2607 (message (concat "Creating unique IDs for items "
2608 "(slow, but only happens once)"))
2609 (sit-for 0.5)
2610 (setq warned-about-id-creation t))
2611 (org-id-get-create) ; ensure drill entry has unique ID
2612 (destructuring-bind (status due age)
2613 (org-drill-entry-status)
2614 (case status
2615 (:unscheduled
2616 (incf *org-drill-dormant-entry-count*))
2617 ;; (:tomorrow
2618 ;; (incf *org-drill-dormant-entry-count*)
2619 ;; (incf *org-drill-due-tomorrow-count*))
2620 (:future
2621 (incf *org-drill-dormant-entry-count*)
2622 (if (eq -1 due)
2623 (incf *org-drill-due-tomorrow-count*)))
2624 (:new
2625 (push (point-marker) *org-drill-new-entries*))
2626 (:failed
2627 (push (point-marker) *org-drill-failed-entries*))
2628 (:young
2629 (push (point-marker) *org-drill-young-mature-entries*))
2630 (:overdue
2631 (push (list (point-marker) due age) overdue-data))
2632 (:old
2633 (push (point-marker) *org-drill-old-mature-entries*))
2634 )))))
2635 scope drill-match)
2636 (org-drill-order-overdue-entries overdue-data)
2637 (setq *org-drill-overdue-entry-count*
2638 (length *org-drill-overdue-entries*))))
2639 (setq *org-drill-due-entry-count* (org-drill-pending-entry-count))
2640 (cond
2641 ((and (null *org-drill-current-item*)
2642 (null *org-drill-new-entries*)
2643 (null *org-drill-failed-entries*)
2644 (null *org-drill-overdue-entries*)
2645 (null *org-drill-young-mature-entries*)
2646 (null *org-drill-old-mature-entries*))
2647 (message "I did not find any pending drill items."))
2649 (org-drill-entries resume-p)
2650 (message "Drill session finished!"))))
2651 (progn
2652 (unless end-pos
2653 (setq *org-drill-cram-mode* nil)
2654 (org-drill-free-markers *org-drill-done-entries*)))))
2655 (cond
2656 (end-pos
2657 (when (markerp end-pos)
2658 (org-drill-goto-entry end-pos)
2659 (org-reveal)
2660 (org-show-entry))
2661 (let ((keystr (command-keybinding-to-string 'org-drill-resume)))
2662 (message
2663 "You can continue the drill session with the command `org-drill-resume'.%s"
2664 (if keystr (format "\nYou can run this command by pressing %s." keystr)
2665 ""))))
2667 (org-drill-final-report)
2668 (if (eql 'sm5 org-drill-spaced-repetition-algorithm)
2669 (org-drill-save-optimal-factor-matrix))
2670 (if org-drill-save-buffers-after-drill-sessions-p
2671 (save-some-buffers))
2672 (message "Drill session finished!")
2673 ))))
2676 (defun org-drill-save-optimal-factor-matrix ()
2677 (message "Saving optimal factor matrix...")
2678 (customize-save-variable 'org-drill-optimal-factor-matrix
2679 org-drill-optimal-factor-matrix))
2682 (defun org-drill-cram (&optional scope drill-match)
2683 "Run an interactive drill session in 'cram mode'. In cram mode,
2684 all drill items are considered to be due for review, unless they
2685 have been reviewed within the last `org-drill-cram-hours'
2686 hours."
2687 (interactive)
2688 (setq *org-drill-cram-mode* t)
2689 (org-drill scope drill-match))
2692 (defun org-drill-tree ()
2693 "Run an interactive drill session using drill items within the
2694 subtree at point."
2695 (interactive)
2696 (org-drill 'tree))
2699 (defun org-drill-directory ()
2700 "Run an interactive drill session using drill items from all org
2701 files in the same directory as the current file."
2702 (interactive)
2703 (org-drill 'directory))
2706 (defun org-drill-again (&optional scope drill-match)
2707 "Run a new drill session, but try to use leftover due items that
2708 were not reviewed during the last session, rather than scanning for
2709 unreviewed items. If there are no leftover items in memory, a full
2710 scan will be performed."
2711 (interactive)
2712 (setq *org-drill-cram-mode* nil)
2713 (cond
2714 ((plusp (org-drill-pending-entry-count))
2715 (org-drill-free-markers *org-drill-done-entries*)
2716 (if (markerp *org-drill-current-item*)
2717 (free-marker *org-drill-current-item*))
2718 (setq *org-drill-start-time* (float-time (current-time))
2719 *org-drill-done-entries* nil
2720 *org-drill-current-item* nil)
2721 (org-drill scope drill-match t))
2723 (org-drill scope drill-match))))
2727 (defun org-drill-resume ()
2728 "Resume a suspended drill session. Sessions are suspended by
2729 exiting them with the `edit' or `quit' options."
2730 (interactive)
2731 (cond
2732 ((org-drill-entries-pending-p)
2733 (org-drill nil nil t))
2734 ((and (plusp (org-drill-pending-entry-count))
2735 ;; Current drill session is finished, but there are still
2736 ;; more items which need to be reviewed.
2737 (y-or-n-p (format
2738 "You have finished the drill session. However, %d items still
2739 need reviewing. Start a new drill session? "
2740 (org-drill-pending-entry-count))))
2741 (org-drill-again))
2743 (message "You have finished the drill session."))))
2746 (defun org-drill-relearn-item ()
2747 "Make the current item due for revision, and set its last interval to 0.
2748 Makes the item behave as if it has been failed, without actually recording a
2749 failure. This command can be used to 'reset' repetitions for an item."
2750 (interactive)
2751 (org-drill-smart-reschedule 4 0))
2754 (defun org-drill-strip-entry-data ()
2755 (dolist (prop org-drill-scheduling-properties)
2756 (org-delete-property prop))
2757 (org-schedule '(4)))
2760 (defun org-drill-strip-all-data (&optional scope)
2761 "Delete scheduling data from every drill entry in scope. This
2762 function may be useful if you want to give your collection of
2763 entries to someone else. Scope defaults to the current buffer,
2764 and is specified by the argument SCOPE, which accepts the same
2765 values as `org-drill-scope'."
2766 (interactive)
2767 (when (yes-or-no-p
2768 "Delete scheduling data from ALL items in scope: are you sure?")
2769 (cond
2770 ((null scope)
2771 ;; Scope is the current buffer. This means we can use
2772 ;; `org-delete-property-globally', which is faster.
2773 (dolist (prop org-drill-scheduling-properties)
2774 (org-delete-property-globally prop))
2775 (org-map-drill-entries (lambda () (org-schedule '(4))) scope))
2777 (org-map-drill-entries 'org-drill-strip-entry-data scope)))
2778 (message "Done.")))
2781 (defun org-drill-add-cloze-fontification ()
2782 ;; Compute local versions of the regexp for cloze deletions, in case
2783 ;; the left and right delimiters are redefined locally.
2784 (setq-local org-drill-cloze-regexp (org-drill--compute-cloze-regexp))
2785 (setq-local org-drill-cloze-keywords (org-drill--compute-cloze-keywords))
2786 (when org-drill-use-visible-cloze-face-p
2787 (add-to-list 'org-font-lock-extra-keywords
2788 (first org-drill-cloze-keywords))))
2790 (add-hook 'org-font-lock-set-keywords-hook 'org-drill-add-cloze-fontification)
2792 ;; Can't add to org-mode-hook, because local variables won't have been loaded
2793 ;; yet.
2795 ;; (defun org-drill-add-cloze-fontification ()
2796 ;; (when (eql major-mode 'org-mode)
2797 ;; ;; Compute local versions of the regexp for cloze deletions, in case
2798 ;; ;; the left and right delimiters are redefined locally.
2799 ;; (setq-local org-drill-cloze-regexp (org-drill--compute-cloze-regexp))
2800 ;; (setq-local org-drill-cloze-keywords (org-drill--compute-cloze-keywords))
2801 ;; (when org-drill-use-visible-cloze-face-p
2802 ;; (font-lock-add-keywords nil ;'org-mode
2803 ;; org-drill-cloze-keywords
2804 ;; nil))))
2806 ;; XXX
2807 ;; (add-hook 'hack-local-variables-hook
2808 ;; 'org-drill-add-cloze-fontification)
2810 ;; (org-drill-add-cloze-fontification)
2813 ;;; Synching card collections =================================================
2816 (defvar *org-drill-dest-id-table* (make-hash-table :test 'equal))
2819 (defun org-drill-copy-entry-to-other-buffer (dest &optional path)
2820 "Copy the subtree at point to the buffer DEST. The copy will receive
2821 the tag 'imported'."
2822 (block org-drill-copy-entry-to-other-buffer
2823 (save-excursion
2824 (let ((src (current-buffer))
2825 (m nil))
2826 (cl-flet ((paste-tree-here (&optional level)
2827 (org-paste-subtree level)
2828 (org-drill-strip-entry-data)
2829 (org-toggle-tag "imported" 'on)
2830 (org-map-drill-entries
2831 (lambda ()
2832 (let ((id (org-id-get)))
2833 (org-drill-strip-entry-data)
2834 (unless (gethash id *org-drill-dest-id-table*)
2835 (puthash id (point-marker)
2836 *org-drill-dest-id-table*))))
2837 'tree)))
2838 (unless path
2839 (setq path (org-get-outline-path)))
2840 (org-copy-subtree)
2841 (switch-to-buffer dest)
2842 (setq m
2843 (condition-case nil
2844 (org-find-olp path t)
2845 (error ; path does not exist in DEST
2846 (return-from org-drill-copy-entry-to-other-buffer
2847 (cond
2848 ((cdr path)
2849 (org-drill-copy-entry-to-other-buffer
2850 dest (butlast path)))
2852 ;; We've looked all the way up the path
2853 ;; Default to appending to the end of DEST
2854 (goto-char (point-max))
2855 (newline)
2856 (paste-tree-here)))))))
2857 (goto-char m)
2858 (outline-next-heading)
2859 (newline)
2860 (forward-line -1)
2861 (paste-tree-here (1+ (or (org-current-level) 0)))
2862 )))))
2866 (defun org-drill-merge-buffers (src &optional dest ignore-new-items-p)
2867 "SRC and DEST are two org mode buffers containing drill items.
2868 For each drill item in DEST that shares an ID with an item in SRC,
2869 overwrite scheduling data in DEST with data taken from the item in SRC.
2870 This is intended for use when two people are sharing a set of drill items,
2871 one person has made some updates to the item set, and the other person
2872 wants to migrate to the updated set without losing their scheduling data.
2874 By default, any drill items in SRC which do not exist in DEST are
2875 copied into DEST. We attempt to place the copied item in the
2876 equivalent location in DEST to its location in SRC, by matching
2877 the heading hierarchy. However if IGNORE-NEW-ITEMS-P is non-nil,
2878 we simply ignore any items that do not exist in DEST, and do not
2879 copy them across."
2880 (interactive "bImport scheduling info from which buffer?")
2881 (unless dest
2882 (setq dest (current-buffer)))
2883 (setq src (get-buffer src)
2884 dest (get-buffer dest))
2885 (when (yes-or-no-p
2886 (format
2887 (concat "About to overwrite all scheduling data for drill items in `%s' "
2888 "with information taken from matching items in `%s'. Proceed? ")
2889 (buffer-name dest) (buffer-name src)))
2890 ;; Compile list of all IDs in the destination buffer.
2891 (clrhash *org-drill-dest-id-table*)
2892 (with-current-buffer dest
2893 (org-map-drill-entries
2894 (lambda ()
2895 (let ((this-id (org-id-get)))
2896 (when this-id
2897 (puthash this-id (point-marker) *org-drill-dest-id-table*))))
2898 'file))
2899 ;; Look through all entries in source buffer.
2900 (with-current-buffer src
2901 (org-map-drill-entries
2902 (lambda ()
2903 (let ((id (org-id-get))
2904 (last-quality nil) (last-reviewed nil)
2905 (scheduled-time nil))
2906 (cond
2907 ((or (null id)
2908 (not (org-drill-entry-p)))
2909 nil)
2910 ((gethash id *org-drill-dest-id-table*)
2911 ;; This entry matches an entry in dest. Retrieve all its
2912 ;; scheduling data, then go to the matching location in dest
2913 ;; and write the data.
2914 (let ((marker (gethash id *org-drill-dest-id-table*)))
2915 (destructuring-bind (last-interval repetitions failures
2916 total-repeats meanq ease)
2917 (org-drill-get-item-data)
2918 (setq last-reviewed (org-entry-get (point) "DRILL_LAST_REVIEWED")
2919 last-quality (org-entry-get (point) "DRILL_LAST_QUALITY")
2920 scheduled-time (org-get-scheduled-time (point)))
2921 (save-excursion
2922 ;; go to matching entry in destination buffer
2923 (switch-to-buffer (marker-buffer marker))
2924 (goto-char marker)
2925 (org-drill-strip-entry-data)
2926 (unless (zerop total-repeats)
2927 (org-drill-store-item-data last-interval repetitions failures
2928 total-repeats meanq ease)
2929 (if last-quality
2930 (org-set-property "LAST_QUALITY" last-quality)
2931 (org-delete-property "LAST_QUALITY"))
2932 (if last-reviewed
2933 (org-set-property "LAST_REVIEWED" last-reviewed)
2934 (org-delete-property "LAST_REVIEWED"))
2935 (if scheduled-time
2936 (org-schedule nil scheduled-time)))))
2937 (remhash id *org-drill-dest-id-table*)
2938 (free-marker marker)))
2940 ;; item in SRC has ID, but no matching ID in DEST.
2941 ;; It must be a new item that does not exist in DEST.
2942 ;; Copy the entire item to the *end* of DEST.
2943 (unless ignore-new-items-p
2944 (org-drill-copy-entry-to-other-buffer dest))))))
2945 'file))
2946 ;; Finally: there may be some items in DEST which are not in SRC, and
2947 ;; which have been scheduled by another user of DEST. Clear out the
2948 ;; scheduling info from all the unmatched items in DEST.
2949 (with-current-buffer dest
2950 (maphash (lambda (id m)
2951 (goto-char m)
2952 (org-drill-strip-entry-data)
2953 (free-marker m))
2954 *org-drill-dest-id-table*))))
2958 ;;; Card types for learning languages =========================================
2960 ;;; Get spell-number.el from:
2961 ;;; http://www.emacswiki.org/emacs/spell-number.el
2962 (autoload 'spelln-integer-in-words "spell-number")
2965 ;;; `conjugate' card type =====================================================
2966 ;;; See spanish.org for usage
2968 (defvar org-drill-verb-tense-alist
2969 '(("present" "tomato")
2970 ("simple present" "tomato")
2971 ("present indicative" "tomato")
2972 ;; past tenses
2973 ("past" "purple")
2974 ("simple past" "purple")
2975 ("preterite" "purple")
2976 ("imperfect" "darkturquoise")
2977 ("present perfect" "royalblue")
2978 ;; future tenses
2979 ("future" "green")
2980 ;; moods (backgrounds).
2981 ("indicative" nil) ; default
2982 ("subjunctive" "medium blue")
2983 ("conditional" "grey30")
2984 ("negative imperative" "red4")
2985 ("positive imperative" "darkgreen")
2987 "Alist where each entry has the form (TENSE COLOUR), where
2988 TENSE is a string naming a tense in which verbs can be
2989 conjugated, and COLOUR is a string specifying a foreground colour
2990 which will be used by `org-drill-present-verb-conjugation' and
2991 `org-drill-show-answer-verb-conjugation' to fontify the verb and
2992 the name of the tense.")
2995 (defun org-drill-get-verb-conjugation-info ()
2996 "Auxiliary function used by `org-drill-present-verb-conjugation' and
2997 `org-drill-show-answer-verb-conjugation'."
2998 (let ((infinitive (org-entry-get (point) "VERB_INFINITIVE" t))
2999 (inf-hint (org-entry-get (point) "VERB_INFINITIVE_HINT" t))
3000 (translation (org-entry-get (point) "VERB_TRANSLATION" t))
3001 (tense (org-entry-get (point) "VERB_TENSE" nil))
3002 (mood (org-entry-get (point) "VERB_MOOD" nil))
3003 (highlight-face nil))
3004 (unless (and infinitive translation (or tense mood))
3005 (error "Missing information for verb conjugation card (%s, %s, %s, %s) at %s"
3006 infinitive translation tense mood (point)))
3007 (setq tense (if tense (downcase (car (read-from-string tense))))
3008 mood (if mood (downcase (car (read-from-string mood))))
3009 infinitive (car (read-from-string infinitive))
3010 inf-hint (if inf-hint (car (read-from-string inf-hint)))
3011 translation (car (read-from-string translation)))
3012 (setq highlight-face
3013 (list :foreground
3014 (or (second (assoc-string tense org-drill-verb-tense-alist t))
3015 "hotpink")
3016 :background
3017 (second (assoc-string mood org-drill-verb-tense-alist t))))
3018 (setq infinitive (propertize infinitive 'face highlight-face))
3019 (setq translation (propertize translation 'face highlight-face))
3020 (if tense (setq tense (propertize tense 'face highlight-face)))
3021 (if mood (setq mood (propertize mood 'face highlight-face)))
3022 (list infinitive inf-hint translation tense mood)))
3025 (defun org-drill-present-verb-conjugation ()
3026 "Present a drill entry whose card type is 'conjugate'."
3027 (cl-flet ((tense-and-mood-to-string
3028 (tense mood)
3029 (cond
3030 ((and tense mood)
3031 (format "%s tense, %s mood" tense mood))
3032 (tense
3033 (format "%s tense" tense))
3034 (mood
3035 (format "%s mood" mood)))))
3036 (destructuring-bind (infinitive inf-hint translation tense mood)
3037 (org-drill-get-verb-conjugation-info)
3038 (org-drill-present-card-using-text
3039 (cond
3040 ((zerop (random* 2))
3041 (format "\nTranslate the verb\n\n%s\n\nand conjugate for the %s.\n\n"
3042 infinitive (tense-and-mood-to-string tense mood)))
3045 (format "\nGive the verb that means\n\n%s %s\n
3046 and conjugate for the %s.\n\n"
3047 translation
3048 (if inf-hint (format " [HINT: %s]" inf-hint) "")
3049 (tense-and-mood-to-string tense mood))))))))
3052 (defun org-drill-show-answer-verb-conjugation (reschedule-fn)
3053 "Show the answer for a drill item whose card type is 'conjugate'.
3054 RESCHEDULE-FN must be a function that calls `org-drill-reschedule' and
3055 returns its return value."
3056 (destructuring-bind (infinitive inf-hint translation tense mood)
3057 (org-drill-get-verb-conjugation-info)
3058 (with-replaced-entry-heading
3059 (format "%s of %s ==> %s\n\n"
3060 (capitalize
3061 (cond
3062 ((and tense mood)
3063 (format "%s tense, %s mood" tense mood))
3064 (tense
3065 (format "%s tense" tense))
3066 (mood
3067 (format "%s mood" mood))))
3068 infinitive translation)
3069 (org-cycle-hide-drawers 'all)
3070 (funcall reschedule-fn))))
3073 ;;; `decline_noun' card type ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3076 (defvar org-drill-noun-gender-alist
3077 '(("masculine" "dodgerblue")
3078 ("masc" "dodgerblue")
3079 ("male" "dodgerblue")
3080 ("m" "dodgerblue")
3081 ("feminine" "orchid")
3082 ("fem" "orchid")
3083 ("female" "orchid")
3084 ("f" "orchid")
3085 ("neuter" "green")
3086 ("neutral" "green")
3087 ("neut" "green")
3088 ("n" "green")
3092 (defun org-drill-get-noun-info ()
3093 "Auxiliary function used by `org-drill-present-noun-declension' and
3094 `org-drill-show-answer-noun-declension'."
3095 (let ((noun (org-entry-get (point) "NOUN" t))
3096 (noun-hint (org-entry-get (point) "NOUN_HINT" t))
3097 (noun-root (org-entry-get (point) "NOUN_ROOT" t))
3098 (noun-gender (org-entry-get (point) "NOUN_GENDER" t))
3099 (translation (org-entry-get (point) "NOUN_TRANSLATION" t))
3100 (highlight-face nil))
3101 (unless (and noun translation)
3102 (error "Missing information for `decline_noun' card (%s, %s, %s, %s) at %s"
3103 noun translation noun-hint noun-root (point)))
3104 (setq noun-root (if noun-root (car (read-from-string noun-root)))
3105 noun (car (read-from-string noun))
3106 noun-gender (downcase (car (read-from-string noun-gender)))
3107 noun-hint (if noun-hint (car (read-from-string noun-hint)))
3108 translation (car (read-from-string translation)))
3109 (setq highlight-face
3110 (list :foreground
3111 (or (second (assoc-string noun-gender
3112 org-drill-noun-gender-alist t))
3113 "red")))
3114 (setq noun (propertize noun 'face highlight-face))
3115 (setq translation (propertize translation 'face highlight-face))
3116 (list noun noun-root noun-gender noun-hint translation)))
3119 (defun org-drill-present-noun-declension ()
3120 "Present a drill entry whose card type is 'decline_noun'."
3121 (destructuring-bind (noun noun-root noun-gender noun-hint translation)
3122 (org-drill-get-noun-info)
3123 (let* ((props (org-entry-properties (point)))
3124 (definite
3125 (cond
3126 ((assoc "DECLINE_DEFINITE" props)
3127 (propertize (if (org-entry-get (point) "DECLINE_DEFINITE")
3128 "definite" "indefinite")
3129 'face 'warning))
3130 (t nil)))
3131 (plural
3132 (cond
3133 ((assoc "DECLINE_PLURAL" props)
3134 (propertize (if (org-entry-get (point) "DECLINE_PLURAL")
3135 "plural" "singular")
3136 'face 'warning))
3137 (t nil))))
3138 (org-drill-present-card-using-text
3139 (cond
3140 ((zerop (random* 2))
3141 (format "\nTranslate the noun\n\n%s (%s)\n\nand list its declensions%s.\n\n"
3142 noun noun-gender
3143 (if (or plural definite)
3144 (format " for the %s %s form" definite plural)
3145 "")))
3147 (format "\nGive the noun that means\n\n%s %s\n
3148 and list its declensions%s.\n\n"
3149 translation
3150 (if noun-hint (format " [HINT: %s]" noun-hint) "")
3151 (if (or plural definite)
3152 (format " for the %s %s form" definite plural)
3153 ""))))))))
3156 (defun org-drill-show-answer-noun-declension (reschedule-fn)
3157 "Show the answer for a drill item whose card type is 'decline_noun'.
3158 RESCHEDULE-FN must be a function that calls `org-drill-reschedule' and
3159 returns its return value."
3160 (destructuring-bind (noun noun-root noun-gender noun-hint translation)
3161 (org-drill-get-noun-info)
3162 (with-replaced-entry-heading
3163 (format "Declensions of %s (%s) ==> %s\n\n"
3164 noun noun-gender translation)
3165 (org-cycle-hide-drawers 'all)
3166 (funcall reschedule-fn))))
3169 ;;; `translate_number' card type ==============================================
3170 ;;; See spanish.org for usage
3173 (defun spelln-integer-in-language (n lang)
3174 (let ((spelln-language lang))
3175 (spelln-integer-in-words n)))
3177 (defun org-drill-present-translate-number ()
3178 (let ((num-min (read (org-entry-get (point) "DRILL_NUMBER_MIN")))
3179 (num-max (read (org-entry-get (point) "DRILL_NUMBER_MAX")))
3180 (language (read (org-entry-get (point) "DRILL_LANGUAGE" t)))
3181 (drilled-number 0)
3182 (drilled-number-direction 'to-english)
3183 (highlight-face 'font-lock-warning-face))
3184 (cond
3185 ((not (fboundp 'spelln-integer-in-words))
3186 (message "`spell-number.el' not loaded, skipping 'translate_number' card...")
3187 (sit-for 0.5)
3188 'skip)
3189 ((not (and (numberp num-min) (numberp num-max) language))
3190 (error "Missing language or minimum or maximum numbers for number card"))
3192 (if (> num-min num-max)
3193 (psetf num-min num-max
3194 num-max num-min))
3195 (setq drilled-number
3196 (+ num-min (random* (abs (1+ (- num-max num-min))))))
3197 (setq drilled-number-direction
3198 (if (zerop (random* 2)) 'from-english 'to-english))
3199 (cond
3200 ((eql 'to-english drilled-number-direction)
3201 (org-drill-present-card-using-text
3202 (format "\nTranslate into English:\n\n%s\n"
3203 (propertize
3204 (spelln-integer-in-language drilled-number language)
3205 'face highlight-face))
3206 (spelln-integer-in-language drilled-number 'english-gb)))
3208 (org-drill-present-card-using-text
3209 (format "\nTranslate into %s:\n\n%s\n"
3210 (capitalize (format "%s" language))
3211 (propertize
3212 (spelln-integer-in-language drilled-number 'english-gb)
3213 'face highlight-face))
3214 (spelln-integer-in-language drilled-number language))))))))
3217 ;; (defun org-drill-show-answer-translate-number (reschedule-fn)
3218 ;; (let* ((language (read (org-entry-get (point) "DRILL_LANGUAGE" t)))
3219 ;; (highlight-face 'font-lock-warning-face)
3220 ;; (non-english
3221 ;; (let ((spelln-language language))
3222 ;; (propertize (spelln-integer-in-words *drilled-number*)
3223 ;; 'face highlight-face)))
3224 ;; (english
3225 ;; (let ((spelln-language 'english-gb))
3226 ;; (propertize (spelln-integer-in-words *drilled-number*)
3227 ;; 'face 'highlight-face))))
3228 ;; (with-replaced-entry-text
3229 ;; (cond
3230 ;; ((eql 'to-english *drilled-number-direction*)
3231 ;; (format "\nThe English translation of %s is:\n\n%s\n"
3232 ;; non-english english))
3233 ;; (t
3234 ;; (format "\nThe %s translation of %s is:\n\n%s\n"
3235 ;; (capitalize (format "%s" language))
3236 ;; english non-english)))
3237 ;; (funcall reschedule-fn))))
3240 ;;; `spanish_verb' card type ==================================================
3241 ;;; Not very interesting, but included to demonstrate how a presentation
3242 ;;; function can manipulate which subheading are hidden versus shown.
3245 (defun org-drill-present-spanish-verb ()
3246 (let ((prompt nil)
3247 (reveal-headings nil))
3248 (with-hidden-comments
3249 (with-hidden-cloze-hints
3250 (with-hidden-cloze-text
3251 (case (random* 6)
3253 (org-drill-hide-all-subheadings-except '("Infinitive"))
3254 (setq prompt
3255 (concat "Translate this Spanish verb, and conjugate it "
3256 "for the *present* tense.")
3257 reveal-headings '("English" "Present Tense" "Notes")))
3259 (org-drill-hide-all-subheadings-except '("English"))
3260 (setq prompt (concat "For the *present* tense, conjugate the "
3261 "Spanish translation of this English verb.")
3262 reveal-headings '("Infinitive" "Present Tense" "Notes")))
3264 (org-drill-hide-all-subheadings-except '("Infinitive"))
3265 (setq prompt (concat "Translate this Spanish verb, and "
3266 "conjugate it for the *past* tense.")
3267 reveal-headings '("English" "Past Tense" "Notes")))
3269 (org-drill-hide-all-subheadings-except '("English"))
3270 (setq prompt (concat "For the *past* tense, conjugate the "
3271 "Spanish translation of this English verb.")
3272 reveal-headings '("Infinitive" "Past Tense" "Notes")))
3274 (org-drill-hide-all-subheadings-except '("Infinitive"))
3275 (setq prompt (concat "Translate this Spanish verb, and "
3276 "conjugate it for the *future perfect* tense.")
3277 reveal-headings '("English" "Future Perfect Tense" "Notes")))
3279 (org-drill-hide-all-subheadings-except '("English"))
3280 (setq prompt (concat "For the *future perfect* tense, conjugate the "
3281 "Spanish translation of this English verb.")
3282 reveal-headings '("Infinitive" "Future Perfect Tense" "Notes"))))
3283 (org-cycle-hide-drawers 'all)
3284 (prog1 (org-drill-presentation-prompt)
3285 (org-drill-hide-subheadings-if 'org-drill-entry-p)))))))
3288 (provide 'org-drill)