splitStreamSegments function
Implementation
List<String> splitStreamSegments(
String src, {
MarkdownBlockRegistry? blockRegistry,
}) {
final normalized =
src.contains('\r')
? src.replaceAll('\r\n', '\n').replaceAll('\r', '\n')
: src;
final lines = normalized.split('\n');
final segments = <String>[];
final current = <String>[];
var inFence = false;
var inLatex = false;
void closeSegment() {
if (current.isNotEmpty) {
segments.add(current.join('\n'));
current.clear();
}
}
for (var index = 0; index < lines.length; index++) {
final line = lines[index];
final trimmed = line.trimLeft();
if (inFence) {
current.add(line);
if (trimmed.startsWith('```')) {
inFence = false;
}
continue;
}
if (inLatex) {
current.add(line);
if (line.contains('\\]')) {
inLatex = false;
}
continue;
}
final custom = blockRegistry?.match(lines, index);
if (custom != null) {
current.addAll(lines.sublist(index, custom.endLine));
index = custom.endLine - 1;
continue;
}
if (line.trim().isEmpty) {
closeSegment();
continue;
}
current.add(line);
if (trimmed.startsWith('```')) {
inFence = true;
continue;
}
if (trimmed.startsWith('\\[')) {
// Mirrors the block parser: strip leading `\[` markers, then the block
// stays open unless the closer appears on the same line.
var rest = trimmed;
while (rest.startsWith('\\[')) {
rest = rest.substring(2);
}
if (!rest.contains('\\]')) {
inLatex = true;
}
}
}
closeSegment();
return segments;
}