rmd_reader.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #-*- conding: utf-8 -*-
  2. import os
  3. from pelican import readers
  4. from pelican import signals
  5. from pelican import settings
  6. from pelican.utils import pelican_open
  7. from markdown import Markdown
  8. try:
  9. from rpy2 import robjects
  10. rmd = True
  11. except ImportError:
  12. rmd = False
  13. class RmdReader(readers.BaseReader):
  14. enabled = rmd
  15. file_extensions = ['Rmd', 'rmd']
  16. # You need to have a read method, which takes a filename and returns
  17. # some content and the associated metadata.
  18. def read(self, filename):
  19. """Parse content and metadata of markdown files"""
  20. # parse Rmd file - generate md file
  21. md_filename = filename.replace('.Rmd', '.aux').replace('.rmd', '.aux')
  22. robjects.r("""
  23. require(knitr);
  24. opts_knit$set(base.dir='{2}/content');
  25. knit('{0}', '{1}', quiet=TRUE, encoding='UTF-8');
  26. """.format(filename, md_filename, settings.DEFAULT_CONFIG.get('PATH')))
  27. # parse md file
  28. md = Markdown(extensions = ['meta', 'codehilite(css_class=highlight)', 'extra'])
  29. with pelican_open(md_filename) as text:
  30. content = md.convert(text)
  31. os.remove(md_filename)
  32. # find metadata
  33. metadata = {}
  34. for name, value in md.Meta.items():
  35. name = name.lower()
  36. meta = self.process_metadata(name, value[0])
  37. metadata[name] = meta
  38. return content, metadata
  39. def add_reader(readers):
  40. readers.reader_classes['rmd'] = RmdReader
  41. def register():
  42. signals.readers_init.connect(add_reader)