extract_toc.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # -*- coding: utf-8 -*-
  2. """
  3. Extract Table of Content
  4. ========================
  5. A Pelican plugin to extract table of contents (ToC) from `article.content` and
  6. place it in its own `article.toc` variable for use in templates.
  7. """
  8. from os import path
  9. from bs4 import BeautifulSoup
  10. from pelican import signals, readers, contents
  11. import logging
  12. logger = logging.getLogger(__name__)
  13. def extract_toc(content):
  14. if isinstance(content, contents.Static):
  15. return
  16. soup = BeautifulSoup(content._content, 'html.parser')
  17. filename = content.source_path
  18. extension = path.splitext(filename)[1][1:]
  19. toc = None
  20. # default Markdown reader
  21. if not toc and readers.MarkdownReader.enabled and extension in readers.MarkdownReader.file_extensions:
  22. toc = soup.find('div', class_='toc')
  23. if toc:
  24. toc.extract()
  25. # default reStructuredText reader
  26. if not toc and readers.RstReader.enabled and extension in readers.RstReader.file_extensions:
  27. toc = soup.find('div', class_='contents topic')
  28. if toc:
  29. toc.extract()
  30. tag = BeautifulSoup(str(toc), 'html.parser')
  31. tag.div['class'] = 'toc'
  32. tag.div['id'] = ''
  33. p = tag.find('p', class_='topic-title first')
  34. if p:
  35. p.extract()
  36. toc = tag
  37. # Pandoc reader (markdown and other formats)
  38. if 'pandoc_reader' in content.settings['PLUGINS']:
  39. try:
  40. from pandoc_reader import PandocReader
  41. except ImportError:
  42. PandocReader = False
  43. if not toc and PandocReader and PandocReader.enabled and extension in PandocReader.file_extensions:
  44. toc = soup.find('nav', id='TOC')
  45. if toc:
  46. toc.extract()
  47. content._content = soup.decode()
  48. content.toc = toc.decode()
  49. if content.toc.startswith('<html>'):
  50. content.toc = content.toc[12:-14]
  51. def register():
  52. signals.content_object_init.connect(extract_toc)