toc.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """
  2. Deals with generating the per-page table of contents.
  3. For the sake of simplicity we use the Python-Markdown `toc` extension to
  4. generate a list of dicts for each toc item, and then store it as AnchorLinks to
  5. maintain compatibility with older versions of MkDocs.
  6. """
  7. def get_toc(toc_tokens):
  8. toc = [_parse_toc_token(i) for i in toc_tokens]
  9. # For the table of contents, always mark the first element as active
  10. if len(toc):
  11. toc[0].active = True
  12. return TableOfContents(toc)
  13. class TableOfContents:
  14. """
  15. Represents the table of contents for a given page.
  16. """
  17. def __init__(self, items):
  18. self.items = items
  19. def __iter__(self):
  20. return iter(self.items)
  21. def __len__(self):
  22. return len(self.items)
  23. def __str__(self):
  24. return ''.join([str(item) for item in self])
  25. class AnchorLink:
  26. """
  27. A single entry in the table of contents.
  28. """
  29. def __init__(self, title, id, level):
  30. self.title, self.id, self.level = title, id, level
  31. self.children = []
  32. @property
  33. def url(self):
  34. return '#' + self.id
  35. def __str__(self):
  36. return self.indent_print()
  37. def indent_print(self, depth=0):
  38. indent = ' ' * depth
  39. ret = '{}{} - {}\n'.format(indent, self.title, self.url)
  40. for item in self.children:
  41. ret += item.indent_print(depth + 1)
  42. return ret
  43. def _parse_toc_token(token):
  44. anchor = AnchorLink(token['name'], token['id'], token['level'])
  45. for i in token['children']:
  46. anchor.children.append(_parse_toc_token(i))
  47. return anchor