Completion: opens by itself, fuzzy, words, index !483

merged merged by cmc on 2026-11-26 05:35 UTC · krz/orgstar:m4-completion into main

38 files changed, +2311 −110

Layout: unified · split

Changed files (38)
Sources/OrgApp/CommandTitles.swift +3 · view
@@ -49,6 +49,8 @@ enum CommandTitles {
49 String(localized: "Column View of File", comment: "Command title"), 49 String(localized: "Column View of File", comment: "Command title"),
50 String(localized: "Combine Agenda Files into iCalendar", comment: "Command title"), 50 String(localized: "Combine Agenda Files into iCalendar", comment: "Command title"),
51 String(localized: "Command Palette…", comment: "Command title"), 51 String(localized: "Command Palette…", comment: "Command title"),
52 String(localized: "Complete Word", comment: "Command title"),
53 String(localized: "Complete Word, Last First", comment: "Command title"),
52 String(localized: "Complete at Point", comment: "Command title"), 54 String(localized: "Complete at Point", comment: "Command title"),
53 String(localized: "Convert Note Sequence Scheme", comment: "Command title"), 55 String(localized: "Convert Note Sequence Scheme", comment: "Command title"),
54 String(localized: "Copy Region", comment: "Command title"), 56 String(localized: "Copy Region", comment: "Command title"),
@@ -86,6 +88,7 @@ enum CommandTitles {
86 String(localized: "Evaluate Time Range", comment: "Command title"), 88 String(localized: "Evaluate Time Range", comment: "Command title"),
87 String(localized: "Expand Snippet", comment: "Command title"), 89 String(localized: "Expand Snippet", comment: "Command title"),
88 String(localized: "Expand Table Columns", comment: "Command title"), 90 String(localized: "Expand Table Columns", comment: "Command title"),
91 String(localized: "Expand Word", comment: "Command title"),
89 String(localized: "Export Agenda Files to iCalendar", comment: "Command title"), 92 String(localized: "Export Agenda Files to iCalendar", comment: "Command title"),
90 String(localized: "Export Table as TSV…", comment: "Command title"), 93 String(localized: "Export Table as TSV…", comment: "Command title"),
91 String(localized: "Export Table to File…", comment: "Command title"), 94 String(localized: "Export Table to File…", comment: "Command title"),
Sources/OrgApp/CompletionSources.swift added +45 · view
@@ -0,0 +1,45 @@
1import Foundation
2import OrgCore
3import OrgIndex
4
5/// What completion takes from the index and the other files, for both apps' editors.
6public enum CompletionSources {
7 /// Answers `query` from `index`, leaving out `path`, whose buffer gives its own. Reads the
8 /// index, so it runs off the main actor; a failed read answers nothing.
9 @concurrent
10 public nonisolated static func answer(_ query: CompletionQuery, index: IndexStore, excluding path: String?) async -> CompletionResult {
11 switch query {
12 case .linkTargets:
13 return CompletionResult(items: (try? index.linkTargets(excluding: path)) ?? [])
14 case .denoteNotes:
15 let notes = ((try? index.denoteNodes()) ?? []).filter { $0.location.path != path }
16 return CompletionResult(items: notes.map { CompletionItem(title: $0.title, id: $0.id, path: $0.location.path, start: 0, heading: false) })
17 case .propertyValues(let name):
18 guard let values = try? index.propertyValues(name, excluding: path) else { return CompletionResult() }
19 return CompletionResult(strings: values.allowed + values.used)
20 case .words(let prefix):
21 return CompletionResult(strings: (try? index.words(prefix, excluding: path)) ?? [])
22 }
23 }
24
25 /// `org-id-get-create` on a heading in another file, through its buffer when it's open:
26 /// the new ID, or nil when the heading isn't where the index put it.
27 @MainActor
28 public static func createID(_ item: CompletionItem, session: DocumentSession, newID: String = UUID().uuidString.lowercased()) -> String? {
29 guard item.heading, let text = session.text(of: item.path) else { return nil }
30 let ns = text as NSString
31 guard item.start < ns.length else { return nil }
32 var end = 0
33 ns.getLineStart(nil, end: nil, contentsEnd: &end, for: NSRange(location: item.start, length: 0))
34 let line = ns.substring(with: NSRange(location: item.start, length: end - item.start))
35 guard line.hasPrefix("*"), line.contains(item.title) else { return nil }
36 guard case .commit = session.perform(CreateID(newID: { newID }), path: item.path, at: item.start, expect: (item.start, line)) else { return nil }
37 return newID
38 }
39
40 /// The text of the open buffers other than `path`, for word completion.
41 @MainActor
42 public static func otherBuffers(_ session: DocumentSession, excluding path: String?) -> [String] {
43 session.openPaths.filter { $0 != path }.compactMap { session.text(of: $0) }
44 }
45}
Sources/OrgApp/FileTree.swift +2 −24 · view
@@ -1,4 +1,5 @@
1import Foundation 1import Foundation
2import OrgCore
2import OrgIndex 3import OrgIndex
3 4
4/// One file the workspace knows about. 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 73extension FuzzyMatch {
73/// at word starts and runs of consecutive characters score higher; shorter names win ties.
74public 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
96 /// Entries ranked by `score` against their relative path, best first. 74 /// Entries ranked by `score` against their relative path, best first.
97 public static func rank(_ query: String, _ files: [FileEntry], limit: Int = 50) -> [FileEntry] { 75 public static func rank(_ query: String, _ files: [FileEntry], limit: Int = 50) -> [FileEntry] {
98 let scored: [(file: FileEntry, score: Int)] = files.compactMap { file in score(query, file.relativePath).map { (file, $0) } } 76 let scored: [(file: FileEntry, score: Int)] = files.compactMap { file in score(query, file.relativePath).map { (file, $0) } }
Sources/OrgApp/OrgPreferences.swift +15 · view
@@ -54,6 +54,7 @@ public enum OrgPreferences {
54 options.clockInSwitchToState = string("clockInSwitchToState", defaults).nonEmpty 54 options.clockInSwitchToState = string("clockInSwitchToState", defaults).nonEmpty
55 options.timerFormat = string("timerFormat", defaults).contains("%s") ? string("timerFormat", defaults) : "%s " 55 options.timerFormat = string("timerFormat", defaults).contains("%s") ? string("timerFormat", defaults) : "%s "
56 options.timerDefault = string("timerDefault", defaults).nonEmpty ?? "0" 56 options.timerDefault = string("timerDefault", defaults).nonEmpty ?? "0"
57 options.completion = completion(defaults)
57 let templates = UserConfig.structureTemplates(defaults) 58 let templates = UserConfig.structureTemplates(defaults)
58 options.structureTemplates = templates.isEmpty ? nil : StructureTemplate.merged(templates) 59 options.structureTemplates = templates.isEmpty ? nil : StructureTemplate.merged(templates)
59 options.trackOrderedPropertyWithTag = switch string("trackOrderedTag", defaults) { 60 options.trackOrderedPropertyWithTag = switch string("trackOrderedTag", defaults) {
@@ -64,6 +65,20 @@ public enum OrgPreferences {
64 return options 65 return options
65 } 66 }
66 67
68 /// The completion settings, `preset` resolved by the keymap preset: Doom's corfu opens
69 /// the list by itself and matches with orderless; Emacs and the Mac keys do neither.
70 public static func completion(_ defaults: UserDefaults = .standard) -> CompletionOptions {
71 let doom = string("keymap", defaults) == "doom"
72 func choice(_ key: String, on: String) -> Bool {
73 let value = string(key, defaults)
74 return value == "preset" ? doom : value == on
75 }
76 return CompletionOptions(
77 auto: choice("completionAuto", on: "on"), delay: Double(max(0, integer("completionAutoDelay", defaults))) / 1000,
78 prefix: max(1, integer("completionAutoPrefix", defaults)), fuzzy: choice("completionStyle", on: "fuzzy"), words: bool("completionWords", defaults)
79 )
80 }
81
67 /// `colors` with the type settings of `[theme]`: font, size, line spacing, heading step. 82 /// `colors` with the type settings of `[theme]`: font, size, line spacing, heading step.
68 public static func theme(_ colors: ThemeSpec, _ defaults: UserDefaults = .standard) -> ThemeSpec { 83 public static func theme(_ colors: ThemeSpec, _ defaults: UserDefaults = .standard) -> ThemeSpec {
69 var spec = colors 84 var spec = colors
Sources/OrgApp/UserConfig.swift +10 · view
@@ -360,6 +360,16 @@ public enum UserConfig {
360 Setting(section: "orgstar", key: "option-as-meta", defaultsKey: "optionAsMeta", 360 Setting(section: "orgstar", key: "option-as-meta", defaultsKey: "optionAsMeta",
361 kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"), 361 kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"),
362 comment: "left, right, both or none", legacy: "general.option-as-meta"), 362 comment: "left, right, both or none", legacy: "general.option-as-meta"),
363 Setting(section: "orgstar", key: "completion-auto", defaultsKey: "completionAuto", kind: .choice([("preset", "preset"), ("on", "on"), ("off", "off")]),
364 fallback: .string("preset"), comment: "the completion list opens by itself as you type: on, off, or preset (on with doom keys, off with emacs and mac)", legacy: ""),
365 Setting(section: "orgstar", key: "completion-auto-delay", defaultsKey: "completionAutoDelay", kind: .integer, fallback: .integer(400),
366 comment: "milliseconds after typing stops before the list opens by itself (corfu-auto-delay)", legacy: ""),
367 Setting(section: "orgstar", key: "completion-auto-prefix", defaultsKey: "completionAutoPrefix", kind: .integer, fallback: .integer(2),
368 comment: "characters typed before the list opens by itself (corfu-auto-prefix)", legacy: ""),
369 Setting(section: "orgstar", key: "completion-style", defaultsKey: "completionStyle", kind: .choice([("preset", "preset"), ("prefix", "prefix"), ("fuzzy", "fuzzy")]),
370 fallback: .string("preset"), comment: "prefix: candidates start with what you typed; fuzzy: its letters in order, best first; preset: fuzzy with doom keys, prefix with emacs and mac", legacy: ""),
371 Setting(section: "orgstar", key: "completion-words", defaultsKey: "completionWords", kind: .bool, fallback: .bool(false),
372 comment: "the list that opens by itself offers words from your buffers and folders where Org offers nothing", legacy: ""),
363 Setting(section: "orgstar", key: "pdf-margin", defaultsKey: "pdfMargin", kind: .integer, fallback: .integer(50), 373 Setting(section: "orgstar", key: "pdf-margin", defaultsKey: "pdfMargin", kind: .integer, fallback: .integer(50),
364 comment: "PDF export's page margins, in points", legacy: ""), 374 comment: "PDF export's page margins, in points", legacy: ""),
365 Setting(section: "orgstar", key: "pdf-font", defaultsKey: "pdfFont", kind: .string, fallback: .string(""), 375 Setting(section: "orgstar", key: "pdf-font", defaultsKey: "pdfFont", kind: .string, fallback: .string(""),
Sources/OrgCore/Commands/Command.swift +2 · view
@@ -99,6 +99,8 @@ public struct EditingOptions: Sendable, Equatable, Codable {
99 public var timerDefault = "0" 99 public var timerDefault = "0"
100 /// The snippets and file templates of `snippets.toml`. 100 /// The snippets and file templates of `snippets.toml`.
101 public var snippets: [Snippet] = [] 101 public var snippets: [Snippet] = []
102 /// How the completion list opens and matches.
103 public var completion = CompletionOptions()
102 104
103 public init( 105 public init(
104 tagsColumn: Int = -77, insertHeadingRespectContent: Bool = false, metaReturnMaySplitLine: Bool = true, 106 tagsColumn: Int = -77, insertHeadingRespectContent: Bool = false, metaReturnMaySplitLine: Bool = true,
Sources/OrgCore/Commands/PropertyCommands.swift +1 −1 · view
@@ -95,7 +95,7 @@ public enum PropertyValues {
95 } 95 }
96 96
97 /// `(read-from-string (concat "(" vals ")"))` as strings: quoted strings, numbers, symbols. 97 /// `(read-from-string (concat "(" vals ")"))` as strings: quoted strings, numbers, symbols.
98 static func readList(_ s: String) -> [String] { 98 public static func readList(_ s: String) -> [String] {
99 var values: [String] = [] 99 var values: [String] = []
100 for m in s.matches(of: /"((?:[^"\\]|\\.)*)"|(\S+)/) { 100 for m in s.matches(of: /"((?:[^"\\]|\\.)*)"|(\S+)/) {
101 if let quoted = m.1 { 101 if let quoted = m.1 {
Sources/OrgCore/Completion/CompletionList.swift added +162 · view
@@ -0,0 +1,162 @@
1import Foundation
2
3/// How the completion list behaves, from `config.toml`, with the preset's choices resolved.
4public struct CompletionOptions: Sendable, Equatable, Codable {
5 /// The list opens by itself after typing (`corfu-auto`).
6 public var auto = false
7 /// The pause after typing before it opens, in seconds (`corfu-auto-delay`).
8 public var delay = 0.4
9 /// Characters typed before it opens (`corfu-auto-prefix`).
10 public var prefix = 2
11 /// Candidates match when the typed characters appear in order, best first, as the
12 /// palette matches; otherwise they start with what's typed.
13 public var fuzzy = false
14 /// Words from the buffers and the index fill the list that opens by itself where Org
15 /// offers nothing.
16 public var words = false
17
18 public init(auto: Bool = false, delay: Double = 0.4, prefix: Int = 2, fuzzy: Bool = false, words: Bool = false) {
19 self.auto = auto
20 self.delay = delay
21 self.prefix = prefix
22 self.fuzzy = fuzzy
23 self.words = words
24 }
25}
26
27/// When the list opens by itself.
28public enum CompletionAuto {
29 /// The pause after a change before the list opens, or nil when it doesn't: the setting is
30 /// off, Vim keys are outside insert state, or the file isn't org and words aren't offered.
31 public static func delay(_ options: CompletionOptions, modal: Bool, insertState: Bool, isOrg: Bool) -> Double? {
32 guard options.auto, !modal || insertState, isOrg || options.words else { return nil }
33 return max(0, options.delay)
34 }
35
36 /// Whether `completion`, found after the pause, opens the list: enough typed, and
37 /// something to show now or from the index.
38 public static func opens(_ completion: Completion?, _ options: CompletionOptions) -> Bool {
39 guard let completion, completion.range.count >= max(1, options.prefix) else { return false }
40 return !completion.candidates.isEmpty || completion.query != nil
41 }
42}
43
44/// The open list, as corfu keeps it: the completion shown and the chosen row, nil while the
45/// typed text stands (`corfu-preselect` prompt).
46public struct CompletionList: Sendable, Equatable {
47 public private(set) var completion: Completion
48 public private(set) var selection: Int?
49
50 public init(_ completion: Completion, selection: Int? = nil) {
51 self.completion = completion
52 self.selection = selection.flatMap { completion.candidates.indices.contains($0) ? $0 : nil }
53 }
54
55 /// New candidates; the chosen one stays chosen if it is still there.
56 public mutating func update(_ completion: Completion) {
57 if completion.candidates != self.completion.candidates { selection = selected.flatMap { completion.candidates.firstIndex(of: $0) } }
58 self.completion = completion
59 }
60
61 /// corfu-cycle: past either end the choice wraps through the typed text.
62 public mutating func move(_ delta: Int) {
63 let count = completion.candidates.count
64 guard count > 0 else { return }
65 if let s = selection {
66 let next = s + delta
67 selection = next < 0 || next >= count ? nil : next
68 } else {
69 selection = delta > 0 ? 0 : count - 1
70 }
71 }
72
73 public var selected: String? { selection.map { completion.candidates[$0] } }
74
75 /// The rows shown when at most `rows` fit: those around the choice.
76 public func visible(rows: Int) -> Range<Int> {
77 let count = completion.candidates.count
78 let first = max(0, min((selection ?? 0) - rows + 1, count - rows))
79 return first..<min(count, first + rows)
80 }
81
82 public enum Action: Equatable {
83 /// The choice moved, or the key did nothing more; show the list again.
84 case shown
85 /// Insert this candidate and close the list.
86 case insert(String)
87 /// Insert the part the candidates share, keeping the list open.
88 case common(String)
89 /// Close the list.
90 case close
91 /// Close the list and let the key do what it otherwise does.
92 case closeAndPass
93 /// Not the list's key.
94 case pass
95 }
96
97 /// What a key does while the list is open.
98 public mutating func key(_ chord: KeyChord) -> Action {
99 switch chord {
100 case KeyChord("n", .control), KeyChord("<down>"), KeyChord("j", .control):
101 move(1)
102 return .shown
103 case KeyChord("p", .control), KeyChord("<up>"), KeyChord("k", .control):
104 move(-1)
105 return .shown
106 case KeyChord("TAB"):
107 // corfu-complete: the choice, else the candidates' common start.
108 let candidates = completion.candidates
109 if let selected { return .insert(selected) }
110 if candidates.count == 1 { return .insert(candidates[0]) }
111 guard let first = candidates.first, ![.template, .snippet, .idLink, .denoteLink].contains(completion.kind) else { return .shown }
112 let common = candidates.dropFirst().reduce(first) { $0.commonPrefix(with: $1) }
113 if common.utf16.count > completion.range.count, common.lowercased().hasPrefix(completion.typed.lowercased()) { return .common(common) }
114 return .shown
115 case KeyChord("RET"):
116 return selected.map { .insert($0) } ?? .closeAndPass
117 case KeyChord("ESC"):
118 return .closeAndPass
119 case KeyChord("g", .control):
120 return .close
121 default:
122 return .pass
123 }
124 }
125}
126
127/// The steps both editors take with a list: finding the completion at the caret again as
128/// typing goes on, and inserting a link.
129public enum CompletionFlow {
130 /// The index's answer for the completion of `kind` starting at `start`.
131 public typealias Fetched = (kind: Completion.Kind, start: Int, result: CompletionResult)
132
133 /// The completion at the caret for a list showing `open`, or for a new list of words
134 /// (`words`) or of what Org offers. Words narrow what was found when the list opened;
135 /// the rest are found again, with the index's answer added when it was for this place.
136 public static func current(_ context: EditContext, open: Completion?, words: Bool, others: () -> [String], fetched: Fetched?) -> Completion? {
137 if let open, open.kind == .word {
138 guard let range = Dabbrev.abbreviation(in: context.text, caret: context.caret), range.lowerBound == open.range.lowerBound else { return nil }
139 return Dabbrev.narrowed(open, to: range, in: context.text)
140 }
141 guard let found = words ? Dabbrev.completion(context, others: others()) : OrgCompletion.at(context) else { return nil }
142 if let fetched, fetched.kind == found.kind, fetched.start == found.range.lowerBound, found.query != nil {
143 return OrgCompletion.filled(found, with: fetched.result, fuzzy: context.options.completion.fuzzy)
144 }
145 return found
146 }
147
148 /// `org-id-get-create` on `item`'s heading in this buffer: the edits giving it `newID`.
149 public static func createID(_ item: CompletionItem, in context: EditContext, newID: String) -> [TextEdit]? {
150 let at = EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: [item.start..<item.start], options: context.options)
151 guard case .commit(let result) = CreateID(newID: { newID }).run(in: at) else { return nil }
152 return result.edits
153 }
154
155 /// The edit putting the link to `item`, with `id`, in place of the link typed, after
156 /// `earlier` edits (an ID given in this buffer) moved the text.
157 public static func linkEdit(_ completion: Completion, _ item: CompletionItem, id: String, after earlier: [TextEdit] = []) -> TextEdit {
158 let range = completion.link ?? completion.range
159 let shift = earlier.filter { $0.range.upperBound <= range.lowerBound }.reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count }
160 return TextEdit(range: (range.lowerBound + shift)..<(range.upperBound + shift), replacement: completion.link(item, id: id))
161 }
162}
Sources/OrgCore/Completion/Dabbrev.swift added +198 · view
@@ -0,0 +1,198 @@
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}
Sources/OrgCore/Completion/FuzzyMatch.swift added +26 · view
@@ -0,0 +1,26 @@
1import 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.
5public 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/IndexCompletion.swift added +134 · view
@@ -0,0 +1,134 @@
1import Foundation
2
3/// A heading or file a link completes to: from the buffer, or from the index for other files.
4public struct CompletionItem: Sendable, Hashable {
5 public var title: String
6 /// Its `ID`, or a Denote note's identifier; nil when the heading has none yet.
7 public var id: String?
8 public var path: String
9 /// Where its heading starts; 0 for a file.
10 public var start: Int
11 /// A heading, not a file.
12 public var heading: Bool
13
14 public init(title: String, id: String?, path: String, start: Int, heading: Bool) {
15 self.title = title
16 self.id = id
17 self.path = path
18 self.start = start
19 self.heading = heading
20 }
21}
22
23/// What a completion asks the index, off the main thread, after the buffer's candidates show.
24public enum CompletionQuery: Sendable, Hashable {
25 /// Headings and files in every folder, for `[[id:`.
26 case linkTargets
27 /// Denote's notes, for `[[denote:`.
28 case denoteNotes
29 /// Values used for a property, and its `_ALL` values.
30 case propertyValues(String)
31 /// Words starting with the abbreviation.
32 case words(String)
33}
34
35/// What the index answers.
36public struct CompletionResult: Sendable, Equatable {
37 public var items: [CompletionItem] = []
38 public var strings: [String] = []
39
40 public init(items: [CompletionItem] = [], strings: [String] = []) {
41 self.items = items
42 self.strings = strings
43 }
44}
45
46extension OrgCompletion {
47 /// `completion` with what the index answered for its query added to the buffer's
48 /// candidates, matching what's typed.
49 public static func filled(_ completion: Completion, with result: CompletionResult, fuzzy: Bool) -> Completion {
50 var filled = completion
51 switch completion.kind {
52 case .idLink, .denoteLink:
53 let items = completion.targets + result.items
54 filled.setItems(items, fuzzy: fuzzy)
55 case .propertyValue:
56 filled.pool = completion.pool + result.strings
57 filled.candidates = matching(filled.pool, completion.typed, fuzzy: fuzzy, ignoringCase: true, sorted: false)
58 case .word:
59 filled = Dabbrev.adding(result.strings, to: completion)
60 default:
61 break
62 }
63 filled.query = nil
64 return filled
65 }
66
67 /// `[[id:` and `[[denote:`: the link type, what's typed after it, and the whole link
68 /// typed so far, through `]]` after the caret.
69 static func linkTarget(_ context: EditContext, lineStart: Int, toHere: String) -> (type: String, typed: Range<Int>, link: Range<Int>)? {
70 guard let match = toHere.firstMatch(of: /\[\[(id|denote):([^\[\]]*)$/) else { return nil }
71 let ns = context.text as NSString
72 let caret = lineStart + (toHere as NSString).length
73 let linkStart = lineStart + toHere.utf16.distance(from: toHere.utf16.startIndex, to: match.range.lowerBound)
74 let typedStart = caret - String(match.2).utf16.count
75 var end = caret
76 if end + 2 <= ns.length, ns.substring(with: NSRange(location: end, length: 2)) == "]]" { end += 2 }
77 return (String(match.1), typedStart..<caret, linkStart..<end)
78 }
79
80 /// The open file's headings and its own ID, for `[[id:`.
81 static func bufferTargets(_ context: EditContext) -> [CompletionItem] {
82 let path = context.options.filePath ?? ""
83 let model = DocumentModel(tree: context.tree)
84 let file = model.property("ID", of: nil).map { id in
85 let title = context.text.firstMatch(of: /(?im)^[ \t]*#\+title:[ \t]*(.*?)[ \t]*$/).map { String($0.1) }
86 return CompletionItem(title: title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension, id: id.value,
87 path: path, start: 0, heading: false)
88 }
89 return (file.map { [$0] } ?? []) + model.headings.map { CompletionItem(title: $0.title, id: $0.id, path: path, start: $0.headingRange.lowerBound, heading: true) }
90 }
91
92 /// Property values in the buffer: those `org-property-get-allowed-values` gives at the
93 /// caret, then those headings give `name`.
94 static func bufferValues(_ name: String, _ context: EditContext) -> [String] {
95 let model = DocumentModel(tree: context.tree)
96 let allowed = PropertyValues.allowed(name, at: context.caret, text: context.text, tree: context.tree)?.values.filter { !$0.isEmpty } ?? []
97 let key = name.uppercased()
98 return allowed + (model.fileProperties + model.headings.flatMap(\.properties)).filter { $0.key.uppercased() == key && !$0.value.isEmpty }.map(\.value)
99 }
100}
101
102extension Completion {
103 /// Candidates for link items: titles, with the file's name where titles repeat.
104 mutating func setItems(_ all: [CompletionItem], fuzzy: Bool) {
105 var counts: [String: Int] = [:]
106 for item in all { counts[item.title, default: 0] += 1 }
107 var labels: [String: CompletionItem] = [:]
108 var order: [String] = []
109 for item in all {
110 var label = counts[item.title, default: 0] > 1 ? "\(item.title) (\((item.path as NSString).lastPathComponent))" : item.title
111 var n = 2
112 while labels[label] != nil {
113 label = "\(item.title) (\((item.path as NSString).lastPathComponent) \(n))"
114 n += 1
115 }
116 labels[label] = item
117 order.append(label)
118 }
119 pool = order
120 candidates = OrgCompletion.matching(order, typed, fuzzy: fuzzy, ignoringCase: true)
121 items = candidates.compactMap { labels[$0] }
122 targets = all
123 }
124
125 /// The item behind a candidate of a link completion.
126 public func item(_ candidate: String) -> CompletionItem? {
127 candidates.firstIndex(of: candidate).flatMap { items.indices.contains($0) ? items[$0] : nil }
128 }
129
130 /// The link a link completion inserts for `item`, given its ID.
131 public func link(_ item: CompletionItem, id: String) -> String {
132 Links.makeString((kind == .denoteLink ? "denote:" : "id:") + id, item.title)
133 }
134}
Sources/OrgCore/Completion/OrgCompletion.swift +82 −9 · view
@@ -3,18 +3,33 @@ import Foundation
3// Completion at point (Org 9.8.7's org-pcomplete): `org-thing-at-point` picks what the caret 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 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 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
8public struct Completion: Sendable, Equatable { 10public struct Completion: Sendable, Equatable {
9 public enum Kind: String, Sendable { 11 public enum Kind: String, Sendable {
10 case keyword, keywordValue, link, entity, tag, todo, heading, drawer, property, srcLanguage, srcHeader, clocktable, template, snippet 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 public var kind: Kind 16 public var kind: Kind
14 /// The text the chosen candidate replaces: from the start of what's typed to the caret. 17 /// The text the chosen candidate replaces: from the start of what's typed to the caret.
15 public var range: Range<Int> 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 public var candidates: [String] 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 /// The block templates `<` completes, for `.template`. 33 /// The block templates `<` completes, for `.template`.
19 public var templates: [StructureTemplate] = [] 34 public var templates: [StructureTemplate] = []
20 /// The snippets whose triggers are the candidates, for `.snippet`; choosing one expands it. 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 /// How the list shows `candidate`: a template with the block it makes. 38 /// How the list shows `candidate`: a template with the block it makes.
24 public func label(_ candidate: String) -> String { 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 if kind == .snippet, let snippet = snippets.first(where: { $0.trigger == candidate }), snippet.name != candidate { 43 if kind == .snippet, let snippet = snippets.first(where: { $0.trigger == candidate }), snippet.name != candidate {
26 return candidate + " " + snippet.name 44 return candidate + " " + snippet.name
27 } 45 }
@@ -39,10 +57,37 @@ public struct Completion: Sendable, Equatable {
39public enum OrgCompletion { 57public enum OrgCompletion {
40 public static func at(_ context: EditContext) -> Completion? { 58 public static func at(_ context: EditContext) -> Completion? {
41 let org = orgAt(context) 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 return snippets(context) ?? org 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 /// Snippet triggers starting with the text from the last blank to the caret. 91 /// Snippet triggers starting with the text from the last blank to the caret.
47 static func snippets(_ context: EditContext) -> Completion? { 92 static func snippets(_ context: EditContext) -> Completion? {
48 let snippets = context.options.snippets.filter { !$0.file } 93 let snippets = context.options.snippets.filter { !$0.file }
@@ -53,9 +98,11 @@ public enum OrgCompletion {
53 while start > 0, let scalar = UnicodeScalar(ns.character(at: start - 1)), !CharacterSet.whitespacesAndNewlines.contains(scalar) { start -= 1 } 98 while start > 0, let scalar = UnicodeScalar(ns.character(at: start - 1)), !CharacterSet.whitespacesAndNewlines.contains(scalar) { start -= 1 }
54 guard start < caret else { return nil } 99 guard start < caret else { return nil }
55 let typed = ns.substring(with: NSRange(location: start, length: caret - start)) 100 let typed = ns.substring(with: NSRange(location: start, length: caret - start))
56 let matching = snippets.filter { $0.trigger.hasPrefix(typed) } 101 let triggers = matching(snippets.map(\.trigger), typed, fuzzy: context.options.completion.fuzzy)
57 guard !matching.isEmpty else { return nil } 102 guard !triggers.isEmpty else { return nil }
58 return Completion(kind: .snippet, range: start..<caret, candidates: matching.map(\.trigger).sorted { $0.localizedStandardCompare($1) == .orderedAscending }, snippets: matching) 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 static func orgAt(_ context: EditContext) -> Completion? { 108 static func orgAt(_ context: EditContext) -> Completion? {
@@ -76,9 +123,9 @@ public enum OrgCompletion {
76 }() 123 }()
77 func make(_ kind: Completion.Kind, from: Int, _ candidates: [String]) -> Completion { 124 func make(_ kind: Completion.Kind, from: Int, _ candidates: [String]) -> Completion {
78 let typed = ns.substring(with: NSRange(location: from, length: caret - from)) 125 let typed = ns.substring(with: NSRange(location: from, length: caret - from))
79 var seen = Set<String>() 126 var completion = Completion(kind: kind, range: from..<caret, candidates: matching(candidates, typed, fuzzy: context.options.completion.fuzzy))
80 let matching = candidates.filter { $0.hasPrefix(typed) && seen.insert($0).inserted } 127 completion.typed = typed
81 return Completion(kind: kind, range: from..<caret, candidates: matching.sorted { $0.localizedStandardCompare($1) == .orderedAscending }) 128 return completion
82 } 129 }
83 func matches(_ pattern: String, _ s: String, caseInsensitive: Bool = true) -> NSTextCheckingResult? { 130 func matches(_ pattern: String, _ s: String, caseInsensitive: Bool = true) -> NSTextCheckingResult? {
84 let regex = try! NSRegularExpression(pattern: pattern, options: caseInsensitive ? [.caseInsensitive] : []) 131 let regex = try! NSRegularExpression(pattern: pattern, options: caseInsensitive ? [.caseInsensitive] : [])
@@ -139,6 +186,15 @@ public enum OrgCompletion {
139 let from = start + NSMaxRange((line as NSString).range(of: "#+")) 186 let from = start + NSMaxRange((line as NSString).range(of: "#+"))
140 return make(.keyword, from: from, caseDouble(fileOptions)) 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 // Link abbreviations and types after `[[`. 198 // Link abbreviations and types after `[[`.
143 do { 199 do {
144 var p = caret 200 var p = caret
@@ -186,6 +242,23 @@ public enum OrgCompletion {
186 let titles = DocumentModel(tree: context.tree).headings.map { Links.normalizedTitle($0.title) } 242 let titles = DocumentModel(tree: context.tree).headings.map { Links.normalizedTitle($0.title) }
187 return make(.heading, from: start + star.location + 1, titles) 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 // Property or drawer names. 262 // Property or drawer names.
190 if matches("^[ \\t]*:\\S*$", toHere, caseInsensitive: false) != nil, afterBlank { 263 if matches("^[ \\t]*:\\S*$", toHere, caseInsensitive: false) != nil, afterBlank {
191 let from = start + NSMaxRange((toHere as NSString).range(of: ":")) 264 let from = start + NSMaxRange((toHere as NSString).range(of: ":"))
Sources/OrgCore/Keymap/PresetDoom.swift +9 · view
@@ -632,6 +632,15 @@ extension KeymapPreset {
632 keys = "C-@" 632 keys = "C-@"
633 command = "editor.complete" 633 command = "editor.complete"
634 mode = "insert" 634 mode = "insert"
635 # +corfu/dabbrev-or-next and +corfu/dabbrev-or-last: words, the first or last chosen.
636 [[bind]]
637 keys = "C-n"
638 command = "editor.dabbrev-completion"
639 mode = "insert"
640 [[bind]]
641 keys = "C-p"
642 command = "editor.dabbrev-completion-previous"
643 mode = "insert"
635 644
636 # Insert state: org-cycle and org-shifttab with Doom's +org-indent-maybe-h, which 645 # Insert state: org-cycle and org-shifttab with Doom's +org-indent-maybe-h, which
637 # demotes or promotes a heading and indents or outdents an item tree. 646 # demotes or promotes a heading and indents or outdents an item tree.
Sources/OrgCore/Keymap/PresetEmacs.swift +6 · view
@@ -62,6 +62,12 @@ extension KeymapPreset {
62 keys = "C-M-i" 62 keys = "C-M-i"
63 command = "editor.complete" 63 command = "editor.complete"
64 [[bind]] 64 [[bind]]
65 keys = "M-/"
66 command = "editor.dabbrev-expand"
67 [[bind]]
68 keys = "C-M-/"
69 command = "editor.dabbrev-completion"
70 [[bind]]
65 keys = "C-x h" 71 keys = "C-x h"
66 command = "edit.select-all" 72 command = "edit.select-all"
67 [[bind]] 73 [[bind]]
Sources/OrgCore/Keymap/PresetMac.swift +3 · view
@@ -302,6 +302,9 @@ extension KeymapPreset {
302 keys = "M-ESC" 302 keys = "M-ESC"
303 command = "editor.complete" 303 command = "editor.complete"
304 [[bind]] 304 [[bind]]
305 keys = "<f5>"
306 command = "editor.dabbrev-expand"
307 [[bind]]
305 keys = "C-s-r" 308 keys = "C-s-r"
306 command = "macro.start" 309 command = "macro.start"
307 [[bind]] 310 [[bind]]
Sources/OrgEditorAppKit/CompletionPopup.swift +150 −70 · view
@@ -9,12 +9,13 @@ final class CompletionPopup {
9 static let rows = 16 9 static let rows = 16
10 let window: NSPanel 10 let window: NSPanel
11 private let stack = NSStackView() 11 private let stack = NSStackView()
12 private(set) var completion: Completion 12 private(set) var list: CompletionList
13 /// The chosen row; nil while the typed text stands (`corfu-preselect` prompt).
14 private(set) var selection: Int?
15 13
16 init(_ completion: Completion) { 14 var completion: Completion { list.completion }
17 self.completion = completion 15 var selected: String? { list.selected }
16
17 init(_ completion: Completion, selection: Int? = nil) {
18 list = CompletionList(completion, selection: selection)
18 window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 200, height: 20), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true) 19 window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 200, height: 20), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true)
19 window.identifier = NSUserInterfaceItemIdentifier("completion") 20 window.identifier = NSUserInterfaceItemIdentifier("completion")
20 window.hasShadow = true 21 window.hasShadow = true
@@ -30,37 +31,24 @@ final class CompletionPopup {
30 window.contentView?.layer?.borderWidth = 1 31 window.contentView?.layer?.borderWidth = 1
31 } 32 }
32 33
33 func update(_ completion: Completion) { 34 func update(_ completion: Completion) { list.update(completion) }
34 if completion.candidates != self.completion.candidates { selection = nil }
35 self.completion = completion
36 }
37 35
38 func move(_ delta: Int) { 36 func move(_ delta: Int) { list.move(delta) }
39 let count = completion.candidates.count
40 guard count > 0 else { return }
41 // corfu-cycle: past either end wraps through the typed text.
42 if let s = selection {
43 let next = s + delta
44 selection = next < 0 || next >= count ? nil : next
45 } else {
46 selection = delta > 0 ? 0 : count - 1
47 }
48 }
49 37
50 var selected: String? { selection.map { completion.candidates[$0] } } 38 func key(_ chord: KeyChord) -> CompletionList.Action { list.key(chord) }
51 39
52 /// Lays the rows out and puts the list under `caret`, a rectangle in screen coordinates. 40 /// Lays the rows out and puts the list under `caret`, a rectangle in screen coordinates.
53 func show(under caret: NSRect, in parent: NSWindow?, font: NSFont) { 41 func show(under caret: NSRect, in parent: NSWindow?, font: NSFont) {
54 stack.arrangedSubviews.forEach { $0.removeFromSuperview() } 42 stack.arrangedSubviews.forEach { $0.removeFromSuperview() }
55 let candidates = completion.candidates 43 let candidates = completion.candidates
56 let first = max(0, min((selection ?? 0) - Self.rows + 1, candidates.count - Self.rows))
57 var width: CGFloat = 80 44 var width: CGFloat = 80
58 for (index, candidate) in candidates.enumerated().dropFirst(first).prefix(Self.rows) { 45 for index in list.visible(rows: Self.rows) {
46 let candidate = candidates[index]
59 let label = NSTextField(labelWithString: " " + completion.label(candidate) + (completion.kind == .snippet ? " " + String(localized: "snippet", comment: "Marks a snippet in the completion list") : "") + " ") 47 let label = NSTextField(labelWithString: " " + completion.label(candidate) + (completion.kind == .snippet ? " " + String(localized: "snippet", comment: "Marks a snippet in the completion list") : "") + " ")
60 label.font = font 48 label.font = font
61 label.drawsBackground = index == selection 49 label.drawsBackground = index == list.selection
62 label.backgroundColor = .selectedContentBackgroundColor 50 label.backgroundColor = .selectedContentBackgroundColor
63 label.textColor = index == selection ? .alternateSelectedControlTextColor : .labelColor 51 label.textColor = index == list.selection ? .alternateSelectedControlTextColor : .labelColor
64 label.lineBreakMode = .byTruncatingTail 52 label.lineBreakMode = .byTruncatingTail
65 stack.addArrangedSubview(label) 53 stack.addArrangedSubview(label)
66 width = max(width, label.intrinsicContentSize.width) 54 width = max(width, label.intrinsicContentSize.width)
@@ -81,56 +69,104 @@ final class CompletionPopup {
81} 69}
82 70
83extension OrgEditor { 71extension OrgEditor {
84 /// `completion-at-point`: one candidate is inserted, several are listed. 72 /// `completion-at-point`: one candidate is inserted, several are listed. Candidates from
73 /// the index join the list when it answers.
85 func completeAtPoint() { 74 func completeAtPoint() {
86 guard let completion = OrgCompletion.at(context()), !completion.candidates.isEmpty else { 75 guard let completion = OrgCompletion.at(context()), !completion.candidates.isEmpty || completion.query != nil else {
87 closeCompletion() 76 closeCompletion()
88 onMessage?("No match") 77 onMessage?("No match")
89 return 78 return
90 } 79 }
91 if completion.candidates.count == 1 { 80 if completion.query == nil, completion.candidates.count == 1 {
92 closeCompletion() 81 closeCompletion()
93 insertCompletion(completion, completion.candidates[0]) 82 insertCompletion(completion, completion.candidates[0])
94 return 83 return
95 } 84 }
96 showCompletion(completion) 85 openCompletion(completion)
97 } 86 }
98 87
99 func showCompletion(_ completion: Completion) { 88 /// Words from the buffers and the index in a list, the first chosen, or with `last` the
100 if let popup = completionPopup { popup.update(completion) } else { completionPopup = CompletionPopup(completion) } 89 /// last (Doom's C-n and C-p in insert state).
90 func completeWord(last: Bool) {
91 guard let completion = Dabbrev.completion(context(), others: otherBuffers()) else {
92 closeCompletion()
93 return fail("No possible abbreviation preceding point")
94 }
95 if completion.candidates.isEmpty, completionSource == nil { return fail("No dynamic expansion for `\(completion.typed)' found") }
96 openCompletion(completion, select: last ? completion.candidates.count - 1 : 0)
97 }
98
99 /// Shows `completion` when it has candidates, and asks the index for more.
100 func openCompletion(_ completion: Completion, select: Int? = nil) {
101 completionFetched = nil
102 if !completion.candidates.isEmpty { showCompletion(completion, select: select) }
103 guard let query = completion.query, let source = completionSource else {
104 if completion.candidates.isEmpty { closeCompletion() }
105 return
106 }
107 let start = completion.range.lowerBound, kind = completion.kind
108 completionTask?.cancel()
109 completionTask = Task { [weak self] in
110 let result = await source(query)
111 guard !Task.isCancelled, let self else { return }
112 self.completionFetched = (kind, start, result)
113 self.fetchedCompletion(kind: kind, start: start, select: select)
114 }
115 }
116
117 /// The index answered: the list shows what it adds, or opens with it.
118 private func fetchedCompletion(kind: Completion.Kind, start: Int, select: Int?) {
119 guard textView.selectedRange().length == 0 else { return }
120 let open = completionPopup?.completion
121 guard open == nil || (open?.kind == kind && open?.range.lowerBound == start) else { return }
122 let words = kind == .word
123 guard let current = CompletionFlow.current(context(), open: nil, words: words, others: otherBuffers, fetched: completionFetched),
124 current.kind == kind, current.range.lowerBound == start, !current.candidates.isEmpty else { return }
125 showCompletion(current, select: open == nil ? select.map { $0 < 0 || $0 >= current.candidates.count ? current.candidates.count - 1 : $0 } : nil)
126 }
127
128 func showCompletion(_ completion: Completion, select: Int? = nil) {
129 if let popup = completionPopup { popup.update(completion) } else { completionPopup = CompletionPopup(completion, selection: select) }
101 let screen = textView.firstRect(forCharacterRange: NSRange(location: completion.range.lowerBound, length: 0), actualRange: nil) 130 let screen = textView.firstRect(forCharacterRange: NSRange(location: completion.range.lowerBound, length: 0), actualRange: nil)
102 completionPopup?.show(under: screen, in: textView.window, font: theme.font) 131 completionPopup?.show(under: screen, in: textView.window, font: theme.font)
103 } 132 }
104 133
105 func closeCompletion() { 134 func closeCompletion() {
106 completionTimer?.cancel() 135 completionTimer?.cancel()
136 completionTask?.cancel()
107 completionPopup?.close() 137 completionPopup?.close()
108 completionPopup = nil 138 completionPopup = nil
109 } 139 }
110 140
111 /// After typing: the open list follows the text; otherwise, with `modal` (corfu-auto), a 141 /// After typing: the open list follows the text; otherwise, as the completion settings
112 /// list opens after a pause once two characters are typed. 142 /// say, a list opens after a pause once enough is typed (corfu-auto).
113 func textTyped() { 143 func textTyped() {
114 completionTimer?.cancel() 144 completionTimer?.cancel()
115 if completionPopup != nil { 145 if completionPopup != nil {
116 refreshCompletion() 146 refreshCompletion()
117 return 147 return
118 } 148 }
119 guard modal, vim.mode == .insert, isOrg else { return } 149 guard let delay = CompletionAuto.delay(options.completion, modal: modal, insertState: vim.mode == .insert, isOrg: isOrg) else { return }
120 let work = DispatchWorkItem { [weak self] in self?.autoComplete() } 150 let work = DispatchWorkItem { [weak self] in self?.autoComplete() }
121 completionTimer = work 151 completionTimer = work
122 DispatchQueue.main.asyncAfter(deadline: .now() + 0.4, execute: work) 152 DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work)
123 } 153 }
124 154
125 func autoComplete() { 155 func autoComplete() {
126 guard completionPopup == nil, textView.selectedRange().length == 0, 156 guard completionPopup == nil, textView.selectedRange().length == 0 else { return }
127 let completion = OrgCompletion.at(context()), completion.range.count >= 2, !completion.candidates.isEmpty else { return } 157 let context = context()
128 showCompletion(completion) 158 var completion = isOrg ? OrgCompletion.at(context) : nil
159 if options.completion.words, completion.map({ $0.candidates.isEmpty && $0.query == nil }) ?? true {
160 completion = Dabbrev.completion(context, others: otherBuffers())
161 }
162 guard CompletionAuto.opens(completion, options.completion), let completion else { return }
163 openCompletion(completion)
129 } 164 }
130 165
131 func refreshCompletion() { 166 func refreshCompletion() {
132 guard let popup = completionPopup else { return } 167 guard let popup = completionPopup else { return }
133 guard textView.selectedRange().length == 0, let completion = OrgCompletion.at(context()), 168 guard textView.selectedRange().length == 0,
169 let completion = CompletionFlow.current(context(), open: popup.completion, words: false, others: otherBuffers, fetched: completionFetched),
134 completion.range.lowerBound == popup.completion.range.lowerBound, !completion.candidates.isEmpty else { 170 completion.range.lowerBound == popup.completion.range.lowerBound, !completion.candidates.isEmpty else {
135 closeCompletion() 171 closeCompletion()
136 return 172 return
@@ -139,7 +175,9 @@ extension OrgEditor {
139 } 175 }
140 176
141 func insertCompletion(_ completion: Completion, _ candidate: String) { 177 func insertCompletion(_ completion: Completion, _ candidate: String) {
178 defer { completionTimer?.cancel() }
142 if completion.kind == .snippet { return expandCompleted(completion, candidate) } 179 if completion.kind == .snippet { return expandCompleted(completion, candidate) }
180 if completion.kind == .idLink || completion.kind == .denoteLink { return insertLink(completion, candidate) }
143 let (text, caret) = completion.insertion(candidate) 181 let (text, caret) = completion.insertion(candidate)
144 let range = NSRange(location: completion.range.lowerBound, length: completion.range.count) 182 let range = NSRange(location: completion.range.lowerBound, length: completion.range.count)
145 guard textView.shouldChangeText(in: range, replacementString: text) else { return } 183 guard textView.shouldChangeText(in: range, replacementString: text) else { return }
@@ -148,47 +186,89 @@ extension OrgEditor {
148 setCaret(completion.range.lowerBound + caret) 186 setCaret(completion.range.lowerBound + caret)
149 } 187 }
150 188
189 /// A link to the chosen heading or note, its title the description. A heading without an
190 /// ID gets one first, here or in its file, as `org-id-get-create` would.
191 func insertLink(_ completion: Completion, _ candidate: String) {
192 guard let item = completion.item(candidate) else { return }
193 var created: [TextEdit] = []
194 var id = item.id
195 if id == nil, completion.kind == .idLink {
196 if item.path == (options.filePath ?? "") {
197 let newID = UUID().uuidString.lowercased()
198 if let edits = CompletionFlow.createID(item, in: context(), newID: newID) {
199 applyEdits(edits)
200 created = edits
201 id = newID
202 }
203 } else {
204 id = createID?(item)
205 }
206 }
207 guard let id else { return fail("Can't give \(item.title) an ID") }
208 let edit = CompletionFlow.linkEdit(completion, item, id: id, after: created)
209 let range = NSRange(edit.range)
210 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { return }
211 textView.textStorage?.replaceCharacters(in: range, with: edit.replacement)
212 textView.didChangeText()
213 setCaret(edit.range.lowerBound + edit.replacement.utf16.count)
214 }
215
216 /// `dabbrev-expand`: the word before the caret completed from the buffers, then the
217 /// index; again right after, the next expansion in its place.
218 func dabbrevExpand() {
219 closeCompletion()
220 let caret = textView.selectedRange().location
221 let repeated = lastCommand?.id == "editor.dabbrev-expand" && lastCommand?.revision == document.revision && dabbrev?.end == caret
222 if !repeated {
223 guard let expansion = DabbrevExpansion(context(), others: otherBuffers()) else { return fail("No possible abbreviation preceding point") }
224 dabbrev = expansion
225 if let source = completionSource {
226 let abbrev = expansion.abbrev, start = expansion.start
227 completionTask = Task { [weak self] in
228 let result = await source(.words(abbrev))
229 guard !Task.isCancelled, let self, self.dabbrev?.start == start else { return }
230 self.dabbrev?.add(result.strings)
231 }
232 }
233 }
234 guard var expansion = dabbrev else { return }
235 let (edit, exhausted) = expansion.advance()
236 dabbrev = expansion
237 let range = NSRange(edit.range)
238 if (document.text as NSString).substring(with: range) != edit.replacement, textView.shouldChangeText(in: range, replacementString: edit.replacement) {
239 textView.textStorage?.replaceCharacters(in: range, with: edit.replacement)
240 textView.didChangeText()
241 }
242 setCaret(expansion.end)
243 completionTimer?.cancel()
244 if exhausted { fail(expansion.failure) }
245 }
246
151 /// Keys while the list is open. Nil lets the key through. 247 /// Keys while the list is open. Nil lets the key through.
152 func completionKey(_ chord: KeyChord) -> Bool? { 248 func completionKey(_ chord: KeyChord) -> Bool? {
153 guard let popup = completionPopup else { return nil } 249 guard let popup = completionPopup else { return nil }
154 let completion = popup.completion 250 let completion = popup.completion
155 switch chord { 251 switch popup.key(chord) {
156 case KeyChord("n", .control), KeyChord("<down>"), KeyChord("j", .control): 252 case .shown:
157 popup.move(1) 253 showCompletion(popup.completion)
158 case KeyChord("p", .control), KeyChord("<up>"), KeyChord("k", .control):
159 popup.move(-1)
160 case KeyChord("TAB"):
161 // corfu-complete: the selection, else the candidates' common start.
162 if let selected = popup.selected {
163 closeCompletion()
164 insertCompletion(completion, selected)
165 } else if completion.candidates.count == 1 {
166 closeCompletion()
167 insertCompletion(completion, completion.candidates[0])
168 } else {
169 let common = completion.candidates.dropFirst().reduce(completion.candidates[0]) { $0.commonPrefix(with: $1) }
170 if common.utf16.count > completion.range.count, completion.kind != .template, completion.kind != .snippet {
171 insertCompletion(completion, common)
172 refreshCompletion()
173 }
174 }
175 return true 254 return true
176 case KeyChord("RET"): 255 case .insert(let candidate):
177 guard let selected = popup.selected else {
178 closeCompletion()
179 return nil
180 }
181 closeCompletion() 256 closeCompletion()
182 insertCompletion(completion, selected) 257 insertCompletion(completion, candidate)
183 return true 258 return true
184 case KeyChord("ESC"), KeyChord("g", .control): 259 case .common(let common):
260 insertCompletion(completion, common)
261 refreshCompletion()
262 return true
263 case .close:
185 closeCompletion() 264 closeCompletion()
186 return chord == KeyChord("ESC") ? nil : true 265 return true
187 default: 266 case .closeAndPass:
267 closeCompletion()
268 return nil
269 case .pass:
188 return nil 270 return nil
189 } 271 }
190 showCompletion(popup.completion)
191 return true
192 } 272 }
193} 273}
194#endif 274#endif
Sources/OrgEditorAppKit/EditorCommands.swift +3 · view
@@ -59,6 +59,9 @@ public enum EditorCommands {
59 EditorCommand(id: "org.toggle-inline-images-linked", title: "Show or Hide Inline Images, Including Described Links", action: .view), 59 EditorCommand(id: "org.toggle-inline-images-linked", title: "Show or Hide Inline Images, Including Described Links", action: .view),
60 EditorCommand(id: "org.latex-preview", title: "Show or Hide LaTeX Previews", action: .view), 60 EditorCommand(id: "org.latex-preview", title: "Show or Hide LaTeX Previews", action: .view),
61 EditorCommand(id: "editor.complete", title: "Complete at Point", action: .view), 61 EditorCommand(id: "editor.complete", title: "Complete at Point", action: .view),
62 EditorCommand(id: "editor.dabbrev-expand", title: "Expand Word", action: .view),
63 EditorCommand(id: "editor.dabbrev-completion", title: "Complete Word", action: .view),
64 EditorCommand(id: "editor.dabbrev-completion-previous", title: "Complete Word, Last First", action: .view),
62 EditorCommand(id: "org.snippet.next-field", title: "Next Snippet Field", action: .view), 65 EditorCommand(id: "org.snippet.next-field", title: "Next Snippet Field", action: .view),
63 EditorCommand(id: "org.snippet.previous-field", title: "Previous Snippet Field", action: .view), 66 EditorCommand(id: "org.snippet.previous-field", title: "Previous Snippet Field", action: .view),
64 EditorCommand(id: "app.new-file-from-template", title: "New File from Template…", action: .app), 67 EditorCommand(id: "app.new-file-from-template", title: "New File from Template…", action: .app),
Sources/OrgEditorAppKit/OrgEditor.swift +15 −1 · view
@@ -87,6 +87,11 @@ public final class OrgEditor: NSObject {
87 /// The open completion list, and the pause before one opens by itself. 87 /// The open completion list, and the pause before one opens by itself.
88 var completionPopup: CompletionPopup? 88 var completionPopup: CompletionPopup?
89 var completionTimer: DispatchWorkItem? 89 var completionTimer: DispatchWorkItem?
90 /// The index's answer for the completion starting at `start`, and the query running.
91 var completionFetched: (kind: Completion.Kind, start: Int, result: CompletionResult)?
92 var completionTask: Task<Void, Never>?
93 /// `dabbrev-expand` being repeated.
94 var dabbrev: DabbrevExpansion?
90 /// The snippet whose fields are being filled in, and the range drawn for it last. 95 /// The snippet whose fields are being filled in, and the range drawn for it last.
91 var snippetSession: SnippetSession? 96 var snippetSession: SnippetSession?
92 var snippetHighlight: Range<Int>? 97 var snippetHighlight: Range<Int>?
@@ -385,6 +390,12 @@ public final class OrgEditor: NSObject {
385 public var onExternal: ((ExternalRequest) -> Void)? 390 public var onExternal: ((ExternalRequest) -> Void)?
386 /// Tags used across the workspace, for tag completion. 391 /// Tags used across the workspace, for tag completion.
387 public var knownTags: @Sendable () -> [String] = { [] } 392 public var knownTags: @Sendable () -> [String] = { [] }
393 /// Answers completion's questions to the index; run off the main actor.
394 public var completionSource: (@Sendable (CompletionQuery) async -> CompletionResult)?
395 /// Gives a heading in another file an ID for a link to it; nil when it can't.
396 public var createID: ((CompletionItem) -> String?)?
397 /// The text of the other open buffers, most recent first, for word completion.
398 public var otherBuffers: () -> [String] = { [] }
388 /// Effects other than messages, for the app to carry out. 399 /// Effects other than messages, for the app to carry out.
389 public var onEffect: ((Effect) -> Void)? 400 public var onEffect: ((Effect) -> Void)?
390 /// Where paste looks for images and files; scripts checking the app set another. 401 /// Where paste looks for images and files; scripts checking the app set another.
@@ -597,7 +608,7 @@ public final class OrgEditor: NSObject {
597 } 608 }
598 609
599 /// The last command run and the revision it left, for `last-command`. 610 /// The last command run and the revision it left, for `last-command`.
600 private var lastCommand: (id: String, revision: Int)? 611 var lastCommand: (id: String, revision: Int)?
601 612
602 /// Runs a command by id, as a key, a menu item or the palette would. 613 /// Runs a command by id, as a key, a menu item or the palette would.
603 public func run(_ id: String) { 614 public func run(_ id: String) {
@@ -634,6 +645,9 @@ public final class OrgEditor: NSObject {
634 case "org.latex-preview": toggleLatex() 645 case "org.latex-preview": toggleLatex()
635 case "editor.toggle-spell-check": toggleSpellCheck() 646 case "editor.toggle-spell-check": toggleSpellCheck()
636 case "editor.complete": completeAtPoint() 647 case "editor.complete": completeAtPoint()
648 case "editor.dabbrev-expand": dabbrevExpand()
649 case "editor.dabbrev-completion": completeWord(last: false)
650 case "editor.dabbrev-completion-previous": completeWord(last: true)
637 case "org.snippet.next-field": nextSnippetField() 651 case "org.snippet.next-field": nextSnippetField()
638 case "org.snippet.previous-field": previousSnippetField() 652 case "org.snippet.previous-field": previousSnippetField()
639 case "editor.toggle-truncate-lines": toggleTruncateLines() 653 case "editor.toggle-truncate-lines": toggleTruncateLines()
Sources/OrgIndex/CompletionQueries.swift added +65 · view
@@ -0,0 +1,65 @@
1import Foundation
2import GRDB
3import OrgCore
4
5/// What completion asks the index: link targets, property values and words. The open file's
6/// own come from its buffer, so `excluding` leaves its rows out.
7extension IndexStore {
8 /// Every heading in org files, and every file with an ID, with its ID if it has one:
9 /// what `[[id:` completes.
10 public func linkTargets(excluding path: String? = nil) throws -> [CompletionItem] {
11 try database.read { db in
12 let files = try Row.fetchAll(db, sql: """
13 SELECT path, org_id, title FROM files WHERE org_id IS NOT NULL AND kind = 'org' AND path IS NOT ? ORDER BY path
14 """, arguments: [path]).map { row in
15 let path: String = row["path"]
16 let title = (row["title"] as String?) ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension
17 return CompletionItem(title: title, id: row["org_id"], path: path, start: 0, heading: false)
18 }
19 let headings = try Row.fetchAll(db, sql: """
20 SELECT f.path, h.title, h.org_id, h.start_offset FROM headings h JOIN files f ON f.id = h.file_id
21 WHERE f.kind = 'org' AND f.path IS NOT ? ORDER BY f.path, h.ordinal
22 """, arguments: [path]).map { row in
23 CompletionItem(title: row["title"], id: row["org_id"], path: row["path"], start: row["start_offset"], heading: true)
24 }
25 return files + headings
26 }
27 }
28
29 /// Values headings give `name` themselves, most used first, and the values its `_ALL`
30 /// properties allow, in order.
31 public func propertyValues(_ name: String, excluding path: String? = nil) throws -> (used: [String], allowed: [String]) {
32 try database.read { db in
33 let used = try String.fetchAll(db, sql: """
34 SELECT p.value FROM properties p JOIN headings h ON h.id = p.heading_id JOIN files f ON f.id = h.file_id
35 WHERE upper(p.key) = upper(?) AND p.inherited = 0 AND f.path IS NOT ? AND p.value != ''
36 GROUP BY p.value ORDER BY count(*) DESC, p.value
37 """, arguments: [name, path])
38 let allowed = try String.fetchAll(db, sql: """
39 SELECT p.value FROM properties p JOIN headings h ON h.id = p.heading_id JOIN files f ON f.id = h.file_id
40 WHERE upper(p.key) = upper(?) AND p.inherited = 0 AND f.path IS NOT ?
41 """, arguments: [name + "_ALL", path])
42 return (used, allowed.flatMap(PropertyValues.readList).filter { $0 != ":ETC" })
43 }
44 }
45
46 /// Words starting with `prefix`, ignoring case, in headings and text before first
47 /// headings that the full-text index finds for it.
48 public func words(_ prefix: String, excluding path: String? = nil, limit: Int = 50) throws -> [String] {
49 let term = prefix.lowercased().split { !$0.isLetter && !$0.isNumber }.first.map(String.init) ?? ""
50 guard !term.isEmpty else { return [] }
51 let match = "\"" + term + "\"*"
52 let texts = try database.read { db in
53 try String.fetchAll(db, sql: """
54 SELECT headings_fts.title || char(10) || headings_fts.body FROM headings_fts
55 JOIN headings h ON h.id = headings_fts.rowid JOIN files f ON f.id = h.file_id
56 WHERE headings_fts MATCH ? AND f.path IS NOT ? LIMIT 200
57 """, arguments: [match, path])
58 + String.fetchAll(db, sql: """
59 SELECT files_fts.body FROM files_fts JOIN files f ON f.id = files_fts.rowid
60 WHERE files_fts MATCH ? AND f.path IS NOT ? LIMIT 50
61 """, arguments: [match, path])
62 }
63 return Dabbrev.words(prefix, in: texts, limit: limit)
64 }
65}
Sources/Orgstar/ContentView.swift +1 · view
@@ -361,6 +361,7 @@ struct ContentView: View {
361 } 361 }
362 clock.remindAtEffort(session) 362 clock.remindAtEffort(session)
363 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] } 363 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
364 commands.completionIndex = workspace.index
364 commands.mainWindowOpen = true 365 commands.mainWindowOpen = true
365 commands.whatsNew = WhatsNew.pending(firstLaunch: noFolders && !welcomeShown) 366 commands.whatsNew = WhatsNew.pending(firstLaunch: noFolders && !welcomeShown)
366 if noFolders, !welcomeShown { 367 if noFolders, !welcomeShown {
Sources/Orgstar/OrgstarApp.swift +33 · view
@@ -2,6 +2,7 @@ import AppKit
2import OrgApp 2import OrgApp
3import OrgCore 3import OrgCore
4import OrgEditorAppKit 4import OrgEditorAppKit
5import OrgIndex
5import OrgMathJax 6import OrgMathJax
6import OrgPresentation 7import OrgPresentation
7#if !APPSTORE 8#if !APPSTORE
@@ -51,6 +52,8 @@ final class AppCommands {
51 #endif 52 #endif
52 /// Tags used across the workspace, for tag completion; the main window sets it. 53 /// Tags used across the workspace, for tag completion; the main window sets it.
53 var knownTags: () -> [String] = { [] } 54 var knownTags: () -> [String] = { [] }
55 /// The index completion asks for headings, values and words; the main window sets it.
56 var completionIndex: IndexStore?
54 /// The pending key prefix, and what can follow it. 57 /// The pending key prefix, and what can follow it.
55 var pendingKeys: String? 58 var pendingKeys: String?
56 /// The editor's evil state in the Doom preset. 59 /// The editor's evil state in the Doom preset.
@@ -809,6 +812,11 @@ struct SettingsView: View {
809 @AppStorage("logIntoDrawer") private var logIntoDrawer = "" 812 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
810 @AppStorage("useSpeedCommands") private var useSpeedCommands = false 813 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
811 @AppStorage("spellCheck") private var spellCheck = false 814 @AppStorage("spellCheck") private var spellCheck = false
815 @AppStorage("completionAuto") private var completionAuto = "preset"
816 @AppStorage("completionAutoDelay") private var completionAutoDelay = 400
817 @AppStorage("completionAutoPrefix") private var completionAutoPrefix = 2
818 @AppStorage("completionStyle") private var completionStyle = "preset"
819 @AppStorage("completionWords") private var completionWords = false
812 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false 820 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
813 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false 821 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
814 @AppStorage("agendaSpan") private var agendaSpan = 10 822 @AppStorage("agendaSpan") private var agendaSpan = 10
@@ -1031,6 +1039,31 @@ struct SettingsView: View {
1031 Text("Spell checking applies to files as they open; Check Spelling While Typing switches the current file. Code, links, dates, tags and keywords aren't checked.") 1039 Text("Spell checking applies to files as they open; Check Spelling While Typing switches the current file. Code, links, dates, tags and keywords aren't checked.")
1032 .settingsFooter() 1040 .settingsFooter()
1033 } 1041 }
1042 Section {
1043 Picker("Completion list opens", selection: $completionAuto) {
1044 Text("As the keys do (by itself with Doom)").tag("preset")
1045 Text("By itself as you type").tag("on")
1046 Text("Only with a key").tag("off")
1047 }
1048 .help(Text(verbatim: "completion-auto"))
1049 Stepper("After a pause of \(completionAutoDelay) ms", value: $completionAutoDelay, in: 0...2000, step: 50)
1050 .help(Text(verbatim: "completion-auto-delay"))
1051 Stepper("Once \(completionAutoPrefix) characters are typed", value: $completionAutoPrefix, in: 1...10)
1052 .help(Text(verbatim: "completion-auto-prefix"))
1053 Picker("Candidates", selection: $completionStyle) {
1054 Text("As the keys do (letters in order with Doom)").tag("preset")
1055 Text("Start with what's typed").tag("prefix")
1056 Text("Have its letters in order, best first").tag("fuzzy")
1057 }
1058 .help(Text(verbatim: "completion-style"))
1059 Toggle("The list offers words from open files and folders", isOn: $completionWords)
1060 .help(Text(verbatim: "completion-words"))
1061 } header: {
1062 Text("Completion")
1063 } footer: {
1064 Text("Doom's keys open the list by itself and match letters in order, as Doom's corfu does; the Emacs and Mac keys do neither unless set here. Expand Word completes the word before the caret from your files whatever is set.")
1065 .settingsFooter()
1066 }
1034 } 1067 }
1035 .formStyle(.grouped) 1068 .formStyle(.grouped)
1036 .frame(height: 860) 1069 .frame(height: 860)
Sources/Orgstar/PaneView.swift +6 · view
@@ -132,6 +132,12 @@ struct PaneView: NSViewRepresentable {
132 editor.onImage = { [weak commands] in commands?.imageHandler?($0, $1) } 132 editor.onImage = { [weak commands] in commands?.imageHandler?($0, $1) }
133 editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } } 133 editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } }
134 editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) } 134 editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) }
135 editor.completionSource = { [weak commands] query in
136 guard let index = await commands?.completionIndex else { return CompletionResult() }
137 return await CompletionSources.answer(query, index: index, excluding: path)
138 }
139 editor.createID = { [weak session] item in session.flatMap { CompletionSources.createID(item, session: $0) } }
140 editor.otherBuffers = { [weak session] in session.map { CompletionSources.otherBuffers($0, excluding: path) } ?? [] }
135 editor.onEffect = { [weak commands, weak session] effect in 141 editor.onEffect = { [weak commands, weak session] effect in
136 switch effect { 142 switch effect {
137 case .storedLinkUsed(let link): commands?.storedLinks.removeAll { $0.link == link } 143 case .storedLinkUsed(let link): commands?.storedLinks.removeAll { $0.link == link }
Sources/OrgstarMobile/EditorScreen.swift +6 · view
@@ -385,6 +385,8 @@ struct EditorScreen: View {
385 bind(editor) 385 bind(editor)
386 editor.focus(view) 386 editor.focus(view)
387 } 387 }
388 // A kept editor missed settings changed while it was off screen.
389 editor.options = editorOptions
388 self.editor = editor 390 self.editor = editor
389 textView = view 391 textView = view
390 if let offset { editor.reveal(offset) } 392 if let offset { editor.reveal(offset) }
@@ -419,6 +421,9 @@ struct EditorScreen: View {
419 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus. 421 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
420 private func bind(_ editor: MobileEditor) { 422 private func bind(_ editor: MobileEditor) {
421 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] } 423 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
424 editor.completionSource = { [index = workspace.index, path] query in await CompletionSources.answer(query, index: index, excluding: path) }
425 editor.createID = { [weak session] item in session.flatMap { CompletionSources.createID(item, session: $0) } }
426 editor.otherBuffers = { [weak session, path] in session.map { CompletionSources.otherBuffers($0, excluding: path) } ?? [] }
422 editor.onChange = { [weak session] in session?.bufferChanged(path) } 427 editor.onChange = { [weak session] in session?.bufferChanged(path) }
423 editor.onMessage = { message = $0 } 428 editor.onMessage = { message = $0 }
424 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) } 429 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
@@ -1024,6 +1029,7 @@ struct CommandPalette: View {
1024 ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"), 1029 ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"),
1025 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), 1030 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"),
1026 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"), 1031 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
1032 ("editor.complete", "Complete at Point"), ("editor.dabbrev-expand", "Expand Word"), ("editor.dabbrev-completion", "Complete Word"),
1027 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"), 1033 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
1028 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"), 1034 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
1029 ("org.table.expand", "Expand Table Columns"), 1035 ("org.table.expand", "Expand Table Columns"),
Sources/OrgstarMobile/MobileEditor+Completion.swift added +285 · view
@@ -0,0 +1,285 @@
1#if os(iOS)
2import OrgApp
3import OrgCore
4import UIKit
5
6/// The completion list under the caret, as on the Mac: keys on a hardware keyboard pick a
7/// row, and a tap inserts one.
8final class CompletionListView: UIView {
9 static let rows = 8
10 private(set) var list: CompletionList
11 private let stack = UIStackView()
12 var onChoose: ((String) -> Void)?
13
14 init(_ completion: Completion, selection: Int?) {
15 list = CompletionList(completion, selection: selection)
16 super.init(frame: .zero)
17 backgroundColor = .secondarySystemBackground
18 layer.borderColor = UIColor.separator.cgColor
19 layer.borderWidth = 1
20 layer.cornerRadius = 6
21 layer.shadowOpacity = 0.15
22 layer.shadowRadius = 6
23 stack.axis = .vertical
24 stack.alignment = .fill
25 addSubview(stack)
26 accessibilityIdentifier = "completion"
27 }
28
29 required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
30
31 var completion: Completion { list.completion }
32
33 func update(_ completion: Completion) { list.update(completion) }
34
35 func key(_ chord: KeyChord) -> CompletionList.Action { list.key(chord) }
36
37 /// Lays the rows out under `caret`, or above it when there isn't room below, kept inside
38 /// `bounds`: the part of the text view not under the keyboard and the key bar.
39 func show(under caret: CGRect, within bounds: CGRect, font: UIFont) {
40 stack.arrangedSubviews.forEach { $0.removeFromSuperview() }
41 var width: CGFloat = 80
42 for index in list.visible(rows: Self.rows) {
43 let candidate = completion.candidates[index]
44 let label = UILabel()
45 label.text = " " + completion.label(candidate) + (completion.kind == .snippet ? " " + String(localized: "snippet", comment: "Marks a snippet in the completion list") : "") + " "
46 label.font = font
47 label.lineBreakMode = .byTruncatingTail
48 label.isUserInteractionEnabled = true
49 label.backgroundColor = index == list.selection ? .tintColor : .clear
50 label.textColor = index == list.selection ? .white : .label
51 label.tag = index
52 label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped(_:))))
53 label.heightAnchor.constraint(equalToConstant: max(28, font.lineHeight + 6)).isActive = true
54 stack.addArrangedSubview(label)
55 width = max(width, label.intrinsicContentSize.width)
56 }
57 width = min(width, bounds.width - 16)
58 let height = stack.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
59 let x = min(max(bounds.minX + 8, caret.minX), bounds.maxX - width - 8)
60 let below = caret.maxY + 2
61 let y = below + height <= bounds.maxY || caret.minY - 2 - height < bounds.minY ? below : caret.minY - 2 - height
62 frame = CGRect(x: x, y: y, width: width, height: height)
63 stack.frame = CGRect(origin: .zero, size: frame.size)
64 }
65
66 @objc private func tapped(_ gesture: UITapGestureRecognizer) {
67 guard let index = gesture.view?.tag, completion.candidates.indices.contains(index) else { return }
68 onChoose?(completion.candidates[index])
69 }
70}
71
72extension MobileEditor {
73 /// Org files complete Org's positions; other files only words.
74 var completesOrg: Bool { fileName.map(DocumentSession.isOrgPath) ?? true }
75
76 /// `completion-at-point`: one candidate is inserted, several are listed.
77 func completeAtPoint() {
78 guard completesOrg, let completion = OrgCompletion.at(editContext()), !completion.candidates.isEmpty || completion.query != nil else {
79 closeCompletion()
80 onMessage?("No match")
81 return
82 }
83 if completion.query == nil, completion.candidates.count == 1 {
84 closeCompletion()
85 insertCompletion(completion, completion.candidates[0])
86 return
87 }
88 openCompletion(completion)
89 }
90
91 /// Words in a list, the first chosen, or with `last` the last.
92 func completeWord(last: Bool) {
93 guard let completion = Dabbrev.completion(editContext(), others: otherBuffers()) else {
94 closeCompletion()
95 return fail("No possible abbreviation preceding point")
96 }
97 if completion.candidates.isEmpty, completionSource == nil { return fail("No dynamic expansion for `\(completion.typed)' found") }
98 openCompletion(completion, select: last ? completion.candidates.count - 1 : 0)
99 }
100
101 func openCompletion(_ completion: Completion, select: Int? = nil) {
102 completionFetched = nil
103 if !completion.candidates.isEmpty { showCompletion(completion, select: select) }
104 guard let query = completion.query, let source = completionSource else {
105 if completion.candidates.isEmpty { closeCompletion() }
106 return
107 }
108 let start = completion.range.lowerBound, kind = completion.kind
109 completionTask?.cancel()
110 completionTask = Task { [weak self] in
111 let result = await source(query)
112 guard !Task.isCancelled, let self else { return }
113 self.completionFetched = (kind, start, result)
114 self.fetchedCompletion(kind: kind, start: start, select: select)
115 }
116 }
117
118 private func fetchedCompletion(kind: Completion.Kind, start: Int, select: Int?) {
119 guard textView.selectedRange.length == 0 else { return }
120 let open = completionList?.completion
121 guard open == nil || (open?.kind == kind && open?.range.lowerBound == start) else { return }
122 guard let current = CompletionFlow.current(editContext(), open: nil, words: kind == .word, others: otherBuffers, fetched: completionFetched),
123 current.kind == kind, current.range.lowerBound == start, !current.candidates.isEmpty else { return }
124 showCompletion(current, select: open == nil ? select.map { $0 < 0 || $0 >= current.candidates.count ? current.candidates.count - 1 : $0 } : nil)
125 }
126
127 func showCompletion(_ completion: Completion, select: Int? = nil) {
128 let view: CompletionListView
129 if let open = completionList {
130 open.update(completion)
131 view = open
132 } else {
133 view = CompletionListView(completion, selection: select)
134 view.onChoose = { [weak self, weak view] candidate in
135 guard let self, let view else { return }
136 let completion = view.completion
137 self.closeCompletion()
138 self.insertCompletion(completion, candidate)
139 }
140 completionList = view
141 textView.addSubview(view)
142 }
143 guard let position = textView.position(from: textView.beginningOfDocument, offset: completion.range.lowerBound) else { return }
144 let caret = textView.caretRect(for: position)
145 let insets = textView.adjustedContentInset
146 let visible = CGRect(x: textView.contentOffset.x, y: textView.contentOffset.y + insets.top,
147 width: textView.bounds.width, height: textView.bounds.height - insets.top - insets.bottom)
148 view.show(under: caret, within: visible, font: theme.font)
149 }
150
151 func closeCompletion() {
152 completionTimer?.invalidate()
153 completionTimer = nil
154 completionTask?.cancel()
155 completionList?.removeFromSuperview()
156 completionList = nil
157 }
158
159 /// After typing: the open list follows the text; otherwise, as the settings say, a list
160 /// opens after a pause once enough is typed.
161 func textTyped() {
162 completionTimer?.invalidate()
163 completionTimer = nil
164 if completionList != nil { return refreshCompletion() }
165 guard let delay = CompletionAuto.delay(options.completion, modal: modal, insertState: vim.mode == .insert, isOrg: completesOrg) else { return }
166 completionTimer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { [weak self] _ in
167 MainActor.assumeIsolated { self?.autoComplete() }
168 }
169 }
170
171 func autoComplete() {
172 guard completionList == nil, textView.selectedRange.length == 0, textView.markedTextRange == nil else { return }
173 let context = editContext()
174 var completion = completesOrg ? OrgCompletion.at(context) : nil
175 if options.completion.words, completion.map({ $0.candidates.isEmpty && $0.query == nil }) ?? true {
176 completion = Dabbrev.completion(context, others: otherBuffers())
177 }
178 guard CompletionAuto.opens(completion, options.completion), let completion else { return }
179 openCompletion(completion)
180 }
181
182 func refreshCompletion() {
183 guard let open = completionList else { return }
184 guard textView.selectedRange.length == 0,
185 let completion = CompletionFlow.current(editContext(), open: open.completion, words: false, others: otherBuffers, fetched: completionFetched),
186 completion.range.lowerBound == open.completion.range.lowerBound, !completion.candidates.isEmpty else {
187 closeCompletion()
188 return
189 }
190 showCompletion(completion)
191 }
192
193 func insertCompletion(_ completion: Completion, _ candidate: String) {
194 defer {
195 completionTimer?.invalidate()
196 completionTimer = nil
197 }
198 if completion.kind == .snippet {
199 textView.selectedRange = NSRange(location: completion.range.lowerBound, length: completion.range.count)
200 _ = perform(ExpandNamedSnippet(trigger: candidate))
201 return
202 }
203 if completion.kind == .idLink || completion.kind == .denoteLink { return insertLink(completion, candidate) }
204 let (text, caret) = completion.insertion(candidate)
205 applyEdits([TextEdit(range: completion.range, replacement: text)])
206 textView.selectedRange = NSRange(location: completion.range.lowerBound + caret, length: 0)
207 }
208
209 /// A link to the chosen heading or note, with an ID given to a heading without one.
210 func insertLink(_ completion: Completion, _ candidate: String) {
211 guard let item = completion.item(candidate) else { return }
212 var created: [TextEdit] = []
213 var id = item.id
214 if id == nil, completion.kind == .idLink {
215 if item.path == (options.filePath ?? "") {
216 let newID = UUID().uuidString.lowercased()
217 if let edits = CompletionFlow.createID(item, in: editContext(), newID: newID) {
218 applyEdits(edits)
219 created = edits
220 id = newID
221 }
222 } else {
223 id = createID?(item)
224 }
225 }
226 guard let id else { return fail("Can't give \(item.title) an ID") }
227 let edit = CompletionFlow.linkEdit(completion, item, id: id, after: created)
228 applyEdits([edit])
229 textView.selectedRange = NSRange(location: edit.range.lowerBound + edit.replacement.utf16.count, length: 0)
230 }
231
232 /// `dabbrev-expand`, repeated right after for the next expansion.
233 func dabbrevExpand() {
234 closeCompletion()
235 let caret = textView.selectedRange.location
236 let repeated = dabbrevRevision == document.revision && dabbrev?.end == caret
237 if !repeated {
238 guard let expansion = DabbrevExpansion(editContext(), others: otherBuffers()) else { return fail("No possible abbreviation preceding point") }
239 dabbrev = expansion
240 if let source = completionSource {
241 let abbrev = expansion.abbrev, start = expansion.start
242 completionTask = Task { [weak self] in
243 let result = await source(.words(abbrev))
244 guard !Task.isCancelled, let self, self.dabbrev?.start == start else { return }
245 self.dabbrev?.add(result.strings)
246 }
247 }
248 }
249 guard var expansion = dabbrev else { return }
250 let (edit, exhausted) = expansion.advance()
251 dabbrev = expansion
252 if (document.text as NSString).substring(with: NSRange(edit.range)) != edit.replacement { applyEdits([edit]) }
253 textView.selectedRange = NSRange(location: expansion.end, length: 0)
254 dabbrevRevision = document.revision
255 if exhausted { fail(expansion.failure) }
256 }
257
258 /// Keys while the list is open; nil lets the key through.
259 func completionKey(_ chord: KeyChord) -> Bool? {
260 guard let open = completionList else { return nil }
261 let completion = open.completion
262 switch open.key(chord) {
263 case .shown:
264 showCompletion(open.completion)
265 return true
266 case .insert(let candidate):
267 closeCompletion()
268 insertCompletion(completion, candidate)
269 return true
270 case .common(let common):
271 insertCompletion(completion, common)
272 refreshCompletion()
273 return true
274 case .close:
275 closeCompletion()
276 return true
277 case .closeAndPass:
278 closeCompletion()
279 return nil
280 case .pass:
281 return nil
282 }
283 }
284}
285#endif
Sources/OrgstarMobile/MobileEditor+Snippets.swift +1 · view
@@ -135,6 +135,7 @@ extension MobileEditor {
135 func textViewDidChange(_ textView: UITextView) { 135 func textViewDidChange(_ textView: UITextView) {
136 guard textView === self.textView else { return } 136 guard textView === self.textView else { return }
137 updateSnippetMirrors() 137 updateSnippetMirrors()
138 textTyped()
138 } 139 }
139} 140}
140#endif 141#endif
Sources/OrgstarMobile/MobileEditor.swift +24 −2 · view
@@ -118,6 +118,21 @@ final class MobileEditor: NSObject, DocumentBuffer {
118 var onImage: ((Data, String) -> Void)? 118 var onImage: ((Data, String) -> Void)?
119 /// Tags used across the workspace, for completion. 119 /// Tags used across the workspace, for completion.
120 var knownTags: @Sendable () -> [String] = { [] } 120 var knownTags: @Sendable () -> [String] = { [] }
121 /// Answers completion's questions to the index, off the main actor.
122 var completionSource: (@Sendable (CompletionQuery) async -> CompletionResult)?
123 /// Gives a heading in another file an ID for a link to it; nil when it can't.
124 var createID: ((CompletionItem) -> String?)?
125 /// The text of the other open buffers, for word completion.
126 var otherBuffers: () -> [String] = { [] }
127 /// The open completion list, the pause before one opens by itself, the index's answer
128 /// and the query running.
129 var completionList: CompletionListView?
130 var completionTimer: Timer?
131 var completionFetched: CompletionFlow.Fetched?
132 var completionTask: Task<Void, Never>?
133 /// `dabbrev-expand` being repeated, and the revision its last expansion left.
134 var dabbrev: DabbrevExpansion?
135 var dabbrevRevision: Int?
121 136
122 var theme: MobileTheme 137 var theme: MobileTheme
123 var fold = FoldState() 138 var fold = FoldState()
@@ -425,6 +440,10 @@ final class MobileEditor: NSObject, DocumentBuffer {
425 } 440 }
426 switch id { 441 switch id {
427 case "org.snippet.next-field": nextSnippetField() 442 case "org.snippet.next-field": nextSnippetField()
443 case "editor.complete": completeAtPoint()
444 case "editor.dabbrev-expand": dabbrevExpand()
445 case "editor.dabbrev-completion": completeWord(last: false)
446 case "editor.dabbrev-completion-previous": completeWord(last: true)
428 case "org.snippet.previous-field": previousSnippetField() 447 case "org.snippet.previous-field": previousSnippetField()
429 case "org.cycle": 448 case "org.cycle":
430 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") } 449 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
@@ -470,7 +489,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
470 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil 489 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
471 case _ where id.hasPrefix("org.fold."): return true 490 case _ where id.hasPrefix("org.fold."): return true
472 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.toggle-inline-images-linked", "org.latex-preview", "editor.toggle-truncate-lines", 491 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.toggle-inline-images-linked", "org.latex-preview", "editor.toggle-truncate-lines",
473 "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward", 492 "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward", "editor.complete", "editor.dabbrev-expand",
493 "editor.dabbrev-completion", "editor.dabbrev-completion-previous",
474 "edit.isearch-forward-regexp", "edit.isearch-backward-regexp": return true 494 "edit.isearch-forward-regexp", "edit.isearch-backward-regexp": return true
475 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last", 495 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
476 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil 496 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
@@ -504,7 +524,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
504 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC", 524 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
505 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>", 525 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
506 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>", 526 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
507 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>", 527 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>", .keyboardF5: "<f5>",
508 ] 528 ]
509 529
510 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac. 530 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
@@ -543,6 +563,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
543 } 563 }
544 } 564 }
545 if isearch != nil, isearchKey(chord) { return true } 565 if isearch != nil, isearchKey(chord) { return true }
566 if let handled = completionKey(chord) { return handled }
546 if let handled = snippetKey(chord) { return handled } 567 if let handled = snippetKey(chord) { return handled }
547 if modal { return handleModal(chord) } 568 if modal { return handleModal(chord) }
548 // Option alone types characters unless it begins a binding. 569 // Option alone types characters unless it begins a binding.
@@ -710,6 +731,7 @@ extension MobileEditor: UITextViewDelegate {
710 if textView.isFirstResponder { focus(textView) } 731 if textView.isFirstResponder { focus(textView) }
711 guard textView === self.textView else { return } 732 guard textView === self.textView else { return }
712 selectionChanged() 733 selectionChanged()
734 if let open = completionList, textView.selectedRange.location != open.completion.range.upperBound { refreshCompletion() }
713 } 735 }
714 736
715 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, and `auto-fill-mode` 737 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, and `auto-fill-mode`
Sources/OrgstarMobile/SearchScreen.swift +1 · view
@@ -1,5 +1,6 @@
1#if os(iOS) 1#if os(iOS)
2import OrgApp 2import OrgApp
3import OrgCore
3import OrgIndex 4import OrgIndex
4import SwiftUI 5import SwiftUI
5 6
Sources/OrgstarMobile/SettingsScreen.swift +37 · view
@@ -120,6 +120,43 @@ struct SettingsScreen: View {
120 } footer: { 120 } footer: {
121 Text("org-enforce-todo-dependencies and org-enforce-todo-checkbox-dependencies.") 121 Text("org-enforce-todo-dependencies and org-enforce-todo-checkbox-dependencies.")
122 } 122 }
123 Section {
124 let _ = model.settingsVersion
125 Picker("Completion list opens", selection: Binding {
126 UserDefaults.standard.string(forKey: "completionAuto") ?? "preset"
127 } set: { model.set("completionAuto", to: .string($0)) }) {
128 Text("As the keys do (by itself with Doom)").tag("preset")
129 Text("By itself as you type").tag("on")
130 Text("Only with a key").tag("off")
131 }
132 .help(Text(verbatim: "completion-auto"))
133 let delay = OrgPreferences.completion().delay
134 Stepper("After a pause of \(Int(delay * 1000)) ms", value: Binding {
135 Int(delay * 1000)
136 } set: { model.set("completionAutoDelay", to: .integer($0)) }, in: 0...2000, step: 50)
137 .help(Text(verbatim: "completion-auto-delay"))
138 let prefix = OrgPreferences.completion().prefix
139 Stepper("Once \(prefix) characters are typed", value: Binding {
140 prefix
141 } set: { model.set("completionAutoPrefix", to: .integer($0)) }, in: 1...10)
142 .help(Text(verbatim: "completion-auto-prefix"))
143 Picker("Candidates", selection: Binding {
144 UserDefaults.standard.string(forKey: "completionStyle") ?? "preset"
145 } set: { model.set("completionStyle", to: .string($0)) }) {
146 Text("As the keys do (letters in order with Doom)").tag("preset")
147 Text("Start with what's typed").tag("prefix")
148 Text("Have its letters in order, best first").tag("fuzzy")
149 }
150 .help(Text(verbatim: "completion-style"))
151 Toggle("The list offers words from open files and folders", isOn: Binding {
152 OrgPreferences.completion().words
153 } set: { model.set("completionWords", to: .bool($0)) })
154 .help(Text(verbatim: "completion-words"))
155 } header: {
156 Text("Completion")
157 } footer: {
158 Text("Doom's keys open the list by itself and match letters in order, as Doom's corfu does; the Emacs and Mac keys do neither unless set here. Expand Word completes the word before the caret from your files whatever is set.")
159 }
123 calendarSection 160 calendarSection
124 reminderSection 161 reminderSection
125 Section { 162 Section {
Tests/OrgAppTests/CompletionSourcesTests.swift added +55 · view
@@ -0,0 +1,55 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import OrgIndex
5import Testing
6@testable import OrgApp
7
8@MainActor
9struct CompletionSourcesTests {
10 @Test func presetDecidesUntilSet() {
11 let defaults = TestDefaults("orgstar-completion")
12 #expect(OrgPreferences.completion(defaults) == CompletionOptions(auto: false, delay: 0.4, prefix: 2, fuzzy: false, words: false))
13 defaults.set("doom", forKey: "keymap")
14 #expect(OrgPreferences.completion(defaults) == CompletionOptions(auto: true, delay: 0.4, prefix: 2, fuzzy: true, words: false))
15 defaults.set("off", forKey: "completionAuto")
16 defaults.set("prefix", forKey: "completionStyle")
17 #expect(OrgPreferences.completion(defaults) == CompletionOptions(auto: false, fuzzy: false))
18 defaults.set("mac", forKey: "keymap")
19 defaults.set("on", forKey: "completionAuto")
20 defaults.set(250, forKey: "completionAutoDelay")
21 defaults.set(3, forKey: "completionAutoPrefix")
22 defaults.set(true, forKey: "completionWords")
23 #expect(OrgPreferences.completion(defaults) == CompletionOptions(auto: true, delay: 0.25, prefix: 3, fuzzy: false, words: true))
24 #expect(UserConfig.apply("[orgstar]\ncompletion-auto = \"sometimes\"\n", to: defaults) == ["config.toml: completion-auto must be one of preset, on, off"])
25 }
26
27 @Test func answersFromTheIndexLeavingOutThisFile() async throws {
28 let index = try IndexStore()
29 try index.write(FileRecord(path: "/n/a.org", root: "/n", kind: .org, bytes: Array("* Here\n".utf8), mtime: 1, settings: IndexSettings()))
30 try index.write(FileRecord(path: "/n/b.org", root: "/n", kind: .org, bytes: Array("* There\nThermal.\n".utf8), mtime: 1, settings: IndexSettings()))
31 let targets = await CompletionSources.answer(.linkTargets, index: index, excluding: "/n/a.org")
32 #expect(targets.items.map(\.title) == ["There"])
33 #expect(await CompletionSources.answer(.words("the"), index: index, excluding: nil).strings == ["There", "Thermal"])
34 }
35
36 /// Completing `[[id:` to a heading in another file without an ID gives it one there.
37 @Test func linkingAHeadingElsewhereGivesItAnID() throws {
38 let notes = try Folder()
39 let target = try notes.write("target.org", "* Intro\n* Plan\nBody\n")
40 let here = try notes.write("here.org", "See ")
41 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
42 session.open(here.path)
43 let item = CompletionItem(title: "Plan", id: nil, path: target.path, start: 8, heading: true)
44 #expect(CompletionSources.createID(item, session: session, newID: "plan-id") == "plan-id")
45 #expect(try String(contentsOf: target, encoding: .utf8) == "* Intro\n* Plan\n:PROPERTIES:\n:ID: plan-id\n:END:\nBody\n")
46 // A heading that moved is left alone.
47 let moved = CompletionItem(title: "Plan", id: nil, path: target.path, start: 0, heading: true)
48 #expect(CompletionSources.createID(moved, session: session, newID: "other") == nil)
49 // The link the completion inserts.
50 var completion = OrgCompletion.at(EditContext(revision: 0, text: "See [[id:Pl", tree: OrgParser.parse("See [[id:Pl"), selection: [11..<11]))!
51 completion = OrgCompletion.filled(completion, with: CompletionResult(items: [item]), fuzzy: false)
52 let edit = CompletionFlow.linkEdit(completion, completion.item("Plan")!, id: "plan-id")
53 #expect(edit.apply(to: "See [[id:Pl") == "See [[id:plan-id][Plan]]")
54 }
55}
Tests/OrgCoreTests/CompletionListTests.swift added +209 · view
@@ -0,0 +1,209 @@
1import Foundation
2import 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).
7struct 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}
Tests/OrgEditorAppKitTests/CompletionPopupTests.swift +61 · view
@@ -73,4 +73,65 @@ struct CompletionPopupTests {
73 ModalTests().type(h, "C-SPC") 73 ModalTests().type(h, "C-SPC")
74 #expect(h.editor.document.text.contains("\\alpha")) 74 #expect(h.editor.document.text.contains("\\alpha"))
75 } 75 }
76
77 /// #139: typing schedules the list only when the setting is on.
78 @Test func typingOpensTheListOnlyWhenSet() {
79 let h = at("* H :work:\n* I :wo")
80 h.editor.textTyped()
81 #expect(h.editor.completionTimer == nil)
82 h.editor.options.completion = CompletionOptions(auto: true, delay: 0.01, prefix: 2)
83 h.editor.textTyped()
84 #expect(h.editor.completionTimer != nil)
85 h.editor.completionTimer?.perform()
86 #expect(h.editor.completionPopup?.completion.candidates == ["work:"])
87 }
88
89 /// #140: with fuzzy matching, letters in order, best first.
90 @Test func fuzzyListFollowsTyping() {
91 let h = at("#+STARTUP: lgd")
92 h.editor.options.completion.fuzzy = true
93 h.editor.run("editor.complete")
94 #expect(h.editor.completionPopup?.completion.candidates.first == "logdone")
95 h.textView.insertText("r", replacementRange: h.textView.selectedRange())
96 #expect(h.editor.completionPopup?.completion.candidates == ["logdrawer", "nologdrawer"])
97 }
98
99 /// #141: M-/ expands and cycles; Doom's C-n lists words with the first chosen.
100 @Test func wordsExpandAndList() {
101 let h = at("help hello\nhe")
102 h.editor.keymap = KeymapPreset.emacs.keymap
103 h.editor.otherBuffers = { ["helmet"] }
104 h.editor.run("editor.dabbrev-expand")
105 #expect(h.editor.document.text == "help hello\nhello")
106 h.editor.run("editor.dabbrev-expand")
107 #expect(h.editor.document.text == "help hello\nhelp")
108 h.editor.run("editor.dabbrev-expand")
109 #expect(h.editor.document.text == "help hello\nhelmet")
110 h.editor.run("editor.dabbrev-expand")
111 #expect(h.editor.document.text == "help hello\nhe" && h.caret == 13)
112
113 let doom = Harness("help hello\n\n")
114 doom.editor.keymap = KeymapPreset.doom.keymap
115 doom.editor.modal = true
116 doom.caret(at: 11)
117 ModalTests().type(doom, "a")
118 doom.textView.insertText("he", replacementRange: doom.textView.selectedRange())
119 ModalTests().type(doom, "C-n")
120 #expect(doom.editor.completionPopup?.completion.candidates == ["hello", "help"] && doom.editor.completionPopup?.selected == "hello")
121 ModalTests().type(doom, "C-n RET")
122 #expect(doom.editor.document.text == "help hello\nhelp\n")
123 }
124
125 /// #143: a heading here without an ID gets one, and the link has its title.
126 @Test func idLinkToAHeadingHere() {
127 let h = at("* Plan\nBody\n* Notes\nSee [[id:Pl")
128 h.editor.options.filePath = "/tmp/here.org"
129 h.editor.run("editor.complete")
130 #expect(h.editor.completionPopup?.completion.candidates == ["Plan"])
131 ModalTests().type(h, "TAB")
132 let text = h.editor.document.text
133 let id = try? #require(text.firstMatch(of: /:ID: +(\S+)/)).1
134 #expect(text.hasPrefix("* Plan\n:PROPERTIES:\n:ID:"))
135 #expect(id.map { text.hasSuffix("See [[id:\($0)][Plan]]") } == true && h.caret == text.utf16.count)
136 }
76} 137}
Tests/OrgIndexTests/CompletionQueriesTests.swift added +49 · view
@@ -0,0 +1,49 @@
1import OrgCore
2import Testing
3@testable import OrgIndex
4
5struct CompletionQueriesTests {
6 func store() throws -> IndexStore {
7 let store = try IndexStore()
8 try store.write(record("/notes/a.org", """
9 :PROPERTIES:
10 :ID: file-a
11 :END:
12 #+TITLE: Project notes
13 * Alpha
14 :PROPERTIES:
15 :ID: alpha
16 :Status: waiting
17 :Status_ALL: todo "in progress" done :ETC
18 :END:
19 Helmet and helium.
20 * Beta
21 :PROPERTIES:
22 :Status: waiting
23 :END:
24 """))
25 try store.write(record("/notes/b.org", "* Gamma\n:PROPERTIES:\n:Status: blocked\n:END:\nHelpful words.\n"))
26 return store
27 }
28
29 @Test func linkTargetsAreEveryHeadingWithItsID() throws {
30 let targets = try store().linkTargets()
31 #expect(targets.map(\.title) == ["Project notes", "Alpha", "Beta", "Gamma"])
32 #expect(targets[0] == CompletionItem(title: "Project notes", id: "file-a", path: "/notes/a.org", start: 0, heading: false))
33 #expect(targets[1].id == "alpha" && targets[2].id == nil && targets[2].heading)
34 #expect(try store().linkTargets(excluding: "/notes/a.org").map(\.title) == ["Gamma"])
35 }
36
37 @Test func propertyValuesMostUsedFirstAndAllowed() throws {
38 let values = try store().propertyValues("status")
39 #expect(values.used == ["waiting", "blocked"])
40 #expect(values.allowed == ["todo", "in progress", "done"])
41 #expect(try store().propertyValues("Status", excluding: "/notes/a.org").used == ["blocked"])
42 }
43
44 @Test func wordsFromTheFullTextIndex() throws {
45 #expect(try store().words("hel") == ["Helmet", "helium", "Helpful"])
46 #expect(try store().words("Hel", excluding: "/notes/b.org") == ["Helmet", "helium"])
47 #expect(try store().words("--").isEmpty)
48 }
49}
docs/manual/guide/02-the-editor.org +35 −3 · view
@@ -237,7 +237,7 @@ Complete at Point (=completion-at-point=) completes the word before the caret fr
237| Preset | Key | 237| Preset | Key |
238|--------+----------------------------------------------------------| 238|--------+----------------------------------------------------------|
239| Emacs | =C-M-i= | 239| Emacs | =C-M-i= |
240| Doom | =C-SPC= or =C-@= in insert state; the list also opens by itself after you type two characters and pause for 0.4 seconds, as Doom's corfu does | 240| Doom | =C-SPC= or =C-@= in insert state |
241| Mac | =⌥⎋= (Option-Escape) while Option is Meta; =⌃Space= stays with macOS, which switches input sources with it | 241| Mac | =⌥⎋= (Option-Escape) while Option is Meta; =⌃Space= stays with macOS, which switches input sources with it |
242 242
243With one candidate, it is inserted. With several, a list opens under the caret, showing up to 16 rows. Nothing is selected until you pick a row. 243With one candidate, it is inserted. With several, a list opens under the caret, showing up to 16 rows. Nothing is selected until you pick a row.
@@ -251,7 +251,39 @@ With one candidate, it is inserted. With several, a list opens under the caret,
251| =ESC= | Close the list; the key then does what it otherwise would | 251| =ESC= | Close the list; the key then does what it otherwise would |
252| =C-g= | Close the list | 252| =C-g= | Close the list |
253 253
254The list follows what you type and closes when nothing matches. Candidates are those that start with what you typed. 254The list follows what you type and closes when nothing matches.
255
256** Opening by itself
257
258The list can open by itself, as corfu's =corfu-auto= does: after you type at least two characters and pause for 0.4 seconds, when the position offers something. With the Doom keys it does, as Doom's corfu does; with the Emacs and Mac keys it doesn't. Settings ▸ Editing ▸ Completion (=completion-auto=, =completion-auto-delay= and =completion-auto-prefix= in =config.toml=) changes all three for any keys; see [[file:13-configuration.org][Configuration]]. With the Doom keys it opens only in insert state.
259
260** Matching
261
262Candidates start with what you typed, sorted; this is Emacs's default (=completion-styles= with =basic= and =partial-completion=). With fuzzy matching (=completion-style = "fuzzy"=), a candidate matches when it has the letters you typed in order, anywhere, as the command palette matches, and the best matches come first: letters at the start of a word and runs of letters next to each other count most, then shorter candidates. Candidates in the case you typed come first when there are any, so =#+ti= lists =title:= rather than =TITLE:=. The Doom keys match fuzzily by default, as Doom's corfu does with orderless; the Emacs and Mac keys match prefixes. =TAB= inserts the part the candidates share only when it starts with what you typed.
263
264** From your folders
265
266Some positions offer what is in your other files too. The file's own candidates show at once and the rest join the list when the index answers, which doesn't hold up typing.
267
268| Where | Candidates | Inserted |
269|----------------------------------------------+----------------------------------------------------------------+----------|
270| After =[[id:= | Heading titles in every folder, and files with an =ID=; a title that several have shows its file's name | =[[id:ID][Title]]=, through =]]= after the caret |
271| After =[[denote:= | Denote's notes, by title | =[[denote:IDENTIFIER][Title]]= |
272| After =:NAME: = in a property drawer | The values the =NAME_ALL= property or =#+PROPERTY: NAME_ALL= allows at the caret, then the values headings give =NAME= in this file and in every folder, most used first | The value |
273
274A heading chosen after =[[id:= that has no =ID= gets one first, in this file or in its own, as =org-id-get-create= adds it, so the link always points at an =ID=. If the heading's file changed so that the heading isn't where the index last saw it, nothing is added and the echo area says so.
275
276** Words
277
278Expand Word (=dabbrev-expand=) completes the word before the caret from words that start with it, ignoring case: in the file, those before the caret nearest first, then those after it nearest first; then in the other open files; then in your folders through the index. Each word is offered once. The case follows what you typed: =he= expands to =hello= from =Hello=, =HE= to =HELLO=, and a word with capitals inside, such as =fooBar=, keeps its own case when you typed its start as it is. Pressing the key again right away replaces the word with the next one; past the last, what you typed comes back and the echo area says =No further dynamic expansion for `he' found=.
279
280| Preset | Expand Word | Complete Word |
281|--------+-------------+------------------------------------------------------------------|
282| Emacs | =M-/= | =C-M-/= |
283| Doom | — | =C-n= in insert state (first chosen), =C-p= (last chosen), as Doom's =+corfu/dabbrev-or-next= |
284| Mac | =F5= (=fn-F5= on keyboards whose top row controls the Mac) | — |
285
286Complete Word lists the same words in the completion list instead, with one chosen. Word characters are Org's: letters, digits and =$=, =%=, ='=, =&=, =*=, =+=, =-=, =/=, ~=~, =\=, =_=, =|= and =~=, so =fo= expands to =fo-y= or =fo/v= but not into =fo.z=. The list that opens by itself offers words only where Org offers nothing, and only with Settings ▸ Editing ▸ Completion ▸ The list offers words from open files and folders (=completion-words=).
255 287
256What is completed, by position: 288What is completed, by position:
257 289
@@ -273,7 +305,7 @@ What is completed, by position:
273| =:= at the start of a line in a property drawer | property names the entry doesn't have yet | 305| =:= at the start of a line in a property drawer | property names the entry doesn't have yet |
274| =:= at the start of a line elsewhere | drawer names | 306| =:= at the start of a line elsewhere | drawer names |
275 307
276Where none of these offers anything, the triggers of your snippets that start with the text before the caret are offered, each with its description and marked =snippet=; choosing one expands it (see [[*Snippets][Snippets]]). Elsewhere, Complete at Point reports =No match=. Completion is for org files only. 308Where none of these offers anything, the triggers of your snippets that match the text before the caret are offered, each with its description and marked =snippet=; choosing one expands it (see [[*Snippets][Snippets]]). Elsewhere, Complete at Point reports =No match=. Completion is for org files only.
277 309
278* Snippets 310* Snippets
279 311
docs/manual/guide/03-keys.org +3 · view
@@ -843,6 +843,9 @@ When a key appears in several rows, it runs the command whose condition holds at
843| Find Previous (=edit.find-previous=) | — | — | — | Goes to the previous match. | 843| Find Previous (=edit.find-previous=) | — | — | — | Goes to the previous match. |
844| Use Selection for Find (=edit.use-selection-for-find=) | — | — | — | Puts the selection in the find bar. | 844| Use Selection for Find (=edit.use-selection-for-find=) | — | — | — | Puts the selection in the find bar. |
845| Complete at Point (=editor.complete=) | =C-M-i= | =⌥⎋= |=C-SPC= (I), =C-@= (I) | Completes what is typed at the caret: =#+= keywords and their values, link types, entities, tags, TODO keywords, headings, drawers, properties, src languages and header arguments, and =<s=-style templates (=completion-at-point=). One candidate is inserted; several open a list. | 845| Complete at Point (=editor.complete=) | =C-M-i= | =⌥⎋= |=C-SPC= (I), =C-@= (I) | Completes what is typed at the caret: =#+= keywords and their values, link types, entities, tags, TODO keywords, headings, drawers, properties, src languages and header arguments, and =<s=-style templates (=completion-at-point=). One candidate is inserted; several open a list. |
846| Expand Word (=editor.dabbrev-expand=) | =M-/= | =F5= | — | Completes the word before the caret from the file, the other open files and your folders; again right away, the next word (=dabbrev-expand=). See Words in [[file:02-the-editor.org][The editor]]. |
847| Complete Word (=editor.dabbrev-completion=) | =C-M-/= | — | =C-n= (I) | Lists the words Expand Word would insert, the first chosen (=dabbrev-completion=; Doom's =+corfu/dabbrev-or-next=). |
848| Complete Word, Last First (=editor.dabbrev-completion-previous=) | — | — | =C-p= (I) | The same, the last chosen (Doom's =+corfu/dabbrev-or-last=). |
846| Fill Paragraph (=org.fill-paragraph=) | =M-q= | =⌃⌘P= | — | Refills the paragraph or list item to the fill column (=org-fill-paragraph=); with a selection, every paragraph it touches. In the Doom preset, =gq= and =gw= fill the lines a motion covers; see [[*Operators][Operators]]. | 849| Fill Paragraph (=org.fill-paragraph=) | =M-q= | =⌃⌘P= | — | Refills the paragraph or list item to the fill column (=org-fill-paragraph=); with a selection, every paragraph it touches. In the Doom preset, =gq= and =gw= fill the lines a motion covers; see [[*Operators][Operators]]. |
847 850
848** Outline: visibility and narrowing 851** Outline: visibility and narrowing
docs/manual/guide/13-configuration.org +12 · view
@@ -89,6 +89,11 @@ Automatic saving writes a file one second after you stop typing. The keymap pres
89| State notes go in a LOGBOOK drawer | On or off | Off | =org-log-into-drawer= | 89| State notes go in a LOGBOOK drawer | On or off | Off | =org-log-into-drawer= |
90| Speed keys | On or off | Off | =org-use-speed-commands= | 90| Speed keys | On or off | Off | =org-use-speed-commands= |
91| Check spelling while typing | On or off | Off | =spell-check= | 91| Check spelling while typing | On or off | Off | =spell-check= |
92| Completion list opens | As the keys do; By itself as you type; Only with a key | As the keys do | =completion-auto= |
93| After a pause of N ms | 0 to 2000, in steps of 50 | 400 | =completion-auto-delay= |
94| Once N characters are typed | 1 to 10 | 2 | =completion-auto-prefix= |
95| Candidates | As the keys do; Start with what's typed; Have its letters in order, best first | As the keys do | =completion-style= |
96| The list offers words from open files and folders | On or off | Off | =completion-words= |
92 97
93The two New headings switches and the fill column show the keys of Insert Heading and Fill Paragraph in the preset you use, and each control's help tag names its =config.toml= key. The two "Emacs hides" and "Emacs shows" switches describe your Emacs, not orgstar's display. Tag alignment, table alignment and Fill Paragraph measure text the way your Emacs displays it, so a file edited in both keeps the same layout. Set them to match your Emacs configuration. They also control whether orgstar hides markers and shows entities when markup is hidden. 98The two New headings switches and the fill column show the keys of Insert Heading and Fill Paragraph in the preset you use, and each control's help tag names its =config.toml= key. The two "Emacs hides" and "Emacs shows" switches describe your Emacs, not orgstar's display. Tag alignment, table alignment and Fill Paragraph measure text the way your Emacs displays it, so a file edited in both keeps the same layout. Set them to match your Emacs configuration. They also control whether orgstar hides markers and shows entities when markup is hidden.
94 99
@@ -100,6 +105,8 @@ Default TODO keywords apply to files without a =#+TODO= line. orgstar reads them
100 105
101The two dependency switches are described under Dependencies in [[file:05-todos-and-tags.org][TODOs and tags]]. 106The two dependency switches are described under Dependencies in [[file:05-todos-and-tags.org][TODOs and tags]].
102 107
108The completion controls are described under Completion in [[file:02-the-editor.org][The editor]]. "As the keys do" follows the Keys preset: the list opens by itself and matches letters in order with Doom, as Doom's corfu does with orderless, and does neither with Emacs or Mac keys. The iOS app has the same controls in Settings ▸ Completion.
109
103The LOGBOOK switch writes =org-log-into-drawer= as ="LOGBOOK"= or =""=. A drawer name of your own in =config.toml= shows the switch on; turning it off and on again replaces the name with =LOGBOOK=. Logging is described under Logging in [[file:05-todos-and-tags.org][TODOs and tags]], speed keys in [[file:03-keys.org][Keys and commands]] and spell checking in [[file:02-the-editor.org][The editor]]. 110The LOGBOOK switch writes =org-log-into-drawer= as ="LOGBOOK"= or =""=. A drawer name of your own in =config.toml= shows the switch on; turning it off and on again replaces the name with =LOGBOOK=. Logging is described under Logging in [[file:05-todos-and-tags.org][TODOs and tags]], speed keys in [[file:03-keys.org][Keys and commands]] and spell checking in [[file:02-the-editor.org][The editor]].
104 111
105** Language 112** Language
@@ -448,6 +455,11 @@ Any other key in =[theme]= is a color; see Themes below.
448| =save= | string | ="automatic"= | =automatic= (one second after typing stops) or =explicit= (only with =⌘S=). | 455| =save= | string | ="automatic"= | =automatic= (one second after typing stops) or =explicit= (only with =⌘S=). |
449| =keymap= | string | ="emacs"= | =emacs=, =mac= or =doom=. Your own bindings go in =keymap.toml=. | 456| =keymap= | string | ="emacs"= | =emacs=, =mac= or =doom=. Your own bindings go in =keymap.toml=. |
450| =option-as-meta= | string | ="left"= | Which Option key is Meta: =left=, =right=, =both= or =none=. | 457| =option-as-meta= | string | ="left"= | Which Option key is Meta: =left=, =right=, =both= or =none=. |
458| =completion-auto= | string | ="preset"= | The completion list opens by itself as you type: =on=, =off=, or =preset= (on with =doom=, off with =emacs= and =mac=) (=corfu-auto=). |
459| =completion-auto-delay= | integer | =400= | Milliseconds after typing stops before it opens (=corfu-auto-delay=, in seconds in Emacs). |
460| =completion-auto-prefix= | integer | =2= | Characters typed before it opens (=corfu-auto-prefix=). |
461| =completion-style= | string | ="preset"= | =prefix=: candidates start with what's typed; =fuzzy=: they have its letters in order, best first; =preset=: =fuzzy= with =doom=, =prefix= with =emacs= and =mac=. |
462| =completion-words= | boolean | =false= | The list that opens by itself offers words from your buffers and folders where Org offers nothing. |
451| =pdf-margin= | integer | =50= | PDF export's page margins, in points. | 463| =pdf-margin= | integer | =50= | PDF export's page margins, in points. |
452| =pdf-font= | string | =""= | A font family for PDF export's text; =""= keeps the export's own. | 464| =pdf-font= | string | =""= | A font family for PDF export's text; =""= keeps the export's own. |
453| =pdf-page-numbers= | boolean | =true= | Number PDF export's pages. | 465| =pdf-page-numbers= | boolean | =true= | Number PDF export's pages. |
docs/manual/guide/14-ios.org +4 · view
@@ -220,6 +220,10 @@ With a hardware keyboard, the editor uses the preset =keymap= sets in the folder
220 220
221See [[file:03-keys.org][Keys and commands]] for the Emacs bindings. 221See [[file:03-keys.org][Keys and commands]] for the Emacs bindings.
222 222
223** Completion
224
225With a hardware keyboard, Complete at Point (=C-M-i=, or =C-SPC= in Doom's insert state), Expand Word (=M-/=, or =F5= with the Mac keys) and Complete Word (=C-M-/=, or =C-n= and =C-p= in Doom's insert state) work as on the Mac; see [[file:02-the-editor.org][The editor]]. The list shows up to 8 rows under the caret; the keys move through it as on the Mac, and tapping a row inserts it. The settings in Settings ▸ Completion are the Mac's: whether the list opens by itself, after which pause and how many characters, prefix or fuzzy matching, and words in the list. With them on, the list also opens as you type on the on-screen keyboard, where tapping a row is the way to choose.
226
223** Snippets 227** Snippets
224 228
225Snippets come from =snippets.toml= in the configuration folder, the same file as on the Mac, and reload when it changes; problems show in red under the folder in Settings. See [[file:02-the-editor.org][The editor]] and [[file:13-configuration.org][Configuration]]. 229Snippets come from =snippets.toml= in the configuration folder, the same file as on the Mac, and reload when it changes; problems show in red under the folder in Settings. See [[file:02-the-editor.org][The editor]] and [[file:13-configuration.org][Configuration]].
docs/manual/guide/15-alongside-emacs.org +11 · view
@@ -223,6 +223,17 @@ orgstar's snippets (see [[file:02-the-editor.org][The editor]]) read yasnippet's
223- A field inside another field's default is skipped by yasnippet once the outer field is typed over; orgstar visits it, empty, where it was. 223- A field inside another field's default is skipped by yasnippet once the outer field is typed over; orgstar visits it, empty, where it was.
224- Capture's escapes for dates and prompts (=%t=, =%U=, =%<…>=, =%^{…}=) work in bodies, which yasnippet doesn't have. 224- Capture's escapes for dates and prompts (=%t=, =%U=, =%<…>=, =%^{…}=) work in bodies, which yasnippet doesn't have.
225 225
226** Completion and dabbrev, corfu and org-roam
227
228Completion follows Emacs's =completion-at-point= with corfu's list (see [[file:02-the-editor.org][The editor]]). Where it differs:
229
230- Expand Word is =dabbrev-expand= with its defaults, and is tested against it in a buffer of its own. It searches the other open files whatever their mode, rather than only buffers in the same mode, and after them the index of your folders, which Emacs doesn't have. Without a word right before the caret it reports =No possible abbreviation preceding point= instead of expanding the word before the blank, and =dabbrev-abbrev-skip-leading-regexp= and =dabbrev-case-fold-search= aren't read.
231- Complete Word (and Doom's =C-n= and =C-p=) lists words in the order Expand Word finds them; =cape-dabbrev= collects the same words, which corfu then sorts by length and history.
232- Fuzzy matching scores as the command palette does, which is close to Doom's orderless with =orderless-flex= but takes no separators: spaces in what's typed are ignored.
233- The list that opens by itself reads one pause and one length for every position (=corfu-auto-delay=, =corfu-auto-prefix=), with Doom's macOS values as defaults (0.4 seconds, two characters).
234- =[[id:= completes every heading in your folders, as =org-roam-node-insert= completes nodes, but a heading without an =ID= gets one when chosen, which org-roam leaves to =org-id-get-create=. The description is the heading's title as written. org-roam's =roam:= links aren't completed.
235- Property values come from the index as well as the buffer; Org's =org-read-property-value= offers only the buffer's.
236
226** Known differences from Emacs Org 237** Known differences from Emacs Org
227 238
228orgstar refuses some things with a message rather than doing something different from Emacs. These are the ones found in the current version. 239orgstar refuses some things with a message rather than doing something different from Emacs. These are the ones found in the current version.
l10n/Localizable.xcstrings +547 · view
@@ -3852,6 +3852,40 @@
3852 } 3852 }
3853 } 3853 }
3854 }, 3854 },
3855 "After a pause of %lld ms": {
3856 "localizations": {
3857 "de": {
3858 "stringUnit": {
3859 "state": "translated",
3860 "value": "Nach einer Pause von %lld ms"
3861 }
3862 },
3863 "es": {
3864 "stringUnit": {
3865 "state": "translated",
3866 "value": "Tras una pausa de %lld ms"
3867 }
3868 },
3869 "fr": {
3870 "stringUnit": {
3871 "state": "translated",
3872 "value": "Après une pause de %lld ms"
3873 }
3874 },
3875 "ja": {
3876 "stringUnit": {
3877 "state": "translated",
3878 "value": "%lld ms の休止後"
3879 }
3880 },
3881 "pt-BR": {
3882 "stringUnit": {
3883 "state": "translated",
3884 "value": "Após uma pausa de %lld ms"
3885 }
3886 }
3887 }
3888 },
3855 "Agenda": { 3889 "Agenda": {
3856 "comment": "Command title", 3890 "comment": "Command title",
3857 "localizations": { 3891 "localizations": {
@@ -5254,6 +5288,74 @@
5254 } 5288 }
5255 } 5289 }
5256 }, 5290 },
5291 "As the keys do (by itself with Doom)": {
5292 "localizations": {
5293 "de": {
5294 "stringUnit": {
5295 "state": "translated",
5296 "value": "Wie die Tasten es tun (bei Doom von selbst)"
5297 }
5298 },
5299 "es": {
5300 "stringUnit": {
5301 "state": "translated",
5302 "value": "Como las teclas (sola con Doom)"
5303 }
5304 },
5305 "fr": {
5306 "stringUnit": {
5307 "state": "translated",
5308 "value": "Comme les touches (d'elle-même avec Doom)"
5309 }
5310 },
5311 "ja": {
5312 "stringUnit": {
5313 "state": "translated",
5314 "value": "キー設定に従う(Doomでは自動)"
5315 }
5316 },
5317 "pt-BR": {
5318 "stringUnit": {
5319 "state": "translated",
5320 "value": "Como as teclas fazem (sozinha com Doom)"
5321 }
5322 }
5323 }
5324 },
5325 "As the keys do (letters in order with Doom)": {
5326 "localizations": {
5327 "de": {
5328 "stringUnit": {
5329 "state": "translated",
5330 "value": "Wie die Tasten es tun (bei Doom Buchstaben in Reihenfolge)"
5331 }
5332 },
5333 "es": {
5334 "stringUnit": {
5335 "state": "translated",
5336 "value": "Como las teclas (letras en orden con Doom)"
5337 }
5338 },
5339 "fr": {
5340 "stringUnit": {
5341 "state": "translated",
5342 "value": "Comme les touches (lettres dans l'ordre avec Doom)"
5343 }
5344 },
5345 "ja": {
5346 "stringUnit": {
5347 "state": "translated",
5348 "value": "キー設定に従う(Doomでは文字の順序で一致)"
5349 }
5350 },
5351 "pt-BR": {
5352 "stringUnit": {
5353 "state": "translated",
5354 "value": "Como as teclas fazem (letras em ordem com Doom)"
5355 }
5356 }
5357 }
5358 },
5257 "Ask what to do with idle time while clocked in": { 5359 "Ask what to do with idle time while clocked in": {
5258 "localizations": { 5360 "localizations": {
5259 "de": { 5361 "de": {
@@ -6598,6 +6700,40 @@
6598 } 6700 }
6599 } 6701 }
6600 }, 6702 },
6703 "By itself as you type": {
6704 "localizations": {
6705 "de": {
6706 "stringUnit": {
6707 "state": "translated",
6708 "value": "Von selbst beim Tippen"
6709 }
6710 },
6711 "es": {
6712 "stringUnit": {
6713 "state": "translated",
6714 "value": "Sola al escribir"
6715 }
6716 },
6717 "fr": {
6718 "stringUnit": {
6719 "state": "translated",
6720 "value": "D'elle-même pendant la frappe"
6721 }
6722 },
6723 "ja": {
6724 "stringUnit": {
6725 "state": "translated",
6726 "value": "入力中に自動で"
6727 }
6728 },
6729 "pt-BR": {
6730 "stringUnit": {
6731 "state": "translated",
6732 "value": "Sozinha ao digitar"
6733 }
6734 }
6735 }
6736 },
6601 "C-c ' or ⌘Return saves, Escape or C-c C-k leaves": { 6737 "C-c ' or ⌘Return saves, Escape or C-c C-k leaves": {
6602 "localizations": { 6738 "localizations": {
6603 "de": { 6739 "de": {
@@ -7220,6 +7356,40 @@
7220 } 7356 }
7221 } 7357 }
7222 }, 7358 },
7359 "Candidates": {
7360 "localizations": {
7361 "de": {
7362 "stringUnit": {
7363 "state": "translated",
7364 "value": "Kandidaten"
7365 }
7366 },
7367 "es": {
7368 "stringUnit": {
7369 "state": "translated",
7370 "value": "Candidatos"
7371 }
7372 },
7373 "fr": {
7374 "stringUnit": {
7375 "state": "translated",
7376 "value": "Candidats"
7377 }
7378 },
7379 "ja": {
7380 "stringUnit": {
7381 "state": "translated",
7382 "value": "候補"
7383 }
7384 },
7385 "pt-BR": {
7386 "stringUnit": {
7387 "state": "translated",
7388 "value": "Candidatos"
7389 }
7390 }
7391 }
7392 },
7223 "Capture": { 7393 "Capture": {
7224 "localizations": { 7394 "localizations": {
7225 "de": { 7395 "de": {
@@ -10047,6 +10217,76 @@
10047 } 10217 }
10048 } 10218 }
10049 }, 10219 },
10220 "Complete Word": {
10221 "comment": "Command title",
10222 "localizations": {
10223 "de": {
10224 "stringUnit": {
10225 "state": "translated",
10226 "value": "Wort vervollständigen"
10227 }
10228 },
10229 "es": {
10230 "stringUnit": {
10231 "state": "translated",
10232 "value": "Completar palabra"
10233 }
10234 },
10235 "fr": {
10236 "stringUnit": {
10237 "state": "translated",
10238 "value": "Compléter le mot"
10239 }
10240 },
10241 "ja": {
10242 "stringUnit": {
10243 "state": "translated",
10244 "value": "単語を補完"
10245 }
10246 },
10247 "pt-BR": {
10248 "stringUnit": {
10249 "state": "translated",
10250 "value": "Completar Palavra"
10251 }
10252 }
10253 }
10254 },
10255 "Complete Word, Last First": {
10256 "comment": "Command title",
10257 "localizations": {
10258 "de": {
10259 "stringUnit": {
10260 "state": "translated",
10261 "value": "Wort vervollständigen, letztes zuerst"
10262 }
10263 },
10264 "es": {
10265 "stringUnit": {
10266 "state": "translated",
10267 "value": "Completar palabra, la última primero"
10268 }
10269 },
10270 "fr": {
10271 "stringUnit": {
10272 "state": "translated",
10273 "value": "Compléter le mot, le dernier d'abord"
10274 }
10275 },
10276 "ja": {
10277 "stringUnit": {
10278 "state": "translated",
10279 "value": "単語を補完(最後から)"
10280 }
10281 },
10282 "pt-BR": {
10283 "stringUnit": {
10284 "state": "translated",
10285 "value": "Completar Palavra, Última Primeiro"
10286 }
10287 }
10288 }
10289 },
10050 "Complete at Point": { 10290 "Complete at Point": {
10051 "comment": "Command title", 10291 "comment": "Command title",
10052 "localizations": { 10292 "localizations": {
@@ -10082,6 +10322,74 @@
10082 } 10322 }
10083 } 10323 }
10084 }, 10324 },
10325 "Completion": {
10326 "localizations": {
10327 "de": {
10328 "stringUnit": {
10329 "state": "translated",
10330 "value": "Vervollständigung"
10331 }
10332 },
10333 "es": {
10334 "stringUnit": {
10335 "state": "translated",
10336 "value": "Compleción"
10337 }
10338 },
10339 "fr": {
10340 "stringUnit": {
10341 "state": "translated",
10342 "value": "Complétion"
10343 }
10344 },
10345 "ja": {
10346 "stringUnit": {
10347 "state": "translated",
10348 "value": "補完"
10349 }
10350 },
10351 "pt-BR": {
10352 "stringUnit": {
10353 "state": "translated",
10354 "value": "Completar"
10355 }
10356 }
10357 }
10358 },
10359 "Completion list opens": {
10360 "localizations": {
10361 "de": {
10362 "stringUnit": {
10363 "state": "translated",
10364 "value": "Vervollständigungsliste öffnet sich"
10365 }
10366 },
10367 "es": {
10368 "stringUnit": {
10369 "state": "translated",
10370 "value": "La lista de compleción se abre"
10371 }
10372 },
10373 "fr": {
10374 "stringUnit": {
10375 "state": "translated",
10376 "value": "La liste de complétion s'ouvre"
10377 }
10378 },
10379 "ja": {
10380 "stringUnit": {
10381 "state": "translated",
10382 "value": "補完リストを開く"
10383 }
10384 },
10385 "pt-BR": {
10386 "stringUnit": {
10387 "state": "translated",
10388 "value": "A lista de completar abre"
10389 }
10390 }
10391 }
10392 },
10085 "Configuration": { 10393 "Configuration": {
10086 "localizations": { 10394 "localizations": {
10087 "de": { 10395 "de": {
@@ -13160,6 +13468,40 @@
13160 } 13468 }
13161 } 13469 }
13162 }, 13470 },
13471 "Doom's keys open the list by itself and match letters in order, as Doom's corfu does; the Emacs and Mac keys do neither unless set here. Expand Word completes the word before the caret from your files whatever is set.": {
13472 "localizations": {
13473 "de": {
13474 "stringUnit": {
13475 "state": "translated",
13476 "value": "Die Doom-Tasten öffnen die Liste von selbst und finden Buchstaben in Reihenfolge, wie Dooms corfu; die Emacs- und Mac-Tasten tun beides nicht, außer es ist hier eingestellt. „Wort erweitern“ vervollständigt das Wort vor der Einfügemarke aus deinen Dateien, unabhängig von diesen Einstellungen."
13477 }
13478 },
13479 "es": {
13480 "stringUnit": {
13481 "state": "translated",
13482 "value": "Las teclas de Doom abren la lista solas y buscan letras en orden, como corfu en Doom; las teclas de Emacs y Mac no hacen ninguna de las dos cosas salvo que se ajuste aquí. Expandir palabra completa la palabra antes del cursor a partir de tus archivos, con cualquier ajuste."
13483 }
13484 },
13485 "fr": {
13486 "stringUnit": {
13487 "state": "translated",
13488 "value": "Les touches Doom ouvrent la liste d'elles-mêmes et cherchent les lettres dans l'ordre, comme corfu dans Doom ; les touches Emacs et Mac ne font ni l'un ni l'autre sauf si c'est réglé ici. Développer le mot complète le mot avant le curseur à partir de vos fichiers, quels que soient ces réglages."
13489 }
13490 },
13491 "ja": {
13492 "stringUnit": {
13493 "state": "translated",
13494 "value": "Doomのキーでは、Doomのcorfuのようにリストが自動で開き、文字の順序で一致します。EmacsとMacのキーでは、ここで設定しない限りどちらも行いません。「単語を展開」は設定にかかわらず、カーソルの前の単語をファイルから補完します。"
13495 }
13496 },
13497 "pt-BR": {
13498 "stringUnit": {
13499 "state": "translated",
13500 "value": "As teclas do Doom abrem a lista sozinhas e buscam letras em ordem, como o corfu do Doom; as teclas do Emacs e do Mac não fazem nenhum dos dois, a menos que configurado aqui. Expandir Palavra completa a palavra antes do cursor a partir dos seus arquivos, qualquer que seja a configuração."
13501 }
13502 }
13503 }
13504 },
13163 "Doom's own org defaults are read from the folder Doom is installed in": { 13505 "Doom's own org defaults are read from the folder Doom is installed in": {
13164 "localizations": { 13506 "localizations": {
13165 "de": { 13507 "de": {
@@ -14844,6 +15186,41 @@
14844 } 15186 }
14845 } 15187 }
14846 }, 15188 },
15189 "Expand Word": {
15190 "comment": "Command title",
15191 "localizations": {
15192 "de": {
15193 "stringUnit": {
15194 "state": "translated",
15195 "value": "Wort erweitern"
15196 }
15197 },
15198 "es": {
15199 "stringUnit": {
15200 "state": "translated",
15201 "value": "Expandir palabra"
15202 }
15203 },
15204 "fr": {
15205 "stringUnit": {
15206 "state": "translated",
15207 "value": "Développer le mot"
15208 }
15209 },
15210 "ja": {
15211 "stringUnit": {
15212 "state": "translated",
15213 "value": "単語を展開"
15214 }
15215 },
15216 "pt-BR": {
15217 "stringUnit": {
15218 "state": "translated",
15219 "value": "Expandir Palavra"
15220 }
15221 }
15222 }
15223 },
14847 "Expanded": { 15224 "Expanded": {
14848 "localizations": { 15225 "localizations": {
14849 "de": { 15226 "de": {
@@ -18183,6 +18560,40 @@
18183 } 18560 }
18184 } 18561 }
18185 }, 18562 },
18563 "Have its letters in order, best first": {
18564 "localizations": {
18565 "de": {
18566 "stringUnit": {
18567 "state": "translated",
18568 "value": "Enthalten seine Buchstaben in Reihenfolge, beste zuerst"
18569 }
18570 },
18571 "es": {
18572 "stringUnit": {
18573 "state": "translated",
18574 "value": "Contienen sus letras en orden, las mejores primero"
18575 }
18576 },
18577 "fr": {
18578 "stringUnit": {
18579 "state": "translated",
18580 "value": "Contiennent ses lettres dans l'ordre, les meilleurs d'abord"
18581 }
18582 },
18583 "ja": {
18584 "stringUnit": {
18585 "state": "translated",
18586 "value": "文字を順に含む(一致度順)"
18587 }
18588 },
18589 "pt-BR": {
18590 "stringUnit": {
18591 "state": "translated",
18592 "value": "Têm as letras em ordem, melhores primeiro"
18593 }
18594 }
18595 }
18596 },
18186 "Headings": { 18597 "Headings": {
18187 "localizations": { 18598 "localizations": {
18188 "de": { 18599 "de": {
@@ -27447,6 +27858,40 @@
27447 } 27858 }
27448 } 27859 }
27449 }, 27860 },
27861 "Once %lld characters are typed": {
27862 "localizations": {
27863 "de": {
27864 "stringUnit": {
27865 "state": "translated",
27866 "value": "Sobald %lld Zeichen getippt sind"
27867 }
27868 },
27869 "es": {
27870 "stringUnit": {
27871 "state": "translated",
27872 "value": "Cuando se han escrito %lld caracteres"
27873 }
27874 },
27875 "fr": {
27876 "stringUnit": {
27877 "state": "translated",
27878 "value": "Dès que %lld caractères sont tapés"
27879 }
27880 },
27881 "ja": {
27882 "stringUnit": {
27883 "state": "translated",
27884 "value": "%lld 文字入力したら"
27885 }
27886 },
27887 "pt-BR": {
27888 "stringUnit": {
27889 "state": "translated",
27890 "value": "Depois de digitar %lld caracteres"
27891 }
27892 }
27893 }
27894 },
27450 "One payment, no subscription": { 27895 "One payment, no subscription": {
27451 "localizations": { 27896 "localizations": {
27452 "de": { 27897 "de": {
@@ -27617,6 +28062,40 @@
27617 } 28062 }
27618 } 28063 }
27619 }, 28064 },
28065 "Only with a key": {
28066 "localizations": {
28067 "de": {
28068 "stringUnit": {
28069 "state": "translated",
28070 "value": "Nur mit einer Taste"
28071 }
28072 },
28073 "es": {
28074 "stringUnit": {
28075 "state": "translated",
28076 "value": "Solo con una tecla"
28077 }
28078 },
28079 "fr": {
28080 "stringUnit": {
28081 "state": "translated",
28082 "value": "Seulement avec une touche"
28083 }
28084 },
28085 "ja": {
28086 "stringUnit": {
28087 "state": "translated",
28088 "value": "キーを押したときのみ"
28089 }
28090 },
28091 "pt-BR": {
28092 "stringUnit": {
28093 "state": "translated",
28094 "value": "Só com uma tecla"
28095 }
28096 }
28097 }
28098 },
27620 "Open": { 28099 "Open": {
27621 "localizations": { 28100 "localizations": {
27622 "de": { 28101 "de": {
@@ -37631,6 +38110,40 @@
37631 } 38110 }
37632 } 38111 }
37633 }, 38112 },
38113 "Start with what's typed": {
38114 "localizations": {
38115 "de": {
38116 "stringUnit": {
38117 "state": "translated",
38118 "value": "Beginnen mit dem Getippten"
38119 }
38120 },
38121 "es": {
38122 "stringUnit": {
38123 "state": "translated",
38124 "value": "Empiezan por lo escrito"
38125 }
38126 },
38127 "fr": {
38128 "stringUnit": {
38129 "state": "translated",
38130 "value": "Commencent par ce qui est tapé"
38131 }
38132 },
38133 "ja": {
38134 "stringUnit": {
38135 "state": "translated",
38136 "value": "入力した文字で始まる"
38137 }
38138 },
38139 "pt-BR": {
38140 "stringUnit": {
38141 "state": "translated",
38142 "value": "Começam com o que foi digitado"
38143 }
38144 }
38145 }
38146 },
37634 "Starting point": { 38147 "Starting point": {
37635 "localizations": { 38148 "localizations": {
37636 "de": { 38149 "de": {
@@ -40172,6 +40685,40 @@
40172 } 40685 }
40173 } 40686 }
40174 }, 40687 },
40688 "The list offers words from open files and folders": {
40689 "localizations": {
40690 "de": {
40691 "stringUnit": {
40692 "state": "translated",
40693 "value": "Die Liste bietet Wörter aus offenen Dateien und Ordnern an"
40694 }
40695 },
40696 "es": {
40697 "stringUnit": {
40698 "state": "translated",
40699 "value": "La lista ofrece palabras de archivos abiertos y carpetas"
40700 }
40701 },
40702 "fr": {
40703 "stringUnit": {
40704 "state": "translated",
40705 "value": "La liste propose des mots des fichiers ouverts et des dossiers"
40706 }
40707 },
40708 "ja": {
40709 "stringUnit": {
40710 "state": "translated",
40711 "value": "開いているファイルとフォルダの単語をリストに表示"
40712 }
40713 },
40714 "pt-BR": {
40715 "stringUnit": {
40716 "state": "translated",
40717 "value": "A lista oferece palavras de arquivos abertos e pastas"
40718 }
40719 }
40720 }
40721 },
40175 "The next agenda entry, or how many are open today.": { 40722 "The next agenda entry, or how many are open today.": {
40176 "localizations": { 40723 "localizations": {
40177 "de": { 40724 "de": {
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