pelican_inline_markdown_extension.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. """
  3. Pelican Inline Markdown Extension
  4. ==================================
  5. An extension for the Python Markdown module that enables
  6. the Pelican Python static site generator to add inline patterns.
  7. """
  8. import markdown
  9. import re
  10. from markdown.util import etree
  11. from markdown.util import AtomicString
  12. class PelicanInlineMarkdownExtensionPattern(markdown.inlinepatterns.Pattern):
  13. """Inline Markdown processing"""
  14. def __init__(self, pelican_markdown_extension, tag, pattern):
  15. super(PelicanInlineMarkdownExtensionPattern,self).__init__(pattern)
  16. self.tag = tag
  17. self.config = pelican_markdown_extension.getConfig('config')
  18. def handleMatch(self, m):
  19. node = markdown.util.etree.Element(self.tag)
  20. tag_attributes = self.config.get(m.group('prefix'), ('', 'pelican-inline'))
  21. tag_class = 'pelican-inline' # default class
  22. tag_style = '' # default is for no styling
  23. if isinstance(tag_attributes, tuple):
  24. tag_style = tag_attributes[0]
  25. tag_class = tag_attributes[1] if len(tag_attributes) > 1 else ''
  26. elif isinstance(tag_attributes, basestring):
  27. tag_class = tag_attributes
  28. if tag_class != '':
  29. node.set('class', tag_class)
  30. if tag_style!= '':
  31. node.set('style', tag_style)
  32. node.text = markdown.util.AtomicString(m.group('text'))
  33. return node
  34. class PelicanInlineMarkdownExtension(markdown.Extension):
  35. """A Markdown extension enabling processing in Markdown for Pelican"""
  36. def __init__(self, config):
  37. try:
  38. # Needed for Markdown versions >= 2.5
  39. self.config['config'] = ['{}', 'config for markdown extension']
  40. super(PelicanInlineMarkdownExtension,self).__init__(**config)
  41. except AttributeError:
  42. # Markdown versions < 2.5
  43. config['config'] = [config['config'], 'config for markdown extension']
  44. super(PelicanInlineMarkdownExtension, self).__init__(config)
  45. def extendMarkdown(self, md, md_globals):
  46. # Regex to detect mathjax
  47. config = self.getConfig('config')
  48. patterns = []
  49. # The following mathjax settings can be set via the settings dictionary
  50. for key in config:
  51. patterns.append(re.escape(key))
  52. inline_regex = r'(?P<prefix>%s)(?P<text>.+?)\2' % ('|'.join(patterns))
  53. # Process after escapes
  54. md.inlinePatterns.add('texthighlight_inlined', PelicanInlineMarkdownExtensionPattern(self, 'span', inline_regex), '>emphasis2')