Sources/OrgCore/Completion/OrgCompletion.swift
353 lines · 20729 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. Headings after `[[id:`, notes after `[[denote:` and
7// property values come from the buffer at once and from the index when it answers
8// `Completion.query`.
9
10public struct Completion: Sendable, Equatable {
11 public enum Kind: String, Sendable {
12 case keyword, keywordValue, link, entity, tag, todo, heading, drawer, property, srcLanguage, srcHeader, clocktable, template, snippet
13 case idLink, denoteLink, propertyValue, word
14 }
15
16 public var kind: Kind
17 /// The text the chosen candidate replaces: from the start of what's typed to the caret.
18 public var range: Range<Int>
19 /// Candidates matching what's typed: starting with it, sorted, or with fuzzy matching,
20 /// best first.
21 public var candidates: [String]
22 /// What's typed: the text of `range`.
23 public var typed = ""
24 /// More candidates to ask the index for; nil when there are none.
25 public var query: CompletionQuery?
26 /// For links, the item behind each candidate, and every item found.
27 public var items: [CompletionItem] = []
28 public var targets: [CompletionItem] = []
29 /// Candidates before matching, for words and property values.
30 public var pool: [String] = []
31 /// For links, the text inserting a candidate replaces: the link typed so far.
32 public var link: Range<Int>?
33 /// The block templates `<` completes, for `.template`.
34 public var templates: [StructureTemplate] = []
35 /// The snippets whose triggers are the candidates, for `.snippet`; choosing one expands it.
36 public var snippets: [Snippet] = []
37
38 /// How the list shows `candidate`: a template with the block it makes.
39 public func label(_ candidate: String) -> String {
40 if kind == .idLink || kind == .denoteLink, let item = item(candidate), candidate == item.title, !item.path.isEmpty {
41 return candidate + " " + (item.path as NSString).lastPathComponent
42 }
43 if kind == .snippet, let snippet = snippets.first(where: { $0.trigger == candidate }), snippet.name != candidate {
44 return candidate + " " + snippet.name
45 }
46 guard kind == .template, let value = OrgCompletion.templateKeys(templates).first(where: { "<" + $0.key == candidate })?.value else { return candidate }
47 return candidate + " " + value
48 }
49
50 /// Text to insert for `candidate`, and where the caret goes in it.
51 public func insertion(_ candidate: String) -> (text: String, caret: Int) {
52 guard kind == .template, let expansion = OrgCompletion.templateExpansion(candidate, templates: templates) else { return (candidate, candidate.utf16.count) }
53 return expansion
54 }
55}
56
57public enum OrgCompletion {
58 public static func at(_ context: EditContext) -> Completion? {
59 let org = orgAt(context)
60 if let org, !org.candidates.isEmpty || org.query != nil { return org }
61 return snippets(context) ?? org
62 }
63
64 /// `candidates` matching `typed`, each once: those starting with it, or with `fuzzy`,
65 /// those with its characters in order, best first, preferring matches in its case.
66 /// `sorted` puts the prefix matches, and fuzzy matches scoring the same, in order.
67 public static func matching(_ candidates: [String], _ typed: String, fuzzy: Bool, ignoringCase: Bool = false, sorted: Bool = true) -> [String] {
68 var seen = Set<String>()
69 let unique = candidates.filter { seen.insert($0).inserted }
70 let byName: (String, String) -> Bool = { $0.localizedStandardCompare($1) == .orderedAscending }
71 guard fuzzy, !typed.isEmpty else {
72 let lowered = typed.lowercased()
73 let prefixed = unique.filter { ignoringCase ? $0.lowercased().hasPrefix(lowered) : $0.hasPrefix(typed) }
74 return sorted ? prefixed.sorted(by: byName) : prefixed
75 }
76 let sameCase = unique.filter { isSubsequence(typed, of: $0) }
77 let pool = sameCase.isEmpty ? unique : sameCase
78 let scored = pool.enumerated().compactMap { index, candidate in FuzzyMatch.score(typed, candidate).map { (candidate, $0, index) } }
79 return scored.sorted { a, b in
80 if a.1 != b.1 { return a.1 > b.1 }
81 return sorted ? byName(a.0, b.0) : a.2 < b.2
82 }.map(\.0)
83 }
84
85 static func isSubsequence(_ typed: String, of candidate: String) -> Bool {
86 var rest = typed[...]
87 for c in candidate where rest.first == c { rest = rest.dropFirst() }
88 return rest.isEmpty
89 }
90
91 /// Snippet triggers starting with the text from the last blank to the caret.
92 static func snippets(_ context: EditContext) -> Completion? {
93 let snippets = context.options.snippets.filter { !$0.file }
94 guard !snippets.isEmpty else { return nil }
95 let ns = context.text as NSString
96 let caret = min(context.caret, ns.length)
97 var start = caret
98 while start > 0, let scalar = UnicodeScalar(ns.character(at: start - 1)), !CharacterSet.whitespacesAndNewlines.contains(scalar) { start -= 1 }
99 guard start < caret else { return nil }
100 let typed = ns.substring(with: NSRange(location: start, length: caret - start))
101 let triggers = matching(snippets.map(\.trigger), typed, fuzzy: context.options.completion.fuzzy)
102 guard !triggers.isEmpty else { return nil }
103 var completion = Completion(kind: .snippet, range: start..<caret, candidates: triggers, snippets: snippets.filter { triggers.contains($0.trigger) })
104 completion.typed = typed
105 return completion
106 }
107
108 static func orgAt(_ context: EditContext) -> Completion? {
109 let ns = context.text as NSString
110 let caret = min(context.caret, ns.length)
111 let lineRange = ns.lineRange(for: NSRange(location: caret, length: 0))
112 var contentsEnd = 0
113 ns.getLineStart(nil, end: nil, contentsEnd: &contentsEnd, for: lineRange)
114 let line = ns.substring(with: NSRange(location: lineRange.location, length: contentsEnd - lineRange.location))
115 let start = lineRange.location
116 let toHere = ns.substring(with: NSRange(location: start, length: caret - start))
117 let afterBlank = ns.substring(with: NSRange(location: caret, length: contentsEnd - caret)).allSatisfy { $0 == " " || $0 == "\t" }
118 /// `pcomplete`'s current argument: from the last blank or `[` on the line to the caret.
119 let argStart: Int = {
120 var p = caret
121 while p > start, ![32, 9, 91].contains(ns.character(at: p - 1)) { p -= 1 }
122 return p
123 }()
124 func make(_ kind: Completion.Kind, from: Int, _ candidates: [String]) -> Completion {
125 let typed = ns.substring(with: NSRange(location: from, length: caret - from))
126 var completion = Completion(kind: kind, range: from..<caret, candidates: matching(candidates, typed, fuzzy: context.options.completion.fuzzy))
127 completion.typed = typed
128 return completion
129 }
130 func matches(_ pattern: String, _ s: String, caseInsensitive: Bool = true) -> NSTextCheckingResult? {
131 let regex = try! NSRegularExpression(pattern: pattern, options: caseInsensitive ? [.caseInsensitive] : [])
132 return regex.firstMatch(in: s, range: NSRange(location: 0, length: (s as NSString).length))
133 }
134 /// Arguments before the current one on the line.
135 func arguments() -> [String] {
136 ns.substring(with: NSRange(location: start, length: argStart - start)).split { " \t[".contains($0) }.map(String.init)
137 }
138
139 // Templates (org-tempo): `<` and a key after only blanks.
140 if let m = matches("^[ \\t]*<[A-Za-z]*$", toHere, caseInsensitive: false) {
141 // The expansion replaces the indentation too.
142 let templates = context.options.structureTemplates ?? StructureTemplate.defaults
143 var completion = make(.template, from: start + (toHere as NSString).range(of: "<").location, templateKeys(templates).map { "<" + $0.key })
144 completion.range = start..<(start + m.range.length)
145 completion.templates = templates
146 return completion
147 }
148 if matches("^[ \\t]*#\\+BEGIN: clocktable[ \\t]", line) != nil {
149 return make(.clocktable, from: argStart, clocktableOptions)
150 }
151 if matches("^[ \\t]*#\\+BEGIN_SRC[ \\t]", line) != nil {
152 return arguments().count == 1 ? make(.srcLanguage, from: argStart, languages) : make(.srcHeader, from: argStart, srcHeaders)
153 }
154 if let m = matches("^[ \\t]*#\\+(\\S+):", line) {
155 let keyword = (line as NSString).substring(with: m.range(at: 1)).lowercased()
156 let arguments = arguments()
157 // The keyword's own text, or (as pcomplete would) nothing past the value.
158 guard argStart >= start + m.range.upperBound else { return nil }
159 let values: [String]
160 switch keyword {
161 case "startup":
162 values = startupOptions.filter { !(arguments.contains("hidestars") && $0 == "showstars") }
163 case "options":
164 values = exportOptions
165 case _ where arguments.count > 1:
166 return nil
167 case "date":
168 let formatter = DateFormatter()
169 formatter.locale = Locale(identifier: "en_US_POSIX")
170 formatter.calendar = context.calendar
171 formatter.timeZone = context.calendar.timeZone
172 formatter.dateFormat = "yyyy-MM-dd EEE"
173 values = ["<" + formatter.string(from: context.now) + ">"]
174 case "exclude_tags": values = ["noexport"]
175 case "select_tags": values = ["export"]
176 case "language": values = ["en"]
177 case "priorities":
178 let p = context.tree.settings.priorities
179 values = ["\(p.highest) \(p.lowest) \(p.default)"]
180 default:
181 return nil
182 }
183 return make(.keywordValue, from: argStart, values)
184 }
185 if matches("^[ \\t]*#\\+[a-zA-Z_]*$", line) != nil, afterBlank {
186 let from = start + NSMaxRange((line as NSString).range(of: "#+"))
187 return make(.keyword, from: from, caseDouble(fileOptions))
188 }
189 // Headings after `[[id:`, Denote's notes after `[[denote:`.
190 if let target = linkTarget(context, lineStart: start, toHere: toHere) {
191 var completion = Completion(kind: target.type == "id" ? .idLink : .denoteLink, range: target.typed, candidates: [])
192 completion.typed = ns.substring(with: NSRange(target.typed))
193 completion.link = target.link
194 completion.setItems(target.type == "id" ? bufferTargets(context) : [], fuzzy: context.options.completion.fuzzy)
195 completion.query = target.type == "id" ? .linkTargets : .denoteNotes
196 return completion
197 }
198 // Link abbreviations and types after `[[`.
199 do {
200 var p = caret
201 while p > start, let ch = UnicodeScalar(ns.character(at: p - 1)), CharacterSet(charactersIn: "-_").union(.alphanumerics).contains(ch), ch.isASCII { p -= 1 }
202 if p - 2 >= start, ns.character(at: p - 1) == 91, ns.character(at: p - 2) == 91 {
203 let abbreviations = Links.abbreviations(in: context.tree.settings.setupKeywords + context.text).keys.map { $0 + ":" }
204 return make(.link, from: p, abbreviations + linkTypes.map { $0 + ":" })
205 }
206 }
207 // Entities after `\`.
208 do {
209 var p = caret
210 while p > start, (48...57).contains(ns.character(at: p - 1)) { p -= 1 }
211 while p > start, let ch = UnicodeScalar(ns.character(at: p - 1)), ch.isASCII, CharacterSet.letters.contains(ch) { p -= 1 }
212 if p > start, ns.character(at: p - 1) == 92 {
213 return make(.entity, from: p, Array(OrgEntities.display.keys))
214 }
215 }
216 // Tags at the end of a heading.
217 if let m = matches("^\\*+ (?:.+? )?(:)((?::|[\\p{L}\\p{N}_@#%]+)+)?[ \\t]*$", line, caseInsensitive: false) {
218 let colon = start + m.range(at: 1).location + 1
219 let group = m.range(at: 2)
220 let inGroup = group.location != NSNotFound && caret >= start + group.location && caret <= start + group.location + group.length
221 if inGroup || caret == colon {
222 let typed = ns.substring(with: NSRange(location: colon, length: caret - colon))
223 let from = colon + ((typed as NSString).range(of: ":", options: .backwards).toOptional.map { NSMaxRange($0) } ?? 0)
224 let heading = DocumentModel(tree: context.tree).headings.last { $0.headingRange.lowerBound <= caret }
225 let own = Set(heading?.localTags ?? [])
226 let alist = FastSelection.tagTable(context.tree.settings.setupKeywords + context.text)?.compactMap { item -> String? in
227 if case .option(_, let name) = item { return name }
228 return nil
229 } ?? []
230 let pool = alist.isEmpty ? SetTags.bufferTags(context) + context.knownTags() : alist
231 return make(.tag, from: from, pool.filter { !own.contains($0) }.map { $0 + ":" })
232 }
233 }
234 // TODO keywords on an empty heading.
235 if matches("^\\*+ +\\S*$", toHere, caseInsensitive: false) != nil, afterBlank {
236 let keywords = context.tree.settings.todoSequences.flatMap { $0.active + $0.done }.map(\.name)
237 return make(.todo, from: argStart, keywords)
238 }
239 // Headings after `[[*`.
240 if let star = (toHere as NSString).range(of: "*", options: .backwards).toOptional, star.location >= 2,
241 (toHere as NSString).substring(with: NSRange(location: star.location - 2, length: 2)) == "[[" {
242 let titles = DocumentModel(tree: context.tree).headings.map { Links.normalizedTitle($0.title) }
243 return make(.heading, from: start + star.location + 1, titles)
244 }
245 // Values of a property in a property drawer.
246 if let m = toHere.firstMatch(of: /^[ \t]*:([^\s:]+):[ \t]+(\S*)$/),
247 context.tree.root.descendants().contains(where: { $0.kind == .propertyDrawer && $0.range.contains(start) }) {
248 let name = String(m.1).hasSuffix("+") ? String(m.1.dropLast()) : String(m.1)
249 guard name.uppercased() != "END", !name.uppercased().hasSuffix("_ALL") else { return nil }
250 let from = caret - String(m.2).utf16.count
251 var completion = Completion(kind: .propertyValue, range: from..<caret, candidates: [])
252 completion.typed = String(m.2)
253 // The value on this line is what's being typed, not a candidate.
254 var values = bufferValues(name, context)
255 let own = ns.substring(with: NSRange(location: from, length: contentsEnd - from)).trimmingCharacters(in: .whitespaces)
256 if let index = values.lastIndex(of: own) { values.remove(at: index) }
257 completion.pool = values
258 completion.candidates = matching(completion.pool, completion.typed, fuzzy: context.options.completion.fuzzy, ignoringCase: true, sorted: false)
259 completion.query = .propertyValues(name)
260 return completion
261 }
262 // Property or drawer names.
263 if matches("^[ \\t]*:\\S*$", toHere, caseInsensitive: false) != nil, afterBlank {
264 let from = start + NSMaxRange((toHere as NSString).range(of: ":"))
265 if let entry = propertyEntry(context, lineStart: start) {
266 return make(.property, from: from, caseDouble(propertyKeys(context).filter { !entry.contains($0) }.map { $0 + ": " }))
267 }
268 return make(.drawer, from: from, caseDouble((["PROPERTIES"] + drawerNames(context.tree)).map { $0 + ":" }))
269 }
270 return nil
271 }
272
273 // MARK: - Sources
274
275 /// Upper and lower case of each, as `org-pcomplete-case-double`.
276 static func caseDouble(_ list: [String]) -> [String] { list.flatMap { [$0.uppercased(), $0.lowercased()] } }
277
278 /// When the line is in a heading's property drawer, the properties the entry already has.
279 static func propertyEntry(_ context: EditContext, lineStart: Int) -> Set<String>? {
280 guard let heading = DocumentModel(tree: context.tree).headings.last(where: { $0.headingRange.lowerBound < lineStart }),
281 let drawer = context.tree.root.descendants().first(where: {
282 $0.kind == .propertyDrawer && $0.range.lowerBound > heading.headingRange.lowerBound && $0.range.contains(lineStart)
283 }) else { return nil }
284 let ns = context.text as NSString
285 // Only on the line after the last property, as `org-pcomplete` checks.
286 var p = drawer.range.lowerBound
287 p = NSMaxRange(ns.lineRange(for: NSRange(location: p, length: 0)))
288 while p < drawer.range.upperBound {
289 let line = ns.substring(with: ns.lineRange(for: NSRange(location: p, length: 0)))
290 guard line.range(of: "^[ \\t]*:\\S+:", options: .regularExpression) != nil, line.range(of: "^[ \\t]*:END:", options: [.regularExpression, .caseInsensitive]) == nil else { break }
291 p = NSMaxRange(ns.lineRange(for: NSRange(location: p, length: 0)))
292 }
293 guard p == lineStart else { return nil }
294 return Set(heading.properties.map { $0.key.uppercased() } + ["CATEGORY"])
295 }
296
297 /// `org-buffer-property-keys` with defaults and column keys.
298 static func propertyKeys(_ context: EditContext) -> [String] {
299 var keys: [String] = []
300 for heading in DocumentModel(tree: context.tree).headings {
301 for property in heading.properties {
302 keys.append(property.key)
303 if property.key.uppercased().hasSuffix("_ALL") { keys.append(String(property.key.dropLast(4))) }
304 }
305 }
306 let ns = context.text as NSString
307 let columnLines = try! NSRegularExpression(pattern: "^[ \\t]*#\\+COLUMNS:(.*)$|^[ \\t]*:COLUMNS:(.*)$", options: [.anchorsMatchLines, .caseInsensitive])
308 let columns = columnLines.matches(in: context.text, range: NSRange(location: 0, length: ns.length)).map {
309 ns.substring(with: $0.range(at: 1).location != NSNotFound ? $0.range(at: 1) : $0.range(at: 2))
310 }
311 for spec in columns {
312 for m in try! NSRegularExpression(pattern: "%[0-9]*([-\\w]+)").matches(in: spec, range: NSRange(location: 0, length: (spec as NSString).length)) {
313 keys.append((spec as NSString).substring(with: m.range(at: 1)))
314 }
315 }
316 return keys + defaultProperties + ["EFFORT"]
317 }
318
319 static func drawerNames(_ tree: OrgTree) -> [String] {
320 let ns = tree.text as NSString
321 return tree.root.descendants().filter { $0.kind == .drawer }.compactMap { node in
322 let first = ns.substring(with: ns.lineRange(for: NSRange(location: node.range.lowerBound, length: 0)))
323 return first.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: CharacterSet(charactersIn: ":"))
324 }
325 }
326
327 /// `org-tempo-keywords-alist`.
328 static let keywordKeys: [(key: String, value: String)] = [("L", "latex"), ("H", "html"), ("A", "ascii"), ("i", "index")]
329
330 /// org-tempo's keys: the block templates', then the keywords'.
331 static func templateKeys(_ templates: [StructureTemplate]) -> [(key: String, value: String)] {
332 templates.map { ($0.key, $0.type) } + keywordKeys
333 }
334
335 /// org-tempo's expansion of `<key`: a block, or for keywords a `#+key: ` line.
336 static func templateExpansion(_ candidate: String, templates: [StructureTemplate]) -> (text: String, caret: Int)? {
337 let key = String(candidate.dropFirst())
338 let keys = templateKeys(templates)
339 guard let index = keys.firstIndex(where: { $0.key == key }) else { return nil }
340 let value = keys[index].value
341 if index >= templates.count {
342 let text = "#+\(value): "
343 return (text, text.utf16.count)
344 }
345 let name = value.split(separator: " ").first.map(String.init) ?? value
346 let begin = "#+begin_\(value)" + (["src", "export"].contains(value) ? " " : "")
347 return (begin + "\n#+end_\(name)", begin.utf16.count)
348 }
349}
350
351private extension NSRange {
352 var toOptional: NSRange? { location == NSNotFound ? nil : self }
353}