chunkText function
Splits text into chunks of at most maxChars characters, trying to break
at sentence boundaries (.). overlap optional characters to overlap between chunks.
maxChars and overlap count grapheme clusters (user-perceived
characters), so a chunk boundary never splits an emoji or separates a
letter from its combining mark.
Audited: 2026-06-12 11:26 EDT
Implementation
List<String> chunkText(String text, {int maxChars = 500, int overlap = 0}) {
if (text.isEmpty) return <String>[];
if (maxChars < 1) return <String>[text];
// Work on a grapheme list throughout. The old code measured and searched in
// code units (length, lastIndexOf) but sliced with the grapheme-indexed
// substringSafe, so emoji text produced overlapping or misplaced chunks.
final List<String> g = text.characters.toList();
final List<String> chunks = List<String>.filled(g.length + 1, '');
int chunkIndex = 0;
int start = 0;
while (start < g.length) {
int end = (start + maxChars).clamp(0, g.length);
// Prefer a sentence boundary: pull `end` back to the last period within the
// window so chunks split between sentences rather than mid-sentence. Require
// lastPeriod > start so we never produce an empty/backward chunk when the
// only period sits at or before the chunk start.
if (end < g.length) {
final int lastPeriod = g.lastIndexOf('.', end);
if (lastPeriod > start) end = lastPeriod + 1;
}
final int chunkStart = start;
chunks[chunkIndex++] = g.sublist(start, end).join().trim();
// Advance to `end`, then (only when more text remains) rewind by `overlap`
// so adjacent chunks share trailing context for search/embedding. Force at
// least one char of forward progress past THIS chunk's start: with
// `overlap >= maxChars` the rewind would otherwise land at or before
// `chunkStart`, looping forever and overflowing the pre-sized `chunks` list.
start = end;
if (overlap > 0 && start < g.length) {
final int rewound = end - overlap;
start = rewound <= chunkStart ? chunkStart + 1 : rewound;
}
}
return chunks.sublist(0, chunkIndex).where((String c) => c.isNotEmpty).toList();
}