Skip to content

Search & ranking

Every keystroke runs two public pieces of the library: a matcher that scores each command and says which characters to highlight, and a ranker that folds in priority and how often and how recently a command was used. The lab below runs exactly those two over this app's registry, so the numbers are the ones the palette sorts by.

Search lab

BaletteQuery.Parse:fuzzy rc

# Command Matched on Score Priority Frecency Rank
1 Registering commands title 42.6 0 0 42.6
2 Show detail pane keyword “raycast” 39.47 0 0 39.47
3 Introduction title 26.73 50 0 39.23
4 Options and security keyword “reference” 35.84 0 0 35.84
5 Search and ranking title 35.61 0 0 35.61
6 Modes and sources title 35.53 0 0 35.53
7 Rename project… title 34.7 0 0 34.7
8 Find a person… keyword “search” 32.27 0 0 32.27
9 GitHub repository keyword “source” 32.27 0 0 32.27
10 Türkçe title 28.86 0 0 28.86
11 Keyboard shortcuts title 28.52 0 0 28.52
12 Keyboard and shortcuts title 28.4 0 0 28.4
13 Français title 27.83 0 0 27.83
14 Delete project title 26.64 0 0 26.64
15 Language keyword “direction” 25.92 0 0 25.92
52 commands searched 27 matched matched and ranked in 0.03 msfrecency loads once the page is interactive
// What the lab runs on every keystroke: the palette's own two steps, over what its root page lists.
BaletteQuery query = BaletteQuery.Parse("rc");
var typing = query.Terms.Count > 0;

// The visible commands without a parent and, while typing, the nested ones found from the root too
// (SearchNestedCommands) - except the rows of a multi-select page.
var candidates = Palette.Commands
    .Where(c => c.IsVisible?.Invoke() != false)
    .Where(c => c.Parent is null || (typing && Options.SearchNestedCommands && Palette.Find(c.Parent) is { MultiSelectChildren: false }));

// The matcher picked in the lab; the palette uses Options.Matcher.
IBaletteMatcher matcher = BaletteFuzzyMatcher.Default;
var matches = new List<BaletteMatch>();
foreach (var command in candidates)
{
    if (matcher.Match(command, query, Options.Weights) is { } match)
    {
        matches.Add(match);
    }
}

// Ranker is the BaletteRanker, injected like the options: score, priority and frecency, best first.
List<BaletteMatch> ranked = Ranker.Rank(matches, typing, id => History.Frecency(id));

Operators

A query is split on spaces and every term has to match (AND), each against whichever field scores it best. A term can carry an fzf operator; the rest are fuzzy. ! excludes a command when the title, subtitle, group or keywords contain the term.

QueryMeans
rc Fuzzy: R and C in order, anywhere - word starts score highest.
wrap word Two terms, both required, in any order.
'export Exact: the substring itself, no gaps.
^set Prefix: the field starts with it.
project$ Suffix: the field ends with it.
show !minimap Negation: drops every command that contains the term.
"word wrap" A quoted phrase: matched exactly, the space included.
!"show detail" show A negated phrase: shows, except the one with that phrase. ^"..." and "..."$ anchor a phrase.
^theme | ^lang Alternatives: a | on its own between two terms means either will do, as in fzf.
francais Diacritics folded: finds Français on the Language page, from the root, with its path.
settigns Nothing matches as typed - in the palette itself, a retry allowing a typo finds Settings.
mcp Smart case, all lower case: case is ignored, so it matches MCP server.
Mcp Smart case, with a capital: case now counts, so MCP server drops out.

Curly quotes work as well as straight ones, which some keyboards type, and a quote left open takes the rest of the query while it is typed, so typing one never shows "no results" midway.

Text as people type it

BaletteFuzzyMatcher.Normalize (on by default) matches what people type against what is stored. Every mapping is one character to one, so the highlighting stays exact, and the operators follow the same rules. The language names under Preferences › Language are written as their speakers write them, and while this page is open the palette also lists a few Folding samples - Café Central, كتاب, Order 12… - stored exactly as shown:

TypedFindsWhy
cafe Café Central Latin letters lose their diacritics.
lodz Łódź office Letters with a stroke too, as in fzf.
turkce Türkçe Under Preferences › Language, found from the root.
sao paulo São Paulo office Two terms, both folded.
علی علي Typed with the Persian yeh (ی), stored with the Arabic one (ي).
فارسي فارسی The other way round: typed with the Arabic yeh, stored with the Persian one.
کتاب كتاب Typed with the Persian kaf (ک), stored with the Arabic one (ك).
اسم إسم Alef with hamza or madda is plain alef.
العربيه العربية Typed with heh (ه), stored with teh marbuta (ة).
۱۲ Order 12 Persian digits are ASCII digits.
٣ Step 3 Arabic-Indic digits too.
order Order 12 Fullwidth letters, which some input methods type, are ASCII.

Try puts the query in the lab at the top of the page; its Open the palette with it button runs it in the palette.

  • Latin letters lose their diacritics - unless the term types one itself, as in fzf: café means that letter, so a term with an accent is matched as written.
  • The Arabic and Persian forms of yeh and kaf (ي/ی, ك/ک), alef with hamza or madda, teh marbuta and heh are one letter: which one is stored depends on the keyboard it was typed on.
  • Arabic-Indic and Persian digits are ASCII digits - ۱۲ finds "Order 12" - and fullwidth ASCII is ASCII.
  • new BaletteFuzzyMatcher { Normalize = false } matches literally, like fzf's --literal: pick Fuzzy, literal in the lab and try the rows above again.

Typos

A query that matches nothing is tried once more allowing a typo per term - a missing, extra, wrong or swapped letter in a term of 4 to 7 characters, two from 8 on - so settigns finds Settings. Only a query that found nothing is retried, so a query that works never gets noisier; the results are scored below every exact match, announced, and marked "No exact matches. Showing close ones." (BaletteStrings.ApproximateResults), and BaletteMatch.IsApproximate tells a template so. Turn it off with options.TypoTolerance = false or TypoTolerance="false" on one palette.

The retry is the palette's, not the matcher's, so the lab above finds nothing for these - the palette does:

@* One palette; options.TypoTolerance = false turns the retry off for every palette. *@
<Balette TypoTolerance="false" />

@* A template can tell a close match from an exact one. *@
<Balette>
    <ItemTemplate>
        @context.Row.Command.Title
        @if (context.Row.Match?.IsApproximate == true)
        {
            <small>close match</small>
        }
    </ItemTemplate>
</Balette>

How a score is made

The fuzzy matcher is fzf's algorithm: a dynamic programme that finds the best alignment of the term inside the text. A query matches when its characters appear in order; among all such alignments it keeps the best one, and its positions are the characters highlighted with <mark> - never splitting a letter from its accents or an emoji from its other half.

ScoreValueFor
ScoreMatch16Every matched character
ScoreGapStart / ScoreGapExtension-3 / -1Skipped characters; the first of a gap costs most
BonusBoundary8A word start: gs finds Go to Settings
BonusCamel7A camelCase hump or a letter-to-digit step: fm finds FuzzyMatcher
BonusNonWord8Punctuation the query actually typed
BonusConsecutive4Characters that follow each other, carrying the bonus that started the run
BonusFirstCharMultiplier2The first query character's bonus counts double

Smart case: a term in lower case ignores case, a term with a capital letter respects it (IgnoreCase = true turns that off). Ties go to the shorter text and the earlier match.

Each field's score is multiplied by its weight, so a hit in the title beats the same hit in a keyword, which beats one in the subtitle. These are this app's weights, from BaletteOptions.Weights:

FieldWeight
Title1
Keywords0.9
Subtitle0.7
Group0.5
A nested command's ancestors0.5
Description0.4
Tags0.3
options.Weights.Description = 0.6; // descriptions count for more

Priority and frecency

With a query, the match decides and the rest only nudges it:

rank = score + priority × 0.25 + ln(1 + frecency) × 6

On the empty query there is nothing to match, so priority leads and frecency orders what is left (priority × 1000 + frecency), inside each group. Only the best MaxResults (150) rows are kept per query - pinned and recent commands are listed beyond it.

Frecency is Firefox's idea: the number of uses, capped at 20, times a weight for how long ago the last one was, divided by 10. Run a command a few times from the palette and watch its row climb in the lab - the history is kept in localStorage, so it survives a reload.

Last usedWeight
Within 4 hours100
Within a day70
Within three days50
Within a week30
Within a month10
Longer ago5
BaletteCmd.Navigate("Introduction", "/").Priority(BaletteCommandPriority.High)   // leads on the empty query
BaletteCmd.New("Feedback: couldn't find a command?").AlwaysShow().Priority(BaletteCommandPriority.Lowest)

options.PriorityWeight = 2;   // how much priority nudges a search
options.FrecencyWeight = 1;   // and how much use, weighted by how recent

In the palette

Nested commands are found from the root too (SearchNestedCommands, on by default), as in kbar: dark lists Theme › Dark under Theme's group, and theme dark matches the ancestors' titles as well. A root command and a nested one that match equally well are listed root first. Only registered and declared commands are found - a lazy page's children do not exist until it opens - and only when every ancestor is visible and enabled and none is a multi-select page, whose rows are choices rather than commands. Modes never include them.

builder.Services.AddBitBaletteServices(options =>
{
    options.HighlightMatches = false;       // no <mark> around the matched characters
    options.GroupWhenSearching = false;     // one flat ranked list while searching
    options.SearchNestedCommands = false;   // nested commands only on their own pages
});

A matcher of your own

IBaletteMatcher is one method - Match(query, text), returning a BaletteFieldMatch with a score and the positions to highlight - set through options.Matcher. Multi-term queries, operators and field weights work with any matcher. BaletteSubstringMatcher is a ready-made case-insensitive substring matcher, for data where fuzziness hurts more than it helps - pick Substring in the lab to compare.

// The palette's matcher, for data where fuzziness hurts: plain substrings.
options.Matcher = BaletteSubstringMatcher.Default;

// Or fzf's --literal: no folding of diacritics and Arabic-script letters.
options.Matcher = new BaletteFuzzyMatcher { Normalize = false };

// Or your own: one method.
public sealed class PrefixMatcher : IBaletteMatcher
{
    public BaletteFieldMatch Match(string query, string text)
        => text.StartsWith(query, StringComparison.OrdinalIgnoreCase)
            ? new BaletteFieldMatch(true, 100 - text.Length, [.. Enumerable.Range(0, query.Length)])
            : BaletteFieldMatch.None;
}

// Called directly, for example in a test.
BaletteQuery query = BaletteQuery.Parse("^go | ^open settings"); // its Terms: text, operator, alternative group
BaletteMatch? match = BaletteFuzzyMatcher.Default.Match(command, "gs");

Matching can also be called directly - in a test, or in a tool that explains a search, the way the lab above and the MCP server's InspectBaletteSearch do, with BaletteRanker (injectable, like the options) ordering the matches as the palette does. BaletteMatch carries the Score, the title's and subtitle's highlight positions, the MatchedKeyword, the Path of a nested command, IsApproximate for a typo match, and whether it came from a source.

Matching runs over the fields of the command only; asynchronous sources opt into it with ApplyMatcher, or keep their own order (see sources).
An unhandled error has occurred. Reload 🗙