Sources/OrgCore/Commands/CtrlCCtrlC.swift

b7b7f8ef81367a5e787840c1b28d8a82bf7da545
orgstar/Sources/OrgCore/Commands/CtrlCCtrlC.swift history · blame · raw

111 lines · 6169 bytes

  1import Foundation
  2
  3// C-c C-c (`org-ctrl-c-ctrl-c`, Org 9.8.7) for the contexts no more specific binding takes:
  4// headings set tags, clock lines get their duration again, timestamps their weekday, cookies
  5// update, items without a checkbox have their list repaired, setup keywords refresh, and
  6// elsewhere there's nothing to do.
  7
  8/// `org-ctrl-c-ctrl-c`.
  9public struct CtrlCCtrlC: OrgCommand {
 10    public init() {}
 11    public var id: String { "org.ctrl-c-ctrl-c" }
 12    public var title: String { "Act at Point (C-c C-c)" }
 13    public func applies(in context: EditContext) -> Bool { true }
 14
 15    static let nothing = CommandStep.failed("`C-c C-c' can do nothing useful here")
 16
 17    public func run(in context: EditContext) -> CommandStep {
 18        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
 19        if KeyContext.holds("src", in: context) { return ExecuteSrcBlock().run(in: context) }
 20        if KeyContext.holds("table", in: context) || TableRecalculate.tblfmLine(in: context) != nil {
 21            // At the table's very start the context is the table itself, which org recalculates.
 22            let atStart = buffer.saveExcursion { buffer.tableBegin() } == context.caret
 23            return TableRecalculate.tblfmLine(in: context) != nil || atStart ? TableRecalculate(all: true).run(in: context) : commitBuffer(context) { buffer in
 24                try buffer.tableMaybeEvalFormula()
 25                buffer.tableAlign()
 26            }
 27        }
 28        if buffer.footnoteReferenceAtPoint() != nil
 29            || buffer.footnoteDefinitions().contains(where: { $0.begin <= context.caret && context.caret < ($0.contentsBegin ?? $0.end) }) {
 30            return FootnoteAction().run(in: context)
 31        }
 32        if buffer.lookingAtLine("^[ \\t]*$") { return Self.nothing }
 33        // On a clock line, changing a timestamp updates the clock too.
 34        if buffer.lookingAtLine("^[ \\t]*CLOCK:") { return commitBuffer(context) { $0.clockUpdateTime() } }
 35        if buffer.lookingAtLine(EmacsBuffer.dblockStart) { return UpdateDynamicBlock().run(in: context) }
 36        if Self.cookieAtCaret(buffer) {
 37            return commitBuffer(context) { buffer in
 38                buffer.saveExcursion {
 39                    buffer.point = buffer.lineStart(buffer.point)
 40                    buffer.updateStatisticsCookies()
 41                }
 42            }
 43        }
 44        if buffer.atTimestamp() != nil { return commitBuffer(context) { try $0.changeTimestamp(0, what: .day) } }
 45        if buffer.atHeading { return SetTags().run(in: context) }
 46        if buffer.atItem {
 47            // The item's checkbox toggles, and the whole list is repaired, its cookie updated.
 48            return commitBuffer(context) { buffer in
 49                buffer.point = buffer.lineStart(buffer.point)
 50                let item = buffer.point
 51                var structure = buffer.listStruct()
 52                let old = structure
 53                let box = structure.checkbox(item)
 54                if let box { structure.set(item) { $0.checkbox = box == "[X]" ? "[ ]" : "[X]" } }
 55                var repaired = structure
 56                buffer.writeStruct(&repaired, repaired.parents, old: old)
 57                if box != nil, repaired == old {
 58                    throw EmacsBuffer.UserError(message: "Cannot toggle this checkbox: \(box == "[X]" ? "all subitems checked" : "unchecked subitems")")
 59                }
 60                buffer.point = item
 61                buffer.updateCheckboxCount()
 62            }
 63        }
 64        if buffer.lookingAtLine("^[ \\t]*#\\+[A-Za-z_]+:") {
 65            return .commit(EditResult(baseRevision: context.revision, edits: [], effects: [.message("Local setup has been refreshed")]))
 66        }
 67        if buffer.lookingAtLine("^[ \\t]*:[^\\s:]+:") { return .failed("Property actions aren't supported yet") }
 68        return Self.nothing
 69    }
 70
 71    /// A `[n/m]` or `[n%]` cookie holds the caret.
 72    static func cookieAtCaret(_ buffer: EmacsBuffer) -> Bool {
 73        let line = buffer.lineStart(buffer.point)..<buffer.lineEnd(buffer.point)
 74        let text = buffer.substring(line.lowerBound, line.upperBound) as NSString
 75        let regex = try! NSRegularExpression(pattern: "\\[[0-9]*(?:%|/[0-9]*)\\]")
 76        return regex.matches(in: text as String, range: NSRange(location: 0, length: text.length)).contains {
 77            let start = line.lowerBound + $0.range.location
 78            return start <= buffer.point && buffer.point < start + $0.range.length
 79        }
 80    }
 81}
 82
 83extension EmacsBuffer {
 84    /// `org-clock-update-time-maybe` on a finished clock line: both dates' weekdays fixed and
 85    /// the duration written again.
 86    func clockUpdateTime() {
 87        saveExcursion {
 88            point = lineStart(point)
 89            skipForward([32, 9])
 90            guard let match = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"),
 91                  match[2] != nil, let first = match[1] else { return }
 92            saveExcursion {
 93                point = first.lowerBound
 94                try? changeTimestamp(0, what: .day)
 95            }
 96            guard let again = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"), let second = again[3] else { return }
 97            saveExcursion {
 98                point = second.lowerBound
 99                try? changeTimestamp(0, what: .day)
100            }
101            guard let final = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"),
102                  let start = final[1], let end = final[3] else { return }
103            if let arrow = final[4] { deleteRegion(arrow.lowerBound, arrow.upperBound) }
104            point = lineEnd(point)
105            let s = TagsMatcher.seconds(substring(end.lowerBound, end.upperBound), now: now, calendar: calendar)
106                - TagsMatcher.seconds(substring(start.lowerBound, start.upperBound), now: now, calendar: calendar)
107            let total = abs(Int(s))
108            insert(" => " + String(format: s < 0 ? "-%d:%02d" : "%2d:%02d", total / 3600, total % 3600 / 60))
109        }
110    }
111}