File: definition.py

package info (click to toggle)
pymdown-extensions 10.13-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,104 kB
  • sloc: python: 60,117; javascript: 846; sh: 8; makefile: 5
file content (65 lines) | stat: -rw-r--r-- 1,754 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""Definition."""
import xml.etree.ElementTree as etree
from .block import Block
from ..blocks import BlocksExtension


class Definition(Block):
    """
    Definition.

    Converts non `ul`, `ol` blocks (ideally `p` tags) into `dt`
    and will convert first level `li` elements of `ul` and `ol`
    elements to `dd` tags. When done, the `ul`, and `ol` elements
    will be removed.
    """

    NAME = 'define'

    def on_create(self, parent):
        """Create the element."""

        return etree.SubElement(parent, 'dl')

    def on_end(self, block):
        """Convert non list items to details."""

        remove = []
        offset = 0
        for i, child in enumerate(list(block)):
            if child.tag.lower() in ('dt', 'dd'):
                continue

            elif child.tag.lower() not in ('ul', 'ol'):
                if child.tag.lower() == 'p':
                    child.tag = 'dt'
                else:
                    dt = etree.Element('dt')
                    dt.append(child)
                    block.insert(i + offset, dt)
                    block.remove(child)
            else:
                for li in list(child):
                    offset += 1
                    li.tag = 'dd'
                    block.insert(i + offset, li)
                    child.remove(li)
                remove.append(child)

        for el in remove:
            block.remove(el)


class DefinitionExtension(BlocksExtension):
    """Definition Blocks Extension."""

    def extendMarkdownBlocks(self, md, block_mgr):
        """Extend Markdown blocks."""

        block_mgr.register(Definition, self.getConfigs())


def makeExtension(*args, **kwargs):
    """Return extension."""

    return DefinitionExtension(*args, **kwargs)