Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/mistune/plugins/task_lists.py: 67%

36 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-01 06:54 +0000

1import re 

2 

3__all__ = ['task_lists'] 

4 

5 

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

7 

8 

9def task_lists_hook(md, state): 

10 return _rewrite_all_list_items(state.tokens) 

11 

12 

13def render_task_list_item(renderer, text, checked=False): 

14 checkbox = ( 

15 '<input class="task-list-item-checkbox" ' 

16 'type="checkbox" disabled' 

17 ) 

18 if checked: 

19 checkbox += ' checked/>' 

20 else: 

21 checkbox += '/>' 

22 

23 if text.startswith('<p>'): 

24 text = text.replace('<p>', '<p>' + checkbox, 1) 

25 else: 

26 text = checkbox + text 

27 

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

29 

30 

31def task_lists(md): 

32 """A mistune plugin to support task lists. Spec defined by 

33 GitHub flavored Markdown and commonly used by many parsers: 

34 

35 .. code-block:: text 

36 

37 - [ ] unchecked task 

38 - [x] checked task 

39 

40 :param md: Markdown instance 

41 """ 

42 md.before_render_hooks.append(task_lists_hook) 

43 if md.renderer and md.renderer.NAME == 'html': 

44 md.renderer.register('task_list_item', render_task_list_item) 

45 

46 

47def _rewrite_all_list_items(tokens): 

48 for tok in tokens: 

49 if tok['type'] == 'list_item': 

50 _rewrite_list_item(tok) 

51 if 'children' in tok: 

52 _rewrite_all_list_items(tok['children']) 

53 return tokens 

54 

55 

56def _rewrite_list_item(tok): 

57 children = tok['children'] 

58 if children: 

59 first_child = children[0] 

60 text = first_child.get('text', '') 

61 m = TASK_LIST_ITEM.match(text) 

62 if m: 

63 mark = m.group(1) 

64 first_child['text'] = text[m.end():] 

65 

66 tok['type'] = 'task_list_item' 

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