org-drill.el 122 KB

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