Sources/OrgCore/Flashcards/FlashcardCommands.swift
296 lines · 13666 bytes
23 symbols in this file
1import Foundation
2
3// org-fc's commands on a heading (org-fc 0.7, with `org-fc-algorithm` sm2-v1): making a card of
4// each type, updating a cloze card's holes, suspending, and rating a position, writing what
5// org-fc writes.
6
7/// `org-fc-type-normal-init`, `org-fc-type-double-init`, `org-fc-type-text-input-init` and
8/// `org-fc-type-cloze-init`: the heading at point becomes a card.
9public struct MakeFlashcard: OrgCommand {
10 public let type: Flashcards.CardType
11 let newID: @Sendable () -> String
12
13 public init(_ type: Flashcards.CardType, newID: @escaping @Sendable () -> String = { UUID().uuidString }) {
14 self.type = type
15 self.newID = newID
16 }
17
18 public var id: String { "org.fc.\(type.rawValue)" }
19 public var title: String {
20 switch type {
21 case .normal: "Make Normal Flashcard"
22 case .double: "Make Double Flashcard"
23 case .cloze: "Make Cloze Flashcard…"
24 case .textInput: "Make Text-Input Flashcard"
25 }
26 }
27
28 public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
29
30 public func run(in context: EditContext) -> CommandStep {
31 guard entryHeading(at: context.caret, in: context.tree) != nil else { return .failed("Before first headline") }
32 var cloze: Flashcards.ClozeType?
33 if type == .cloze {
34 guard let answer = context.answers["cloze-type"] else {
35 return .prompt(Prompt(key: "cloze-type", message: "Cloze Type: ", choices: Flashcards.ClozeType.allCases.map(\.rawValue)))
36 }
37 guard let chosen = Flashcards.ClozeType(rawValue: answer) else { return .failed("Invalid cloze card type: \(answer)") }
38 cloze = chosen
39 }
40 return commitBuffer(context) { buffer in
41 try buffer.saveExcursion {
42 try buffer.backToHeading()
43 switch type {
44 case .normal:
45 try buffer.fcInitCard("normal", newID: newID)
46 try buffer.fcReviewDataUpdate(["front"])
47 case .double:
48 try buffer.fcInitCard("double", newID: newID)
49 try buffer.fcReviewDataUpdate(["front", "back"])
50 case .textInput:
51 guard buffer.fcHasAnswerLine() else { throw EmacsBuffer.UserError(message: "The card has no answer line") }
52 try buffer.fcInitCard("text-input", newID: newID)
53 try buffer.fcReviewDataUpdate(["front"])
54 case .cloze:
55 try buffer.fcInitCard("cloze", newID: newID)
56 try buffer.fcClozeUpdate()
57 buffer.entryPut("FC_CLOZE_TYPE", cloze!.rawValue)
58 }
59 }
60 }
61 }
62}
63
64/// `org-fc-update`: a cloze card's new holes get positions and review data; other types
65/// have nothing to update.
66public struct UpdateFlashcard: OrgCommand {
67 public init() {}
68 public var id: String { "org.fc.update" }
69 public var title: String { "Update Flashcard" }
70 public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
71 public func run(in context: EditContext) -> CommandStep {
72 commitBuffer(context) { buffer in
73 try buffer.saveExcursion {
74 try buffer.fcGotoEntryHeading()
75 if buffer.entryProperty("FC_TYPE") == "cloze" { try buffer.fcClozeUpdate() }
76 }
77 }
78 }
79}
80
81/// `org-fc-suspend-card` and `org-fc-unsuspend-card`.
82public struct SuspendFlashcard: OrgCommand {
83 public let suspend: Bool
84 public init(suspend: Bool = true) { self.suspend = suspend }
85 public var id: String { suspend ? "org.fc.suspend" : "org.fc.unsuspend" }
86 public var title: String { suspend ? "Suspend Flashcard" : "Unsuspend Flashcard" }
87 public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
88 public func run(in context: EditContext) -> CommandStep {
89 commitBuffer(context) { buffer in
90 try buffer.saveExcursion {
91 try buffer.fcGotoEntryHeading()
92 let tags = try SetTags.tags(in: buffer)
93 if suspend {
94 try buffer.fcAddTag(Flashcards.suspendedTag)
95 } else {
96 try SetTags.set(tags.filter { $0 != Flashcards.suspendedTag }, in: buffer)
97 }
98 }
99 }
100 }
101}
102
103/// `org-fc-review-rate`: the review data of the card with ID `card` at `position` updated
104/// for `rating` by SM2. `random` stands for the interval fuzz's `cl-random`, as a fraction
105/// of its limit. The caret may be anywhere: the card is found by its ID, so a review can rate
106/// cards whose offsets moved.
107public struct RateFlashcard: OrgCommand {
108 public let card: String
109 public let position: String
110 public let rating: Flashcards.Rating
111 public let random: Double
112
113 public init(card: String, position: String, rating: Flashcards.Rating, random: Double = Double.random(in: 0..<1)) {
114 self.card = card
115 self.position = position
116 self.rating = rating
117 self.random = random
118 }
119
120 public var id: String { "internal.fc.rate" }
121 public var title: String { "Rate Flashcard" }
122 public func applies(in context: EditContext) -> Bool { true }
123 public func run(in context: EditContext) -> CommandStep {
124 commitBuffer(context) { buffer in
125 try buffer.saveExcursion {
126 buffer.point = 0
127 let id = NSRegularExpression.escapedPattern(for: card)
128 while let match = buffer.searchForward("^[ \\t]*:ID:[ \\t]+" + id + "[ \\t]*$", caseInsensitive: true) {
129 try buffer.backToHeading()
130 if try SetTags.tags(in: buffer).contains(Flashcards.tag), buffer.entryID() == card {
131 try buffer.fcRate(position, rating: rating, random: random)
132 return
133 }
134 buffer.point = match[0]!.upperBound
135 }
136 throw EmacsBuffer.UserError(message: "The card is no longer in the file")
137 }
138 }
139 }
140}
141
142extension EmacsBuffer {
143 /// `org-fc--init-card`, from point at the heading.
144 func fcInitCard(_ type: String, newID: () -> String) throws {
145 if try SetTags.tags(in: self).contains(Flashcards.tag) { throw UserError(message: "Headline is already a flashcard") }
146 try backToHeading()
147 entryPut("FC_CREATED", Flashcards.timestamp(now))
148 entryPut("FC_TYPE", type)
149 entryPut("FC_ALGO", Flashcards.algorithm)
150 if entryID() == nil { entryPut("ID", newID()) }
151 try fcAddTag(Flashcards.tag)
152 }
153
154 /// `org-fc--add-tag`: the tag goes first unless the heading has it.
155 func fcAddTag(_ tag: String) throws {
156 let tags = try SetTags.tags(in: self)
157 if !tags.contains(tag) { try SetTags.set([tag] + tags, in: self) }
158 }
159
160 /// `org-fc-goto-entry-heading`.
161 func fcGotoEntryHeading() throws {
162 try backToHeading()
163 while try !SetTags.tags(in: self).contains(Flashcards.tag) {
164 guard upHeadingSafe() != nil else { throw UserError(message: "Not inside a flashcard entry") }
165 }
166 }
167
168 /// Whether `org-fc-text-input-content` finds a line, from point at the heading.
169 func fcHasAnswerLine() -> Bool {
170 saveExcursion {
171 func entry() -> (String, Bool) {
172 let end = saveExcursion { () -> Int in outlineNextHeading(); return point }
173 return (substring(lineStart(point), end), end < length)
174 }
175 let back = saveExcursion { () -> (String, Bool)? in
176 let level = outlineLevel
177 let end = endOfSubtree()
178 var found: (String, Bool)?
179 while outlineNextHeading(), point < end {
180 guard outlineLevel == level + 1, let match = lookingAt(complexHeadingPattern), let title = match[4],
181 Flashcards.backTitles.contains(substring(title.lowerBound, title.upperBound)) else { continue }
182 found = entry()
183 }
184 return found
185 }
186 let (text, followed) = back ?? entry()
187 return Flashcards.firstContentLine(text, followedByHeading: followed) != nil
188 }
189 }
190
191 private static let reviewDataPattern = "^[ \\t]*:" + Flashcards.drawer + ":[ \\t]*$"
192
193 /// `org-fc-review-data-position`: the start of the drawer's first line and of its `:END:`
194 /// line, from point at the heading; with `create`, a new drawer's.
195 func fcReviewDataPosition(create: Bool) -> (Int, Int)? {
196 endOfMetaData()
197 let end = atHeading ? point : saveExcursion { outlineNextHeading(); return point }
198 while let match = searchForward(Self.reviewDataPattern, bound: end, caseInsensitive: true) {
199 let begin = lineEnd(match[0]!.upperBound) + 1
200 let close = saveExcursion { () -> Int? in
201 point = match[0]!.upperBound
202 return searchForward("^[ \\t]*:END:[ \\t]*$", bound: end, caseInsensitive: true).map { lineStart($0[0]!.lowerBound) }
203 }
204 if let close, begin <= close { return (begin, close) }
205 }
206 guard create else { return nil }
207 if !bolp { insert("\n") }
208 insert(":" + Flashcards.drawer + ":\n:END:\n")
209 let at = lineStart(point - 1)
210 return (at, at)
211 }
212
213 /// `org-fc-review-data-parse`: the table's headers and rows by position name.
214 func fcReviewDataParse() throws -> (headers: [String], rows: [(name: String, values: [String: String])]) {
215 let algorithm = entryProperty("FC_ALGO") ?? Flashcards.algorithm
216 guard algorithm == Flashcards.algorithm else { throw UserError(message: "orgstar schedules only SM2 cards, not \(algorithm)") }
217 guard let (begin, _) = saveExcursion({ fcReviewDataPosition(create: false) }) else { return (Flashcards.SM2.headers, []) }
218 return saveExcursion {
219 point = begin
220 let table = tableToLisp()
221 guard let first = table.first, let headers = first else { return (Flashcards.SM2.headers, []) }
222 let rows = table.dropFirst(2).compactMap { $0 }.map { cells -> (name: String, values: [String: String]) in
223 let values = Dictionary(zip(headers, cells), uniquingKeysWith: { a, _ in a })
224 return (values["position"] ?? "", values)
225 }
226 return (headers, rows)
227 }
228 }
229
230 /// `org-fc-review-data-write`.
231 func fcReviewDataWrite(headers: [String], rows: [[String: String]]) {
232 saveExcursion {
233 let lines = ["| " + headers.joined(separator: " | ") + " |\n", "|" + headers.map { _ in "-" }.joined(separator: "+") + "|\n"]
234 + rows.map { row in "| " + headers.map { row[$0] ?? "nil" }.joined(separator: " | ") + " |\n" }
235 let (begin, end) = fcReviewDataPosition(create: true)!
236 deleteRegion(begin, end)
237 point = begin
238 insert(lines.joined())
239 tableAlign()
240 }
241 }
242
243 /// `org-fc-review-data-update`: rows for exactly `names`, new ones with SM2's initial data.
244 func fcReviewDataUpdate(_ names: [String]) throws {
245 let (headers, rows) = try fcReviewDataParse()
246 let sm2 = Flashcards.SM2()
247 let kept = names.map { name in rows.first { $0.name == name }?.values ?? sm2.initial(name, now: now) }
248 fcReviewDataWrite(headers: headers, rows: kept)
249 }
250
251 /// `org-fc-type-cloze-update`, from point at the heading.
252 func fcClozeUpdate() throws {
253 var end = saveExcursion { () -> Int in outlineNextHeading(); return point - 1 }
254 var hole = Int(Flashcards.number(entryProperty(Flashcards.clozeMaxProperty) ?? "-1")) + 1
255 var ids: [String] = []
256 saveExcursion {
257 while let match = searchForward(Flashcards.holePattern, bound: end, caseInsensitive: false) {
258 if let id = match[3] {
259 ids.append(substring(id.lowerBound, id.upperBound))
260 } else {
261 let id = String(hole)
262 hole += 1
263 end += 1 + (id as NSString).length
264 point = match[0]!.upperBound - 1
265 insert("@" + id)
266 ids.append(id)
267 }
268 }
269 }
270 entryPut(Flashcards.clozeMaxProperty, String(hole - 1))
271 try fcReviewDataUpdate(ids)
272 }
273
274 /// `org-fc-algo-update-review-data`, from point at the heading. Returns the row before.
275 @discardableResult
276 func fcRate(_ position: String, rating: Flashcards.Rating, random: Double) throws -> [String: String] {
277 let (headers, rows) = try fcReviewDataParse()
278 guard let current = rows.first(where: { $0.name == position })?.values else {
279 throw UserError(message: "No review data row found for this position")
280 }
281 let next = Flashcards.SM2().next(current, rating: rating, now: now, random: random)
282 let updated = rows.map { row -> [String: String] in
283 guard row.name == position else { return row.values }
284 var values = row.values
285 for header in headers { values[header] = next[header] ?? row.values[header] }
286 return values
287 }
288 fcReviewDataWrite(headers: headers, rows: updated)
289 return current
290 }
291}
292
293extension Flashcards {
294 /// `org-fc-type-cloze-max-hole-property`.
295 static let clozeMaxProperty = "FC_CLOZE_MAX"
296}