Skip to content

Instantly share code, notes, and snippets.

@jg-you jg-you/mdown_toc.py
Last active Mar 19, 2016

Embed
What would you like to do?
Generate TOC for a markdown file
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @author: Jean-Gabriel Young <jean.gabriel.young@gmail.com>
"""Generate TOC for a markdown file."""
import re
# Match between 1 and 4 #
section = re.compile('^\s*(#){1,4}\s?')
strip_url = re.compile('[\W_]+', re.UNICODE)
def gen_toc(markdown_file):
"""Generate TOC for a markdown file."""
toc_content = []
for l in markdown_file:
match = section.match(l)
if match is not None:
level = match.group().count('#') - 1
title = strip_url.sub(' ', section.sub('', l)).strip()
url = title.replace(' ', '-').lower()
toc_content.append((level, title, url))
toc = []
numerotation = [1, 1, 1, 1]
for item in toc_content:
toc.append(' ' * (item[0]) + str(numerotation[item[0]]) +
". " + "[" + item[1] + "](#" + item[2] + ")")
numerotation[item[0]] += 1
numerotation[item[0] + 1:] = [1] * (3 - item[0])
return toc
if __name__ == "__main__":
# Options parser.
import argparse as ap
import sys
prs = ap.ArgumentParser(description="Generate TOC for a markdown file.")
prs.add_argument('markdown_file', type=str,
help='Markdown file')
if len(sys.argv) == 1:
prs.print_help()
sys.exit(1)
args = prs.parse_args()
with open(args.markdown_file, 'r') as f:
toc = gen_toc(f)
for item in toc:
print(item)

Top level

Sub-section A

Sub-section B

Sub-sub-section B.1

Sub-section C

Sub-sub-section C.1

Sub-sub-section C.2

> python mdown_toc.py mdown_toc_example.md
1. [Top level](#top-level)
1. [Sub section A](#sub-section-a)
2. [Sub section B](#sub-section-b)
1. [Sub sub section B 1](#sub-sub-section-b-1)
3. [Sub section C](#sub-section-c)
1. [Sub sub section C 1](#sub-sub-section-c-1)
2. [Sub sub section C 2](#sub-sub-section-c-2)
@jg-you

This comment has been minimized.

Copy link
Owner Author

commented Mar 19, 2016

Probably not robust, but it works for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.