1""" 2POST-PROCESSORS 3============================================================================= 4 5Markdown also allows post-processors, which are similar to preprocessors in 6that they need to implement a "run" method. However, they are run after core 7processing. 8 9""" 10 11 12import markdown 13 14class Processor: 15 def __init__(self, markdown_instance=None): 16 if markdown_instance: 17 self.markdown = markdown_instance 18 19class Postprocessor(Processor): 20 """ 21 Postprocessors are run after the ElementTree it converted back into text. 22 23 Each Postprocessor implements a "run" method that takes a pointer to a 24 text string, modifies it as necessary and returns a text string. 25 26 Postprocessors must extend markdown.Postprocessor. 27 28 """ 29 30 def run(self, text): 31 """ 32 Subclasses of Postprocessor should implement a `run` method, which 33 takes the html document as a single text string and returns a 34 (possibly modified) string. 35 36 """ 37 pass 38 39 40class RawHtmlPostprocessor(Postprocessor): 41 """ Restore raw html to the document. """ 42 43 def run(self, text): 44 """ Iterate over html stash and restore "safe" html. """ 45 for i in range(self.markdown.htmlStash.html_counter): 46 html, safe = self.markdown.htmlStash.rawHtmlBlocks[i] 47 if self.markdown.safeMode and not safe: 48 if str(self.markdown.safeMode).lower() == 'escape': 49 html = self.escape(html) 50 elif str(self.markdown.safeMode).lower() == 'remove': 51 html = '' 52 else: 53 html = markdown.HTML_REMOVED_TEXT 54 if safe or not self.markdown.safeMode: 55 text = text.replace("<p>%s</p>" % 56 (markdown.preprocessors.HTML_PLACEHOLDER % i), 57 html + "\n") 58 text = text.replace(markdown.preprocessors.HTML_PLACEHOLDER % i, 59 html) 60 return text 61 62 def escape(self, html): 63 """ Basic html escaping """ 64 html = html.replace('&', '&') 65 html = html.replace('<', '<') 66 html = html.replace('>', '>') 67 return html.replace('"', '"') 68 69 70class AndSubstitutePostprocessor(Postprocessor): 71 """ Restore valid entities """ 72 def __init__(self): 73 pass 74 75 def run(self, text): 76 text = text.replace(markdown.AMP_SUBSTITUTE, "&") 77 return text 78