Skip to content
This repository was archived by the owner on Oct 17, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ All notable changes to this project are documented here. The format follows [Kee
- Settings: shortcut, theme, size, translucency, visible results, sources, search engine, menu bar item, and open at login.
- Liquid Glass on macOS 26 and the popover material on earlier versions, or a solid background.
- System Settings topics and keywords from System Settings' own search terms, so "dark mode", "low power", or "firewall" find the right pane, shown with the pane's icon.
- A result chosen for a query also leans shorter and longer starts of that query its way, so you can type less next time.

### Fixed

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Common Command is built to feel like part of macOS:

- **It matches your Mac.** The panel follows light and dark mode, uses Liquid Glass on macOS 26 (the popover material before that), and highlights with your accent colour. Choose a fixed theme, a solid background, or a size in Settings.
- **It stays out of the way.** The panel never activates the app, so the app you were in stays frontmost and keeps its menu bar. Escape, or a click anywhere else, returns you to it with nothing to restore.
- **It learns.** Whatever you choose for a query comes first the next time you type it, and things you open often rise for every query. Usage decays with a one-week half-life, so last year's habits fade.
- **It learns.** Whatever you choose for a query comes first the next time you type it, and leans the same way for a shorter start: choose Safari for "safari" once, and "sa" prefers it too. Things you open often rise for every query. Usage decays with a one-week half-life, so last year's habits fade.
- **Typing is forgiving.** "vsc" finds Visual Studio Code, "sys set" finds System Settings, "cafe" finds Café. Matched letters are drawn in bold.

Free and open source under the MIT licence. No network access except the web searches and links you open, no analytics, no helper tools, and no Accessibility or Full Disk Access permissions.
Expand Down
27 changes: 13 additions & 14 deletions Sources/CommandKit/Ranker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ public enum Ranker {
) -> [Ranked] {
let q = Fuzzy.prepare(query)
guard !q.isEmpty, limit > 0 else { return [] }
let key = Usage.key(query)
let booster = usage.booster(for: query, at: now)
// Only the best few are ever shown, so keep those in order instead of sorting every match.
var top: [(ranked: Ranked, length: Int)] = []
var top: [(ranked: Ranked, name: [UInt32])] = []
top.reserveCapacity(limit + 1)
for candidate in candidates {
var best: Match?
Expand All @@ -43,29 +43,28 @@ public enum Ranker {
highlightsTitle = false
}
guard let matchScore else { continue }
let score = matchScore + candidate.weight + usage.boost(for: candidate.item.id, key: key, at: now)
let length = candidate.names[0].keys.count
if top.count == limit, let last = top.last, !isOrderedBefore(score, length, candidate.item, last) {
let score = matchScore + candidate.weight + booster.boost(for: candidate.item.id)
let name = candidate.names[0].keys
if top.count == limit, let last = top.last, !isOrderedBefore(score, name, last) {
continue
}
let entry = (
Ranked(item: candidate.item, score: score, highlights: highlightsTitle ? best?.positions ?? [] : []),
length
name
)
let index =
top.firstIndex { !isOrderedBefore($0.ranked.score, $0.length, $0.ranked.item, entry) } ?? top.count
let index = top.firstIndex { !isOrderedBefore($0.ranked.score, $0.name, entry) } ?? top.count
top.insert(entry, at: index)
if top.count > limit { top.removeLast() }
}
return top.map(\.ranked)
}

/// Higher score first; on a tie the shorter name, then alphabetical.
static func isOrderedBefore(_ score: Int, _ length: Int, _ item: Item, _ other: (ranked: Ranked, length: Int))
-> Bool
{
/// Higher score first; on a tie the shorter name, then alphabetical by folded name. A one-letter query
/// ties hundreds of names, so this compares the keys already folded for matching rather than calling
/// `localizedStandardCompare`, which costs more than the match itself.
static func isOrderedBefore(_ score: Int, _ name: [UInt32], _ other: (ranked: Ranked, name: [UInt32])) -> Bool {
if score != other.ranked.score { return score > other.ranked.score }
if length != other.length { return length < other.length }
return item.title.localizedStandardCompare(other.ranked.item.title) == .orderedAscending
if name.count != other.name.count { return name.count < other.name.count }
return name.lexicographicallyPrecedes(other.name)
}
}
49 changes: 40 additions & 9 deletions Sources/CommandKit/Usage.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import Foundation

/// What has been opened, how often, and how recently, and which result was chosen for which query. It
/// moves things you use up the list, and makes the query you typed last time pick the same thing again.
/// moves things you use up the list, makes the query you typed last time pick the same thing again, and
/// lets a shorter or longer start of that query lean the same way.
public struct Usage: Codable, Sendable, Equatable {
struct Entry: Codable, Sendable, Equatable {
/// Uses, each decayed by its age, as of `last`.
Expand Down Expand Up @@ -32,17 +33,47 @@ public struct Usage: Codable, Sendable, Equatable {
}

public func boost(for id: String, query: String, at now: Date) -> Int {
boost(for: id, key: Self.key(query), at: now)
booster(for: query, at: now).boost(for: id)
}

/// For ranking many items against one query: `key` is `Usage.key(query)`, folded once.
func boost(for id: String, key: String, at now: Date) -> Int {
var boost = 0
if choices[key] == id { boost += Self.choiceBoost }
if let entry = entries[id] {
boost += min(Self.maximumFrecencyBoost, Int(12 * log2(1 + decayed(entry, at: now))))
/// Boosts for one query, worked out once so ranking many items costs a lookup each.
public struct Booster: Sendable {
let choices: [String: Int]
let usage: Usage
let now: Date

public func boost(for id: String) -> Int {
var boost = choices[id] ?? 0
if let entry = usage.entries[id] {
boost += min(Usage.maximumFrecencyBoost, Int(12 * log2(1 + usage.decayed(entry, at: now))))
}
return boost
}
}

public func booster(for query: String, at now: Date) -> Booster {
Booster(choices: choiceBoosts(Self.key(query)), usage: self, now: now)
}

/// The exact query earns the full boost. A query that starts a past one ("sa" after choosing Safari for
/// "safari"), or that a past one starts ("safar" after "saf"), earns a share of half of it, in proportion
/// to how much of the longer one they have in common.
func choiceBoosts(_ key: String) -> [String: Int] {
guard !key.isEmpty else { return [:] }
var boosts: [String: Int] = [:]
for (stored, id) in choices {
let boost: Int
if stored == key {
boost = Self.choiceBoost
} else if stored.hasPrefix(key) || key.hasPrefix(stored) {
let shared = min(stored.count, key.count)
boost = Self.choiceBoost / 2 * shared / max(stored.count, key.count)
} else {
continue
}
boosts[id] = max(boosts[id] ?? 0, boost)
}
return boost
return boosts
}

func decayed(_ entry: Entry, at now: Date) -> Double {
Expand Down
28 changes: 28 additions & 0 deletions Tests/CommandKitTests/SearchTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ func titles(_ ranked: [Ranked]) -> [String] { ranked.map(\.item.title) }
#expect(Ranker.rank(apps, query: "saf", usage: usage, now: now, limit: 1).first?.item.title == "Safari")
}

@Test func aChoiceForALongerQueryLeansAShorterOneTheSameWay() {
var usage = Usage()
// Equally frequent, so only the remembered query can separate them.
usage.record("app:Safari", query: "", at: now)
usage.record("app:Sublime Text", query: "sublime", at: now)
#expect(Ranker.rank(apps, query: "s", usage: usage, now: now, limit: 1).first?.item.title == "Sublime Text")
}

@Test func alternativeNamesMatchWithoutHighlighting() {
let localised = [app("Systemeinstellungen", alternatives: ["System Settings"])]
let ranked = Ranker.rank(localised, query: "system set", usage: Usage(), now: now, limit: 1)
Expand Down Expand Up @@ -195,6 +203,26 @@ func titles(_ ranked: [Ranked]) -> [String] { ranked.map(\.item.title) }
#expect(usage.boost(for: "a", query: "cafe", at: now) >= Usage.choiceBoost)
}

@Test func sharedStartsEarnAShareOfTheBoost() {
var usage = Usage()
usage.record("safari", query: "safari", at: now)
usage.record("saf-tool", query: "saf", at: now)
usage.record("slack", query: "sl", at: now)
#expect(usage.choiceBoosts("safari") == ["safari": 120, "saf-tool": 30])
#expect(usage.choiceBoosts("sa") == ["safari": 20, "saf-tool": 40])
#expect(usage.choiceBoosts("safar") == ["safari": 50, "saf-tool": 36])
#expect(usage.choiceBoosts("s") == ["safari": 10, "saf-tool": 20, "slack": 30])
#expect(usage.choiceBoosts("x").isEmpty)
#expect(usage.choiceBoosts("").isEmpty)
}

@Test func anItemChosenForSeveralQueriesTakesTheBestBoost() {
var usage = Usage()
usage.record("safari", query: "sa", at: now)
usage.record("safari", query: "safari", at: now)
#expect(usage.choiceBoosts("saf") == ["safari": 40])
}

@Test func storageStaysBounded() {
var usage = Usage()
for i in 0..<(Usage.maximumEntries + 50) { usage.record("id\(i)", query: "q\(i)", at: now) }
Expand Down
Loading