asciidoc_reader.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. """
  3. AsciiDoc Reader
  4. ===============
  5. This plugin allows you to use AsciiDoc to write your posts.
  6. File extension should be ``.asc``, ``.adoc``, or ``asciidoc``.
  7. """
  8. from pelican.readers import BaseReader
  9. from pelican.utils import pelican_open
  10. from pelican import signals
  11. try:
  12. # asciidocapi won't import on Py3
  13. from .asciidocapi import AsciiDocAPI, AsciiDocError
  14. # AsciiDocAPI class checks for asciidoc.py
  15. AsciiDocAPI()
  16. except:
  17. asciidoc_enabled = False
  18. else:
  19. asciidoc_enabled = True
  20. class AsciiDocReader(BaseReader):
  21. """Reader for AsciiDoc files"""
  22. enabled = asciidoc_enabled
  23. file_extensions = ['asc', 'adoc', 'asciidoc']
  24. default_options = ["--no-header-footer", "-a newline=\\n"]
  25. default_backend = 'html5'
  26. def read(self, source_path):
  27. """Parse content and metadata of asciidoc files"""
  28. from cStringIO import StringIO
  29. with pelican_open(source_path) as source:
  30. text = StringIO(source)
  31. content = StringIO()
  32. ad = AsciiDocAPI()
  33. options = self.settings.get('ASCIIDOC_OPTIONS', [])
  34. options = self.default_options + options
  35. for o in options:
  36. ad.options(*o.split())
  37. backend = self.settings.get('ASCIIDOC_BACKEND', self.default_backend)
  38. ad.execute(text, content, backend=backend)
  39. content = content.getvalue()
  40. metadata = {}
  41. for name, value in ad.asciidoc.document.attributes.items():
  42. name = name.lower()
  43. metadata[name] = self.process_metadata(name, value)
  44. if 'doctitle' in metadata:
  45. metadata['title'] = metadata['doctitle']
  46. return content, metadata
  47. def add_reader(readers):
  48. for ext in AsciiDocReader.file_extensions:
  49. readers.reader_classes[ext] = AsciiDocReader
  50. def register():
  51. signals.readers_init.connect(add_reader)