Completion: opens by itself, fuzzy, words, index !483
5 files changed, +320 −33
Changed files (5)
Sources/OrgApp/FileTree.swift +2 −24 · view
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import Foundation |
| 2 | import OrgCore | |
| 2 | 3 | import OrgIndex |
| 3 | 4 | |
| 4 | 5 | /// One file the workspace knows about. |
| @@ -69,30 +70,7 @@ public struct FileTreeNode: Sendable, Hashable, Identifiable { | ||
| 69 | 70 | } |
| 70 | 71 | } |
| 71 | 72 | |
| 72 | /// Subsequence matching for quick open: every query character must appear in order. Matches | |
| 73 | /// at word starts and runs of consecutive characters score higher; shorter names win ties. | |
| 74 | public enum FuzzyMatch { | |
| 75 | /// What a match at a word start adds, before `score` scales it by 100. | |
| 76 | public static let wordStartBonus = 8 | |
| 77 | ||
| 78 | public static func score(_ query: String, _ candidate: String) -> Int? { | |
| 79 | let query = Array(query.lowercased().filter { !$0.isWhitespace }) | |
| 80 | let text = Array(candidate.lowercased()) | |
| 81 | guard !query.isEmpty else { return 0 } | |
| 82 | var score = 0 | |
| 83 | var q = 0 | |
| 84 | var previousMatch = -2 | |
| 85 | for (i, c) in text.enumerated() where q < query.count && c == query[q] { | |
| 86 | score += 1 | |
| 87 | if i == previousMatch + 1 { score += 5 } | |
| 88 | if i == 0 || "/ -_.".contains(text[i - 1]) { score += wordStartBonus } | |
| 89 | previousMatch = i | |
| 90 | q += 1 | |
| 91 | } | |
| 92 | guard q == query.count else { return nil } | |
| 93 | return score * 100 - text.count | |
| 94 | } | |
| 95 | ||
| 73 | extension FuzzyMatch { | |
| 96 | 74 | /// Entries ranked by `score` against their relative path, best first. |
| 97 | 75 | public static func rank(_ query: String, _ files: [FileEntry], limit: Int = 50) -> [FileEntry] { |
| 98 | 76 | let scored: [(file: FileEntry, score: Int)] = files.compactMap { file in score(query, file.relativePath).map { (file, $0) } } |
Sources/OrgCore/Completion/FuzzyMatch.swift added +26 · view
| @@ -0,0 +1,26 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// Subsequence matching for quick open: every query character must appear in order. Matches | |
| 4 | /// at word starts and runs of consecutive characters score higher; shorter names win ties. | |
| 5 | public enum FuzzyMatch { | |
| 6 | /// What a match at a word start adds, before `score` scales it by 100. | |
| 7 | public static let wordStartBonus = 8 | |
| 8 | ||
| 9 | public static func score(_ query: String, _ candidate: String) -> Int? { | |
| 10 | let query = Array(query.lowercased().filter { !$0.isWhitespace }) | |
| 11 | let text = Array(candidate.lowercased()) | |
| 12 | guard !query.isEmpty else { return 0 } | |
| 13 | var score = 0 | |
| 14 | var q = 0 | |
| 15 | var previousMatch = -2 | |
| 16 | for (i, c) in text.enumerated() where q < query.count && c == query[q] { | |
| 17 | score += 1 | |
| 18 | if i == previousMatch + 1 { score += 5 } | |
| 19 | if i == 0 || "/ -_.".contains(text[i - 1]) { score += wordStartBonus } | |
| 20 | previousMatch = i | |
| 21 | q += 1 | |
| 22 | } | |
| 23 | guard q == query.count else { return nil } | |
| 24 | return score * 100 - text.count | |
| 25 | } | |
| 26 | } | |
Sources/OrgCore/Completion/OrgCompletion.swift +82 −9 · view
| @@ -3,18 +3,33 @@ import Foundation | ||
| 3 | 3 | // Completion at point (Org 9.8.7's org-pcomplete): `org-thing-at-point` picks what the caret |
| 4 | 4 | // is on, and each context offers what its `pcomplete/org-mode/…` function does. Link types |
| 5 | 5 | // after `[[`, workspace tags and org-tempo's `<` templates are added, and snippet triggers |
| 6 | // where no org context offers anything. | |
| 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`. | |
| 7 | 9 | |
| 8 | 10 | public struct Completion: Sendable, Equatable { |
| 9 | 11 | public enum Kind: String, Sendable { |
| 10 | 12 | case keyword, keywordValue, link, entity, tag, todo, heading, drawer, property, srcLanguage, srcHeader, clocktable, template, snippet |
| 13 | case idLink, denoteLink, propertyValue, word | |
| 11 | 14 | } |
| 12 | 15 | |
| 13 | 16 | public var kind: Kind |
| 14 | 17 | /// The text the chosen candidate replaces: from the start of what's typed to the caret. |
| 15 | 18 | public var range: Range<Int> |
| 16 | /// Candidates starting with what's typed, sorted. | |
| 19 | /// Candidates matching what's typed: starting with it, sorted, or with fuzzy matching, | |
| 20 | /// best first. | |
| 17 | 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>? | |
| 18 | 33 | /// The block templates `<` completes, for `.template`. |
| 19 | 34 | public var templates: [StructureTemplate] = [] |
| 20 | 35 | /// The snippets whose triggers are the candidates, for `.snippet`; choosing one expands it. |
| @@ -22,6 +37,9 @@ public struct Completion: Sendable, Equatable { | ||
| 22 | 37 | |
| 23 | 38 | /// How the list shows `candidate`: a template with the block it makes. |
| 24 | 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 | } | |
| 25 | 43 | if kind == .snippet, let snippet = snippets.first(where: { $0.trigger == candidate }), snippet.name != candidate { |
| 26 | 44 | return candidate + " " + snippet.name |
| 27 | 45 | } |
| @@ -39,10 +57,37 @@ public struct Completion: Sendable, Equatable { | ||
| 39 | 57 | public enum OrgCompletion { |
| 40 | 58 | public static func at(_ context: EditContext) -> Completion? { |
| 41 | 59 | let org = orgAt(context) |
| 42 | if let org, !org.candidates.isEmpty { return org } | |
| 60 | if let org, !org.candidates.isEmpty || org.query != nil { return org } | |
| 43 | 61 | return snippets(context) ?? org |
| 44 | 62 | } |
| 45 | 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 | ||
| 46 | 91 | /// Snippet triggers starting with the text from the last blank to the caret. |
| 47 | 92 | static func snippets(_ context: EditContext) -> Completion? { |
| 48 | 93 | let snippets = context.options.snippets.filter { !$0.file } |
| @@ -53,9 +98,11 @@ public enum OrgCompletion { | ||
| 53 | 98 | while start > 0, let scalar = UnicodeScalar(ns.character(at: start - 1)), !CharacterSet.whitespacesAndNewlines.contains(scalar) { start -= 1 } |
| 54 | 99 | guard start < caret else { return nil } |
| 55 | 100 | 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) | |
| 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 | |
| 59 | 106 | } |
| 60 | 107 | |
| 61 | 108 | static func orgAt(_ context: EditContext) -> Completion? { |
| @@ -76,9 +123,9 @@ public enum OrgCompletion { | ||
| 76 | 123 | }() |
| 77 | 124 | func make(_ kind: Completion.Kind, from: Int, _ candidates: [String]) -> Completion { |
| 78 | 125 | 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 }) | |
| 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 | |
| 82 | 129 | } |
| 83 | 130 | func matches(_ pattern: String, _ s: String, caseInsensitive: Bool = true) -> NSTextCheckingResult? { |
| 84 | 131 | let regex = try! NSRegularExpression(pattern: pattern, options: caseInsensitive ? [.caseInsensitive] : []) |
| @@ -139,6 +186,15 @@ public enum OrgCompletion { | ||
| 139 | 186 | let from = start + NSMaxRange((line as NSString).range(of: "#+")) |
| 140 | 187 | return make(.keyword, from: from, caseDouble(fileOptions)) |
| 141 | 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 | } | |
| 142 | 198 | // Link abbreviations and types after `[[`. |
| 143 | 199 | do { |
| 144 | 200 | var p = caret |
| @@ -186,6 +242,23 @@ public enum OrgCompletion { | ||
| 186 | 242 | let titles = DocumentModel(tree: context.tree).headings.map { Links.normalizedTitle($0.title) } |
| 187 | 243 | return make(.heading, from: start + star.location + 1, titles) |
| 188 | 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 | } | |
| 189 | 262 | // Property or drawer names. |
| 190 | 263 | if matches("^[ \\t]*:\\S*$", toHere, caseInsensitive: false) != nil, afterBlank { |
| 191 | 264 | let from = start + NSMaxRange((toHere as NSString).range(of: ":")) |
Sources/OrgstarMobile/SearchScreen.swift +1 · view
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | #if os(iOS) |
| 2 | 2 | import OrgApp |
| 3 | import OrgCore | |
| 3 | 4 | import OrgIndex |
| 4 | 5 | import SwiftUI |
| 5 | 6 | |
Tests/OrgCoreTests/CompletionListTests.swift added +209 · view
| @@ -0,0 +1,209 @@ | ||
| 1 | import Foundation | |
| 2 | import Testing | |
| 3 | @testable import OrgCore | |
| 4 | ||
| 5 | /// The list that opens by itself (#139), fuzzy matching (#140), word completion (#141) and | |
| 6 | /// completion from the index (#143). | |
| 7 | struct CompletionListTests { | |
| 8 | func context(_ text: String, _ caret: Int? = nil, options: EditingOptions = .org) -> EditContext { | |
| 9 | let caret = caret ?? text.utf16.count | |
| 10 | return EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], options: options) | |
| 11 | } | |
| 12 | ||
| 13 | var fuzzy: EditingOptions { | |
| 14 | var options = EditingOptions.org | |
| 15 | options.completion.fuzzy = true | |
| 16 | return options | |
| 17 | } | |
| 18 | ||
| 19 | // MARK: - #139 | |
| 20 | ||
| 21 | @Test func autoOpensOnlyWhenSetAndInInsertState() { | |
| 22 | let off = CompletionOptions() | |
| 23 | #expect(CompletionAuto.delay(off, modal: false, insertState: false, isOrg: true) == nil) | |
| 24 | #expect(CompletionAuto.delay(off, modal: true, insertState: true, isOrg: true) == nil) | |
| 25 | let on = CompletionOptions(auto: true, delay: 0.25, prefix: 3) | |
| 26 | #expect(CompletionAuto.delay(on, modal: false, insertState: false, isOrg: true) == 0.25) | |
| 27 | #expect(CompletionAuto.delay(on, modal: true, insertState: true, isOrg: true) == 0.25) | |
| 28 | #expect(CompletionAuto.delay(on, modal: true, insertState: false, isOrg: true) == nil) | |
| 29 | // Outside org files only words are offered. | |
| 30 | #expect(CompletionAuto.delay(on, modal: false, insertState: false, isOrg: false) == nil) | |
| 31 | #expect(CompletionAuto.delay(CompletionOptions(auto: true, words: true), modal: false, insertState: false, isOrg: false) == 0.4) | |
| 32 | } | |
| 33 | ||
| 34 | @Test func autoOpensOnceEnoughIsTyped() { | |
| 35 | let options = CompletionOptions(auto: true, prefix: 3) | |
| 36 | #expect(!CompletionAuto.opens(OrgCompletion.at(context("#+TI")), options)) | |
| 37 | #expect(CompletionAuto.opens(OrgCompletion.at(context("#+TIT")), options)) | |
| 38 | #expect(!CompletionAuto.opens(OrgCompletion.at(context("#+XYZQ")), options)) | |
| 39 | #expect(!CompletionAuto.opens(nil, options)) | |
| 40 | // An index query opens it before anything is found. | |
| 41 | #expect(CompletionAuto.opens(OrgCompletion.at(context("[[id:abc")), options)) | |
| 42 | } | |
| 43 | ||
| 44 | // MARK: - #140 | |
| 45 | ||
| 46 | @Test func fuzzyMatchesLettersInOrderBestFirst() { | |
| 47 | #expect(OrgCompletion.at(context("#+STARTUP: lgd"))?.candidates == []) | |
| 48 | let found = OrgCompletion.at(context("#+STARTUP: lgd", options: fuzzy))!.candidates | |
| 49 | #expect(found.first == "logdone" && found.contains("lognotedone") && found.contains("nologdone")) | |
| 50 | #expect(found.firstIndex(of: "logdone")! < found.firstIndex(of: "nologdone")!) | |
| 51 | // Word starts and runs rank first; the prefix match beats one inside a word. | |
| 52 | #expect(OrgCompletion.matching(["nofold", "fold", "fnadjust"], "fo", fuzzy: true) == ["fold", "nofold"]) | |
| 53 | // Keywords in the case typed. | |
| 54 | #expect(OrgCompletion.at(context("#+ttl", options: fuzzy))!.candidates.allSatisfy { $0 == $0.lowercased() }) | |
| 55 | #expect(OrgCompletion.at(context("#+ttl", options: fuzzy))!.candidates.contains("title: ")) | |
| 56 | // Prefix matching stays as it was. | |
| 57 | #expect(OrgCompletion.at(context("#+STARTUP: in"))?.candidates == ["indent", "inlineimages"]) | |
| 58 | } | |
| 59 | ||
| 60 | @Test func fuzzyMatchesSnippetTriggers() { | |
| 61 | var options = fuzzy | |
| 62 | options.snippets = [Snippet(trigger: "meeting", name: "Meeting", body: "x"), Snippet(trigger: "todo", name: "Todo", body: "y")] | |
| 63 | #expect(OrgCompletion.at(context("mtg", options: options))?.candidates == ["meeting"]) | |
| 64 | } | |
| 65 | ||
| 66 | @Test func listKeysAndTheCommonPart() { | |
| 67 | var list = CompletionList(OrgCompletion.at(context("#+STARTUP: entities"))!) | |
| 68 | #expect(list.key(KeyChord("TAB")) == .common("entitiesp")) | |
| 69 | #expect(list.key(KeyChord("n", .control)) == .shown && list.selected == "entitiesplain") | |
| 70 | #expect(list.key(KeyChord("p", .control)) == .shown && list.selected == nil) | |
| 71 | #expect(list.key(KeyChord("p", .control)) == .shown && list.selected == "entitiespretty") | |
| 72 | #expect(list.key(KeyChord("RET")) == .insert("entitiespretty")) | |
| 73 | #expect(list.key(KeyChord("g", .control)) == .close) | |
| 74 | #expect(list.key(KeyChord("ESC")) == .closeAndPass) | |
| 75 | // The chosen candidate stays chosen when more arrive. | |
| 76 | list.update(OrgCompletion.at(context("#+STARTUP: e"))!) | |
| 77 | #expect(list.selected == "entitiespretty") | |
| 78 | // Fuzzy candidates that don't start alike don't shorten what's typed. | |
| 79 | let spread = OrgCompletion.at(context("#+STARTUP: nd", options: fuzzy))! | |
| 80 | var fuzzyList = CompletionList(spread) | |
| 81 | #expect(fuzzyList.key(KeyChord("TAB")) == .shown) | |
| 82 | } | |
| 83 | ||
| 84 | // MARK: - #141 | |
| 85 | ||
| 86 | @Test func dabbrevSearchesBackThenForward() { | |
| 87 | let text = "fa fb\nf fc fd" | |
| 88 | let caret = 7 | |
| 89 | #expect(DabbrevExpansion(context(text, caret))?.expansions == ["fb", "fa", "fc", "fd"]) | |
| 90 | #expect(Dabbrev.completion(context(text, caret))?.candidates == ["fb", "fa", "fc", "fd"]) | |
| 91 | // Other buffers after this one, from their start; each word once, ignoring case. | |
| 92 | let more = Dabbrev.completion(context("Foo\nf"), others: ["fun FOO fix"])! | |
| 93 | #expect(more.candidates == ["foo", "fun", "fix"] && more.range == 4..<5 && more.query == .words("f")) | |
| 94 | // Org's word characters. | |
| 95 | #expect(DabbrevExpansion(context("fo_x fo-y fo.z fo'w fo/v fo2\nfo"))?.expansions == ["fo2", "fo/v", "fo'w", "fo-y", "fo_x"]) | |
| 96 | #expect(DabbrevExpansion(context("*bold*\nb"))?.expansions == []) | |
| 97 | #expect(DabbrevExpansion(context("x ")) == nil) | |
| 98 | } | |
| 99 | ||
| 100 | @Test func dabbrevCyclesAndRestores() { | |
| 101 | var expansion = DabbrevExpansion(context("help hello\nhe"))! | |
| 102 | #expect(expansion.advance() == (TextEdit(range: 11..<13, replacement: "hello"), false)) | |
| 103 | #expect(expansion.advance() == (TextEdit(range: 11..<16, replacement: "help"), false)) | |
| 104 | expansion.add(["helmet", "Hello"]) | |
| 105 | #expect(expansion.advance() == (TextEdit(range: 11..<15, replacement: "helmet"), false)) | |
| 106 | #expect(expansion.advance() == (TextEdit(range: 11..<17, replacement: "he"), true)) | |
| 107 | #expect(expansion.failure == "No further dynamic expansion for `he' found") | |
| 108 | } | |
| 109 | ||
| 110 | @Test func dabbrevCase() { | |
| 111 | #expect(Dabbrev.substitute("Hello", for: "he", replacing: "he") == "hello") | |
| 112 | #expect(Dabbrev.substitute("hello", for: "HE", replacing: "HE") == "HELLO") | |
| 113 | #expect(Dabbrev.substitute("HeLp", for: "He", replacing: "He") == "HeLp") | |
| 114 | #expect(Dabbrev.substitute("hex", for: "He", replacing: "Hello") == "Hex") | |
| 115 | #expect(Dabbrev.substitute("fooBar", for: "foo", replacing: "foo") == "fooBar") | |
| 116 | #expect(Dabbrev.substitute("alpine", for: "Al", replacing: "Al") == "Alpine") | |
| 117 | #expect(Dabbrev.substitute("12ab", for: "12", replacing: "12") == "12ab") | |
| 118 | } | |
| 119 | ||
| 120 | static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil | |
| 121 | ||
| 122 | /// `dabbrev-expand` repeated in a buffer alone: each expansion, then the message. | |
| 123 | static let dabbrevCases: [String] = [ | |
| 124 | "fa fb\nf| fc fd", "Hello help\nhe|", "Hello HELP hex\nHE|", "Hello HeLp hex\nHe|", "fooBar\nfoo|", "alpha alpine\nAl|", | |
| 125 | "Foo foo FOO\nf|", "fo_x fo-y fo.z fo'w fo/v fo2\nfo|", "12ab 12cd\n12|", "*bold* =code= ~x~\nb|", "abc ab\nab|", | |
| 126 | "naïve naïf\nna|", "* Heading one\n:PROPERTIES:\n:CATEGORY: head\n:END:\nHe|", "The THEME theory\nth|", "x A Apple\nA|", | |
| 127 | ] | |
| 128 | ||
| 129 | @Test(.enabled(if: oracle && EmacsOracle.isAvailable)) | |
| 130 | func dabbrevMatchesEmacs() throws { | |
| 131 | let form = """ | |
| 132 | (progn (require 'dabbrev) (let ((dabbrev-check-other-buffers nil) (dabbrev-check-all-buffers nil) (start nil) (out nil) (done nil)) | |
| 133 | (save-excursion (setq start (progn (skip-syntax-backward "w_") (point)))) | |
| 134 | (setq last-command nil) | |
| 135 | (while (and (not done) (< (length out) 12)) | |
| 136 | (condition-case e | |
| 137 | (progn (setq this-command 'dabbrev-expand) (dabbrev-expand nil) (setq last-command 'dabbrev-expand) | |
| 138 | (push (buffer-substring-no-properties start (point)) out)) | |
| 139 | (error (push (error-message-string e) out) (setq done t)))) | |
| 140 | (erase-buffer) | |
| 141 | (insert (mapconcat #'identity (nreverse out) "\\n")))) | |
| 142 | """ | |
| 143 | let cases = Self.dabbrevCases.map { marked -> (String, Int) in | |
| 144 | let caret = (marked as NSString).range(of: "|").location | |
| 145 | return (marked.replacingOccurrences(of: "|", with: ""), caret) | |
| 146 | } | |
| 147 | let results = try EmacsOracle.run(cases.map { EmacsOracle.Case(text: $0.0, point: EmacsOracle.point($0.1, in: $0.0) , form: form) }) | |
| 148 | for ((text, caret), result) in zip(cases, results) { | |
| 149 | var expansion = DabbrevExpansion(context(text, caret))! | |
| 150 | var ours: [String] = [] | |
| 151 | while true { | |
| 152 | let (edit, exhausted) = expansion.advance() | |
| 153 | if exhausted { | |
| 154 | ours.append(expansion.failure) | |
| 155 | break | |
| 156 | } | |
| 157 | ours.append(edit.replacement) | |
| 158 | } | |
| 159 | #expect(ours.joined(separator: "\n") == result.text, "\(text.debugDescription)") | |
| 160 | } | |
| 161 | } | |
| 162 | ||
| 163 | // MARK: - #143 | |
| 164 | ||
| 165 | @Test func idLinksCompleteHeadingsFromTheBufferThenTheIndex() { | |
| 166 | var options = fuzzy | |
| 167 | options.filePath = "/notes/here.org" | |
| 168 | let text = "* Alpha\n:PROPERTIES:\n:ID: a1\n:END:\n* Beta\nSee [[id:al]]" | |
| 169 | let completion = OrgCompletion.at(context(text, text.utf16.count - 2, options: options))! | |
| 170 | #expect(completion.kind == .idLink && completion.typed == "al" && completion.query == .linkTargets) | |
| 171 | #expect(completion.candidates == ["Alpha"]) | |
| 172 | #expect(completion.link == 46..<55) | |
| 173 | let other = CompletionItem(title: "All hands", id: nil, path: "/notes/other.org", start: 10, heading: true) | |
| 174 | let twin = CompletionItem(title: "Alpha", id: "a2", path: "/notes/other.org", start: 40, heading: true) | |
| 175 | let filled = OrgCompletion.filled(completion, with: CompletionResult(items: [other, twin]), fuzzy: true) | |
| 176 | #expect(Set(filled.candidates) == ["Alpha (here.org)", "Alpha (other.org)", "All hands"]) | |
| 177 | #expect(filled.item("All hands") == other && filled.label("All hands") == "All hands other.org") | |
| 178 | // A heading here without an ID gets one, and the link moves with the drawer. | |
| 179 | let beta = CompletionItem(title: "Beta", id: nil, path: "/notes/here.org", start: 35, heading: true) | |
| 180 | let edits = CompletionFlow.createID(beta, in: context(text, options: options), newID: "b1")! | |
| 181 | let link = CompletionFlow.linkEdit(completion, beta, id: "b1", after: edits) | |
| 182 | var result = text | |
| 183 | for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { result = edit.apply(to: result) } | |
| 184 | result = link.apply(to: result) | |
| 185 | #expect(result == "* Alpha\n:PROPERTIES:\n:ID: a1\n:END:\n* Beta\n:PROPERTIES:\n:ID: b1\n:END:\nSee [[id:b1][Beta]]") | |
| 186 | } | |
| 187 | ||
| 188 | @Test func denoteLinksAskTheIndex() { | |
| 189 | let completion = OrgCompletion.at(context("[[denote:"))! | |
| 190 | #expect(completion.kind == .denoteLink && completion.candidates.isEmpty && completion.query == .denoteNotes) | |
| 191 | let note = CompletionItem(title: "Reading list", id: "20260101T090000", path: "/n/20260101T090000--reading-list.org", start: 0, heading: false) | |
| 192 | let filled = OrgCompletion.filled(completion, with: CompletionResult(items: [note]), fuzzy: false) | |
| 193 | #expect(filled.candidates == ["Reading list"] && filled.link(note, id: note.id!) == "[[denote:20260101T090000][Reading list]]") | |
| 194 | } | |
| 195 | ||
| 196 | @Test func propertyValuesFromTheBufferAllowedFirst() { | |
| 197 | let text = "#+PROPERTY: Status_ALL todo \"in progress\" done\n* A\n:PROPERTIES:\n:Status: waiting\n:END:\n* B\n:PROPERTIES:\n:Status: i\n:END:\n" | |
| 198 | let caret = (text as NSString).range(of: ":Status: i").location + 10 | |
| 199 | let completion = OrgCompletion.at(context(text, caret))! | |
| 200 | #expect(completion.kind == .propertyValue && completion.query == .propertyValues("Status")) | |
| 201 | #expect(completion.candidates == ["in progress"]) | |
| 202 | let all = OrgCompletion.at(context(text, caret - 1))! | |
| 203 | #expect(all.candidates == ["todo", "in progress", "done", "waiting"]) | |
| 204 | let filled = OrgCompletion.filled(all, with: CompletionResult(strings: ["blocked", "done"]), fuzzy: false) | |
| 205 | #expect(filled.candidates == ["todo", "in progress", "done", "waiting", "blocked"]) | |
| 206 | // Names still complete as before. | |
| 207 | #expect(OrgCompletion.at(context("* H\n:PROPERTIES:\n:A: 1\n:CU\n:END:\n", 26))?.kind == .property) | |
| 208 | } | |
| 209 | } | |