Sources/OrgCore/Commands/ColumnEdit.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgCore/Commands/ColumnEdit.swift history · blame · raw

121 lines · 6924 bytes

  1import Foundation
  2
  3// Editing in column view (org-colview.el, Org 9.8.7): `org-columns-edit-value` and
  4// `org-columns-next-allowed-value` for the entry whose heading holds the caret.
  5
  6extension EditContext {
  7    /// The same context with the caret at `offset`.
  8    func at(_ offset: Int) -> EditContext {
  9        EditContext(revision: revision, text: text, tree: tree, selection: [offset..<offset], now: now, calendar: calendar,
 10                    answers: answers, hidden: hidden, options: options, knownTags: knownTags, lastCommand: lastCommand)
 11    }
 12
 13    /// The same context with `more` answers.
 14    func answering(_ more: [String: String]) -> EditContext {
 15        EditContext(revision: revision, text: text, tree: tree, selection: selection, now: now, calendar: calendar,
 16                    answers: answers.merging(more) { $1 }, hidden: hidden, options: options, knownTags: knownTags, lastCommand: lastCommand)
 17    }
 18}
 19
 20/// `e` in column view: `org-columns-edit-value` with the value given. ITEM edits the headline,
 21/// TODO, PRIORITY, TAGS, SCHEDULED and DEADLINE go through their commands, and other
 22/// properties are set in the entry's drawer.
 23public struct SetColumnValue: OrgCommand {
 24    public let property: String
 25    public let value: String
 26    public init(property: String, value: String) {
 27        self.property = property
 28        self.value = value
 29    }
 30    public var id: String { "org.columns.edit-value" }
 31    public var title: String { "Edit Column Value" }
 32    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
 33
 34    public func run(in context: EditContext) -> CommandStep {
 35        guard let heading = entryHeading(at: context.caret, in: context.tree) else { return .failed("Before first headline") }
 36        let value = self.value.trimmingCharacters(in: .whitespaces)
 37        let here = context.at(heading.range.lowerBound)
 38        switch property.uppercased() {
 39        case "CLOCKSUM", "CLOCKSUM_T", "ALLTAGS", "BLOCKED", "CLOSED", "FILE", "TIMESTAMP", "TIMESTAMP_IA":
 40            return .failed("This special column cannot be edited")
 41        case "ITEM":
 42            // `org-edit-headline`.
 43            return commitBuffer(here) { buffer in
 44                guard let match = buffer.lookingAt(buffer.complexHeadingPattern) else { return }
 45                let old = match[4].map { buffer.substring($0.lowerBound, $0.upperBound) }
 46                guard old != value else { return }
 47                if let title = match[4] {
 48                    buffer.replace(title.lowerBound..<title.upperBound, with: value)
 49                } else {
 50                    buffer.point = (match[3] ?? match[2] ?? match[1])!.upperBound
 51                    buffer.insert(" " + value)
 52                }
 53                buffer.alignTags(onLineAt: heading.range.lowerBound)
 54            }
 55        case "TODO":
 56            return SetTodo(keyword: value.isEmpty ? nil : value).run(in: here)
 57        case "PRIORITY":
 58            return SetPriority(value: value.isEmpty ? " " : nil).run(in: value.isEmpty ? here : here.answering(["priority": value]))
 59        case "TAGS":
 60            let tags = value.split(whereSeparator: { $0 == ":" || $0 == " " }).map(String.init)
 61            return SetTags.set(tags, in: here)
 62        case "SCHEDULED", "DEADLINE":
 63            let deadline = property.uppercased() == "DEADLINE"
 64            if value.isEmpty { return RemovePlanning(deadline: deadline).run(in: here) }
 65            return SetPlanning(deadline: deadline).run(in: here.answering(["date": value]))
 66        default:
 67            // Column keys are upper case, as `org-columns-compile-format` reads them, and so is
 68            // the line `org-entry-put` writes.
 69            return SetProperty(key: property.uppercased(), value: value).run(in: here)
 70        }
 71    }
 72}
 73
 74/// `n` and `p` in column view: `org-columns-next-allowed-value`, the next (or previous) of the
 75/// property's allowed values, `[ ]` and `[X]` for a checkbox summary, or a day later (or
 76/// earlier) for SCHEDULED and DEADLINE.
 77public struct NextColumnValue: OrgCommand {
 78    public let property: String
 79    /// The column's summary operator, for checkbox columns.
 80    public let summary: String?
 81    public let previous: Bool
 82    public init(property: String, summary: String? = nil, previous: Bool = false) {
 83        self.property = property
 84        self.summary = summary
 85        self.previous = previous
 86    }
 87    public var id: String { previous ? "org.columns.previous-value" : "org.columns.next-value" }
 88    public var title: String { previous ? "Previous Allowed Value" : "Next Allowed Value" }
 89    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
 90
 91    public func run(in context: EditContext) -> CommandStep {
 92        guard let heading = entryHeading(at: context.caret, in: context.tree) else { return .failed("Before first headline") }
 93        let key = property.uppercased()
 94        if key == "ITEM" { return .failed("Cannot edit item headline from here") }
 95        if key == "SCHEDULED" || key == "DEADLINE" {
 96            // The planning timestamp a day later or earlier.
 97            let ns = context.text as NSString
 98            let next = NSMaxRange(ns.lineRange(for: NSRange(location: heading.range.lowerBound, length: 0)))
 99            guard next < ns.length else { return .failed("No \(key) in this entry") }
100            let line = ns.lineRange(for: NSRange(location: next, length: 0))
101            let found = ns.range(of: key + ": *<", options: .regularExpression, range: line)
102            guard found.location != NSNotFound else { return .failed("No \(key) in this entry") }
103            return ShiftTimestampDay(later: !previous).run(in: context.at(NSMaxRange(found)))
104        }
105        var allowed = PropertyValues.allowed(property, at: heading.range.lowerBound, text: context.text, tree: context.tree)?.values ?? []
106        if allowed.isEmpty, let summary, ["X", "X/", "X%"].contains(summary) { allowed = ["[ ]", "[X]"] }
107        guard !allowed.isEmpty else { return .failed("Allowed values for this property have not been defined") }
108        if previous { allowed.reverse() }
109        let model = DocumentModel(tree: context.tree)
110        guard let index = model.headings.firstIndex(where: { $0.headingRange.lowerBound == heading.range.lowerBound }) else { return .failed("Before first headline") }
111        let current = ColumnView.value(key, heading: index, model: model, text: context.text as NSString, clocksum: [:])
112        let new: String
113        if let i = allowed.firstIndex(of: current) {
114            if allowed.count == 1 { return .failed("Only one allowed value for this property") }
115            new = i + 1 < allowed.count ? allowed[i + 1] : allowed[0]
116        } else {
117            new = allowed[0]
118        }
119        return SetColumnValue(property: property, value: new).run(in: context)
120    }
121}