tabbed.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """
  2. Tabbed.
  3. pymdownx.tabbed
  4. MIT license.
  5. Copyright (c) 2017 Isaac Muse <isaacmuse@gmail.com>
  6. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  7. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  8. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  9. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  11. of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  13. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  14. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  15. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  16. DEALINGS IN THE SOFTWARE.
  17. """
  18. from markdown import Extension
  19. from markdown import util as md_util
  20. from markdown.blockprocessors import BlockProcessor
  21. import xml.etree.ElementTree as etree
  22. import re
  23. class TabbedProcessor(BlockProcessor):
  24. """Tabbed block processor."""
  25. START = re.compile(
  26. r'(?:^|\n)={3}(!)? +"(.*?)" *(?:\n|$)'
  27. )
  28. COMPRESS_SPACES = re.compile(r' {2,}')
  29. def __init__(self, *args):
  30. """Initialize."""
  31. super().__init__(*args)
  32. self.tab_group_count = 0
  33. def test(self, parent, block):
  34. """Test block."""
  35. sibling = self.lastChild(parent)
  36. return (
  37. self.START.search(block) or
  38. (
  39. block.startswith(' ' * self.tab_length) and sibling is not None and
  40. sibling.tag.lower() == 'div' and sibling.attrib.get('class', '') == 'tabbed-set'
  41. )
  42. )
  43. def run(self, parent, blocks):
  44. """Convert to tabbed block."""
  45. sibling = self.lastChild(parent)
  46. block = blocks.pop(0)
  47. m = self.START.search(block)
  48. if m:
  49. # remove the first line
  50. block = block[m.end():]
  51. # Get the tabs block and the non-tab content
  52. block, non_tabs = self.detab(block)
  53. if m:
  54. special = m.group(1) if m.group(1) else ''
  55. title = m.group(2) if m.group(2) else m.group(3)
  56. if (
  57. sibling and sibling.tag.lower() == 'div' and
  58. sibling.attrib.get('class', '') == 'tabbed-set' and
  59. special != '!'
  60. ):
  61. first = False
  62. sfences = sibling
  63. else:
  64. first = True
  65. self.tab_group_count += 1
  66. sfences = etree.SubElement(
  67. parent,
  68. 'div',
  69. {'class': 'tabbed-set', 'data-tabs': '%d:0' % self.tab_group_count}
  70. )
  71. data = sfences.attrib['data-tabs'].split(':')
  72. tab_set = int(data[0])
  73. tab_count = int(data[1]) + 1
  74. attributes = {
  75. "name": "__tabbed_%d" % tab_set,
  76. "type": "radio",
  77. "id": "__tabbed_%d_%d" % (tab_set, tab_count)
  78. }
  79. if first:
  80. attributes['checked'] = 'checked'
  81. etree.SubElement(
  82. sfences,
  83. 'input',
  84. attributes
  85. )
  86. lab = etree.SubElement(
  87. sfences,
  88. "label",
  89. {
  90. "for": "__tabbed_%d_%d" % (tab_set, tab_count)
  91. }
  92. )
  93. lab.text = md_util.AtomicString(title)
  94. div = etree.SubElement(
  95. sfences,
  96. "div",
  97. {
  98. "class": "tabbed-content"
  99. }
  100. )
  101. sfences.attrib['data-tabs'] = '%d:%d' % (tab_set, tab_count)
  102. else:
  103. div = self.lastChild(sibling)
  104. self.parser.parseChunk(div, block)
  105. if non_tabs:
  106. # Insert the non-details content back into blocks
  107. blocks.insert(0, non_tabs)
  108. class TabbedExtension(Extension):
  109. """Add Tabbed extension."""
  110. def extendMarkdown(self, md):
  111. """Add Tabbed to Markdown instance."""
  112. md.registerExtension(self)
  113. self.tab_processor = TabbedProcessor(md.parser)
  114. md.parser.blockprocessors.register(self.tab_processor, "tabbed", 105)
  115. def reset(self):
  116. """Reset."""
  117. self.tab_processor.tab_group_count = 0
  118. def makeExtension(*args, **kwargs):
  119. """Return extension."""
  120. return TabbedExtension(*args, **kwargs)