Skip to content

Build your personal knowledge base with Trilium Notes

fix(search): punctuation-aware exact word and phrase matching (#10616)

perfectra1na8420e01fa7b
diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
index 996c731b2f..1b81a0b32b 100644
--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
@@ -9,8 +9,11 @@ import {
FUZZY_SEARCH_CONFIG,
fuzzyMatchWord,
normalizeSearchText,
+ stripWordPunctuation,
+ tokenizeIntoWords,
validateAndPreprocessContent,
- validateFuzzySearchTokens} from "../utils/text_utils.js";
+ validateFuzzySearchTokens,
+ wordsContainPhrase} from "../utils/text_utils.js";
import Expression from "./expression.js";
import preprocessContent from "./note_content_fulltext_preprocessor.js";
import { getSql } from "../../../services/sql/index.js";
@@ -135,8 +138,10 @@ class NoteContentFulltextExp extends Expression {
* @returns true if the word is found as an exact match (not substring)
*/
private exactWordMatch(wordToFind: string, text: string): boolean {
- const words = text.split(/\s+/);
- return words.some(word => word === wordToFind);
+ // Strip boundary punctuation from both sides so a content word wrapped in
+ // punctuation (e.g. "(sync)") still matches the bare token ("sync").
+ const needle = stripWordPunctuation(wordToFind);
+ return tokenizeIntoWords(text).some(word => word === needle);
}
/**
@@ -176,14 +181,20 @@ class NoteContentFulltextExp extends Expression {
return this.exactWordMatch(phrase, normalizedContent);
}
- // For multi-word phrases, check if the phrase appears as consecutive words
- if (normalizedContent.includes(phrase)) {
+ // For multi-word phrases, scan the tokenized content for a consecutive run
+ // of the phrase words. Tokenizing (instead of a raw substring scan) lets a
+ // phrase match across punctuation, newlines and repeated whitespace.
+ const phraseWords = normalizedTokens
+ .map(t => stripWordPunctuation(t))
+ .filter(word => word.length > 0);
+ if (wordsContainPhrase(tokenizeIntoWords(content), phraseWords)) {
return true;
}
- // For flatText, also check if the phrase appears in attribute values
- // Attributes in flatText appear as "#name=value" or "~name=value"
- // So we need to check for "=phrase" to match attribute values
+ // For flatText, also check if the phrase appears in attribute values.
+ // Attributes in flatText appear as "#name=value" or "~name=value", so we
+ // look for "=phrase" against the raw string — this depends on the
+ // #name=value structure and must stay a raw-string scan.
if (checkFlatTextAttributes && normalizedContent.includes(`=${phrase}`)) {
return true;
}
diff --git a/packages/trilium-core/src/services/search/search_result.ts b/packages/trilium-core/src/services/search/search_result.ts
index 8b4444d4df..c66489035c 100644
--- a/packages/trilium-core/src/services/search/search_result.ts
+++ b/packages/trilium-core/src/services/search/search_result.ts
@@ -3,7 +3,10 @@ import becca_service from "../../becca/becca_service.js";
import {
calculateOptimizedEditDistance,
FUZZY_SEARCH_CONFIG,
- normalizeSearchText} from "./utils/text_utils.js";
+ normalizeSearchText,
+ stripWordPunctuation,
+ tokenizeIntoWords,
+ wordsContainPhrase} from "./utils/text_utils.js";
// Scoring constants for better maintainability
const SCORE_WEIGHTS = {
@@ -89,17 +92,20 @@ class SearchResult {
}
addScoreForStrings(tokens: string[], str: string, factor: number, enableFuzzyMatching: boolean = true) {
- // normalizeSearchText already lowercases — no need for .toLowerCase() first
- const normalizedStr = normalizeSearchText(str);
- const chunks = normalizedStr.split(" ");
+ // Tokenize (strip boundary punctuation) so a chunk like "(sync)" scores as
+ // an exact token match for "sync" rather than only a contains match.
+ const chunks = tokenizeIntoWords(str);
- // Pre-normalize tokens once instead of per-chunk
- const normalizedTokens = tokens.map(t => normalizeSearchText(t));
+ // Pre-normalize and strip tokens once instead of per-chunk
+ const normalizedTokens = tokens.map(t => stripWordPunctuation(normalizeSearchText(t)));
let tokenScore = 0;
for (const chunk of chunks) {
for (let ti = 0; ti < normalizedTokens.length; ti++) {
const normalizedToken = normalizedTokens[ti];
+ if (!normalizedToken) {
+ continue;
+ }
if (chunk === normalizedToken) {
tokenScore += SCORE_WEIGHTS.TOKEN_EXACT_MATCH * tokens[ti].length * factor;
@@ -130,12 +136,12 @@ class SearchResult {
}
/**
- * Checks if the query matches as a complete word in the text
+ * Checks if the query matches as a complete word (or consecutive run of words)
+ * in the text. Tokenizing both sides makes this punctuation-aware, so a title
+ * like "(sync) notes" is a word match for the query "sync".
*/
private isWordMatch(text: string, query: string): boolean {
- return text.includes(` ${query} `) ||
- text.startsWith(`${query} `) ||
- text.endsWith(` ${query}`);
+ return wordsContainPhrase(tokenizeIntoWords(text), tokenizeIntoWords(query));
}
/**
diff --git a/packages/trilium-core/src/services/search/services/build_comparator.ts b/packages/trilium-core/src/services/search/services/build_comparator.ts
index c090b458f3..5e872049cd 100644
--- a/packages/trilium-core/src/services/search/services/build_comparator.ts
+++ b/packages/trilium-core/src/services/search/services/build_comparator.ts
@@ -1,4 +1,4 @@
-import { normalizeSearchText, fuzzyMatchWord, FUZZY_SEARCH_CONFIG } from "../utils/text_utils.js";
+import { FUZZY_SEARCH_CONFIG, fuzzyMatchWord, normalizeSearchText, stripWordPunctuation, tokenizeIntoWords } from "../utils/text_utils.js";
const cachedRegexes: Record<string, RegExp> = {};
@@ -27,9 +27,10 @@ const stringComparators: Record<string, Comparator<string>> = {
return normalizedVal.includes(normalizedCompared);
}
- // For single word, split into words and check for exact word match
- const words = normalizedVal.split(/\s+/);
- return words.some(word => word === normalizedCompared);
+ // For single word, tokenize into punctuation-stripped words and check for
+ // an exact word match, so a value like "(Books)" matches the token "books".
+ const words = tokenizeIntoWords(normalizedVal);
+ return words.some(word => word === stripWordPunctuation(normalizedCompared));
},
"!=": (comparedValue) => (val) => {
// Negation of exact word/phrase match
@@ -44,9 +45,10 @@ const stringComparators: Record<string, Comparator<string>> = {
return !normalizedVal.includes(normalizedCompared);
}
- // For single word, split into words and check for exact word match, then negate
- const words = normalizedVal.split(/\s+/);
- return !words.some(word => word === normalizedCompared);
+ // For single word, tokenize into punctuation-stripped words and check for
+ // an exact word match, then negate.
+ const words = tokenizeIntoWords(normalizedVal);
+ return !words.some(word => word === stripWordPunctuation(normalizedCompared));
},
">": (comparedValue) => (val) => val > comparedValue,
">=": (comparedValue) => (val) => val >= comparedValue,
@@ -72,8 +74,8 @@ const stringComparators: Record<string, Comparator<string>> = {
return true;
}
- // Then try fuzzy word matching
- const words = normalizedVal.split(/\s+/);
+ // Then try fuzzy word matching over the tokenized (punctuation-stripped) value
+ const words = tokenizeIntoWords(normalizedVal);
return words.some(word => fuzzyMatchWord(normalizedCompared, word));
},
"~*": (comparedValue) => (val) => {
diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.ts
index aaffa40aa8..74d9cc2b7e 100644
--- a/packages/trilium-core/src/services/search/services/search.spec.ts
+++ b/packages/trilium-core/src/services/search/services/search.spec.ts
@@ -5,6 +5,8 @@ import BBranch from "../../../becca/entities/bbranch.js";
import SearchContext from "../search_context.js";
import dateUtils from "../../utils/date.js";
import becca from "../../../becca/becca.js";
+import { getContext } from "../../context.js";
+import noteService from "../../notes.js";
import { findNoteByTitle, note, NoteBuilder } from "../../../test/becca_mocking.js";
describe("Search", () => {
@@ -387,6 +389,25 @@ describe("Search", () => {
expect(searchResults.length).toEqual(5);
});
+ it("exact word search matches a content word wrapped in punctuation (#10616)", () => {
+ // The note body contains "(sync)" (parenthesised). Exact-word search for
+ // "sync" must still find it — content tokenization strips boundary
+ // punctuation so "(sync)" tokenizes to the word "sync". The title
+ // deliberately omits the word so the match comes from the body.
+ const guide = getContext().init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Networking Guide",
+ content: "see (sync) mode",
+ type: "text"
+ }).note);
+
+ const searchContext = new SearchContext();
+ const searchResults = searchService.findResultsWithQuery("=sync", searchContext);
+
+ expect(searchResults.length).toEqual(1);
+ expect(searchResults[0].noteId).toEqual(guide.noteId);
+ });
+
it("fuzzy attribute search", () => {
rootNote.child(note("Europe")
.label("country", "", true)
diff --git a/packages/trilium-core/src/services/search/utils/text_utils.spec.ts b/packages/trilium-core/src/services/search/utils/text_utils.spec.ts
index 146f5cc0fe..cfb5b8c85e 100644
--- a/packages/trilium-core/src/services/search/utils/text_utils.spec.ts
+++ b/packages/trilium-core/src/services/search/utils/text_utils.spec.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { calculateOptimizedEditDistance, validateFuzzySearchTokens, fuzzyMatchWord, stripHtmlTags } from './text_utils.js';
+import { calculateOptimizedEditDistance, validateFuzzySearchTokens, fuzzyMatchWord, stripHtmlTags, stripWordPunctuation, tokenizeIntoWords, wordsContainPhrase } from './text_utils.js';
describe('Fuzzy Search Core', () => {
describe('calculateOptimizedEditDistance', () => {
@@ -63,6 +63,67 @@ describe('Fuzzy Search Core', () => {
});
});
+ describe('stripWordPunctuation', () => {
+ it('strips leading and trailing punctuation while keeping the inner word', () => {
+ expect(stripWordPunctuation('(sync)')).toBe('sync');
+ expect(stripWordPunctuation('sync,')).toBe('sync');
+ expect(stripWordPunctuation('"sync"')).toBe('sync');
+ expect(stripWordPunctuation('—dash—')).toBe('dash');
+ });
+
+ it('keeps connector/symbol chars and inner punctuation', () => {
+ // "+" is a math symbol (Sm), "_" is a connector (Pc) — both deliberately kept.
+ expect(stripWordPunctuation('c++')).toBe('c++');
+ expect(stripWordPunctuation('_private')).toBe('_private');
+ // Inner apostrophe is preserved; only leading/trailing punctuation is stripped.
+ expect(stripWordPunctuation("d'artagnan")).toBe("d'artagnan");
+ });
+
+ it('handles words that are entirely punctuation or empty', () => {
+ expect(stripWordPunctuation('...')).toBe('');
+ expect(stripWordPunctuation('')).toBe('');
+ });
+ });
+
+ describe('tokenizeIntoWords', () => {
+ it('normalizes, splits on whitespace and strips per-word punctuation', () => {
+ expect(tokenizeIntoWords('see (sync) mode')).toEqual(['see', 'sync', 'mode']);
+ expect(tokenizeIntoWords('sync, async')).toEqual(['sync', 'async']);
+ expect(tokenizeIntoWords('"sync"')).toEqual(['sync']);
+ });
+
+ it('keeps symbol/connector tokens and inner punctuation intact', () => {
+ expect(tokenizeIntoWords('c++ _private')).toEqual(['c++', '_private']);
+ expect(tokenizeIntoWords("d'artagnan is dead")).toEqual(['d\'artagnan', 'is', 'dead']);
+ });
+
+ it('normalizes diacritics via the shared normalizer', () => {
+ expect(tokenizeIntoWords('ktorý')).toEqual(['ktory']);
+ });
+
+ it('returns an empty array for empty or whitespace-only input', () => {
+ expect(tokenizeIntoWords('')).toEqual([]);
+ expect(tokenizeIntoWords(' ')).toEqual([]);
+ });
+ });
+
+ describe('wordsContainPhrase', () => {
+ it('matches a consecutive run of words in order', () => {
+ expect(wordsContainPhrase(['a', 'exact', 'phrase', 'b'], ['exact', 'phrase'])).toBe(true);
+ expect(wordsContainPhrase(['exact', 'phrase'], ['exact', 'phrase'])).toBe(true);
+ });
+
+ it('does not match non-consecutive or out-of-order words', () => {
+ expect(wordsContainPhrase(['exact', 'x', 'phrase'], ['exact', 'phrase'])).toBe(false);
+ expect(wordsContainPhrase(['phrase', 'exact'], ['exact', 'phrase'])).toBe(false);
+ });
+
+ it('never matches an empty phrase or a phrase longer than the haystack', () => {
+ expect(wordsContainPhrase(['a', 'b'], [])).toBe(false);
+ expect(wordsContainPhrase(['a'], ['a', 'b'])).toBe(false);
+ });
+ });
+
describe('stripHtmlTags', () => {
it('strips simple HTML tags', () => {
expect(stripHtmlTags('<p>Hello</p>')).toBe('Hello');
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 8048dc709a..7e39f4093a 100644
--- a/packages/trilium-core/src/services/search/utils/text_utils.ts
+++ b/packages/trilium-core/src/services/search/utils/text_utils.ts
@@ -356,3 +356,83 @@ export function fuzzyMatchWordWithResult(token: string, text: string, maxDistanc
export function fuzzyMatchWord(token: string, text: string, maxDistance: number = FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE): boolean {
return fuzzyMatchWordWithResult(token, text, maxDistance) !== null;
}
+
+/**
+ * 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++`.
+ */
+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).
+ */
+export function stripWordPunctuation(word: string): string {
+ if (!word) {
+ return "";
+ }
+
+ return word.replace(LEADING_PUNCTUATION, "").replace(TRAILING_PUNCTUATION, "");
+}
+
+/**
+ * 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.
+ */
+export function tokenizeIntoWords(text: string): string[] {
+ return normalizeSearchText(text)
+ .split(/\s+/)
+ .map(stripWordPunctuation)
+ .filter((word) => word.length > 0);
+}
+
+/**
+ * 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.
+ */
+export function wordsContainPhrase(words: string[], phrase: string[]): boolean {
+ if (phrase.length === 0 || phrase.length > words.length) {
+ return false;
+ }
+
+ for (let i = 0; i <= words.length - phrase.length; i++) {
+ if (phrase.every((phraseWord, j) => words[i + j] === phraseWord)) {
+ return true;
+ }
+ }
+
+ return false;
+}