Sources/OrgCore/Commands/CitationCommands.swift
160 lines · 8193 bytes
16 symbols in this file
1import Foundation
2
3/// A citation in a buffer, with the parts `org-cite-insert` tells apart.
4public struct CitationAt: Sendable, Equatable {
5 /// `[cite…]`, without the blanks after it.
6 public var range: Range<Int>
7 /// The `:` ending `[cite/style`.
8 public var colon: Int
9 /// Each reference, its `;` included, and its `@key`.
10 public var references: [(range: Range<Int>, key: Range<Int>)]
11
12 /// The style and variant as written (`t/c`); nil without one.
13 public func style(in text: String) -> String? {
14 let ns = text as NSString
15 let written = ns.substring(with: NSRange(location: range.lowerBound + 5, length: colon - range.lowerBound - 5))
16 return written.hasPrefix("/") ? String(written.dropFirst()) : nil
17 }
18
19 public static func == (a: CitationAt, b: CitationAt) -> Bool {
20 a.range == b.range && a.colon == b.colon && a.references.map(\.range) == b.references.map(\.range) && a.references.map(\.key) == b.references.map(\.key)
21 }
22}
23
24public enum Citations {
25 /// The citation holding `offset`: from just after its `[` to its `]`, as
26 /// `org-cite-boundaries` bounds it.
27 public static func citation(at offset: Int, tree: OrgTree) -> CitationAt? {
28 var node = tree.root
29 while let child = node.children.first(where: { $0.range.contains(offset) }) {
30 if child.kind == .citation { return citation(child) }
31 node = child
32 }
33 return nil
34 }
35
36 static func citation(_ node: SyntaxNode) -> CitationAt? {
37 let text = node.text as NSString
38 let colon = text.range(of: ":")
39 guard colon.location != NSNotFound else { return nil }
40 let key = try! NSRegularExpression(pattern: CiteProcessor.keyPattern)
41 var references: [(range: Range<Int>, key: Range<Int>)] = []
42 func collect(_ node: SyntaxNode) {
43 for child in node.children {
44 if child.kind == .citationReference {
45 let own = child.text
46 guard let m = key.firstMatch(in: own, range: NSRange(location: 0, length: (own as NSString).length)) else { continue }
47 let start = child.range.lowerBound + m.range.location
48 references.append((child.range, start..<(start + m.range.length)))
49 } else {
50 collect(child)
51 }
52 }
53 }
54 collect(node)
55 return CitationAt(range: node.range, colon: node.range.lowerBound + colon.location, references: references)
56 }
57
58 /// The citation keys a caret at `offset` follows, as `org-cite-basic-goto` picks them: the
59 /// reference's, or every key of the citation. Nil off a citation.
60 public static func keys(at offset: Int, text: String, tree: OrgTree) -> [String]? {
61 guard let citation = citation(at: offset, tree: tree) else { return nil }
62 let ns = text as NSString
63 let keys = citation.references.map { ns.substring(with: NSRange(location: $0.key.lowerBound + 1, length: $0.key.count - 1)) }
64 if let reference = citation.references.firstIndex(where: { $0.range.contains(offset) }) { return [keys[reference]] }
65 var seen = Set<String>()
66 return keys.filter { seen.insert($0).inserted }
67 }
68
69 /// What Insert Citation… does at `offset`, as `org-cite-make-insert-processor` decides.
70 public enum Place: Sendable, Equatable {
71 /// Outside a citation: a new one.
72 case new
73 /// On `[cite/style`: a new style.
74 case style
75 /// Elsewhere in a citation: a reference added before or after the caret.
76 case reference
77 /// Inside a key: the key replaced, its prefix and suffix kept.
78 case key
79 }
80
81 public static func place(at offset: Int, tree: OrgTree) -> Place {
82 guard let citation = citation(at: offset, tree: tree), offset > citation.range.lowerBound else { return .new }
83 if offset <= citation.colon { return .style }
84 if let current = citation.references.first(where: { $0.range.contains(offset) }), offset > current.key.lowerBound, offset < current.key.upperBound {
85 return .key
86 }
87 return .reference
88 }
89
90 /// `@key` with a prefix and suffix around it, a blank between them unless they have one.
91 static func reference(_ key: String, prefix: String, suffix: String) -> String {
92 var out = "@" + key
93 if !prefix.isEmpty { out = prefix + (prefix.last!.isWhitespace ? "" : " ") + out }
94 if !suffix.isEmpty { out += (suffix.first!.isWhitespace || ",.:".contains(suffix.first!) ? "" : " ") + suffix }
95 return out
96 }
97}
98
99/// Insert Citation…'s edit, once the key and style are chosen: `org-cite-insert` with the
100/// basic processor. Outside a citation, `[cite/style:@key]`; on a citation's style, the style
101/// replaced; on its common prefix or before a reference's `@`, a reference before; on its
102/// common suffix or a reference's suffix, one after; on a key, that key replaced. A prefix
103/// and suffix go around the new reference.
104public struct InsertCitation: OrgCommand {
105 public var key: String?
106 public var style: String?
107 public var prefix: String
108 public var suffix: String
109
110 public init(key: String?, style: String? = nil, prefix: String = "", suffix: String = "") {
111 self.key = key
112 self.style = style
113 self.prefix = prefix
114 self.suffix = suffix
115 }
116
117 public var id: String { "internal.insert-citation" }
118 public var title: String { "Insert Citation" }
119
120 public func applies(in context: EditContext) -> Bool { true }
121
122 public func run(in context: EditContext) -> CommandStep {
123 let caret = context.caret
124 let styleText = (style?.trimmingCharacters(in: .whitespaces)).flatMap { $0.isEmpty ? nil : "/" + $0 } ?? ""
125 func commit(_ range: Range<Int>, _ replacement: String, caret: Int) -> CommandStep {
126 .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: replacement)], selection: [caret..<caret]))
127 }
128 let place = Citations.place(at: caret, tree: context.tree)
129 if place == .style, let citation = Citations.citation(at: caret, tree: context.tree) {
130 guard style != nil else { return .failed("Aborted") }
131 // A point in the old style ends up where the deletion leaves it, at the style's start.
132 let start = citation.range.lowerBound + 5
133 return commit(start..<citation.colon, styleText, caret: min(caret, start))
134 }
135 guard let key, !key.isEmpty else { return .failed("Aborted") }
136 let reference = Citations.reference(key, prefix: prefix, suffix: suffix)
137 guard place != .new, let citation = Citations.citation(at: caret, tree: context.tree), let first = citation.references.first,
138 let last = citation.references.last else {
139 let text = "[cite\(styleText):\(reference)]"
140 return commit(caret..<caret, text, caret: caret + (text as NSString).length)
141 }
142 let ns = context.text as NSString
143 func before(_ r: (range: Range<Int>, key: Range<Int>)) -> CommandStep {
144 let inserted = reference + ";"
145 return commit(r.range.lowerBound..<r.range.lowerBound, inserted, caret: caret > r.range.lowerBound ? caret + (inserted as NSString).length : caret)
146 }
147 func after(_ r: (range: Range<Int>, key: Range<Int>)) -> CommandStep {
148 let end = r.range.upperBound
149 let inserted = ns.character(at: end - 1) == 59 ? reference + ";" : ";" + reference
150 return commit(end..<end, inserted, caret: caret >= end ? caret + (inserted as NSString).length : caret)
151 }
152 guard let current = citation.references.first(where: { $0.range.contains(caret) }) else {
153 // On the common prefix or suffix.
154 return caret < first.range.lowerBound ? before(first) : after(last)
155 }
156 if caret <= current.key.lowerBound { return before(current) }
157 if caret >= current.key.upperBound { return after(current) }
158 return commit(current.key, "@" + key, caret: current.key.lowerBound)
159 }
160}