parseSections static method

List<MarkdownSection> parseSections(
  1. String markdown
)

Parse markdown into a tree of MarkdownSections organised by heading level.

Top-level content that appears before any heading is ignored. The returned list contains only the root-level sections; deeper headings are nested in MarkdownSection.children.

Implementation

static List<MarkdownSection> parseSections(String markdown) {
  final lines = markdown.split('\n');
  final rootSections = <MarkdownSection>[];

  // Flat list of (level, heading, startLine) tuples.
  final headings = <_HeadingInfo>[];

  for (var i = 0; i < lines.length; i++) {
    final match = _headingPattern.firstMatch(lines[i].trimRight());
    if (match != null) {
      headings.add(_HeadingInfo(
        level: match.group(1)!.length,
        heading: match.group(2)!.trim(),
        lineIndex: i,
      ));
    }
  }

  if (headings.isEmpty) return rootSections;

  // Build flat sections with raw content.
  final flatSections = <_FlatSection>[];
  for (var i = 0; i < headings.length; i++) {
    final start = headings[i].lineIndex + 1;
    final end =
        (i + 1 < headings.length) ? headings[i + 1].lineIndex : lines.length;
    final content = lines.sublist(start, end).join('\n').trim();
    flatSections.add(_FlatSection(
      level: headings[i].level,
      heading: headings[i].heading,
      content: content,
    ));
  }

  // Convert the flat list into a tree.
  return _buildTree(flatSections, 0, flatSections.length, 0);
}