Sources/OrgCore/Flashcards/Flashcards.swift

cf1c2de361bd33dc4f739537ae53e36a30076444
orgstar/Sources/OrgCore/Flashcards/Flashcards.swift

291 lines · 14904 bytes

  1import Foundation
  2
  3/// Flashcards in org-fc's format (github.com/l3kn/org-fc), so cards and their review data
  4/// carry over to Emacs: a heading tagged `fc` with `FC_CREATED`, `FC_TYPE`, `FC_ALGO` and an
  5/// `ID`, and a `REVIEW_DATA` drawer holding a table with a row per position (position, ease,
  6/// box, interval, due). `suspended` leaves a card out of reviews.
  7public enum Flashcards {
  8    public static let tag = "fc"
  9    public static let suspendedTag = "suspended"
 10    public static let drawer = "REVIEW_DATA"
 11    /// `FC_ALGO` of new cards: org-fc's SM2, the only algorithm `org-fc` loads by default.
 12    public static let algorithm = "sm2"
 13    /// `org-fc-algorithm`, written to the review history.
 14    public static let historyAlgorithm = "sm2-v1"
 15    /// `org-fc-back-heading-titles`.
 16    public static let backTitles = ["Back"]
 17    /// `org-fc-type-cloze-context`.
 18    public static let clozeContext = 1
 19
 20    public enum CardType: String, CaseIterable, Sendable {
 21        case normal, double, cloze
 22        case textInput = "text-input"
 23    }
 24
 25    /// `org-fc-type-cloze-types`.
 26    public enum ClozeType: String, CaseIterable, Sendable {
 27        case deletion, enumeration, context, single
 28    }
 29
 30    public enum Rating: String, CaseIterable, Sendable {
 31        case again, hard, good, easy
 32    }
 33
 34    /// One row of the review data table.
 35    public struct Position: Sendable, Equatable {
 36        public var name: String
 37        /// The row's cells by column name, as written.
 38        public var values: [String: String]
 39
 40        public init(name: String, values: [String: String]) {
 41            self.name = name
 42            self.values = values
 43        }
 44
 45        public var due: Date? { values["due"].flatMap(Flashcards.date) }
 46        public var ease: Double { Flashcards.number(values["ease"]) }
 47        public var box: Int { Int(Flashcards.number(values["box"])) }
 48        public var interval: Double { Flashcards.number(values["interval"]) }
 49    }
 50
 51    /// A heading tagged `fc` with a `REVIEW_DATA` drawer after its property drawer, as org-fc's
 52    /// indexer finds them.
 53    public struct Card: Sendable, Equatable {
 54        public var id: String
 55        public var title: String
 56        /// `FC_TYPE` as written.
 57        public var type: String
 58        public var clozeType: ClozeType?
 59        /// `FC_ALGO`; nil for cards from before org-fc 0.6, which are SM2's.
 60        public var algorithm: String?
 61        public var created: Date?
 62        public var suspended: Bool
 63        /// Inherited tags first, then the heading's own.
 64        public var tags: [String]
 65        public var positions: [Position]
 66        /// Where the heading starts, and its line.
 67        public var headingOffset: Int
 68        public var headingLine: String
 69        /// The entry's text before its first subheading, without planning lines and drawers.
 70        public var body: String
 71        /// The subheadings, without planning lines and drawers.
 72        public var children: String
 73        /// The text of the `Back` subheading, if there is one.
 74        public var back: String?
 75        /// The first line of the answer, as text-input cards compare it: the line after the
 76        /// `Back` heading's metadata, or the entry's.
 77        public var answerLine: String?
 78
 79        public var cardType: CardType? { CardType(rawValue: type) }
 80
 81        /// Positions due before `now`, unless the card is suspended.
 82        public func due(at now: Date) -> [Position] {
 83            suspended ? [] : positions.filter { ($0.due ?? .distantFuture) < now }
 84        }
 85    }
 86
 87    // MARK: - Reading
 88
 89    /// The cards in `text`.
 90    public static func cards(in text: String, defaults: OrgSettings = .default) -> [Card] {
 91        guard text.contains(":" + tag + ":") else { return [] }
 92        let tree = OrgParser.parse(text, defaults: defaults)
 93        let model = DocumentModel(tree: tree)
 94        let ns = text as NSString
 95        var cards: [Card] = []
 96        for (index, heading) in model.headings.enumerated() where heading.localTags.contains(tag) {
 97            let lineEnd = ns.lineRange(for: NSRange(location: heading.headingRange.lowerBound, length: 0))
 98            let bodyStart = NSMaxRange(lineEnd)
 99            let childIndexes = model.headings.indices.filter { model.headings[$0].parent == index }
100            let bodyEnd = childIndexes.first.map { model.headings[$0].sectionRange.lowerBound } ?? heading.sectionRange.upperBound
101            let entry = ns.substring(with: NSRange(location: bodyStart, length: max(0, bodyEnd - bodyStart)))
102            guard let positions = reviewData(entry) else { continue }
103            func property(_ key: String) -> String? { heading.properties.last { $0.key.uppercased() == key && !$0.additive }?.value }
104            let backIndex = childIndexes.last { model.headings[$0].level == heading.level + 1 && backTitles.contains(model.headings[$0].title) }
105            let backRange = backIndex.map { model.headings[$0].sectionRange }
106            let back = backRange.map { ns.substring(with: NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound)) }
107            let children = ns.substring(with: NSRange(location: bodyEnd, length: heading.sectionRange.upperBound - bodyEnd))
108            let headingLine = ns.substring(with: NSRange(location: lineEnd.location, length: lineEnd.length)).trimmingCharacters(in: .newlines)
109            cards.append(Card(
110                id: property("ID") ?? "", title: heading.title, type: property("FC_TYPE") ?? "",
111                clozeType: property("FC_CLOZE_TYPE").flatMap(ClozeType.init(rawValue:)), algorithm: property("FC_ALGO"),
112                created: property("FC_CREATED").flatMap(date), suspended: heading.localTags.contains(suspendedTag),
113                tags: model.tags(of: index).map(\.value), positions: positions,
114                headingOffset: heading.headingRange.lowerBound, headingLine: headingLine,
115                body: readable(entry), children: readable(children), back: back.map { readable(lines($0).dropFirst().joined(separator: "\n")) },
116                answerLine: back.map { firstContentLine($0, followedByHeading: backRange!.upperBound < ns.length) }
117                    ?? firstContentLine(headingLine + "\n" + entry, followedByHeading: bodyEnd < ns.length)
118            ))
119        }
120        return cards
121    }
122
123    /// The rows of the `REVIEW_DATA` drawer in an entry's text, if it has one after its
124    /// property drawer.
125    static func reviewData(_ entry: String) -> [Position]? {
126        let all = lines(entry)
127        guard let properties = all.firstIndex(where: { isDrawerLine($0, "PROPERTIES") }),
128              let propertiesEnd = all[properties...].firstIndex(where: { isDrawerLine($0, "END") }),
129              let start = all[(propertiesEnd + 1)...].firstIndex(where: { isDrawerLine($0, drawer) }),
130              let end = all[(start + 1)...].firstIndex(where: { isDrawerLine($0, "END") }) else { return nil }
131        var headers: [String] = []
132        var positions: [Position] = []
133        var separated = false
134        for line in all[(start + 1)..<end] {
135            let trimmed = line.trimmingCharacters(in: .whitespaces)
136            guard trimmed.hasPrefix("|"), trimmed.hasSuffix("|") else { continue }
137            if trimmed.range(of: "^\\|[-+]+\\|$", options: .regularExpression) != nil {
138                separated = true
139                continue
140            }
141            let cells = trimmed.dropFirst().dropLast().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
142            if !separated {
143                headers = cells
144            } else if cells.count == headers.count {
145                let values = Dictionary(zip(headers, cells), uniquingKeysWith: { a, _ in a })
146                positions.append(Position(name: values["position"] ?? "", values: values))
147            }
148        }
149        return positions
150    }
151
152    static func isDrawerLine(_ line: String, _ name: String) -> Bool {
153        line.trimmingCharacters(in: .whitespaces).caseInsensitiveCompare(":" + name + ":") == .orderedSame
154    }
155
156    static func lines(_ text: String) -> [String] {
157        text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
158    }
159
160    /// `text` without planning lines and drawers, and without blank lines at either end.
161    public static func readable(_ text: String) -> String {
162        var kept: [String] = []
163        var inDrawer = false
164        for line in lines(text) {
165            let trimmed = line.trimmingCharacters(in: .whitespaces)
166            if inDrawer {
167                if trimmed.caseInsensitiveCompare(":END:") == .orderedSame { inDrawer = false }
168                continue
169            }
170            if trimmed.range(of: "^:[\\w-]+:$", options: .regularExpression) != nil {
171                inDrawer = true
172                continue
173            }
174            if trimmed.range(of: "^(SCHEDULED|DEADLINE|CLOSED):", options: .regularExpression) != nil { continue }
175            kept.append(line)
176        }
177        while kept.first?.trimmingCharacters(in: .whitespaces).isEmpty == true { kept.removeFirst() }
178        while kept.last?.trimmingCharacters(in: .whitespaces).isEmpty == true { kept.removeLast() }
179        return kept.joined(separator: "\n")
180    }
181
182    /// `org-fc-text-input-content`: the line after a heading's planning and drawers, unless
183    /// it is a heading. `text` starts with the heading line and runs to the next heading.
184    static func firstContentLine(_ text: String, followedByHeading: Bool) -> String? {
185        var lines = lines(text)
186        if text.hasSuffix("\n") { lines.removeLast() }
187        var i = 1
188        while i < lines.count, lines[i].range(of: "^(SCHEDULED|DEADLINE): *<[^>]+>", options: .regularExpression) != nil { i += 1 }
189        while i < lines.count, lines[i].range(of: "^[ \\t]*:[\\w-]+:[ \\t]*$", options: .regularExpression) != nil {
190            guard let end = lines[(i + 1)...].firstIndex(where: { $0.contains(":END:") }) else { return nil }
191            i = end + 1
192        }
193        guard i < lines.count else { return followedByHeading ? nil : "" }
194        return lines[i].range(of: "^\\*+ ", options: .regularExpression) != nil ? nil : lines[i]
195    }
196
197    // MARK: - Values
198
199    /// `string-to-number`.
200    static func number(_ string: String?) -> Double {
201        guard let string else { return 0 }
202        let trimmed = string.trimmingCharacters(in: .whitespaces)
203        if let value = Double(trimmed) { return value }
204        let prefix = trimmed.prefix { $0.isNumber || $0 == "." || $0 == "-" || $0 == "+" }
205        return Double(prefix) ?? 0
206    }
207
208    /// `org-fc-timestamp-in`: `%FT%TZ` in UTC, `days` after `now`.
209    public static func timestamp(_ now: Date, plus days: Double = 0) -> String {
210        let seconds = now.timeIntervalSince1970 + days * 60 * 60 * 24
211        var time = time_t(seconds.rounded(.down))
212        var parts = tm()
213        gmtime_r(&time, &parts)
214        return String(format: "%04d-%02d-%02dT%02d:%02d:%02dZ", Int(parts.tm_year) + 1900, Int(parts.tm_mon) + 1, Int(parts.tm_mday),
215                      Int(parts.tm_hour), Int(parts.tm_min), Int(parts.tm_sec))
216    }
217
218    /// A `%FT%TZ` timestamp.
219    public static func date(_ string: String) -> Date? {
220        let parts = string.split(whereSeparator: { "-T:Z".contains($0) }).compactMap { Int($0) }
221        guard string.hasSuffix("Z"), parts.count == 6 else { return nil }
222        var t = tm()
223        t.tm_year = Int32(parts[0] - 1900)
224        t.tm_mon = Int32(parts[1] - 1)
225        t.tm_mday = Int32(parts[2])
226        t.tm_hour = Int32(parts[3])
227        t.tm_min = Int32(parts[4])
228        t.tm_sec = Int32(parts[5])
229        return Date(timeIntervalSince1970: TimeInterval(timegm(&t)))
230    }
231
232    // MARK: - Review history
233
234    /// A line of `org-fc-review-history-file`, as `org-fc-algo-log-review` appends it: the
235    /// position's values before the rating, and the seconds between showing and rating it.
236    public static func historyLine(at now: Date, path: String, id: String, position: Position, rating: Rating, seconds: Double) -> String {
237        [timestamp(now), path, id, position.name, position.values["ease"] ?? "", position.values["box"] ?? "", position.values["interval"] ?? "",
238         rating.rawValue, String(format: "%.2f", seconds), historyAlgorithm].joined(separator: "\t") + "\n"
239    }
240
241    // MARK: - Review sessions
242
243    /// A position to review.
244    public struct Item: Sendable, Equatable {
245        public var path: String
246        public var card: Card
247        public var position: String
248
249        public init(path: String, card: Card, position: String) {
250            self.path = path
251            self.card = card
252            self.position = position
253        }
254    }
255
256    /// The positions due at `now`, as `org-fc-review` queues them with its default filters:
257    /// suspended cards and positions not yet due left out, and one position for each card
258    /// other than single and enumeration cloze cards. Shuffled as `org-fc-shuffle-positions`
259    /// does: each card's positions keep their order.
260    public static func due<G: RandomNumberGenerator>(_ cards: [(path: String, card: Card)], at now: Date, shuffle: Bool = true, using generator: inout G) -> [Item] {
261        var keyed: [(Double, Item)] = []
262        for (path, card) in cards {
263            var due = card.due(at: now)
264            guard !due.isEmpty else { continue }
265            if !(card.cardType == .cloze && [.single, .enumeration].contains(card.clozeType)) { due = [due[0]] }
266            let keys = due.map { _ in Double.random(in: 0..<1, using: &generator) }.sorted(by: >)
267            keyed += zip(keys, due).map { ($0, Item(path: path, card: card, position: $1.name)) }
268        }
269        guard shuffle else { return keyed.map(\.1) }
270        return keyed.enumerated().sorted { $0.element.0 != $1.element.0 ? $0.element.0 > $1.element.0 : $0.offset < $1.offset }.map(\.element.1)
271    }
272
273    public static func due(_ cards: [(path: String, card: Card)], at now: Date, shuffle: Bool = true) -> [Item] {
274        var generator = SystemRandomNumberGenerator()
275        return due(cards, at: now, shuffle: shuffle, using: &generator)
276    }
277
278    /// When each position a review would show falls due: every position of single and
279    /// enumeration cloze cards, the earliest of the others' (a review shows one of them).
280    public static func dueDates(_ card: Card) -> [Date] {
281        guard !card.suspended else { return [] }
282        let dates = card.positions.compactMap(\.due)
283        if card.cardType == .cloze && [.single, .enumeration].contains(card.clozeType) { return dates }
284        return dates.min().map { [$0] } ?? []
285    }
286
287    /// How many positions a review started at `now` would show.
288    public static func dueCount(_ cards: [Card], at now: Date) -> Int {
289        cards.reduce(0) { $0 + dueDates($1).filter { $0 < now }.count }
290    }
291}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form