asciidoc_reader.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. import six
  12. try:
  13. # asciidocapi won't import on Py3
  14. from .asciidocapi import AsciiDocAPI, AsciiDocError
  15. # AsciiDocAPI class checks for asciidoc.py
  16. AsciiDocAPI()
  17. except:
  18. asciidoc_enabled = False
  19. else:
  20. asciidoc_enabled = True
  21. class AsciiDocReader(BaseReader):
  22. """Reader for AsciiDoc files"""
  23. enabled = asciidoc_enabled
  24. file_extensions = ['asc', 'adoc', 'asciidoc']
  25. default_options = ["--no-header-footer", "-a newline=\\n"]
  26. default_backend = 'html5'
  27. def read(self, source_path):
  28. """Parse content and metadata of asciidoc files"""
  29. from cStringIO import StringIO
  30. with pelican_open(source_path) as source:
  31. text = StringIO(source.encode('utf8'))
  32. content = StringIO()
  33. ad = AsciiDocAPI()
  34. options = self.settings.get('ASCIIDOC_OPTIONS', [])
  35. options = self.default_options + options
  36. for o in options:
  37. ad.options(*o.split())
  38. backend = self.settings.get('ASCIIDOC_BACKEND', self.default_backend)
  39. ad.execute(text, content, backend=backend)
  40. content = content.getvalue().decode('utf8')
  41. metadata = {}
  42. for name, value in ad.asciidoc.document.attributes.items():
  43. name = name.lower()
  44. metadata[name] = self.process_metadata(name, six.text_type(value))
  45. if 'doctitle' in metadata:
  46. metadata['title'] = metadata['doctitle']
  47. return content, metadata
  48. def add_reader(readers):
  49. for ext in AsciiDocReader.file_extensions:
  50. readers.reader_classes[ext] = AsciiDocReader
  51. def register():
  52. signals.readers_init.connect(add_reader)