Sources/OrgCore/Completion/OrgCompletion.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/OrgCore/Completion/OrgCompletion.swift history · blame · raw

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