Commit 7d77bed210

7d77bed2106790e8555535f723f1411dd6d8e268

parent: 8c691f1229

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 03:33 UTC

Palette: recent commands first, frequent ones ranked higher

An empty query lists the last ten commands run from the palette, then the
rest by title. Matches gain a bonus for use, at most one word-start match.
Recents and use counts are kept in UserDefaults by command id, in OrgApp
for the Mac palette and the iOS Commands list.

Closes #138

Layout: unified · split

Changed files (4)
Sources/OrgApp/CommandRanking.swift added +138 · view
@@ -0,0 +1,138 @@
1import Foundation
2import OrgCore
3
4/// The commands run from the command palette: the last ten, most recent first, and how often
5/// each was run, kept in `UserDefaults` by command id.
6public final class CommandUsage: Sendable {
7 public static let shared = CommandUsage()
8 /// The recents the palette lists for an empty query.
9 public static let recentLimit = 10
10 /// Uses past this count add nothing more to a command's rank.
11 public static let usesCounted = 20
12
13 private nonisolated(unsafe) let defaults: UserDefaults
14 private static let recentKey = "commandRecents"
15 private static let countsKey = "commandUseCounts"
16
17 public init(defaults: UserDefaults = .standard) {
18 self.defaults = defaults
19 }
20
21 /// Command ids, most recent first.
22 public var recent: [String] { defaults.stringArray(forKey: Self.recentKey) ?? [] }
23
24 public func uses(of id: String) -> Int {
25 (defaults.dictionary(forKey: Self.countsKey)?[id] as? Int) ?? 0
26 }
27
28 public func record(_ id: String) {
29 defaults.set(Array(([id] + recent.filter { $0 != id }).prefix(Self.recentLimit)), forKey: Self.recentKey)
30 var counts = defaults.dictionary(forKey: Self.countsKey) ?? [:]
31 counts[id] = ((counts[id] as? Int) ?? 0) + 1
32 defaults.set(counts, forKey: Self.countsKey)
33 }
34
35 /// What frequent use adds to a `FuzzyMatch.score`: at most one word-start match, so a
36 /// frequent command wins a tie and never beats a clearly better match.
37 public func bonus(for id: String) -> Int {
38 min(uses(of: id), Self.usesCounted) * FuzzyMatch.wordStartBonus * 100 / Self.usesCounted
39 }
40}
41
42/// The command palette's order, on the Mac and on iOS.
43public enum CommandRanking {
44 /// For an empty query, the recent commands among `items` and then the rest by title; for a
45 /// query, no recents and the matches best first, frequent use breaking near ties.
46 public static func rank<Item>(_ items: [Item], query: String, usage: CommandUsage = .shared,
47 id: (Item) -> String, titles: (Item) -> [String]) -> (recent: [Item], rest: [Item]) {
48 func title(_ item: Item) -> String { titles(item).first ?? id(item) }
49 if query.allSatisfy(\.isWhitespace) {
50 let recentIDs = usage.recent
51 let recent = recentIDs.compactMap { wanted in items.first { id($0) == wanted } }
52 let rest = items.filter { !recentIDs.contains(id($0)) }
53 .sorted { title($0).localizedStandardCompare(title($1)) == .orderedAscending }
54 return (recent, rest)
55 }
56 let scored: [(item: Item, score: Int)] = items.compactMap { item in
57 guard let score = titles(item).compactMap({ FuzzyMatch.score(query, $0) }).max() else { return nil }
58 return (item, score + usage.bonus(for: id(item)))
59 }
60 let ranked = scored.sorted { a, b in
61 a.score != b.score ? a.score > b.score : title(a.item).localizedStandardCompare(title(b.item)) == .orderedAscending
62 }
63 return ([], ranked.map(\.item))
64 }
65}
66
67/// Commands by subject: the Org menu's submenus on the Mac and iPad, and the sections of the
68/// iOS Commands list.
69public enum CommandGroups {
70 public struct Group: Sendable {
71 public let title: String
72 /// A command belongs to the first group with a prefix its id starts with.
73 public let prefixes: [String]
74 }
75
76 /// The Org menu's submenus, in menu order.
77 public static let orgMenu: [Group] = [
78 Group(title: String(localized: "Visibility", comment: "Org menu submenu"), prefixes: ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
79 Group(title: String(localized: "Headings", comment: "Org menu submenu"), prefixes: ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
80 Group(title: String(localized: "TODO and Tags", comment: "Org menu submenu"), prefixes: ["org.todo.", "org.priority.", "org.tags.", "org.effort."]),
81 Group(title: String(localized: "Properties and Columns", comment: "Org menu submenu"), prefixes: ["org.property.", "org.columns", "org.drawer."]),
82 Group(title: String(localized: "Dates and Timers", comment: "Org menu submenu"), prefixes: ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
83 Group(title: String(localized: "Lists", comment: "Org menu submenu"), prefixes: ["org.item.", "org.checkbox."]),
84 Group(title: String(localized: "Tables", comment: "Org menu submenu"), prefixes: ["org.table", "app.table-", "app.plot"]),
85 Group(title: String(localized: "Links and Footnotes", comment: "Org menu submenu"), prefixes: ["org.link.", "org.id.", "org.footnote."]),
86 Group(title: String(localized: "Blocks", comment: "Org menu submenu"), prefixes: ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
87 Group(title: String(localized: "Text", comment: "Org menu submenu"), prefixes: ["org.emphasize", "org.fill-"]),
88 Group(title: String(localized: "Attachments", comment: "Org menu submenu"), prefixes: ["app.attach."]),
89 Group(title: String(localized: "Notes", comment: "Org menu submenu"), prefixes: ["app.dailies.", "app.node.", "app.backlinks"]),
90 Group(title: String(localized: "Encryption", comment: "Org menu submenu"), prefixes: ["app.crypt."]),
91 ]
92
93 /// The Org menu's groups and the app's commands outside the Org menu.
94 public static let commandList: [Group] = orgMenu + [
95 Group(title: String(localized: "Clock", comment: "Commands list section"), prefixes: ["app.clock."]),
96 Group(title: String(localized: "Export", comment: "Commands list section"), prefixes: ["app.export", "app.copy-rich-text", "app.publish"]),
97 Group(title: String(localized: "File", comment: "Commands list section"), prefixes: ["app.save", "app.word-count", "app.recovery", "app.sync-conflicts"]),
98 Group(title: String(localized: "Edit", comment: "Commands list section"), prefixes: ["edit."]),
99 Group(title: String(localized: "View", comment: "Commands list section"), prefixes: ["app.toggle-markup", "editor.", "app.split-", "app.pane-"]),
100 ]
101
102 /// The index in `groups` of the group `id` belongs to, or nil for none.
103 public static func group(of id: String, in groups: [Group] = orgMenu) -> Int? {
104 groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
105 }
106}
107
108/// Why a command doesn't apply at the caret, for a list that shows it greyed: what it needs
109/// that the caret isn't in, or that there is nothing for it to do there.
110public enum CommandReason {
111 public static func reason(for id: String, in context: EditContext) -> String {
112 func starts(_ prefixes: String...) -> Bool { prefixes.contains { id.hasPrefix($0) } }
113 if starts("org.table", "app.table-export", "app.plot"), !KeyContext.holds("table", in: context) {
114 return String(localized: "No table at point")
115 }
116 if starts("org.item.", "org.checkbox."), !KeyContext.holds("item", in: context) {
117 return String(localized: "Not in a list", comment: "Why a command is greyed in the Commands list")
118 }
119 if starts("org.babel."), !KeyContext.holds("src", in: context) {
120 return String(localized: "Not in a code block", comment: "Why a command is greyed in the Commands list")
121 }
122 if starts("org.link.open"), !OpenLinkAtPoint().applies(in: context) {
123 return String(localized: "Not on a link", comment: "Why a command is greyed in the Commands list")
124 }
125 if starts("org.timestamp.up", "org.timestamp.down", "org.timestamp.day-", "org.timestamp.evaluate-range"), !KeyContext.holds("timestamp", in: context) {
126 return String(localized: "Not on a timestamp", comment: "Why a command is greyed in the Commands list")
127 }
128 if starts("app.crypt.open-entry", "app.crypt.decrypt-entry"), OrgCrypt.encryptedRange(context.text, at: context.caret) == nil {
129 return String(localized: "Not an encrypted entry")
130 }
131 if starts("org.heading.", "org.subtree.", "org.todo.", "org.priority.", "org.tags.", "org.property.", "org.effort.",
132 "org.schedule", "org.deadline", "org.archive.", "app.refile", "app.archive", "app.crypt.encrypt-entry"),
133 context.tree.root.child(containing: context.caret)?.kind != .section {
134 return String(localized: "Not in a subtree")
135 }
136 return String(localized: "Nothing to do here", comment: "Why a command is greyed in the Commands list")
137 }
138}
Sources/OrgApp/FileTree.swift +4 −1 · view
@@ -72,6 +72,9 @@ public struct FileTreeNode: Sendable, Hashable, Identifiable {
7272/// Subsequence matching for quick open: every query character must appear in order. Matches
7373/// at word starts and runs of consecutive characters score higher; shorter names win ties.
7474public enum FuzzyMatch {
75 /// What a match at a word start adds, before `score` scales it by 100.
76 public static let wordStartBonus = 8
77
7578 public static func score(_ query: String, _ candidate: String) -> Int? {
7679 let query = Array(query.lowercased().filter { !$0.isWhitespace })
7780 let text = Array(candidate.lowercased())
@@ -82,7 +85,7 @@ public enum FuzzyMatch {
8285 for (i, c) in text.enumerated() where q < query.count && c == query[q] {
8386 score += 1
8487 if i == previousMatch + 1 { score += 5 }
85 if i == 0 || "/ -_.".contains(text[i - 1]) { score += 8 }
88 if i == 0 || "/ -_.".contains(text[i - 1]) { score += wordStartBonus }
8689 previousMatch = i
8790 q += 1
8891 }
Sources/Orgstar/Keys.swift +39 −24 · view
@@ -303,7 +303,8 @@ let hiddenCommandIDs = AppStoreCommands.hidden
303303let hiddenCommandIDs: Set<String> = []
304304#endif
305305
306/// M-x and ⇧⌘P: every command by title, with its keys.
306/// M-x and ⇧⌘P: every command by title, with its keys. An empty query lists the commands run
307/// from here most recently, then the rest; matches rank commands used often a little higher.
307308struct PaletteView: View {
308309 let commands: AppCommands
309310 let run: (String) -> Void
@@ -312,43 +313,32 @@ struct PaletteView: View {
312313 @State private var selected = 0
313314 @Environment(\.dismiss) private var dismiss
314315
315 private var matches: [EditorCommand] {
316 let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) }.compactMap { command in
317 guard let score = FuzzyMatch.score(query, command.localizedTitle) ?? FuzzyMatch.score(query, command.title) else { return nil }
318 return (command, score)
319 }
320 return scored.sorted { $0.score != $1.score ? $0.score > $1.score : $0.command.localizedTitle < $1.command.localizedTitle }.map(\.command)
316 private var matches: (recent: [EditorCommand], rest: [EditorCommand]) {
317 CommandRanking.rank(EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) }, query: query,
318 id: \.id, titles: { [$0.localizedTitle, $0.title] })
321319 }
322320
323321 var body: some View {
324 let matches = matches
322 let ranked = matches
323 let matches = ranked.recent + ranked.rest
325324 let current = min(selected, matches.count - 1)
326325 VStack(spacing: 0) {
327326 TextField("Run command", text: $query)
328327 .textFieldStyle(.plain)
329328 .font(.title3)
330329 .padding(12)
331 .onSubmit { if current >= 0 { run(matches[current].id) } }
330 .onSubmit { if current >= 0 { choose(matches[current].id) } }
332331 .movesSelection($selected, current: current, count: matches.count)
333332 .onChange(of: query) { selected = 0 }
334333 Divider()
335334 ScrollViewReader { proxy in
336 List(matches.indices, id: \.self) { index in
337 let command = matches[index]
338 Button {
339 run(command.id)
340 } label: {
341 HStack {
342 Text(command.localizedTitle)
343 Spacer()
344 if let keys = commands.keyLabel(for: command.id) {
345 Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
346 }
347 }
348 .contentShape(Rectangle())
335 List {
336 if !ranked.recent.isEmpty {
337 Section("Recent") { rows(matches, 0..<ranked.recent.count, current) }
338 Section("All Commands") { rows(matches, ranked.recent.count..<matches.count, current) }
339 } else {
340 rows(matches, matches.indices, current)
349341 }
350 .buttonStyle(.plain)
351 .selectedRow(index == current)
352342 }
353343 .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
354344 }
@@ -356,4 +346,29 @@ struct PaletteView: View {
356346 .frame(width: 520, height: 360)
357347 .onExitCommand { dismiss() }
358348 }
349
350 private func rows(_ matches: [EditorCommand], _ indices: Range<Int>, _ current: Int) -> some View {
351 ForEach(indices, id: \.self) { index in
352 let command = matches[index]
353 Button {
354 choose(command.id)
355 } label: {
356 HStack {
357 Text(command.localizedTitle)
358 Spacer()
359 if let keys = commands.keyLabel(for: command.id) {
360 Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
361 }
362 }
363 .contentShape(Rectangle())
364 }
365 .buttonStyle(.plain)
366 .selectedRow(index == current)
367 }
368 }
369
370 private func choose(_ id: String) {
371 CommandUsage.shared.record(id)
372 run(id)
373 }
359374}
Tests/OrgAppTests/CommandRankingTests.swift added +71 · view
@@ -0,0 +1,71 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgApp
5
6struct CommandRankingTests {
7 private func rank(_ titles: [String], _ query: String, _ usage: CommandUsage) -> (recent: [String], rest: [String]) {
8 CommandRanking.rank(titles, query: query, usage: usage, id: { $0 }, titles: { [$0] })
9 }
10
11 @Test func recentsAreTheLastTenMostRecentFirst() {
12 let usage = CommandUsage(defaults: TestDefaults("orgstar-command-usage"))
13 for n in 1...12 { usage.record("c\(n)") }
14 usage.record("c5")
15 #expect(usage.recent == ["c5", "c12", "c11", "c10", "c9", "c8", "c7", "c6", "c4", "c3"])
16 #expect(usage.uses(of: "c5") == 2 && usage.uses(of: "c1") == 1 && usage.uses(of: "other") == 0)
17 }
18
19 @Test func emptyQueryListsRecentsThenTheRestByTitle() {
20 let usage = CommandUsage(defaults: TestDefaults("orgstar-command-usage"))
21 usage.record("Tags")
22 usage.record("Gone")
23 usage.record("Schedule")
24 let ranked = rank(["Tags", "Archive", "Schedule", "Deadline"], " ", usage)
25 // A recent command no longer offered is left out.
26 #expect(ranked.recent == ["Schedule", "Tags"])
27 #expect(ranked.rest == ["Archive", "Deadline"])
28 }
29
30 @Test func frequentUseBreaksTies() {
31 let usage = CommandUsage(defaults: TestDefaults("orgstar-command-usage"))
32 #expect(FuzzyMatch.score("ac", "Alpha Copy") == FuzzyMatch.score("ac", "Alpha Cuts"))
33 #expect(rank(["Alpha Cuts", "Alpha Copy"], "ac", usage).rest == ["Alpha Copy", "Alpha Cuts"])
34 usage.record("Alpha Cuts")
35 let ranked = rank(["Alpha Cuts", "Alpha Copy"], "ac", usage)
36 #expect(ranked.recent.isEmpty && ranked.rest == ["Alpha Cuts", "Alpha Copy"])
37 }
38
39 @Test func frequentUseNeverBeatsAClearlyBetterMatch() throws {
40 let usage = CommandUsage(defaults: TestDefaults("orgstar-command-usage"))
41 for _ in 0..<100 { usage.record("Make Fun") }
42 #expect(usage.bonus(for: "Make Fun") == FuzzyMatch.wordStartBonus * 100)
43 // One word start apart, less one character of length.
44 let better = try #require(FuzzyMatch.score("mu", "Move Up")), worse = try #require(FuzzyMatch.score("mu", "Make Fun"))
45 #expect(better - worse == FuzzyMatch.wordStartBonus * 100 + 1)
46 #expect(rank(["Make Fun", "Move Up"], "mu", usage).rest == ["Move Up", "Make Fun"])
47 }
48
49 @Test func groupsByFirstMatchingPrefix() {
50 #expect(CommandGroups.group(of: "org.table.align").map { CommandGroups.orgMenu[$0].prefixes.first } == "org.table")
51 #expect(CommandGroups.group(of: "org.ctrl-c-ctrl-c") == nil)
52 #expect(CommandGroups.group(of: "app.clock.in") == nil)
53 #expect(CommandGroups.group(of: "app.clock.in", in: CommandGroups.commandList) == CommandGroups.orgMenu.count)
54 }
55
56 private func context(_ text: String, caret: Int) -> EditContext {
57 EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
58 }
59
60 @Test func reasonNamesWhatTheCaretIsNotIn() {
61 let text = "Before\n* One\nBody\n| a | b |\n- item\n"
62 #expect(CommandReason.reason(for: "org.table.align", in: context(text, caret: 0)) == "No table at point")
63 #expect(CommandReason.reason(for: "org.item.indent", in: context(text, caret: 0)) == "Not in a list")
64 #expect(CommandReason.reason(for: "org.subtree.move-up", in: context(text, caret: 0)) == "Not in a subtree")
65 #expect(CommandReason.reason(for: "org.link.open", in: context(text, caret: 0)) == "Not on a link")
66 #expect(CommandReason.reason(for: "org.babel.execute", in: context(text, caret: 0)) == "Not in a code block")
67 // In the entry, a subtree command that still doesn't apply has nothing to do.
68 #expect(CommandReason.reason(for: "org.subtree.move-up", in: context(text, caret: 15)) == "Nothing to do here")
69 #expect(CommandReason.reason(for: "org.table.align", in: context(text, caret: 20)) == "Nothing to do here")
70 }
71}
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