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