Sources/OrgCore/Completion/OrgCompletion.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgCore/Completion/OrgCompletion.swift

374 lines · 22285 bytes

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form