excerptAround function
Returns an excerpt of text around the first occurrence of query, with
contextChars characters on each side and ellipsis at truncation points.
contextChars counts grapheme clusters (user-perceived characters), so the
excerpt never cuts an emoji or a letter-plus-combining-mark in half and the
window is the same visible width whatever the script.
Example:
excerptAround('👋👋 hello world', 'hello', contextChars: 2); // '... 👋 hello w ...'
Audited: 2026-06-12 11:26 EDT
Implementation
String excerptAround(String text, String query, {int contextChars = 60, String ellipsis = '...'}) {
if (text.isEmpty) return '';
final String q = query.trim();
// Match case-insensitively but slice the original-case text: lowercase only
// for locating the index so the returned excerpt preserves the source casing.
final int idx = q.isEmpty ? -1 : text.toLowerCase().indexOf(q.toLowerCase());
if (idx < 0) return _headTailExcerpt(text, contextChars, ellipsis);
// indexOf gives a code-unit offset but substringSafe is grapheme-indexed.
// The old code fed code-unit arithmetic straight into substringSafe, so any
// emoji or combining mark before the match shifted the window off the match.
// Convert the offset to a grapheme position first (clamped, because
// lowercasing can lengthen the searched copy).
final int total = text.characters.length;
final int matchAt = text.substring(0, idx.clamp(0, text.length)).characters.length;
final int start = (matchAt - contextChars).clamp(0, total);
final int end = (matchAt + q.characters.length + contextChars).clamp(0, total);
// Add a leading/trailing ellipsis only when the window is actually clipped at
// that edge; an excerpt that reaches the real start or end gets no ellipsis.
final String head = start > 0 ? '$ellipsis ' : '';
final String tail = end < total ? ' $ellipsis' : '';
return '$head${text.substringSafe(start, end)}$tail';
}