postprocessors.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # markdown is released under the BSD license
  2. # Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later)
  3. # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
  4. # Copyright 2004 Manfred Stienstra (the original version)
  5. #
  6. # All rights reserved.
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions are met:
  10. #
  11. # * Redistributions of source code must retain the above copyright
  12. # notice, this list of conditions and the following disclaimer.
  13. # * Redistributions in binary form must reproduce the above copyright
  14. # notice, this list of conditions and the following disclaimer in the
  15. # documentation and/or other materials provided with the distribution.
  16. # * Neither the name of the <organization> nor the
  17. # names of its contributors may be used to endorse or promote products
  18. # derived from this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE PYTHON MARKDOWN PROJECT ''AS IS'' AND ANY
  21. # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  23. # DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT
  24. # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. # POSSIBILITY OF SUCH DAMAGE.
  31. """
  32. POST-PROCESSORS
  33. =============================================================================
  34. Markdown also allows post-processors, which are similar to preprocessors in
  35. that they need to implement a "run" method. However, they are run after core
  36. processing.
  37. """
  38. from __future__ import absolute_import
  39. from __future__ import unicode_literals
  40. from . import util
  41. from . import odict
  42. import re
  43. def build_postprocessors(md_instance, **kwargs):
  44. """ Build the default postprocessors for Markdown. """
  45. postprocessors = odict.OrderedDict()
  46. postprocessors["raw_html"] = RawHtmlPostprocessor(md_instance)
  47. postprocessors["amp_substitute"] = AndSubstitutePostprocessor()
  48. postprocessors["unescape"] = UnescapePostprocessor()
  49. return postprocessors
  50. class Postprocessor(util.Processor):
  51. """
  52. Postprocessors are run after the ElementTree it converted back into text.
  53. Each Postprocessor implements a "run" method that takes a pointer to a
  54. text string, modifies it as necessary and returns a text string.
  55. Postprocessors must extend markdown.Postprocessor.
  56. """
  57. def run(self, text):
  58. """
  59. Subclasses of Postprocessor should implement a `run` method, which
  60. takes the html document as a single text string and returns a
  61. (possibly modified) string.
  62. """
  63. pass
  64. class RawHtmlPostprocessor(Postprocessor):
  65. """ Restore raw html to the document. """
  66. def run(self, text):
  67. """ Iterate over html stash and restore "safe" html. """
  68. for i in range(self.markdown.htmlStash.html_counter):
  69. html, safe = self.markdown.htmlStash.rawHtmlBlocks[i]
  70. if self.markdown.safeMode and not safe:
  71. if str(self.markdown.safeMode).lower() == 'escape':
  72. html = self.escape(html)
  73. elif str(self.markdown.safeMode).lower() == 'remove':
  74. html = ''
  75. else:
  76. html = self.markdown.html_replacement_text
  77. if self.isblocklevel(html) and (safe or not self.markdown.safeMode):
  78. text = text.replace("<p>%s</p>" %
  79. (self.markdown.htmlStash.get_placeholder(i)),
  80. html + "\n")
  81. text = text.replace(self.markdown.htmlStash.get_placeholder(i),
  82. html)
  83. return text
  84. def escape(self, html):
  85. """ Basic html escaping """
  86. html = html.replace('&', '&amp;')
  87. html = html.replace('<', '&lt;')
  88. html = html.replace('>', '&gt;')
  89. return html.replace('"', '&quot;')
  90. def isblocklevel(self, html):
  91. m = re.match(r'^\<\/?([^ >]+)', html)
  92. if m:
  93. if m.group(1)[0] in ('!', '?', '@', '%'):
  94. # Comment, php etc...
  95. return True
  96. return util.isBlockLevel(m.group(1))
  97. return False
  98. class AndSubstitutePostprocessor(Postprocessor):
  99. """ Restore valid entities """
  100. def run(self, text):
  101. text = text.replace(util.AMP_SUBSTITUTE, "&")
  102. return text
  103. class UnescapePostprocessor(Postprocessor):
  104. """ Restore escaped chars """
  105. RE = re.compile('%s(\d+)%s' % (util.STX, util.ETX))
  106. def unescape(self, m):
  107. return util.int2str(int(m.group(1)))
  108. def run(self, text):
  109. return self.RE.sub(self.unescape, text)