org-drill.el 124 KB

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