smartsymbols.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. """
  2. Smart Symbols.
  3. pymdownx.smartsymbols
  4. Really simple plugin to add support for:
  5. copyright, trademark, and registered symbols
  6. plus/minus, not equal, arrows via:
  7. copyright = `(c)`
  8. trademark = `(tm)`
  9. registered = `(r)`
  10. plus/minus = `+/-`
  11. care/of = `c/o`
  12. fractions = `1/2` etc.
  13. (only certain available unicode fractions)
  14. arrows:
  15. left = `<--`
  16. right = `-->`
  17. both = `<-->`
  18. not equal = `=/=`
  19. (maybe this could be =/= in the future as this might be more
  20. intuitive to non-programmers)
  21. MIT license.
  22. Copyright (c) 2014 - 2017 Isaac Muse <isaacmuse@gmail.com>
  23. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  24. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  25. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  26. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  27. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  28. of the Software.
  29. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  30. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  31. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  32. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  33. DEALINGS IN THE SOFTWARE.
  34. """
  35. from markdown import Extension
  36. from markdown import treeprocessors
  37. from markdown.util import Registry
  38. from markdown.inlinepatterns import HtmlInlineProcessor
  39. RE_TRADE = ("smart-trademark", r'\(tm\)', r'&trade;')
  40. RE_COPY = ("smart-copyright", r'\(c\)', r'&copy;')
  41. RE_REG = ("smart-registered", r'\(r\)', r'&reg;')
  42. RE_PLUSMINUS = ("smart-plus-minus", r'\+/-', r'&plusmn;')
  43. RE_NOT_EQUAL = ("smart-not-equal", r'=/=', r'&ne;')
  44. RE_CARE_OF = ("smart-care-of", r'\bc/o\b', r'&#8453;')
  45. RE_ORDINAL_NUMBERS = (
  46. "smart-ordinal-numbers",
  47. r'''(?x)
  48. \b
  49. (?P<leading>(?:[1-9][0-9]*)?)
  50. (?P<tail>(?<=1)(?:1|2|3)th|1st|2nd|3rd|[04-9]th)
  51. \b
  52. ''',
  53. lambda m: '%s%s<sup>%s</sup>' % (
  54. m.group('leading') if m.group('leading') else '',
  55. m.group('tail')[:-2], m.group('tail')[1:]
  56. )
  57. )
  58. RE_ARROWS = (
  59. "smart-arrows",
  60. r'(?P<arrows>\<-{2}\>|(?<!-)-{2}\>|\<-{2}(?!-))',
  61. lambda m: ARR[m.group('arrows')]
  62. )
  63. RE_FRACTIONS = (
  64. "smart-fractions",
  65. r'(?<!\d)(?P<fractions>1/4|1/2|3/4|1/3|2/3|1/5|2/5|3/5|4/5|1/6|5/6|1/8|3/8|5/8|7/8)(?!\d)',
  66. lambda m: FRAC[m.group('fractions')]
  67. )
  68. REPL = {
  69. 'trademark': RE_TRADE,
  70. 'copyright': RE_COPY,
  71. 'registered': RE_REG,
  72. 'plusminus': RE_PLUSMINUS,
  73. 'arrows': RE_ARROWS,
  74. 'notequal': RE_NOT_EQUAL,
  75. 'fractions': RE_FRACTIONS,
  76. 'ordinal_numbers': RE_ORDINAL_NUMBERS,
  77. 'care_of': RE_CARE_OF
  78. }
  79. FRAC = {
  80. "1/4": "&frac14;",
  81. "1/2": "&frac12;",
  82. "3/4": "&frac34;",
  83. "1/3": "&#8531;",
  84. "2/3": "&#8532;",
  85. "1/5": "&#8533;",
  86. "2/5": "&#8534;",
  87. "3/5": "&#8535;",
  88. "4/5": "&#8536;",
  89. "1/6": "&#8537;",
  90. "5/6": "&#8538;",
  91. "1/8": "&#8539;",
  92. "3/8": "&#8540;",
  93. "5/8": "&#8541;",
  94. "7/8": "&#8542;"
  95. }
  96. ARR = {
  97. '-->': "&rarr;",
  98. '<--': "&larr;",
  99. '<-->': "&harr;"
  100. }
  101. class SmartSymbolsPattern(HtmlInlineProcessor):
  102. """Smart symbols patterns handler."""
  103. def __init__(self, pattern, replace, md):
  104. """Setup replace pattern."""
  105. super(SmartSymbolsPattern, self).__init__(pattern, md)
  106. self.replace = replace
  107. def handleMatch(self, m, data):
  108. """Replace symbol."""
  109. return self.md.htmlStash.store(
  110. m.expand(self.replace(m) if callable(self.replace) else self.replace),
  111. ), m.start(0), m.end(0)
  112. class SmartSymbolsExtension(Extension):
  113. """Smart Symbols extension."""
  114. def __init__(self, *args, **kwargs):
  115. """Setup config of which symbols are enabled."""
  116. self.config = {
  117. 'trademark': [True, 'Trademark'],
  118. 'copyright': [True, 'Copyright'],
  119. 'registered': [True, 'Registered'],
  120. 'plusminus': [True, 'Plus/Minus'],
  121. 'arrows': [True, 'Arrows'],
  122. 'notequal': [True, 'Not Equal'],
  123. 'fractions': [True, 'Fractions'],
  124. 'ordinal_numbers': [True, 'Ordinal Numbers'],
  125. 'care_of': [True, 'Care/of']
  126. }
  127. super(SmartSymbolsExtension, self).__init__(*args, **kwargs)
  128. def add_pattern(self, patterns, md):
  129. """Construct the inline symbol pattern."""
  130. self.patterns.register(SmartSymbolsPattern(patterns[1], patterns[2], md), patterns[0], 30)
  131. def extendMarkdown(self, md):
  132. """Create a dict of inline replace patterns and add to the tree processor."""
  133. configs = self.getConfigs()
  134. self.patterns = Registry()
  135. for k, v in REPL.items():
  136. if configs[k]:
  137. self.add_pattern(v, md)
  138. inline_processor = treeprocessors.InlineProcessor(md)
  139. inline_processor.inlinePatterns = self.patterns
  140. md.treeprocessors.register(inline_processor, "smart-symbols", 2.1)
  141. def makeExtension(*args, **kwargs):
  142. """Return extension."""
  143. return SmartSymbolsExtension(*args, **kwargs)