Skip to content

Build your personal knowledge base with Trilium Notes

chore(search): trim comments and inline single-use helpers

Elian Doran376f8d81ae42
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index 83f8ff8cdb..ed2dfbe3b4 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -171,13 +171,8 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void
cb(results);
}
-// autocomplete.js's own "val" setter is silent by default (it goes through Typeahead.setVal,
-// which skips _checkInputValue when the widget isn't activated) — it never dispatches a native
-// "input" event. Consumers that track the live query text (e.g. NoteAutocomplete.tsx's
-// onTextChange, bound to "input") would otherwise go stale whenever the text is changed
-// programmatically rather than typed. Every function below that sets the value on the user's
-// behalf re-triggers "input" itself so that channel stays generically accurate for any caller,
-// not just one dialog.
+// `autocomplete("val", ...)` does not dispatch a native "input" event, so each function below
+// fires one to keep consumers bound to it, such as NoteAutocomplete's onTextChange, in sync.
function clearText($el: JQuery<HTMLElement>) {
searchDelay = 0;
@@ -386,8 +381,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
html += `<span class="search-result-attributes">${suggestion.highlightedAttributeSnippet}</span>`;
}
- // Add content snippet below, only for consumers that opted in (e.g. the
- // jump-to-note dialog) — link dialogs/relation editors/`@`-mentions stay compact.
if (options.showContentSnippets && suggestion.highlightedContentSnippet) {
html += `<span class="search-result-content">${suggestion.highlightedContentSnippet}</span>`;
}
diff --git a/apps/client/src/services/search_jump.ts b/apps/client/src/services/search_jump.ts
index f44f7eb72b..8096a4709d 100644
--- a/apps/client/src/services/search_jump.ts
+++ b/apps/client/src/services/search_jump.ts
@@ -2,19 +2,13 @@ import appContext from "../components/app_context.js";
import type NoteContext from "../components/note_context.js";
/**
- * One-shot consumer of `viewScope.searchTerms`: when a note is opened from search results the terms
- * ride along in the view scope (see `link.ts`); this reads them, clears them, and fires a seeded
- * `findInText` so the find bar opens on the first match. Mirrors how `viewScope.bookmark` is
- * consumed by the type widgets.
+ * Reads `viewScope.searchTerms`, which `link.ts` sets when a note is opened from search results,
+ * clears them, and fires a seeded `findInText` so the find bar opens on the first match. Mirrors
+ * how the type widgets consume `viewScope.bookmark`.
*
- * The terms are cleared synchronously (before the deferred trigger) so the belt-and-suspenders
- * double invocation — the content-ready effect plus the same-note re-click `noteSwitched` listener —
- * only opens the bar once.
- *
- * The trigger itself is deferred to the next animation frame so it runs *after* the `noteSwitched`
- * dispatch that led here has fully drained. FindWidget also handles `noteSwitched` (by calling
- * `closeSearch`); without the defer, a synchronous trigger from within the same dispatch could open
- * the bar only for FindWidget's own `noteSwitched -> closeSearch` to immediately close it again.
+ * Clearing is synchronous so that the two call paths, the content-ready one and the same-note
+ * re-click one, open the bar only once. The trigger waits a frame so it runs after the
+ * `noteSwitched` dispatch drains, because FindWidget calls `closeSearch` on that same event.
*/
export function consumeSearchTerms(noteContext: NoteContext | undefined | null, ntxId: string | null | undefined): void {
const viewScope = noteContext?.viewScope;
@@ -25,10 +19,9 @@ export function consumeSearchTerms(noteContext: NoteContext | undefined | null,
viewScope.searchTerms = undefined;
requestAnimationFrame(() => {
- // Navigation replaces the context's viewScope object (note_context.setNote /
- // resetViewScope), so an identity change here means the tab moved on before the frame
- // fired — the seeded find would target the wrong note. A fresh navigation from search
- // results carries its own searchTerms and runs its own consumption, so aborting is safe.
+ // Navigation replaces the viewScope object, so a different identity here means the tab
+ // moved on and this find would target the wrong note. The new navigation carries its own
+ // searchTerms, so aborting loses nothing.
if (noteContext.viewScope !== viewScope) {
return;
}
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index e7aa482a69..88d690c4dc 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -1082,8 +1082,6 @@ table.promoted-attributes-in-tooltip th {
word-wrap: break-word;
}
-/* Highlight the server-injected <b> tags with the same vars the snippet cards
- (SearchResultsList.css / ListOrGridView.css) and quick-search dropdown use. */
.aa-dropdown-menu .aa-suggestion .search-result-content b {
background: var(--note-list-view-search-result-highlight-background);
color: var(--note-list-view-search-result-highlight-color);
diff --git a/apps/client/src/widgets/dialogs/jump_to_note.spec.ts b/apps/client/src/widgets/dialogs/jump_to_note.spec.ts
deleted file mode 100644
index 22c98a9b69..0000000000
--- a/apps/client/src/widgets/dialogs/jump_to_note.spec.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { deriveSearchViewScope } from "./jump_to_note";
-
-describe("deriveSearchViewScope", () => {
- it("attaches searchTerms for a typed search string", () => {
- expect(deriveSearchViewScope(false, "hello")).toEqual({ searchTerms: ["hello"] });
- });
-
- it("trims the typed text before using it as a search term", () => {
- expect(deriveSearchViewScope(false, " hello world ")).toEqual({ searchTerms: ["hello world"] });
- });
-
- it("returns an empty viewScope in command-palette mode, even with typed text", () => {
- // Regression: command suggestions never carry a notePath so this branch is normally
- // unreachable for them, but the gate itself must not leak searchTerms if it ever is.
- expect(deriveSearchViewScope(true, ">some command")).toEqual({});
- });
-
- it("returns an empty viewScope for an untyped/blank query (e.g. a 'recent notes' pick)", () => {
- expect(deriveSearchViewScope(false, "")).toEqual({});
- expect(deriveSearchViewScope(false, " ")).toEqual({});
- expect(deriveSearchViewScope(false, undefined)).toEqual({});
- });
-
- it("does not attach a stale search term once the query has actually been cleared", () => {
- // Reproduces the review finding: typing "hello", then clearing/switching to recent
- // notes without the ref going stale, must gate the same as never having typed anything.
- expect(deriveSearchViewScope(false, "hello")).toEqual({ searchTerms: ["hello"] });
- expect(deriveSearchViewScope(false, "")).toEqual({});
- });
-});
diff --git a/apps/client/src/widgets/dialogs/jump_to_note.tsx b/apps/client/src/widgets/dialogs/jump_to_note.tsx
index accebf8c06..49e90641e2 100644
--- a/apps/client/src/widgets/dialogs/jump_to_note.tsx
+++ b/apps/client/src/widgets/dialogs/jump_to_note.tsx
@@ -50,10 +50,8 @@ export default function JumpToNoteDialogComponent() {
setMode(newMode);
}
- // Keep the ref that gates viewScope.searchTerms (see onItemSelected) in sync with what's
- // about to be displayed. The "recent-notes" branch above resets the *displayed* text to ""
- // without going through the native "input" event that normally updates this ref, so without
- // this the ref would still hold the previous session's typed query (#task-7 review).
+ // The "recent-notes" branch above resets the displayed text without firing "input", which
+ // is what normally updates this ref, so keep it in sync with what is about to be shown.
actualText.current = initialText;
setInitialText(initialText);
@@ -71,7 +69,8 @@ export default function JumpToNoteDialogComponent() {
setShown(false);
if (suggestion.notePath) {
- const viewScope = deriveSearchViewScope(isCommandMode, actualText.current);
+ const searchString = !isCommandMode ? actualText.current?.trim() : "";
+ const viewScope: ViewScope = searchString ? { searchTerms: [ searchString ] } : {};
appContext.tabManager.getActiveContext()?.setNote(suggestion.notePath, { viewScope });
} else if (suggestion.commandId) {
await commandRegistry.executeCommand(suggestion.commandId);
@@ -163,20 +162,3 @@ export default function JumpToNoteDialogComponent() {
</Modal>
);
}
-
-/**
- * Only carry search terms into the opened note when the dialog was actually used as a text
- * search — not the command palette, and not an untyped "recent notes" pick — since jumping
- * from a command or a blank query shouldn't highlight anything. Exported (and kept pure) so
- * the gating itself is unit-testable without rendering the dialog; the caller is responsible
- * for keeping `typedText` accurate (see the `actualText` ref sync in `openDialog`/`onTextChange`
- * and the "input"-triggering functions in note_autocomplete.ts).
- *
- * The autocomplete response has no per-suggestion token list, so we pass the trimmed raw query
- * as a single term rather than re-deriving a token list client-side — simple, and good enough
- * for jump-to-match highlighting.
- */
-export function deriveSearchViewScope(isCommandMode: boolean, typedText: string | undefined): ViewScope {
- const searchString = !isCommandMode ? typedText?.trim() : "";
- return searchString ? { searchTerms: [searchString] } : {};
-}
diff --git a/apps/client/src/widgets/find.spec.ts b/apps/client/src/widgets/find.spec.ts
deleted file mode 100644
index 540cb37562..0000000000
--- a/apps/client/src/widgets/find.spec.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { deriveSeededFind } from "./find.js";
-
-describe("deriveSeededFind", () => {
- it("uses the first token as the seed and the rest as extra highlight tokens", () => {
- expect(deriveSeededFind([ "alpha", "beta", "gamma" ])).toEqual({
- seed: "alpha",
- extraTokens: [ "beta", "gamma" ]
- });
- });
-
- it("treats a single token as the seed with no extras", () => {
- expect(deriveSeededFind([ "alpha" ])).toEqual({ seed: "alpha", extraTokens: [] });
- });
-
- it("keeps a quoted phrase (already a single token) intact as the seed", () => {
- expect(deriveSeededFind([ "hello world" ])).toEqual({ seed: "hello world", extraTokens: [] });
- });
-
- it("degrades to an empty seed for an empty term list", () => {
- expect(deriveSeededFind([])).toEqual({ seed: "", extraTokens: [] });
- });
-});
diff --git a/apps/client/src/widgets/find.ts b/apps/client/src/widgets/find.ts
index fff01b7d66..e4f3f58c80 100644
--- a/apps/client/src/widgets/find.ts
+++ b/apps/client/src/widgets/find.ts
@@ -267,19 +267,12 @@ export default class FindWidget extends NoteContextAwareWidget {
/**
* Opens the find bar pre-seeded from search terms carried in on note open (jump-to-match),
- * scrolling to the first match so Enter/F3 immediately cycles the results.
- *
- * The bar is shown whenever there is at least one match — deliberately, even for non-Electron
- * users who have no Ctrl+F to summon it: (a) Enter/F3 cycling is bound on the input, (b) leaving
- * the bar open is the affordance that lets the user dismiss the highlights (closeSearch only
- * unmarks while the bar is visible). With zero matches nothing is shown and performFind leaves
- * no marks behind, so there is nothing to leak.
- *
- * Kept separate from the manual-open flow above, whose pre-existing show()/isAlreadyVisible
- * ordering is intentionally left untouched.
+ * scrolling to the first match so Enter/F3 immediately cycles the results. The bar stays open
+ * on a match because `closeSearch` only unmarks while it is visible, so it is what lets the
+ * user dismiss the highlights.
*/
private async seededFind(searchTerms: string[]) {
- const { seed, extraTokens } = deriveSeededFind(searchTerms);
+ const [ seed = "", ...extraTokens ] = searchTerms;
this.$input.val(seed);
const { totalFound } = await this.performFind();
@@ -448,13 +441,3 @@ export default class FindWidget extends NoteContextAwareWidget {
}
}
}
-
-/**
- * Splits the search terms carried in on note open into the seed (first token — a quoted phrase
- * arrives as a single token) that drives the find counter and Enter/F3 cycling, and the remaining
- * tokens that get a muted highlight-all pass (HTML handler only). Extracted and kept pure so the
- * seed/extras split is unit-testable without instantiating the jQuery widget.
- */
-export function deriveSeededFind(searchTerms: string[]): { seed: string; extraTokens: string[] } {
- return { seed: searchTerms[0] ?? "", extraTokens: searchTerms.slice(1) };
-}
diff --git a/apps/client/src/widgets/quick_search.ts b/apps/client/src/widgets/quick_search.ts
index d2addf98f8..28372abe92 100644
--- a/apps/client/src/widgets/quick_search.ts
+++ b/apps/client/src/widgets/quick_search.ts
@@ -165,9 +165,9 @@ export default class QuickSearchWidget extends BasicWidget {
private currentDisplayedCount: number = 0;
private isLoadingMore: boolean = false;
- // Plain tokens the server highlighted for the last completed search. Consumed by
- // jump-to-match producers to know what to highlight in the opened note.
- private lastHighlightedTokens: string[] = [];
+ // Attached to each result link so the opened note jumps to the first match; undefined when the
+ // last search highlighted nothing, which keeps the links at a plain `#notePath`.
+ private lastResultViewScope: ViewScope | undefined;
doRender() {
this.$widget = $(TPL);
@@ -255,7 +255,7 @@ export default class QuickSearchWidget extends BasicWidget {
const { searchResultNoteIds, searchResults, highlightedTokens, error } = await server.get<QuickSearchResponse>(`quick-search/${encodeURIComponent(searchString)}`);
- this.lastHighlightedTokens = highlightedTokens || [];
+ this.lastResultViewScope = highlightedTokens?.length ? { searchTerms: highlightedTokens } : undefined;
if (error) {
const tooltip = new Tooltip(this.$searchString[0], {
@@ -304,12 +304,10 @@ export default class QuickSearchWidget extends BasicWidget {
for (const result of resultsToDisplay) {
if (!result.notePath) continue;
- // Carry the highlighted search tokens into the opened note (jump-to-match) via the
- // view scope. Set the href with .attr() rather than interpolating it into the HTML
- // string so query separators aren't parsed as HTML entities. calculateHash omits
- // searchTerms when the token list is empty, so this degrades to a plain `#notePath`.
+ // Set the href with .attr() rather than interpolating it into the HTML string, so
+ // the query separators are not parsed as HTML entities.
const $item = $(`<a class="dropdown-item" tabindex="0">`);
- $item.attr("href", calculateHash({ notePath: result.notePath, viewScope: this.resultViewScope() }));
+ $item.attr("href", calculateHash({ notePath: result.notePath, viewScope: this.lastResultViewScope }));
// Build the display HTML with content snippet below the title
let itemHtml = `<div class="quick-search-item">
@@ -354,7 +352,7 @@ export default class QuickSearchWidget extends BasicWidget {
const noteIdsToDisplay = this.allSearchResultNoteIds.slice(startIndex, endIndex);
for (const note of await froca.getNotes(noteIdsToDisplay)) {
- const $link = await linkService.createLink(note.noteId, { showNotePath: true, showNoteIcon: true, viewScope: this.resultViewScope() });
+ const $link = await linkService.createLink(note.noteId, { showNotePath: true, showNoteIcon: true, viewScope: this.lastResultViewScope });
$link.addClass("dropdown-item");
$link.attr("tabIndex", "0");
$link.on("click auxclick", (e) => {
@@ -380,15 +378,6 @@ export default class QuickSearchWidget extends BasicWidget {
this.isLoadingMore = false;
}
- /**
- * View scope attached to each result link so the opened note jumps to the first match and
- * pre-fills the find bar. Undefined when the last search highlighted no tokens, so links stay
- * plain `#notePath`.
- */
- private resultViewScope(): ViewScope | undefined {
- return this.lastHighlightedTokens.length ? { searchTerms: this.lastHighlightedTokens } : undefined;
- }
-
private handleScroll() {
if (this.isLoadingMore) return;
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 83e6a2612e..62d4b2fcc5 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -874,18 +874,10 @@ export function useNoteBlob(note: FNote | null | undefined, componentId?: string
}
/**
- * Handles the same-note re-click half of jump-to-match consumption (see `search_jump.ts`), shared
- * by the text and code type widgets. The other half — consuming when a note's content first loads
- * — is done directly at each widget's content-ready point (`[blob]` effect / `onContentChange`),
- * because that signal differs between the read-only and editable variants.
- *
- * Re-clicking the same search result re-runs `setNote` (it proceeds because the viewScope now
- * carries new `searchTerms` and so differs from the current one) and fires `noteSwitched` without
- * changing the blob — so the content-ready path doesn't re-run. We consume here instead, but only
- * when the switch targets the note this widget already shows: a genuine switch to a *different*
- * note is handled by the newly mounted widget's content-ready path, and consuming it here (against
- * this widget's stale, about-to-unmount content) would clear the terms before the real content is
- * ready, so we skip it.
+ * Calls `consumeSearchTerms` when a search result is re-clicked while its note is already open.
+ * That switch does not change the blob, so the widget's own content-ready path does not re-run.
+ * The switch must target the note this widget shows: a switch to a different note belongs to the
+ * newly mounted widget, and consuming it here would clear the terms before its content is ready.
*/
export function useSearchTermsConsumer(note: FNote | null | undefined, noteContext: NoteContext | undefined, ntxId: string | null | undefined) {
useTriliumEvent("noteSwitched", ({ noteContext: switchedContext }) => {
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsx
index 3740493d15..bb649e7e87 100644
--- a/apps/client/src/widgets/type_widgets/code/Code.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx
@@ -57,8 +57,7 @@ export function ReadOnlyCode({ note, viewScope, ntxId, noteContext, parentCompon
setContent(newContent);
- // Jump to the first search match (and pre-fill the find bar) when navigated from search
- // results; the same-note re-click case is covered by useSearchTermsConsumer below.
+ // Jump to the first search match when navigated from search results.
consumeSearchTerms(noteContext, ntxId);
}, [ blob ]);
useSearchTermsConsumer(note, noteContext, ntxId);
@@ -122,9 +121,7 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentC
codeEditor.setMimeType(note.mime);
codeEditor.clearHistory();
- // Jump to the first search match (and pre-fill the find bar) when navigated from search
- // results. Runs once the content has loaded into the editor; the same-note re-click case
- // is covered by useSearchTermsConsumer below.
+ // Jump to the first search match when navigated from search results.
consumeSearchTerms(noteContext, ntxId);
},
dataSaved,
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 8cecb4e556..a3fadb8936 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -67,9 +67,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
contentRef.current = newContent;
watchdogRef.current?.editor?.setData(newContent);
- // Jump to the first search match (and pre-fill the find bar) when navigated from search
- // results. Runs once the content has loaded into the editor; the same-note re-click case
- // is covered by useSearchTermsConsumer below.
+ // Jump to the first search match when navigated from search results.
consumeSearchTerms(noteContext, ntxId);
// Scroll to bookmark anchor if navigated with ?bookmark=...
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 7b12fd5a0f..7b785a0607 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -38,17 +38,14 @@ export default function ReadOnlyText({ note, noteContext, ntxId, parentComponent
const { isRtl } = useNoteLanguage(note);
const readOnlyContentRef = usePreactRef<HTMLDivElement>(null);
- // Scroll to bookmark anchor if navigated with ?bookmark=... Gated on the blob: the mount
- // run fires while the content is still loading (empty container), and consuming the
- // bookmark there would leave nothing for the post-load run — this effect only re-fires
- // on [blob].
+ // Scroll to bookmark anchor if navigated with ?bookmark=... The blob gate skips the mount run,
+ // which fires against an empty container while the content is still loading.
useEffect(() => {
if (!blob) return;
consumeBookmark(readOnlyContentRef.current, noteContext?.viewScope);
}, [blob]);
- // Jump to the first search match (and pre-fill the find bar) when navigated from search results.
- // Runs once the content has loaded; the same-note re-click case is covered by the hook below.
+ // Jump to the first search match when navigated from search results.
useEffect(() => {
if (blob) consumeSearchTerms(noteContext, ntxId);
}, [blob]);
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md
index 1d13e0fd98..565eefe7d3 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md
@@ -57,7 +57,7 @@ The options available are:
## Viewing search results
-Results appear below the search pane as a list of **snippet cards** — each card shows the note title and a short excerpt of the text that matched, with your search terms highlighted.
+Results appear below the search pane as a list of **snippet cards**. Each card shows the note title and a short excerpt of the text that matched, with your search terms highlighted.
* The **total number of results** is always shown, so you can immediately tell how broad a query is.
* A **page-size selector** lets you choose how many results to display per page. Your choice is remembered and synced across your devices (stored in the `searchResultsPageSize` option), so you do not have to reset it on every device.
@@ -80,7 +80,7 @@ Every example below is backed 1:1 by an automated test, so the documentation can
### Default matching (no prefix)
-**Rule:** typing words with no prefix finds notes that contain those words anywhere in the title, content or attributes — as whole words _or_ as substrings — and ranks the closest matches first.
+**Rule:** typing words with no prefix finds notes that contain those words anywhere in the title, content or attributes, as whole words or as substrings. The closest matches are ranked first.
| Query | Example note content | Matches? | Why |
| --- | --- | --- | --- |
@@ -89,7 +89,7 @@ Every example below is backed 1:1 by an automated test, so the documentation can
### Exact match with the `=` prefix
-**Rule:** a leading `=` switches the full-text search to exact matching — it finds the whole word or phrase only, ignoring surrounding punctuation, with **no** substring and **no** fuzzy matching. Use it when a normal search returns too many near-matches.
+**Rule:** a leading `=` switches the full-text search to exact matching. It finds the whole word or phrase only, ignoring surrounding punctuation, with **no** substring and **no** fuzzy matching. Use it when a normal search returns too many near-matches.
| Query | Example note content | Matches? | Why |
| --- | --- | --- | --- |
@@ -109,7 +109,7 @@ To match an exact **phrase**, quote it after the `=` (single, double or backtick
### Attribute and property equality (`=`, `!=`)
-**Rule:** when `=` compares an attribute or property — `#label=value`, `note.title=value` — it is **strict full-value equality**: the _whole_ value must equal what you typed (case- and diacritic-insensitive). This is **not** word matching. `!=` inverts it.
+**Rule:** when `=` compares an attribute or property, as in `#label=value` or `note.title=value`, it is **strict full-value equality**: the _whole_ value must equal what you typed, ignoring case and diacritics. This is **not** word matching. `!=` inverts it.
The examples below assume four notes: _Austria_ (`#capital=Vienna`), _Somewhere_ (`#capital=Vienna Austria`), _Czech Republic_ (`#capital=Prague`) and _Switzerland_ (`#capital=Zürich`).
@@ -122,11 +122,11 @@ The examples below assume four notes: _Austria_ (`#capital=Vienna`), _Somewhere_
| `#capital!=Vienna` | `Prague` | Yes | `!=` matches every value that is not `Vienna` |
| `#capital!=Vienna` | `Vienna` | No | `!=` excludes the exact value |
-> **Quick search relaxes this.** The [Quick search](Quick%20search.md) bar and autocomplete apply relaxed attribute matching — an attribute `=` is treated as "contains" — so `#capital=Vienna` typed there also matches `Vienna Austria`; the strict full-value equality described here applies only in the full Search.
+> **Quick search relaxes this.** The [Quick search](Quick%20search.md) bar and autocomplete treat an attribute `=` as "contains", so `#capital=Vienna` typed there also matches `Vienna Austria`. The strict full-value equality described here applies only in the full Search.
### Fuzzy operators (`~=` and `~*`)
-**Rule:** the fuzzy operators tolerate typos. `~=` (fuzzy-equals) matches a value that is a close whole-word variant of your term; `~*` (fuzzy-contains) matches when your term appears — as a fragment _or_ a near-miss — anywhere inside the value. Both work on note properties (`note.title`, `note.content`, …) and on labels (`#label`). Fuzzy operators require at least 3 characters.
+**Rule:** the fuzzy operators tolerate typos. `~=` (fuzzy-equals) matches a value that is a close whole-word variant of your term. `~*` (fuzzy-contains) matches when your term appears anywhere inside the value, either as a fragment or as a near-miss. Both work on note properties such as `note.title` and `note.content`, and on labels (`#label`). Fuzzy operators require at least 3 characters.
The examples assume a note titled `Books` carrying the label `#author=Tolkien`, and a note whose content is `learn programming today`.
@@ -176,9 +176,9 @@ The last point is the least obvious: if a note's only content is a reference lin
| Query | Setup | Matches? | Why |
| --- | --- | --- | --- |
-| `special topic` | a note whose only content is a reference link to a note titled `Special Topic` | Yes — the linking note is found; the linked target ranks first | the target's title is indexed into the linking note's searchable text |
-| `special` | the same note (only a reference link to `Special Topic`) | Yes — a single word from the target's title is enough to find the linking note | the indexed title is normalized just like body text, so even one lowercased word matches |
-| `zurich` | a note whose only content is a reference link to a note titled `Zürich` | Yes — the linking note is found | the indexed title has its accents normalized, so the plain form matches the accented title |
+| `special topic` | a note whose only content is a reference link to a note titled `Special Topic` | Yes, and the linked target ranks first | the target's title is indexed into the linking note's searchable text |
+| `special` | the same note (only a reference link to `Special Topic`) | Yes, one word from the target's title is enough | the indexed title is normalized just like body text, so even one lowercased word matches |
+| `zurich` | a note whose only content is a reference link to a note titled `Zürich` | Yes | the indexed title has its accents normalized, so the plain form matches the accented title |
### Diacritics
@@ -358,7 +358,7 @@ You can open Trilium and automatically trigger a search by including the search
| Parameter | Value | Description |
| --- | --- | --- |
| `MIN_FUZZY_TOKEN_LENGTH` | 3 | Minimum characters for fuzzy matching |
-| `MAX_EDIT_DISTANCE` | 2 | Ceiling on character changes, reached only by 6+ character terms; shorter terms allow fewer — see the _Fuzzy tolerance (AUTO)_ section above |
+| `MAX_EDIT_DISTANCE` | 2 | Ceiling on character changes, reached only by 6+ character terms; shorter terms allow fewer. See the _Fuzzy tolerance (AUTO)_ section above |
| `RESULT_SUFFICIENCY_THRESHOLD` | 5 | Minimum exact results before fuzzy fallback |
| `MAX_CONTENT_SIZE` | 10MB | Maximum note content size for search processing |
diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
index a25cb29641..5b70d1d220 100644
--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
@@ -4,10 +4,7 @@ import striptags from "striptags";
import { normalizeSearchText } from "../utils/text_utils";
import { normalize, unescapeHtml } from "../../utils/index";
-/**
- * Resolves a note's title by its id. Injected by the caller so this module stays
- * pure and browser-safe (no becca import here). Returns null for unknown notes.
- */
+/** Resolves a note's title by its id, injected so this module stays free of a becca import. */
export type NoteTitleResolver = (noteId: string) => string | null;
export default function preprocessContent(rawContent: string | Uint8Array, type: string, mime: string, raw?: boolean, resolveNoteTitle?: NoteTitleResolver) {
@@ -16,23 +13,16 @@ export default function preprocessContent(rawContent: string | Uint8Array, type:
if (type === "text" && mime === "text/html") {
if (!raw) {
- // Pull searchable text out of link previews and internal-link targets BEFORE
- // stripTags discards their data-* metadata and (stale) anchor text. Extraction
- // runs against the original, case-preserved markup so link target noteIds still
- // resolve (normalize() lowercases, which would corrupt the ids).
+ // Runs before stripTags(), which discards the data-* metadata and anchor text, and
+ // against the original markup, because normalize() lowercases the noteIds it needs.
const injectedText = extractLinkSearchText(originalContent, resolveNoteTitle);
// Content size already filtered at DB level, safe to process
content = stripTags(content);
if (injectedText) {
- // Normalize the appended text the same way the body was normalized above.
- // Extraction ran against the case-preserved original so link-target noteIds
- // still resolved, but the default single-token content match lowercases the
- // query token and does a raw `content.includes()` (see note_content_fulltext
- // matchesContent), so the injected titles/metadata must be lowercased and
- // diacritic-stripped too — otherwise `special` misses a linked "Special Topic"
- // and `zurich` misses a linked "Zürich" in phase 1.
+ // The body above was normalized, and matchesContent() compares a lowercased query
+ // token against the raw string, so the injected text must be normalized too.
content = `${content} ${normalize(injectedText)}`;
}
}
@@ -141,18 +131,13 @@ function processCanvasContent(content: string) {
/** Metadata attributes to index from link previews, in the order they are appended. */
const LINK_PREVIEW_ATTRIBUTES = ["data-url", "data-title", "data-description", "data-site-name"] as const;
-// Matches the opening tag of a link-embed section or link-mention span (serialized by
-// packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts dataDowncast).
+// Must match what link_embed_editing.ts writes in its dataDowncast.
const LINK_PREVIEW_TAG_RE = /<(?:section|span)\b[^>]*\bclass=["'][^"']*\blink-(?:embed|mention)\b[^"']*["'][^>]*>/gi;
-// Copy of services/notes.ts findInternalLinks: captures the target noteId of a reference
-// link or plain internal link. Kept inline so the preprocessor stays free of the notes service.
+// Mirrors findInternalLinks() in services/notes.ts, inlined to keep that import out of here.
const INTERNAL_LINK_RE = /href="[^"]*#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)\/?"/g;
-/**
- * Builds a space-separated bag of extra searchable text from a text/html note's link
- * previews (their data-* metadata) and internal-link targets (their resolved titles).
- */
+/** Collects extra searchable text from a note's link previews and internal-link targets. */
function extractLinkSearchText(content: string, resolveNoteTitle?: NoteTitleResolver): string {
const parts: string[] = [];
diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.ts
index ed49364f52..42a0e389a4 100644
--- a/packages/trilium-core/src/services/search/services/search.ts
+++ b/packages/trilium-core/src/services/search/services/search.ts
@@ -589,7 +589,7 @@ function extractContentSnippet(noteId: string, searchTokens: HighlightedTokenInf
// Find the first line that contains a search token
let firstMatchLine = -1;
for (let i = 0; i < normalizedLines.length; i++) {
- if (tokenInfos.some((info) => tokenInfoMatches(info, normalizedLines[i]))) {
+ if (tokenInfos.some((info) => tokenInfoFirstIndex(info, normalizedLines[i]) !== -1)) {
firstMatchLine = i;
break;
}
@@ -664,7 +664,7 @@ function extractAttributeSnippet(noteId: string, searchTokens: HighlightedTokenI
const normalizedName = normalizePreservingLength(attrName);
const normalizedValue = normalizePreservingLength(attrValue);
const hasMatch = tokenInfos.some((info) =>
- tokenInfoMatches(info, normalizedName) || tokenInfoMatches(info, normalizedValue));
+ tokenInfoFirstIndex(info, normalizedName) !== -1 || tokenInfoFirstIndex(info, normalizedValue) !== -1);
if (hasMatch) {
matchingAttributes.push({
@@ -858,16 +858,9 @@ function tokenInfoFirstIndex(info: HighlightedTokenInfo, normalizedText: string)
return normalizedText.indexOf(normalizePreservingLength(info.token));
}
-/** Whether a token matches anywhere within already-normalized text. */
-function tokenInfoMatches(info: HighlightedTokenInfo, normalizedText: string): boolean {
- return tokenInfoFirstIndex(info, normalizedText) !== -1;
-}
-
/**
- * Normalizes the highlight token input for {@link highlightSearchResults}: widens
- * legacy strings to plain token infos, strips marker/angle characters from plain
- * tokens (regex patterns are kept verbatim), drops blanks, dedupes, and sorts
- * longest-first so longer matches win before shorter ones.
+ * Widens, cleans, dedupes and sorts the highlight tokens for `highlightSearchResults()`. The sort
+ * is longest-first so a longer match wins over a shorter one it contains.
*/
function normalizeHighlightTokens(tokens: HighlightedTokenInfo[] | string[]): HighlightedTokenInfo[] {
const seen = new Set<string>();
@@ -905,11 +898,9 @@ function buildHighlightRegex(info: HighlightedTokenInfo): RegExp | null {
}
/**
- * Wraps every match of one token in a single field with `{`/`}` markers (later
- * turned into `<b>`/`</b>`). Match positions are found on a length-preserving
- * normalization so they align 1:1 with the original field. The wrap count is
- * capped to bound pathological regex patterns, and zero-width matches break the
- * loop rather than spin forever.
+ * Wraps every match of one token in a field with the `{`/`}` markers that `renderHighlights()`
+ * turns into `<b>`/`</b>`. Positions come from a length-preserving normalization, so they align
+ * 1:1 with the original field.
*/
function highlightField(field: string | undefined, info: HighlightedTokenInfo): string | undefined {
if (!field) {
@@ -929,7 +920,8 @@ function highlightField(field: string | undefined, info: HighlightedTokenInfo):
break; // Zero-width match can't be highlighted; avoid an infinite loop.
}
- field = wrapText(field, match.index, matchLength, "{", "}");
+ const matchEnd = match.index + matchLength;
+ field = `${field.slice(0, match.index)}{${field.slice(match.index, matchEnd)}}${field.slice(matchEnd)}`;
// Two marker characters were inserted, so advance past them as well.
regex.lastIndex += 2;
@@ -941,10 +933,6 @@ function highlightField(field: string | undefined, info: HighlightedTokenInfo):
return field;
}
-function wrapText(text: string, start: number, length: number, prefix: string, suffix: string) {
- return text.substring(0, start) + prefix + text.substr(start, length) + suffix + text.substring(start + length);
-}
-
/** Escapes the text for display, then turns the { } markers into the <b> tags they stand for. */
function renderHighlights(text: string) {
return escapeHtml(text).replace(/{/g, "<b>").replace(/}/g, "</b>");
diff --git a/packages/trilium-core/src/services/search/utils/text_utils.ts b/packages/trilium-core/src/services/search/utils/text_utils.ts
index 048b71883d..b137ea66bc 100644
--- a/packages/trilium-core/src/services/search/utils/text_utils.ts
+++ b/packages/trilium-core/src/services/search/utils/text_utils.ts
@@ -280,19 +280,10 @@ function escapeRegExp(string: string): string {
}
/**
- * Returns the maximum edit distance allowed for a fuzzy match of a token of the
- * given length, scaled by length in the style of Elasticsearch's `fuzziness:
- * AUTO`. A flat edit distance of 2 is too loose for short words (e.g. "sync"
- * would match "send"), so short tokens get a tighter bound.
- *
- * - 0-2 chars: 0 (no fuzzy matching)
- * - 3-5 chars: 1
- * - 6+ chars: 2
- *
- * The result never exceeds {@link FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE}.
- *
- * @param tokenLength The length of the token being matched.
- * @returns The maximum allowed edit distance for that token.
+ * Maximum edit distance allowed for a fuzzy match, scaled by token length the way
+ * Elasticsearch's `fuzziness: AUTO` does: 0 for 1-2 characters, 1 for 3-5, and
+ * `FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE` beyond that. A flat distance of 2 is loose
+ * enough to match "sync" against "send".
*/
export function getAutoMaxEditDistance(tokenLength: number): number {
if (tokenLength <= 2) {
@@ -329,11 +320,8 @@ export function fuzzyMatchWordWithResult(token: string, text: string, maxDistanc
const normalizedToken = token.toLowerCase();
const normalizedText = text.toLowerCase();
- // NOTE: no whole-text substring shortcut here. Substring relationships are
- // NOT fuzzy matches — callers that want substring semantics do their own
- // .includes() check first (note_flat_text smartMatch, build_comparator ~=,
- // note_content_fulltext tokenMatchesContent). Letting "async" count as a
- // fuzzy match for "sync" was a false positive (#10616).
+ // A substring is not a fuzzy match, so there is no whole-text shortcut here. Callers that
+ // want substring semantics run their own `includes()` check first.
// For fuzzy matching, split into words and check each against the token
const words = normalizedText.split(/\s+/).filter(word => word.length > 0);
@@ -343,9 +331,8 @@ export function fuzzyMatchWordWithResult(token: string, text: string, maxDistanc
const word = words[i];
const originalWord = originalWords[i];
- // A word that literally contains the token is a substring relationship,
- // not a fuzzy (typo) one — skip it so e.g. "sync" does not fuzzy-match
- // "async". Callers handle substrings via their own .includes() checks.
+ // A word containing the token is a substring relationship, not a typo, so "sync"
+ // must not fuzzy-match "async".
if (word.length > normalizedToken.length && word.includes(normalizedToken)) {
continue;
}
@@ -355,8 +342,7 @@ export function fuzzyMatchWordWithResult(token: string, text: string, maxDistanc
continue;
}
- // Use optimized edit distance calculation. maxDistance is length-scaled
- // (Elasticsearch AUTO-style) via getAutoMaxEditDistance by default.
+ // Use optimized edit distance calculation
const distance = calculateOptimizedEditDistance(normalizedToken, word, maxDistance);
if (distance <= maxDistance) {
return originalWord; // Return the original word with case preserved
@@ -385,35 +371,19 @@ export function fuzzyMatchWord(token: string, text: string, maxDistance: number
}
/**
- * Unicode character class for punctuation that should be trimmed from word
- * boundaries during tokenization: initial/final quotes (Pi/Pf), open/close
- * brackets (Ps/Pe), other punctuation such as `,` `.` `!` `#` `"` `'` (Po) and
- * dashes (Pd).
- *
- * Deliberately EXCLUDED so those characters survive tokenization:
- * - Connector punctuation (Pc), e.g. `_` — keeps identifiers like `_private`.
- * - Symbols (S*), e.g. `+`, `=`, `$` — keeps tokens like `c++`.
+ * Punctuation trimmed from word boundaries during tokenization: quotes, brackets, dashes and
+ * general punctuation. Connector punctuation (`_`) and symbols (`+`, `=`) are excluded, so
+ * `_private` and `c++` survive intact.
*/
const WORD_BOUNDARY_PUNCTUATION = "\\p{Pi}\\p{Pf}\\p{Ps}\\p{Pe}\\p{Po}\\p{Pd}";
const LEADING_PUNCTUATION = new RegExp(`^[${WORD_BOUNDARY_PUNCTUATION}]+`, "u");
const TRAILING_PUNCTUATION = new RegExp(`[${WORD_BOUNDARY_PUNCTUATION}]+$`, "u");
/**
- * Strips leading and trailing punctuation from a single word so that a search
- * token and a content word compare equal even when the content word is wrapped
- * in punctuation, e.g. `(sync)` -> `sync`, `sync,` -> `sync`, `"sync"` -> `sync`.
- *
- * Tradeoffs (documented deliberately):
- * - KEEPS connector punctuation (`_`, class Pc) and symbols (`+`, `=`, `$`,
- * class S), so `c++` and `_private` survive intact.
- * - Only leading/trailing punctuation is removed; INNER punctuation is untouched,
- * so `d'artagnan` keeps its apostrophe.
- * - Trailing symbol-like punctuation that IS in the stripped classes is removed:
- * `f#` -> `f`. This is acceptable because stripping is applied symmetrically to
- * both the query token and the content word, so matching stays self-consistent.
- *
- * @param word A single word (no internal whitespace expected).
- * @returns The word with boundary punctuation removed (may be empty).
+ * Strips leading and trailing punctuation from a word, so a query token matches a content word
+ * wrapped in punctuation: `(sync)`, `sync,` and `"sync"` all compare equal to `sync`. Inner
+ * punctuation is untouched, so `d'artagnan` keeps its apostrophe. `f#` does lose its `#`, which
+ * stays consistent because the same stripping runs on both sides of every comparison.
*/
export function stripWordPunctuation(word: string): string {
if (!word) {
@@ -424,16 +394,8 @@ export function stripWordPunctuation(word: string): string {
}
/**
- * Splits text into normalized, punctuation-stripped words. This is the
- * tokenization used by exact word / phrase matching so that punctuation in
- * content (parentheses, quotes, trailing commas, newlines) does not prevent a
- * word from matching.
- *
- * Pipeline: {@link normalizeSearchText} (lowercase + strip diacritics) ->
- * split on whitespace -> {@link stripWordPunctuation} each -> drop empties.
- *
- * @param text The text to tokenize.
- * @returns An array of normalized words with empty entries removed.
+ * Splits text into normalized, punctuation-stripped words. Exact word and phrase matching
+ * tokenize through this, so punctuation in the content cannot prevent a word from matching.
*/
export function tokenizeIntoWords(text: string): string[] {
return normalizeSearchText(text)
@@ -443,12 +405,8 @@ export function tokenizeIntoWords(text: string): string[] {
}
/**
- * Returns true if `phrase` appears as a consecutive run of words inside `words`.
- * Both arrays are expected to already be tokenized (e.g. via
- * {@link tokenizeIntoWords}). An empty phrase never matches.
- *
- * @param words The haystack words, in order.
- * @param phrase The needle words that must appear consecutively and in order.
+ * Whether `phrase` appears as a consecutive run of words inside `words`. Both are expected to be
+ * tokenized already, via `tokenizeIntoWords()`. An empty phrase never matches.
*/
export function wordsContainPhrase(words: string[], phrase: string[]): boolean {
if (phrase.length === 0 || phrase.length > words.length) {