Last active
May 22, 2024 20:33
-
-
Save juliangroen/f797e8ca3bf4280322f9c49fbbd55423 to your computer and use it in GitHub Desktop.
Markdown TOC Maker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import sys | |
from pathlib import Path | |
def parse_markdown_for_toc(markdown_content): | |
heading_pattern = re.compile(r'^(#{1,})\s+(.+?)(\s*)$', re.MULTILINE) | |
toc = [] | |
for match in heading_pattern.finditer(markdown_content): | |
hashes, heading, _ = match.groups() | |
level = len(hashes) | |
anchor = re.sub(r'[^\w\s-]', '', heading).replace(' ', '-').lower() | |
toc.append((level, heading.strip(), anchor)) | |
toc_str = "" | |
for level, heading, anchor in toc: | |
toc_str += " " * (level - 1) + f"* [{heading}](#{anchor})\n" | |
return toc_str | |
def create_toc_from_markdown_file(file_path): | |
markdown_path = Path(file_path) | |
markdown_content = markdown_path.read_text(encoding='utf-8') | |
toc = parse_markdown_for_toc(markdown_content) | |
return toc | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print(f"Usage: python {sys.argv[0]} <path_to_markdown_file>") | |
sys.exit(1) | |
file_path = sys.argv[1] | |
toc = create_toc_from_markdown_file(file_path) | |
print(toc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment