Sources/OrgCore/Commands/CtrlCCtrlC.swift

17f8f98b6004506388fd32955223d5b562f0790b
orgstar/Sources/OrgCore/Commands/CtrlCCtrlC.swift

108 lines · 6072 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) : TableCommand(.align).run(in: context)
 24        }
 25        if buffer.footnoteReferenceAtPoint() != nil
 26            || buffer.footnoteDefinitions().contains(where: { $0.begin <= context.caret && context.caret < ($0.contentsBegin ?? $0.end) }) {
 27            return FootnoteAction().run(in: context)
 28        }
 29        if buffer.lookingAtLine("^[ \\t]*$") { return Self.nothing }
 30        // On a clock line, changing a timestamp updates the clock too.
 31        if buffer.lookingAtLine("^[ \\t]*CLOCK:") { return commitBuffer(context) { $0.clockUpdateTime() } }
 32        if buffer.lookingAtLine(EmacsBuffer.dblockStart) { return UpdateDynamicBlock().run(in: context) }
 33        if Self.cookieAtCaret(buffer) {
 34            return commitBuffer(context) { buffer in
 35                buffer.saveExcursion {
 36                    buffer.point = buffer.lineStart(buffer.point)
 37                    buffer.updateStatisticsCookies()
 38                }
 39            }
 40        }
 41        if buffer.atTimestamp() != nil { return commitBuffer(context) { try $0.changeTimestamp(0, what: .day) } }
 42        if buffer.atHeading { return SetTags().run(in: context) }
 43        if buffer.atItem {
 44            // The item's checkbox toggles, and the whole list is repaired, its cookie updated.
 45            return commitBuffer(context) { buffer in
 46                buffer.point = buffer.lineStart(buffer.point)
 47                let item = buffer.point
 48                var structure = buffer.listStruct()
 49                let old = structure
 50                let box = structure.checkbox(item)
 51                if let box { structure.set(item) { $0.checkbox = box == "[X]" ? "[ ]" : "[X]" } }
 52                var repaired = structure
 53                buffer.writeStruct(&repaired, repaired.parents, old: old)
 54                if box != nil, repaired == old {
 55                    throw EmacsBuffer.UserError(message: "Cannot toggle this checkbox: \(box == "[X]" ? "all subitems checked" : "unchecked subitems")")
 56                }
 57                buffer.point = item
 58                buffer.updateCheckboxCount()
 59            }
 60        }
 61        if buffer.lookingAtLine("^[ \\t]*#\\+[A-Za-z_]+:") {
 62            return .commit(EditResult(baseRevision: context.revision, edits: [], effects: [.message("Local setup has been refreshed")]))
 63        }
 64        if buffer.lookingAtLine("^[ \\t]*:[^\\s:]+:") { return .failed("Property actions aren't supported yet") }
 65        return Self.nothing
 66    }
 67
 68    /// A `[n/m]` or `[n%]` cookie holds the caret.
 69    static func cookieAtCaret(_ buffer: EmacsBuffer) -> Bool {
 70        let line = buffer.lineStart(buffer.point)..<buffer.lineEnd(buffer.point)
 71        let text = buffer.substring(line.lowerBound, line.upperBound) as NSString
 72        let regex = try! NSRegularExpression(pattern: "\\[[0-9]*(?:%|/[0-9]*)\\]")
 73        return regex.matches(in: text as String, range: NSRange(location: 0, length: text.length)).contains {
 74            let start = line.lowerBound + $0.range.location
 75            return start <= buffer.point && buffer.point < start + $0.range.length
 76        }
 77    }
 78}
 79
 80extension EmacsBuffer {
 81    /// `org-clock-update-time-maybe` on a finished clock line: both dates' weekdays fixed and
 82    /// the duration written again.
 83    func clockUpdateTime() {
 84        saveExcursion {
 85            point = lineStart(point)
 86            skipForward([32, 9])
 87            guard let match = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"),
 88                  match[2] != nil, let first = match[1] else { return }
 89            saveExcursion {
 90                point = first.lowerBound
 91                try? changeTimestamp(0, what: .day)
 92            }
 93            guard let again = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"), let second = again[3] else { return }
 94            saveExcursion {
 95                point = second.lowerBound
 96                try? changeTimestamp(0, what: .day)
 97            }
 98            guard let final = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"),
 99                  let start = final[1], let end = final[3] else { return }
100            if let arrow = final[4] { deleteRegion(arrow.lowerBound, arrow.upperBound) }
101            point = lineEnd(point)
102            let s = TagsMatcher.seconds(substring(end.lowerBound, end.upperBound), now: now, calendar: calendar)
103                - TagsMatcher.seconds(substring(start.lowerBound, start.upperBound), now: now, calendar: calendar)
104            let total = abs(Int(s))
105            insert(" => " + String(format: s < 0 ? "-%d:%02d" : "%2d:%02d", total / 3600, total % 3600 / 60))
106        }
107    }
108}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form