Sources/OrgCore/Completion/Dabbrev.swift
198 lines · 10291 bytes
1import Foundation
2
3/// `dabbrev-expand` with Emacs's defaults: the word before the caret completed from words that
4/// start with it, ignoring case, in the buffer (before the caret nearest first, then after it
5/// nearest first), then in the other open buffers from their start, then in the index. Each
6/// expansion is offered once; its case follows the abbreviation's as
7/// `dabbrev--substitute-expansion` makes it.
8public enum Dabbrev {
9 /// Word and symbol constituents of Org's syntax table: letters, digits and `$%'&*+-/=\_|~`.
10 static let wordClass = "[\\p{L}\\p{M}\\p{N}$%'&*+\\-/=\\\\_|~]"
11
12 static func isWordCharacter(_ c: unichar) -> Bool {
13 if c < 128 {
14 guard let scalar = UnicodeScalar(c) else { return false }
15 return CharacterSet.alphanumerics.contains(scalar) || "$%'&*+-/=\\_|~".unicodeScalars.contains(scalar)
16 }
17 guard let scalar = UnicodeScalar(c) else { return true }
18 return CharacterSet.letters.union(.decimalDigits).union(.nonBaseCharacters).contains(scalar)
19 }
20
21 /// The abbreviation before `caret`: back to the start of its word. Nil when the character
22 /// before the caret isn't part of a word.
23 public static func abbreviation(in text: String, caret: Int) -> Range<Int>? {
24 let ns = text as NSString
25 let caret = min(caret, ns.length)
26 var start = caret
27 while start > 0, isWordCharacter(ns.character(at: start - 1)) { start -= 1 }
28 return start < caret ? start..<caret : nil
29 }
30
31 /// Words starting with `abbrev`, ignoring case, that are longer than it, in `text`, with
32 /// where they start.
33 static func words(_ abbrev: String, in text: String) -> [(start: Int, word: String)] {
34 let pattern = "(?<!\(wordClass))" + NSRegularExpression.escapedPattern(for: abbrev) + "\(wordClass)+"
35 guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else { return [] }
36 let ns = text as NSString
37 return regex.matches(in: text, range: NSRange(location: 0, length: ns.length)).map { ($0.range.location, ns.substring(with: $0.range)) }
38 }
39
40 /// Expansions in the buffer: words before `start` nearest first, then words from `end`
41 /// on nearest first, as typed in the buffer.
42 public static func expansions(of abbrev: String, in text: String, before start: Int, after end: Int) -> [String] {
43 let found = words(abbrev, in: text)
44 return unique(found.filter { $0.start < start }.reversed().map(\.word) + found.filter { $0.start >= end }.map(\.word))
45 }
46
47 /// Expansions in another buffer, from its start.
48 public static func expansions(of abbrev: String, in text: String) -> [String] {
49 unique(words(abbrev, in: text).map(\.word))
50 }
51
52 /// The first of each set equal ignoring case.
53 public static func unique(_ words: [String], excluding: Set<String> = []) -> [String] {
54 var seen = excluding
55 return words.filter { seen.insert($0.lowercased()).inserted }
56 }
57
58 /// The text that replaces `old` (the abbreviation, or the expansion inserted before on a
59 /// repeat): `expansion` with its case made to follow `abbrev`'s, unless the expansion has
60 /// mixed case or the abbreviation does and the expansion starts with it as typed.
61 public static func substitute(_ expansion: String, for abbrev: String, replacing old: String) -> String {
62 guard let firstLetter = abbrev.firstIndex(where: \.isLetter) else { return expansion }
63 let rest = String(expansion.dropFirst())
64 let restOneCase = rest == rest.lowercased() || rest == rest.uppercased()
65 let lettersAfterFirst = abbrev.distance(from: firstLetter, to: abbrev.endIndex)
66 let abbrevOneCase = abbrev == abbrev.lowercased() || (abbrev == abbrev.uppercased() && lettersAfterFirst > 1)
67 if !(restOneCase && abbrevOneCase), expansion.hasPrefix(abbrev) { return expansion }
68 return caseLike(old, expansion.lowercased())
69 }
70
71 /// `replace-match`'s case conversion: `text` in capitals when `old` is all capitals with a
72 /// word of more than one letter, with capital initials when every word of `old` starts
73 /// with a capital, else as it is.
74 static func caseLike(_ old: String, _ text: String) -> String {
75 let words = old.split { !$0.isLetter && !$0.isNumber }
76 guard old.contains(where: \.isUppercase) else { return text }
77 if !old.contains(where: \.isLowercase) {
78 return words.contains(where: { $0.filter(\.isLetter).count > 1 }) ? text.uppercased() : capitalized(text)
79 }
80 let initialsCapital = words.allSatisfy { word in word.first { $0.isLetter }.map(\.isUppercase) ?? true }
81 return initialsCapital ? capitalized(text) : text
82 }
83
84 /// The first letter of each word in capitals (`upcase-initials`).
85 static func capitalized(_ text: String) -> String {
86 var out = ""
87 var inWord = false
88 for c in text {
89 let wordCharacter = c.isLetter || c.isNumber
90 out += !inWord && wordCharacter ? c.uppercased() : String(c)
91 inWord = wordCharacter
92 }
93 return out
94 }
95
96 /// The words that complete the one before the caret, from the buffer and `others` (the
97 /// other open buffers' text), as they would be inserted, with the index to ask for more.
98 public static func completion(_ context: EditContext, others: [String] = []) -> Completion? {
99 guard let range = abbreviation(in: context.text, caret: context.caret) else { return nil }
100 let abbrev = (context.text as NSString).substring(with: NSRange(range))
101 let found = unique(expansions(of: abbrev, in: context.text, before: range.lowerBound, after: range.upperBound) + others.flatMap { expansions(of: abbrev, in: $0) })
102 var completion = Completion(kind: .word, range: range, candidates: candidates(found, abbrev: abbrev))
103 completion.typed = abbrev
104 completion.pool = found
105 completion.query = .words(abbrev)
106 return completion
107 }
108
109 /// A word completion after more is typed: the expansions found when it opened that
110 /// still start with the abbreviation.
111 public static func narrowed(_ completion: Completion, to range: Range<Int>, in text: String) -> Completion {
112 var narrowed = completion
113 let abbrev = (text as NSString).substring(with: NSRange(range))
114 narrowed.range = range
115 narrowed.typed = abbrev
116 narrowed.candidates = candidates(completion.pool.filter { $0.lowercased().hasPrefix(abbrev.lowercased()) && $0.count > abbrev.count }, abbrev: abbrev)
117 return narrowed
118 }
119
120 /// `completion` with words the index found added after the buffers'.
121 public static func adding(_ words: [String], to completion: Completion) -> Completion {
122 var added = completion
123 added.pool += unique(words, excluding: Set(completion.pool.map { $0.lowercased() } + [completion.typed.lowercased()]))
124 added.candidates = candidates(added.pool, abbrev: completion.typed)
125 added.query = nil
126 return added
127 }
128
129 /// `expansions` as inserted in place of `abbrev`, each once.
130 public static func candidates(_ expansions: [String], abbrev: String) -> [String] {
131 var seen = Set<String>()
132 return expansions.map { substitute($0, for: abbrev, replacing: abbrev) }.filter { seen.insert($0).inserted }
133 }
134
135 /// Words starting with `prefix`, ignoring case, in `texts` in order: what the index adds.
136 public static func words(_ prefix: String, in texts: [String], limit: Int = 50) -> [String] {
137 var result: [String] = []
138 var seen = Set<String>()
139 for text in texts {
140 for (_, word) in words(prefix, in: text) where seen.insert(word.lowercased()).inserted {
141 result.append(word)
142 if result.count == limit { return result }
143 }
144 }
145 return result
146 }
147}
148
149/// `dabbrev-expand` repeated: each call replaces what the last inserted with the next
150/// expansion; past the last, the abbreviation comes back.
151public struct DabbrevExpansion: Sendable, Equatable {
152 /// Where the abbreviation starts.
153 public let start: Int
154 public let abbrev: String
155 /// Expansions as found, the index's added when they arrive.
156 public private(set) var expansions: [String]
157 /// The next expansion to use.
158 public private(set) var next = 0
159 /// What is between `start` and the caret now.
160 public private(set) var inserted: String
161
162 public init?(_ context: EditContext, others: [String] = []) {
163 guard let range = Dabbrev.abbreviation(in: context.text, caret: context.caret) else { return nil }
164 start = range.lowerBound
165 let abbrev = (context.text as NSString).substring(with: NSRange(range))
166 self.abbrev = abbrev
167 inserted = abbrev
168 expansions = Dabbrev.unique(Dabbrev.expansions(of: abbrev, in: context.text, before: range.lowerBound, after: range.upperBound)
169 + others.flatMap { Dabbrev.expansions(of: abbrev, in: $0) })
170 }
171
172 public var end: Int { start + inserted.utf16.count }
173
174 /// Adds expansions found later (the index's), leaving out those already found.
175 public mutating func add(_ more: [String]) {
176 expansions += Dabbrev.unique(more, excluding: Set(expansions.map { $0.lowercased() } + [abbrev.lowercased()]))
177 }
178
179 /// The edit for the next expansion, or for the abbreviation again when there is none
180 /// left; `exhausted` says which.
181 public mutating func advance() -> (edit: TextEdit, exhausted: Bool) {
182 let range = start..<end
183 guard next < expansions.count else {
184 inserted = abbrev
185 next = expansions.count + 1
186 return (TextEdit(range: range, replacement: abbrev), true)
187 }
188 let text = Dabbrev.substitute(expansions[next], for: abbrev, replacing: inserted)
189 next += 1
190 inserted = text
191 return (TextEdit(range: range, replacement: text), false)
192 }
193
194 /// What the echo area says when nothing is inserted.
195 public var failure: String {
196 expansions.isEmpty ? "No dynamic expansion for `\(abbrev)' found" : "No further dynamic expansion for `\(abbrev)' found"
197 }
198}