/markdown/extensions/meta.py

https://github.com/ashwoods/Python-Markdown
Python | 96 lines | 85 code | 1 blank | 10 comment | 0 complexity | ba491ac2887f800fd047cb6eda58e97f MD5 | raw file
  1. #!usr/bin/python
  2. """
  3. Meta Data Extension for Python-Markdown
  4. =======================================
  5. This extension adds Meta Data handling to markdown.
  6. Basic Usage:
  7. >>> import markdown
  8. >>> text = '''Title: A Test Doc.
  9. ... Author: Waylan Limberg
  10. ... John Doe
  11. ... Blank_Data:
  12. ...
  13. ... The body. This is paragraph one.
  14. ... '''
  15. >>> md = markdown.Markdown(['meta'])
  16. >>> print md.convert(text)
  17. <p>The body. This is paragraph one.</p>
  18. >>> print md.Meta
  19. {u'blank_data': [u''], u'author': [u'Waylan Limberg', u'John Doe'], u'title': [u'A Test Doc.']}
  20. Make sure text without Meta Data still works (markdown < 1.6b returns a <p>).
  21. >>> text = ' Some Code - not extra lines of meta data.'
  22. >>> md = markdown.Markdown(['meta'])
  23. >>> print md.convert(text)
  24. <pre><code>Some Code - not extra lines of meta data.
  25. </code></pre>
  26. >>> md.Meta
  27. {}
  28. Copyright 2007-2008 [Waylan Limberg](http://achinghead.com).
  29. Project website: <http://www.freewisdom.org/project/python-markdown/Meta-Data>
  30. Contact: markdown@freewisdom.org
  31. License: BSD (see ../docs/LICENSE for details)
  32. """
  33. import re
  34. import markdown
  35. # Global Vars
  36. META_RE = re.compile(r'^[ ]{0,3}(?P<key>[A-Za-z0-9_-]+):\s*(?P<value>.*)')
  37. META_MORE_RE = re.compile(r'^[ ]{4,}(?P<value>.*)')
  38. class MetaExtension (markdown.Extension):
  39. """ Meta-Data extension for Python-Markdown. """
  40. def extendMarkdown(self, md, md_globals):
  41. """ Add MetaPreprocessor to Markdown instance. """
  42. md.preprocessors.add("meta", MetaPreprocessor(md), "_begin")
  43. class MetaPreprocessor(markdown.preprocessors.Preprocessor):
  44. """ Get Meta-Data. """
  45. def run(self, lines):
  46. """ Parse Meta-Data and store in Markdown.Meta. """
  47. meta = {}
  48. key = None
  49. while 1:
  50. line = lines.pop(0)
  51. if line.strip() == '':
  52. break # blank line - done
  53. m1 = META_RE.match(line)
  54. if m1:
  55. key = m1.group('key').lower().strip()
  56. value = m1.group('value').strip()
  57. try:
  58. meta[key].append(value)
  59. except KeyError:
  60. meta[key] = [value]
  61. else:
  62. m2 = META_MORE_RE.match(line)
  63. if m2 and key:
  64. # Add another line to existing key
  65. meta[key].append(m2.group('value').strip())
  66. else:
  67. lines.insert(0, line)
  68. break # no meta data - done
  69. self.markdown.Meta = meta
  70. return lines
  71. def makeExtension(configs={}):
  72. return MetaExtension(configs=configs)
  73. if __name__ == "__main__":
  74. import doctest
  75. doctest.testmod()