Sources/OrgCore/Commands/CtrlCCtrlC.swift
113 lines · 6311 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) || ExecuteSrcBlock.atCallOrInline(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.propertyAtPoint() != nil || buffer.lookingAtLine("^[ \\t]*:(?:PROPERTIES|END):[ \\t]*$") && buffer.existingPropertyBlock() != nil {
68 return PropertyAction().run(in: context)
69 }
70 return Self.nothing
71 }
72
73 /// A `[n/m]` or `[n%]` cookie holds the caret.
74 static func cookieAtCaret(_ buffer: EmacsBuffer) -> Bool {
75 let line = buffer.lineStart(buffer.point)..<buffer.lineEnd(buffer.point)
76 let text = buffer.substring(line.lowerBound, line.upperBound) as NSString
77 let regex = try! NSRegularExpression(pattern: "\\[[0-9]*(?:%|/[0-9]*)\\]")
78 return regex.matches(in: text as String, range: NSRange(location: 0, length: text.length)).contains {
79 let start = line.lowerBound + $0.range.location
80 return start <= buffer.point && buffer.point < start + $0.range.length
81 }
82 }
83}
84
85extension EmacsBuffer {
86 /// `org-clock-update-time-maybe` on a finished clock line: both dates' weekdays fixed and
87 /// the duration written again.
88 func clockUpdateTime() {
89 saveExcursion {
90 point = lineStart(point)
91 skipForward([32, 9])
92 guard let match = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"),
93 match[2] != nil, let first = match[1] else { return }
94 saveExcursion {
95 point = first.lowerBound
96 try? changeTimestamp(0, what: .day)
97 }
98 guard let again = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"), let second = again[3] else { return }
99 saveExcursion {
100 point = second.lowerBound
101 try? changeTimestamp(0, what: .day)
102 }
103 guard let final = lookingAt("[ \\t]*CLOCK: *[\\[<]([^\\]>]+)[\\]>](-+[\\[<]([^\\]>]+)[\\]>]([ \\t]*=>.*)?)?"),
104 let start = final[1], let end = final[3] else { return }
105 if let arrow = final[4] { deleteRegion(arrow.lowerBound, arrow.upperBound) }
106 point = lineEnd(point)
107 let s = TagsMatcher.seconds(substring(end.lowerBound, end.upperBound), now: now, calendar: calendar)
108 - TagsMatcher.seconds(substring(start.lowerBound, start.upperBound), now: now, calendar: calendar)
109 let total = abs(Int(s))
110 insert(" => " + String(format: s < 0 ? "-%d:%02d" : "%2d:%02d", total / 3600, total % 3600 / 60))
111 }
112 }
113}