Sources/OrgCore/Commands/CtrlCCtrlC.swift

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