Sources/OrgCore/Commands/CtrlCCtrlC.swift

144 lines · 8175 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 toggle their checkbox, or without one have their list repaired, setup keywords
  6// refresh, tables evaluate a typed formula, then align or recalculate a row marked `#`, and
  7// elsewhere there's nothing to do.
  8
  9/// `org-ctrl-c-ctrl-c`.
 10public struct CtrlCCtrlC: OrgCommand {
 11    public init() {}
 12    public var id: String { "org.ctrl-c-ctrl-c" }
 13    public var title: String { "Act at Point (C-c C-c)" }
 14    public func applies(in context: EditContext) -> Bool { true }
 15
 16    static let nothing = CommandStep.failed("`C-c C-c' can do nothing useful here")
 17
 18    public func run(in context: EditContext) -> CommandStep {
 19        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
 20        if KeyContext.holds("src", in: context) || ExecuteSrcBlock.atCallOrInline(context) { return ExecuteSrcBlock().run(in: context) }
 21        if KeyContext.holds("table", in: context) || TableRecalculate.tblfmLine(in: context) != nil {
 22            // At the table's very start the context is the table itself, which org recalculates.
 23            let atStart = buffer.saveExcursion { buffer.tableBegin() } == context.caret
 24            if TableRecalculate.tblfmLine(in: context) != nil || atStart { return TableRecalculate(all: true).run(in: context) }
 25            // `org-table-maybe-eval-formula`, then `org-table-maybe-recalculate-line` on a row
 26            // marked `#`, which aligns, or else `org-table-align`.
 27            return TableRecalculate.recalculating(context, form: "(org-ctrl-c-ctrl-c)") { buffer in
 28                try buffer.tableMaybeEvalFormula()
 29                guard buffer.lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else { return buffer.tableAlign() }
 30                try buffer.tableRecalculate(all: false)
 31            }
 32        }
 33        // Org says to edit table.el tables with C-c '; here their borders line up again.
 34        if KeyContext.holds("table-el", in: context) { return TableElAlign().run(in: context) }
 35        if buffer.footnoteReferenceAtPoint() != nil
 36            || buffer.footnoteDefinitions().contains(where: { $0.begin <= context.caret && context.caret < ($0.contentsBegin ?? $0.end) }) {
 37            return FootnoteAction().run(in: context)
 38        }
 39        if buffer.lookingAtLine("^[ \\t]*$") { return Self.nothing }
 40        // On a clock line, changing a timestamp updates the clock too.
 41        if buffer.lookingAtLine("^[ \\t]*CLOCK:") { return commitBuffer(context) { $0.clockUpdateTime() } }
 42        if buffer.lookingAtLine(EmacsBuffer.dblockStart) { return UpdateDynamicBlock().run(in: context) }
 43        if Self.cookieAtCaret(buffer) {
 44            return commitBuffer(context) { buffer in
 45                buffer.saveExcursion {
 46                    buffer.point = buffer.lineStart(buffer.point)
 47                    buffer.updateStatisticsCookies()
 48                }
 49            }
 50        }
 51        if buffer.atTimestamp() != nil { return commitBuffer(context) { try $0.changeTimestamp(0, what: .day) } }
 52        if buffer.atHeading { return SetTags().run(in: context) }
 53        if buffer.atItem, buffer.atRadioList() { return commitBuffer(context) { try $0.toggleRadioButton() } }
 54        if buffer.atItem {
 55            // The item's checkbox toggles, and the whole list is repaired, its cookie updated.
 56            return commitBuffer(context) { buffer in
 57                let origin = buffer.marker(buffer.point)
 58                defer {
 59                    buffer.point = origin.position
 60                    buffer.release(origin)
 61                }
 62                buffer.point = buffer.lineStart(buffer.point)
 63                let item = buffer.point
 64                var structure = buffer.listStruct()
 65                let old = structure
 66                let box = structure.checkbox(item)
 67                if let box { structure.set(item) { $0.checkbox = box == "[X]" ? "[ ]" : "[X]" } }
 68                var repaired = structure
 69                buffer.writeStruct(&repaired, repaired.parents, old: old)
 70                if box != nil, repaired == old {
 71                    throw EmacsBuffer.UserError(message: "Cannot toggle this checkbox: \(box == "[X]" ? "all subitems checked" : "unchecked subitems")")
 72                }
 73                buffer.point = item
 74                buffer.updateCheckboxCount()
 75            }
 76        }
 77        if let list = buffer.affiliatedListStart() {
 78            // On the list's affiliated keywords, the list is repaired.
 79            var step = commitBuffer(context) { buffer in
 80                let origin = buffer.marker(buffer.point)
 81                defer {
 82                    buffer.point = origin.position
 83                    buffer.release(origin)
 84                }
 85                buffer.point = list
 86                var structure = buffer.listStruct()
 87                buffer.writeStruct(&structure, structure.parents, old: structure)
 88                buffer.updateCheckboxCount()
 89            }
 90            if case .commit(let result) = step, result.edits.isEmpty {
 91                step = .commit(EditResult(baseRevision: context.revision, edits: [], effects: [.message("Cannot update this checkbox")]))
 92            }
 93            return step
 94        }
 95        if buffer.lookingAtLine("^[ \\t]*#\\+[A-Za-z_]+:") {
 96            return .commit(EditResult(baseRevision: context.revision, edits: [], effects: [.refreshSetup, .message("Local setup has been refreshed")]))
 97        }
 98        if buffer.propertyAtPoint() != nil || buffer.lookingAtLine("^[ \\t]*:(?:PROPERTIES|END):[ \\t]*$") && buffer.existingPropertyBlock() != nil {
 99            return PropertyAction().run(in: context)
100        }
101        return Self.nothing
102    }
103
104    /// A `[n/m]` or `[n%]` cookie holds the caret.
105    static func cookieAtCaret(_ buffer: EmacsBuffer) -> Bool {
106        let line = buffer.lineStart(buffer.point)..<buffer.lineEnd(buffer.point)
107        let text = buffer.substring(line.lowerBound, line.upperBound) as NSString
108        let regex = try! NSRegularExpression(pattern: "\\[[0-9]*(?:%|/[0-9]*)\\]")
109        return regex.matches(in: text as String, range: NSRange(location: 0, length: text.length)).contains {
110            let start = line.lowerBound + $0.range.location
111            return start <= buffer.point && buffer.point < start + $0.range.length
112        }
113    }
114}
115
116extension EmacsBuffer {
117    /// `org-clock-update-time-maybe` on a finished clock line: both dates' weekdays fixed and
118    /// the duration written again.
119    func clockUpdateTime() {
120        saveExcursion {
121            point = lineStart(point)
122            skipForward([32, 9])
123            guard let match = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"),
124                  match[2] != nil, let first = match[1] else { return }
125            saveExcursion {
126                point = first.lowerBound
127                try? changeTimestamp(0, what: .day, updateClock: false)
128            }
129            guard let again = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"), let second = again[3] else { return }
130            saveExcursion {
131                point = second.lowerBound
132                try? changeTimestamp(0, what: .day, updateClock: false)
133            }
134            guard let final = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"),
135                  let start = final[1], let end = final[3] else { return }
136            if let arrow = final[4] { deleteRegion(arrow.lowerBound, arrow.upperBound) }
137            point = lineEnd(point)
138            let s = TagsMatcher.seconds(substring(end.lowerBound, end.upperBound), now: now, calendar: calendar)
139                - TagsMatcher.seconds(substring(start.lowerBound, start.upperBound), now: now, calendar: calendar)
140            let total = abs(Int(s))
141            insert(" => " + String(format: s < 0 ? "-%d:%02d" : "%2d:%02d", total / 3600, total % 3600 / 60))
142        }
143    }
144}