Sources/OrgCore/Commands/EntryFields.swift

design-themes-widgets
orgstar/Sources/OrgCore/Commands/EntryFields.swift history · blame · raw

147 lines · 6908 bytes

  1import Foundation
  2
  3/// An entry's heading parts, planning and notes, as a form edits them. The notes are the text
  4/// after the planning line, drawers and clock lines, up to the next heading, without trailing
  5/// blank lines.
  6public struct EntryFields: Equatable, Sendable {
  7    public var todo: String?
  8    /// The cookie's letter or number: `A`, `10`.
  9    public var priority: String?
 10    public var title: String
 11    public var tags: [String]
 12    /// The timestamps' text without brackets: `2026-10-17 Sat 18:00 +1w`.
 13    public var scheduled: String?
 14    public var deadline: String?
 15    public var notes: String
 16
 17    public init(todo: String?, priority: String?, title: String, tags: [String], scheduled: String?, deadline: String?, notes: String) {
 18        self.todo = todo
 19        self.priority = priority
 20        self.title = title
 21        self.tags = tags
 22        self.scheduled = scheduled
 23        self.deadline = deadline
 24        self.notes = notes
 25    }
 26
 27    /// The fields of the entry whose heading is at or before `offset`; nil before the first heading.
 28    public static func read(_ text: String, at offset: Int, settings: OrgSettings) -> EntryFields? {
 29        let buffer = EmacsBuffer(text, point: offset, settings: settings)
 30        guard (try? buffer.backToHeading()) != nil, let match = buffer.lookingAt(buffer.complexHeadingPattern) else { return nil }
 31        func group(_ i: Int) -> String? { match[i].map { buffer.substring($0.lowerBound, $0.upperBound) } }
 32        let notes = buffer.notesRange()
 33        return EntryFields(
 34            todo: group(2),
 35            priority: group(3).map { String($0.dropFirst(2).dropLast()) },
 36            title: group(4) ?? "",
 37            tags: group(5).map { $0.split(separator: ":").map(String.init) } ?? [],
 38            scheduled: buffer.planningValue(.scheduled),
 39            deadline: buffer.planningValue(.deadline),
 40            notes: buffer.substring(notes.lowerBound, notes.upperBound)
 41        )
 42    }
 43}
 44
 45extension EmacsBuffer {
 46    /// The notes of the entry at point: from past its meta-data to before the trailing blanks
 47    /// of the entry's text.
 48    func notesRange() -> Range<Int> {
 49        saveExcursion {
 50            let end = entryEnd
 51            endOfMetaDataFull()
 52            let start = min(point, end)
 53            point = end
 54            skipBackward([32, 9, 10, 13])
 55            return start..<max(start, point)
 56        }
 57    }
 58}
 59
 60/// Replaces the title of the entry's heading, keeping its keyword, priority and tags.
 61public struct SetHeadingTitle: OrgCommand {
 62    let text: String
 63    public init(title: String) { text = title }
 64    public var id: String { "org.heading.set-title" }
 65    public var title: String { "Set Heading Title" }
 66    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
 67    public func run(in context: EditContext) -> CommandStep {
 68        guard entryHeading(at: context.caret, in: context.tree) != nil else { return .failed("Before first headline") }
 69        // A heading is one line.
 70        let new = text.split(whereSeparator: \.isNewline).joined(separator: " ").trimmingCharacters(in: .whitespaces)
 71        return commitBuffer(context) { buffer in
 72            try buffer.saveExcursion {
 73                try buffer.backToHeading()
 74                guard let match = buffer.lookingAt(buffer.complexHeadingPattern) else { return }
 75                if let old = match[4] {
 76                    buffer.replace(old, with: new)
 77                } else if !new.isEmpty {
 78                    buffer.point = (1...3).compactMap { match[$0]?.upperBound }.max()!
 79                    buffer.insert(" " + new)
 80                }
 81                buffer.alignTags(onLineAt: buffer.point)
 82            }
 83        }
 84    }
 85}
 86
 87/// Replaces the entry's notes (see `EntryFields.notes`).
 88public struct SetEntryNotes: OrgCommand {
 89    let notes: String
 90    public init(notes: String) { self.notes = notes }
 91    public var id: String { "org.entry.set-notes" }
 92    public var title: String { "Set Notes" }
 93    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
 94    public func run(in context: EditContext) -> CommandStep {
 95        guard entryHeading(at: context.caret, in: context.tree) != nil else { return .failed("Before first headline") }
 96        var new = notes
 97        while new.last?.isWhitespace == true { new.removeLast() }
 98        return commitBuffer(context) { buffer in
 99            buffer.saveExcursion {
100                let old = buffer.notesRange()
101                if !old.isEmpty {
102                    // An emptied note takes its line break with it.
103                    let end = new.isEmpty && buffer.character(at: old.upperBound) == 10 ? old.upperBound + 1 : old.upperBound
104                    buffer.replace(old.lowerBound..<end, with: new)
105                } else if !new.isEmpty {
106                    buffer.point = old.lowerBound
107                    if !buffer.bolp { buffer.insert("\n") }
108                    buffer.insert(new + "\n")
109                }
110            }
111        }
112    }
113}
114
115/// Writes the changes made on a copy of the text back as one edit: the span between what the
116/// two texts share at their start and end, when the text there still reads as it did.
117public struct ReplaceChangedText: OrgCommand {
118    public let edit: TextEdit
119    let expected: String
120
121    /// Nil when the texts are the same.
122    public init?(from old: String, to new: String) {
123        let a = Array(old.utf16)
124        let b = Array(new.utf16)
125        let shorter = min(a.count, b.count)
126        var prefix = 0
127        while prefix < shorter, a[prefix] == b[prefix] { prefix += 1 }
128        var suffix = 0
129        while suffix < shorter - prefix, a[a.count - 1 - suffix] == b[b.count - 1 - suffix] { suffix += 1 }
130        while prefix > 0, prefix < a.count, UTF16.isTrailSurrogate(a[prefix]) { prefix -= 1 }
131        while suffix > 0, UTF16.isTrailSurrogate(a[a.count - suffix]) { suffix -= 1 }
132        guard a.count != b.count || prefix != a.count else { return nil }
133        edit = TextEdit(range: prefix..<(a.count - suffix), replacement: String(decoding: b[prefix..<(b.count - suffix)], as: UTF16.self))
134        expected = String(decoding: a[prefix..<(a.count - suffix)], as: UTF16.self)
135    }
136
137    public var id: String { "org.replace-changed-text" }
138    public var title: String { "Replace Changed Text" }
139    public func applies(in context: EditContext) -> Bool { true }
140    public func run(in context: EditContext) -> CommandStep {
141        let text = context.text as NSString
142        guard edit.range.upperBound <= text.length, text.substring(with: NSRange(edit.range)) == expected else {
143            return .failed("The entry changed; nothing was saved.")
144        }
145        return .commit(EditResult(baseRevision: context.revision, edits: [edit], selection: nil, effects: []))
146    }
147}