buildTableOfContents function

String buildTableOfContents(
  1. String markdown, {
  2. int maxDepth = 3,
})

Build a table of contents from headings.

Implementation

String buildTableOfContents(String markdown, {int maxDepth = 3}) {
  final headings = extractHeadings(markdown);
  final buffer = StringBuffer();

  for (final h in headings) {
    if (h.level > maxDepth) continue;
    final indent = '  ' * (h.level - 1);
    final anchor = h.text
        .toLowerCase()
        .replaceAll(RegExp(r'[^\w\s-]'), '')
        .replaceAll(RegExp(r'\s+'), '-');
    buffer.writeln('$indent- [${h.text}](#$anchor)');
  }

  return buffer.toString();
}