OLD | NEW |
(Empty) | |
| 1 """ |
| 2 Meta Data Extension for Python-Markdown |
| 3 ======================================= |
| 4 |
| 5 This extension adds Meta Data handling to markdown. |
| 6 |
| 7 See <https://pythonhosted.org/Markdown/extensions/meta_data.html> |
| 8 for documentation. |
| 9 |
| 10 Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com). |
| 11 |
| 12 All changes Copyright 2008-2014 The Python Markdown Project |
| 13 |
| 14 License: [BSD](http://www.opensource.org/licenses/bsd-license.php) |
| 15 |
| 16 """ |
| 17 |
| 18 from __future__ import absolute_import |
| 19 from __future__ import unicode_literals |
| 20 from . import Extension |
| 21 from ..preprocessors import Preprocessor |
| 22 import re |
| 23 import logging |
| 24 |
| 25 log = logging.getLogger('MARKDOWN') |
| 26 |
| 27 # Global Vars |
| 28 META_RE = re.compile(r'^[ ]{0,3}(?P<key>[A-Za-z0-9_-]+):\s*(?P<value>.*)') |
| 29 META_MORE_RE = re.compile(r'^[ ]{4,}(?P<value>.*)') |
| 30 BEGIN_RE = re.compile(r'^-{3}(\s.*)?') |
| 31 END_RE = re.compile(r'^(-{3}|\.{3})(\s.*)?') |
| 32 |
| 33 |
| 34 class MetaExtension (Extension): |
| 35 """ Meta-Data extension for Python-Markdown. """ |
| 36 |
| 37 def extendMarkdown(self, md, md_globals): |
| 38 """ Add MetaPreprocessor to Markdown instance. """ |
| 39 md.preprocessors.add("meta", |
| 40 MetaPreprocessor(md), |
| 41 ">normalize_whitespace") |
| 42 |
| 43 |
| 44 class MetaPreprocessor(Preprocessor): |
| 45 """ Get Meta-Data. """ |
| 46 |
| 47 def run(self, lines): |
| 48 """ Parse Meta-Data and store in Markdown.Meta. """ |
| 49 meta = {} |
| 50 key = None |
| 51 if lines and BEGIN_RE.match(lines[0]): |
| 52 lines.pop(0) |
| 53 while lines: |
| 54 line = lines.pop(0) |
| 55 m1 = META_RE.match(line) |
| 56 if line.strip() == '' or END_RE.match(line): |
| 57 break # blank line or end of YAML header - done |
| 58 if m1: |
| 59 key = m1.group('key').lower().strip() |
| 60 value = m1.group('value').strip() |
| 61 try: |
| 62 meta[key].append(value) |
| 63 except KeyError: |
| 64 meta[key] = [value] |
| 65 else: |
| 66 m2 = META_MORE_RE.match(line) |
| 67 if m2 and key: |
| 68 # Add another line to existing key |
| 69 meta[key].append(m2.group('value').strip()) |
| 70 else: |
| 71 lines.insert(0, line) |
| 72 break # no meta data - done |
| 73 self.markdown.Meta = meta |
| 74 return lines |
| 75 |
| 76 |
| 77 def makeExtension(*args, **kwargs): |
| 78 return MetaExtension(*args, **kwargs) |
OLD | NEW |