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