escapeall.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. """
  2. EscapeAll.
  3. pymdownx.escapeall
  4. Escape everything.
  5. MIT license.
  6. Copyright (c) 2017 Isaac Muse <isaacmuse@gmail.com>
  7. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  8. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  9. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  10. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  12. of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  14. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  15. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  16. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  17. DEALINGS IN THE SOFTWARE.
  18. """
  19. from markdown import Extension
  20. from markdown.inlinepatterns import InlineProcessor, SubstituteTagInlineProcessor
  21. from markdown.postprocessors import Postprocessor
  22. from markdown import util as md_util
  23. import re
  24. from . import util
  25. # We need to ignore these as they are used in Markdown processing
  26. STX = '\u0002'
  27. ETX = '\u0003'
  28. ESCAPE_RE = r'\\(.)'
  29. ESCAPE_NO_NL_RE = r'\\([^\n])'
  30. HARDBREAK_RE = r'\\\n'
  31. UNESCAPE_PATTERN = re.compile(r'%s(\d+)%s' % (md_util.STX, md_util.ETX))
  32. class EscapeAllPattern(InlineProcessor):
  33. """Return an escaped character."""
  34. def __init__(self, pattern, nbsp):
  35. """Initialize."""
  36. self.nbsp = nbsp
  37. InlineProcessor.__init__(self, pattern)
  38. def handleMatch(self, m, data):
  39. """Convert the char to an escaped character."""
  40. char = m.group(1)
  41. if self.nbsp and char == ' ':
  42. escape = md_util.AMP_SUBSTITUTE + 'nbsp;'
  43. elif char in (STX, ETX):
  44. escape = char
  45. else:
  46. escape = '%s%s%s' % (md_util.STX, util.get_ord(char), md_util.ETX)
  47. return escape, m.start(0), m.end(0)
  48. class EscapeAllPostprocessor(Postprocessor):
  49. """Post processor to strip out unwanted content."""
  50. def unescape(self, m):
  51. """Unescape the escaped chars."""
  52. return util.get_char(int(m.group(1)))
  53. def run(self, text):
  54. """Search document for escaped chars."""
  55. return UNESCAPE_PATTERN.sub(self.unescape, text)
  56. class EscapeAllExtension(Extension):
  57. """Extension that allows you to escape everything."""
  58. def __init__(self, *args, **kwargs):
  59. """Initialize."""
  60. self.config = {
  61. 'hardbreak': [
  62. False,
  63. "Turn escaped newlines to hardbreaks - Default: False"
  64. ],
  65. 'nbsp': [
  66. False,
  67. "Turn escaped spaces to non-breaking spaces - Default: False"
  68. ]
  69. }
  70. super(EscapeAllExtension, self).__init__(*args, **kwargs)
  71. def extendMarkdown(self, md):
  72. """Escape all."""
  73. config = self.getConfigs()
  74. hardbreak = config['hardbreak']
  75. md.inlinePatterns.register(
  76. EscapeAllPattern(ESCAPE_NO_NL_RE if hardbreak else ESCAPE_RE, config['nbsp']),
  77. "escape",
  78. 180
  79. )
  80. md.postprocessors.register(EscapeAllPostprocessor(md), "unescape", 10)
  81. if config['hardbreak']:
  82. md.inlinePatterns.register(SubstituteTagInlineProcessor(HARDBREAK_RE, 'br'), "hardbreak", 5.1)
  83. def makeExtension(*args, **kwargs):
  84. """Return extension."""
  85. return EscapeAllExtension(*args, **kwargs)