"""Build a static documentation page using a documented Markdown subset."""
from pathlib import Path
import html
import re
import shutil
ROOT = Path(__file__).resolve().parent
def inline(value):
# Escape HTML first; only explicitly supported markup becomes HTML.
value = html.escape(value)
tokens = []
def token(markup):
tokens.append(markup)
return f'\x00{len(tokens) - 1}\x00'
value = re.sub(r'`([^`]+)`', lambda m: token(f'{m[1]}'), value)
def link(match):
label, url = match.groups()
if not re.match(r'^(https?://|mailto:|#)', html.unescape(url), re.I):
return label
return token(f'{label}')
value = re.sub(r'\[([^\]]+)\]\(([^\s)]+)\)', link, value)
value = re.sub(r'\*\*([^*]+)\*\*', r'\1', value)
for i in reversed(range(len(tokens))):
value = value.replace(f'\x00{i}\x00', tokens[i])
return value
def render(source):
lines = source.splitlines()
output, navigation = [], []
index, section, heading = 0, False, 0
while index < len(lines):
line = lines[index].strip()
index += 1
if not line:
continue
if line.startswith('```'):
code = []
while index < len(lines) and not lines[index].strip().startswith('```'):
code.append(lines[index])
index += 1
index += 1
output.append('
' + html.escape('\n'.join(code)) + '')
elif re.match(r'^#{1,3} ', line):
level = len(line.split(' ', 1)[0])
title = line[level + 1:]
if level == 2:
if section:
output.append('')
heading += 1
anchor = f'section-{heading}'
navigation.append(f'{heading:02}{html.escape(title)}')
output.append(f'| {cell} | ' for cell in cells(line)) + '
|---|
| {cell} | ' for cell in cells(lines[index])) + '
{inline(line[2:])}') else: output.append(f'
{inline(line)}
') if section: output.append('