Footnote Extension.
| 32 | TABBED_RE = re.compile(r'((\t)|( ))(.*)') |
| 33 | |
| 34 | class FootnoteExtension(markdown.Extension): |
| 35 | """ Footnote Extension. """ |
| 36 | |
| 37 | def __init__ (self, configs): |
| 38 | """ Setup configs. """ |
| 39 | self.config = {'PLACE_MARKER': |
| 40 | ["///Footnotes Go Here///", |
| 41 | "The text string that marks where the footnotes go"], |
| 42 | 'UNIQUE_IDS': |
| 43 | [False, |
| 44 | "Avoid name collisions across " |
| 45 | "multiple calls to reset()."]} |
| 46 | |
| 47 | for key, value in configs: |
| 48 | self.config[key][0] = value |
| 49 | |
| 50 | # In multiple invocations, emit links that don't get tangled. |
| 51 | self.unique_prefix = 0 |
| 52 | |
| 53 | self.reset() |
| 54 | |
| 55 | def extendMarkdown(self, md, md_globals): |
| 56 | """ Add pieces to Markdown. """ |
| 57 | md.registerExtension(self) |
| 58 | self.parser = md.parser |
| 59 | # Insert a preprocessor before ReferencePreprocessor |
| 60 | md.preprocessors.add("footnote", FootnotePreprocessor(self), |
| 61 | "<reference") |
| 62 | # Insert an inline pattern before ImageReferencePattern |
| 63 | FOOTNOTE_RE = r'\[\^([^\]]*)\]' # blah blah [^1] blah |
| 64 | md.inlinePatterns.add("footnote", FootnotePattern(FOOTNOTE_RE, self), |
| 65 | "<reference") |
| 66 | # Insert a tree-processor that would actually add the footnote div |
| 67 | # This must be before the inline treeprocessor so inline patterns |
| 68 | # run on the contents of the div. |
| 69 | md.treeprocessors.add("footnote", FootnoteTreeprocessor(self), |
| 70 | "<inline") |
| 71 | # Insert a postprocessor after amp_substitute oricessor |
| 72 | md.postprocessors.add("footnote", FootnotePostprocessor(self), |
| 73 | ">amp_substitute") |
| 74 | |
| 75 | def reset(self): |
| 76 | """ Clear the footnotes on reset, and prepare for a distinct document. """ |
| 77 | self.footnotes = markdown.odict.OrderedDict() |
| 78 | self.unique_prefix += 1 |
| 79 | |
| 80 | def findFootnotesPlaceholder(self, root): |
| 81 | """ Return ElementTree Element that contains Footnote placeholder. """ |
| 82 | def finder(element): |
| 83 | for child in element: |
| 84 | if child.text: |
| 85 | if child.text.find(self.getConfig("PLACE_MARKER")) > -1: |
| 86 | return child, True |
| 87 | if child.tail: |
| 88 | if child.tail.find(self.getConfig("PLACE_MARKER")) > -1: |
| 89 | return (child, element), False |
| 90 | finder(child) |
| 91 | return None |