asciidoc_reader.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. if value is None:
  44. continue
  45. name = name.lower()
  46. metadata[name] = self.process_metadata(name, six.text_type(value))
  47. if 'doctitle' in metadata:
  48. metadata['title'] = metadata['doctitle']
  49. return content, metadata
  50. def add_reader(readers):
  51. for ext in AsciiDocReader.file_extensions:
  52. readers.reader_classes[ext] = AsciiDocReader
  53. def register():
  54. signals.readers_init.connect(add_reader)