Editor

Markdown Table of Contents

#317 · Parsing · Intermediate · 75 XP · about 15 min

Long README files often start with a table of contents built from their headings. Write table_of_contents(markdown) that reads a Markdown document (lines separated by \n) and returns a list with one string per heading, in order.

A line is a heading when it starts with 1 to 6 # characters followed by a space, and the number of # characters is its level. Its title is the rest of the line with spaces removed from both ends, and a heading needs a title that is not empty. Lines such as #hashtag (no space) or ####### Seven (seven of them) are not headings.

Lines inside fenced code blocks are not headings either. A line that starts with three backticks opens a code block, and the next line that starts with three backticks closes it. A code block that is never closed runs to the end of the document.

Each entry is '- ' followed by the title, indented by two spaces for every level it sits below the highest level used in the document. So when the top headings are ##, those get no indent and ### headings get two spaces.

Examples

table_of_contents('# Guide\nIntro text\n## Install\n## Usage\n### Options')
# returns ['- Guide', '  - Install', '  - Usage', '    - Options']

fence = '`' * 3
doc = '## Setup\n' + fence + 'bash\n# not a heading\n' + fence + '\n### Linux'
table_of_contents(doc)
# returns ['- Setup', '  - Linux']

table_of_contents('No headings at all')
# returns []

Constraints

  • markdown has at most 200,000 lines.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.