parse static method

List<MemorySection> parse(
  1. String content
)

Parse a markdown file into sections.

Implementation

static List<MemorySection> parse(String content) {
  final sections = <MemorySection>[];
  final lines = content.split('\n');
  String? currentHeading;
  int currentLevel = 0;
  final buffer = StringBuffer();

  for (final line in lines) {
    final headingMatch = RegExp(r'^(#{1,6})\s+(.+)$').firstMatch(line);

    if (headingMatch != null) {
      // Save previous section.
      if (currentHeading != null) {
        sections.add(
          MemorySection(
            heading: currentHeading,
            level: currentLevel,
            content: buffer.toString().trim(),
            tags: _extractTags(buffer.toString()),
          ),
        );
      }

      currentHeading = headingMatch.group(2)!;
      currentLevel = headingMatch.group(1)!.length;
      buffer.clear();
    } else {
      buffer.writeln(line);
    }
  }

  // Save last section.
  if (currentHeading != null) {
    sections.add(
      MemorySection(
        heading: currentHeading,
        level: currentLevel,
        content: buffer.toString().trim(),
        tags: _extractTags(buffer.toString()),
      ),
    );
  } else if (buffer.toString().trim().isNotEmpty) {
    sections.add(
      MemorySection(
        heading: 'General',
        level: 1,
        content: buffer.toString().trim(),
      ),
    );
  }

  return sections;
}