summaryrefslogtreecommitdiff
path: root/src/mistune/plugins/task_lists.py
blob: 8571c320a575e1f96b3ded30a3d286be1d862ede (plain) (blame)
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
66
67
import re

__all__ = ['task_lists']


TASK_LIST_ITEM = re.compile(r'^(\[[ xX]\])\s+')


def task_lists_hook(md, state):
    return _rewrite_all_list_items(state.tokens)


def render_task_list_item(renderer, text, checked=False):
    checkbox = (
        '<input class="task-list-item-checkbox" '
        'type="checkbox" disabled'
    )
    if checked:
        checkbox += ' checked/>'
    else:
        checkbox += '/>'

    if text.startswith('<p>'):
        text = text.replace('<p>', '<p>' + checkbox, 1)
    else:
        text = checkbox + text

    return '<li class="task-list-item">' + text + '</li>\n'


def task_lists(md):
    """A mistune plugin to support task lists. Spec defined by
    GitHub flavored Markdown and commonly used by many parsers:

    .. code-block:: text

        - [ ] unchecked task
        - [x] checked task

    :param md: Markdown instance
    """
    md.before_render_hooks.append(task_lists_hook)
    if md.renderer and md.renderer.NAME == 'html':
        md.renderer.register('task_list_item', render_task_list_item)


def _rewrite_all_list_items(tokens):
    for tok in tokens:
        if tok['type'] == 'list_item':
            _rewrite_list_item(tok)
        if 'children' in tok:
            _rewrite_all_list_items(tok['children'])
    return tokens


def _rewrite_list_item(tok):
    children = tok['children']
    if children:
        first_child = children[0]
        text = first_child.get('text', '')
        m = TASK_LIST_ITEM.match(text)
        if m:
            mark = m.group(1)
            first_child['text'] = text[m.end():]

            tok['type'] = 'task_list_item'
            tok['attrs'] = {'checked': mark != '[ ]'}