rmd_reader.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. # replace single backslashes with double backslashes
  21. filename = filename.replace('\\', '\\\\')
  22. # parse Rmd file - generate md file
  23. md_filename = filename.replace('.Rmd', '.aux').replace('.rmd', '.aux')
  24. robjects.r("""
  25. require(knitr);
  26. opts_knit$set(base.dir='{2}/content');
  27. knit('{0}', '{1}', quiet=TRUE, encoding='UTF-8');
  28. """.format(filename, md_filename, settings.DEFAULT_CONFIG.get('PATH')))
  29. md_reader = readers.MarkdownReader(self.settings)
  30. content, metadata = md_reader.read(md_filename)
  31. os.remove(md_filename)
  32. return content, metadata
  33. def add_reader(readers):
  34. readers.reader_classes['rmd'] = RmdReader
  35. def register():
  36. signals.readers_init.connect(add_reader)