Skip to content

Instantly share code, notes, and snippets.

@BaseCase
Created March 22, 2018 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BaseCase/225ee9b70ebbdd329638894686884d5e to your computer and use it in GitHub Desktop.
Save BaseCase/225ee9b70ebbdd329638894686884d5e to your computer and use it in GitHub Desktop.
Generate a table of contents for a markdown file
#!/usr/bin/env python
import sys
def main():
if not len(sys.argv) == 2:
print("Please provide exactly one filename.")
sys.exit(1)
filename = sys.argv[1]
toc = generate_toc_for_file(filename)
print('\n'.join(toc))
def generate_toc_for_file(filename):
flat_contents = []
with open(filename) as f:
for line in f.readlines():
if line.startswith('#'):
flat_contents.append(parse_header_line(line))
return tocify(flat_contents)
def parse_header_line(text):
split = text.split(' ')
header_level = len(split[0])
header_text = ' '.join(split[1:]).strip()
return (header_level, header_text)
def tocify(contents):
toc = []
for (level, text) in contents:
indent = ' ' * (level - 1)
row = "{indent}- [{title}]({href})".format(
indent=indent,
title=text,
href=generate_href(text))
toc.append(row)
return toc
def generate_href(title):
return ('#' + title
.strip()
.lower()
.replace(' ', '-')
.replace('/', '')
.replace('.', '')
.replace(',', '')
.replace('`', '')
.replace('(', '')
.replace(')', '')
)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment