Sources/OrgCore/Completion/OrgCompletion.swift
280 lines · 16196 bytes
1import Foundation
2
3// Completion at point (Org 9.8.7's org-pcomplete): `org-thing-at-point` picks what the caret
4// is on, and each context offers what its `pcomplete/org-mode/…` function does. Link types
5// after `[[`, workspace tags and org-tempo's `<` templates are added, and snippet triggers
6// where no org context offers anything.
7
8public struct Completion: Sendable, Equatable {
9 public enum Kind: String, Sendable {
10 case keyword, keywordValue, link, entity, tag, todo, heading, drawer, property, srcLanguage, srcHeader, clocktable, template, snippet
11 }
12
13 public var kind: Kind
14 /// The text the chosen candidate replaces: from the start of what's typed to the caret.
15 public var range: Range<Int>
16 /// Candidates starting with what's typed, sorted.
17 public var candidates: [String]
18 /// The block templates `<` completes, for `.template`.
19 public var templates: [StructureTemplate] = []
20 /// The snippets whose triggers are the candidates, for `.snippet`; choosing one expands it.
21 public var snippets: [Snippet] = []
22
23 /// How the list shows `candidate`: a template with the block it makes.
24 public func label(_ candidate: String) -> String {
25 if kind == .snippet, let snippet = snippets.first(where: { $0.trigger == candidate }), snippet.name != candidate {
26 return candidate + " " + snippet.name
27 }
28 guard kind == .template, let value = OrgCompletion.templateKeys(templates).first(where: { "<" + $0.key == candidate })?.value else { return candidate }
29 return candidate + " " + value
30 }
31
32 /// Text to insert for `candidate`, and where the caret goes in it.
33 public func insertion(_ candidate: String) -> (text: String, caret: Int) {
34 guard kind == .template, let expansion = OrgCompletion.templateExpansion(candidate, templates: templates) else { return (candidate, candidate.utf16.count) }
35 return expansion
36 }
37}
38
39public enum OrgCompletion {
40 public static func at(_ context: EditContext) -> Completion? {
41 let org = orgAt(context)
42 if let org, !org.candidates.isEmpty { return org }
43 return snippets(context) ?? org
44 }
45
46 /// Snippet triggers starting with the text from the last blank to the caret.
47 static func snippets(_ context: EditContext) -> Completion? {
48 let snippets = context.options.snippets.filter { !$0.file }
49 guard !snippets.isEmpty else { return nil }
50 let ns = context.text as NSString
51 let caret = min(context.caret, ns.length)
52 var start = caret
53 while start > 0, let scalar = UnicodeScalar(ns.character(at: start - 1)), !CharacterSet.whitespacesAndNewlines.contains(scalar) { start -= 1 }
54 guard start < caret else { return nil }
55 let typed = ns.substring(with: NSRange(location: start, length: caret - start))
56 let matching = snippets.filter { $0.trigger.hasPrefix(typed) }
57 guard !matching.isEmpty else { return nil }
58 return Completion(kind: .snippet, range: start..<caret, candidates: matching.map(\.trigger).sorted { $0.localizedStandardCompare($1) == .orderedAscending }, snippets: matching)
59 }
60
61 static func orgAt(_ context: EditContext) -> Completion? {
62 let ns = context.text as NSString
63 let caret = min(context.caret, ns.length)
64 let lineRange = ns.lineRange(for: NSRange(location: caret, length: 0))
65 var contentsEnd = 0
66 ns.getLineStart(nil, end: nil, contentsEnd: &contentsEnd, for: lineRange)
67 let line = ns.substring(with: NSRange(location: lineRange.location, length: contentsEnd - lineRange.location))
68 let start = lineRange.location
69 let toHere = ns.substring(with: NSRange(location: start, length: caret - start))
70 let afterBlank = ns.substring(with: NSRange(location: caret, length: contentsEnd - caret)).allSatisfy { $0 == " " || $0 == "\t" }
71 /// `pcomplete`'s current argument: from the last blank or `[` on the line to the caret.
72 let argStart: Int = {
73 var p = caret
74 while p > start, ![32, 9, 91].contains(ns.character(at: p - 1)) { p -= 1 }
75 return p
76 }()
77 func make(_ kind: Completion.Kind, from: Int, _ candidates: [String]) -> Completion {
78 let typed = ns.substring(with: NSRange(location: from, length: caret - from))
79 var seen = Set<String>()
80 let matching = candidates.filter { $0.hasPrefix(typed) && seen.insert($0).inserted }
81 return Completion(kind: kind, range: from..<caret, candidates: matching.sorted { $0.localizedStandardCompare($1) == .orderedAscending })
82 }
83 func matches(_ pattern: String, _ s: String, caseInsensitive: Bool = true) -> NSTextCheckingResult? {
84 let regex = try! NSRegularExpression(pattern: pattern, options: caseInsensitive ? [.caseInsensitive] : [])
85 return regex.firstMatch(in: s, range: NSRange(location: 0, length: (s as NSString).length))
86 }
87 /// Arguments before the current one on the line.
88 func arguments() -> [String] {
89 ns.substring(with: NSRange(location: start, length: argStart - start)).split { " \t[".contains($0) }.map(String.init)
90 }
91
92 // Templates (org-tempo): `<` and a key after only blanks.
93 if let m = matches("^[ \\t]*<[A-Za-z]*$", toHere, caseInsensitive: false) {
94 // The expansion replaces the indentation too.
95 let templates = context.options.structureTemplates ?? StructureTemplate.defaults
96 var completion = make(.template, from: start + (toHere as NSString).range(of: "<").location, templateKeys(templates).map { "<" + $0.key })
97 completion.range = start..<(start + m.range.length)
98 completion.templates = templates
99 return completion
100 }
101 if matches("^[ \\t]*#\\+BEGIN: clocktable[ \\t]", line) != nil {
102 return make(.clocktable, from: argStart, clocktableOptions)
103 }
104 if matches("^[ \\t]*#\\+BEGIN_SRC[ \\t]", line) != nil {
105 return arguments().count == 1 ? make(.srcLanguage, from: argStart, languages) : make(.srcHeader, from: argStart, srcHeaders)
106 }
107 if let m = matches("^[ \\t]*#\\+(\\S+):", line) {
108 let keyword = (line as NSString).substring(with: m.range(at: 1)).lowercased()
109 let arguments = arguments()
110 // The keyword's own text, or (as pcomplete would) nothing past the value.
111 guard argStart >= start + m.range.upperBound else { return nil }
112 let values: [String]
113 switch keyword {
114 case "startup":
115 values = startupOptions.filter { !(arguments.contains("hidestars") && $0 == "showstars") }
116 case "options":
117 values = exportOptions
118 case _ where arguments.count > 1:
119 return nil
120 case "date":
121 let formatter = DateFormatter()
122 formatter.locale = Locale(identifier: "en_US_POSIX")
123 formatter.calendar = context.calendar
124 formatter.timeZone = context.calendar.timeZone
125 formatter.dateFormat = "yyyy-MM-dd EEE"
126 values = ["<" + formatter.string(from: context.now) + ">"]
127 case "exclude_tags": values = ["noexport"]
128 case "select_tags": values = ["export"]
129 case "language": values = ["en"]
130 case "priorities":
131 let p = context.tree.settings.priorities
132 values = ["\(p.highest) \(p.lowest) \(p.default)"]
133 default:
134 return nil
135 }
136 return make(.keywordValue, from: argStart, values)
137 }
138 if matches("^[ \\t]*#\\+[a-zA-Z_]*$", line) != nil, afterBlank {
139 let from = start + NSMaxRange((line as NSString).range(of: "#+"))
140 return make(.keyword, from: from, caseDouble(fileOptions))
141 }
142 // Link abbreviations and types after `[[`.
143 do {
144 var p = caret
145 while p > start, let ch = UnicodeScalar(ns.character(at: p - 1)), CharacterSet(charactersIn: "-_").union(.alphanumerics).contains(ch), ch.isASCII { p -= 1 }
146 if p - 2 >= start, ns.character(at: p - 1) == 91, ns.character(at: p - 2) == 91 {
147 let abbreviations = Links.abbreviations(in: context.tree.settings.setupKeywords + context.text).keys.map { $0 + ":" }
148 return make(.link, from: p, abbreviations + linkTypes.map { $0 + ":" })
149 }
150 }
151 // Entities after `\`.
152 do {
153 var p = caret
154 while p > start, (48...57).contains(ns.character(at: p - 1)) { p -= 1 }
155 while p > start, let ch = UnicodeScalar(ns.character(at: p - 1)), ch.isASCII, CharacterSet.letters.contains(ch) { p -= 1 }
156 if p > start, ns.character(at: p - 1) == 92 {
157 return make(.entity, from: p, Array(OrgEntities.display.keys))
158 }
159 }
160 // Tags at the end of a heading.
161 if let m = matches("^\\*+ (?:.+? )?(:)((?::|[\\p{L}\\p{N}_@#%]+)+)?[ \\t]*$", line, caseInsensitive: false) {
162 let colon = start + m.range(at: 1).location + 1
163 let group = m.range(at: 2)
164 let inGroup = group.location != NSNotFound && caret >= start + group.location && caret <= start + group.location + group.length
165 if inGroup || caret == colon {
166 let typed = ns.substring(with: NSRange(location: colon, length: caret - colon))
167 let from = colon + ((typed as NSString).range(of: ":", options: .backwards).toOptional.map { NSMaxRange($0) } ?? 0)
168 let heading = DocumentModel(tree: context.tree).headings.last { $0.headingRange.lowerBound <= caret }
169 let own = Set(heading?.localTags ?? [])
170 let alist = FastSelection.tagTable(context.tree.settings.setupKeywords + context.text)?.compactMap { item -> String? in
171 if case .option(_, let name) = item { return name }
172 return nil
173 } ?? []
174 let pool = alist.isEmpty ? SetTags.bufferTags(context) + context.knownTags() : alist
175 return make(.tag, from: from, pool.filter { !own.contains($0) }.map { $0 + ":" })
176 }
177 }
178 // TODO keywords on an empty heading.
179 if matches("^\\*+ +\\S*$", toHere, caseInsensitive: false) != nil, afterBlank {
180 let keywords = context.tree.settings.todoSequences.flatMap { $0.active + $0.done }.map(\.name)
181 return make(.todo, from: argStart, keywords)
182 }
183 // Headings after `[[*`.
184 if let star = (toHere as NSString).range(of: "*", options: .backwards).toOptional, star.location >= 2,
185 (toHere as NSString).substring(with: NSRange(location: star.location - 2, length: 2)) == "[[" {
186 let titles = DocumentModel(tree: context.tree).headings.map { Links.normalizedTitle($0.title) }
187 return make(.heading, from: start + star.location + 1, titles)
188 }
189 // Property or drawer names.
190 if matches("^[ \\t]*:\\S*$", toHere, caseInsensitive: false) != nil, afterBlank {
191 let from = start + NSMaxRange((toHere as NSString).range(of: ":"))
192 if let entry = propertyEntry(context, lineStart: start) {
193 return make(.property, from: from, caseDouble(propertyKeys(context).filter { !entry.contains($0) }.map { $0 + ": " }))
194 }
195 return make(.drawer, from: from, caseDouble((["PROPERTIES"] + drawerNames(context.tree)).map { $0 + ":" }))
196 }
197 return nil
198 }
199
200 // MARK: - Sources
201
202 /// Upper and lower case of each, as `org-pcomplete-case-double`.
203 static func caseDouble(_ list: [String]) -> [String] { list.flatMap { [$0.uppercased(), $0.lowercased()] } }
204
205 /// When the line is in a heading's property drawer, the properties the entry already has.
206 static func propertyEntry(_ context: EditContext, lineStart: Int) -> Set<String>? {
207 guard let heading = DocumentModel(tree: context.tree).headings.last(where: { $0.headingRange.lowerBound < lineStart }),
208 let drawer = context.tree.root.descendants().first(where: {
209 $0.kind == .propertyDrawer && $0.range.lowerBound > heading.headingRange.lowerBound && $0.range.contains(lineStart)
210 }) else { return nil }
211 let ns = context.text as NSString
212 // Only on the line after the last property, as `org-pcomplete` checks.
213 var p = drawer.range.lowerBound
214 p = NSMaxRange(ns.lineRange(for: NSRange(location: p, length: 0)))
215 while p < drawer.range.upperBound {
216 let line = ns.substring(with: ns.lineRange(for: NSRange(location: p, length: 0)))
217 guard line.range(of: "^[ \\t]*:\\S+:", options: .regularExpression) != nil, line.range(of: "^[ \\t]*:END:", options: [.regularExpression, .caseInsensitive]) == nil else { break }
218 p = NSMaxRange(ns.lineRange(for: NSRange(location: p, length: 0)))
219 }
220 guard p == lineStart else { return nil }
221 return Set(heading.properties.map { $0.key.uppercased() } + ["CATEGORY"])
222 }
223
224 /// `org-buffer-property-keys` with defaults and column keys.
225 static func propertyKeys(_ context: EditContext) -> [String] {
226 var keys: [String] = []
227 for heading in DocumentModel(tree: context.tree).headings {
228 for property in heading.properties {
229 keys.append(property.key)
230 if property.key.uppercased().hasSuffix("_ALL") { keys.append(String(property.key.dropLast(4))) }
231 }
232 }
233 let ns = context.text as NSString
234 let columnLines = try! NSRegularExpression(pattern: "^[ \\t]*#\\+COLUMNS:(.*)$|^[ \\t]*:COLUMNS:(.*)$", options: [.anchorsMatchLines, .caseInsensitive])
235 let columns = columnLines.matches(in: context.text, range: NSRange(location: 0, length: ns.length)).map {
236 ns.substring(with: $0.range(at: 1).location != NSNotFound ? $0.range(at: 1) : $0.range(at: 2))
237 }
238 for spec in columns {
239 for m in try! NSRegularExpression(pattern: "%[0-9]*([-\\w]+)").matches(in: spec, range: NSRange(location: 0, length: (spec as NSString).length)) {
240 keys.append((spec as NSString).substring(with: m.range(at: 1)))
241 }
242 }
243 return keys + defaultProperties + ["EFFORT"]
244 }
245
246 static func drawerNames(_ tree: OrgTree) -> [String] {
247 let ns = tree.text as NSString
248 return tree.root.descendants().filter { $0.kind == .drawer }.compactMap { node in
249 let first = ns.substring(with: ns.lineRange(for: NSRange(location: node.range.lowerBound, length: 0)))
250 return first.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: CharacterSet(charactersIn: ":"))
251 }
252 }
253
254 /// `org-tempo-keywords-alist`.
255 static let keywordKeys: [(key: String, value: String)] = [("L", "latex"), ("H", "html"), ("A", "ascii"), ("i", "index")]
256
257 /// org-tempo's keys: the block templates', then the keywords'.
258 static func templateKeys(_ templates: [StructureTemplate]) -> [(key: String, value: String)] {
259 templates.map { ($0.key, $0.type) } + keywordKeys
260 }
261
262 /// org-tempo's expansion of `<key`: a block, or for keywords a `#+key: ` line.
263 static func templateExpansion(_ candidate: String, templates: [StructureTemplate]) -> (text: String, caret: Int)? {
264 let key = String(candidate.dropFirst())
265 let keys = templateKeys(templates)
266 guard let index = keys.firstIndex(where: { $0.key == key }) else { return nil }
267 let value = keys[index].value
268 if index >= templates.count {
269 let text = "#+\(value): "
270 return (text, text.utf16.count)
271 }
272 let name = value.split(separator: " ").first.map(String.init) ?? value
273 let begin = "#+begin_\(value)" + (["src", "export"].contains(value) ? " " : "")
274 return (begin + "\n#+end_\(name)", begin.utf16.count)
275 }
276}
277
278private extension NSRange {
279 var toOptional: NSRange? { location == NSNotFound ? nil : self }
280}