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

44 statements  

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

1import re 

2 

3__all__ = ['plugin_task_lists'] 

4 

5 

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

7 

8 

9def task_lists_hook(md, tokens, state): 

10 return _rewrite_all_list_items(tokens) 

11 

12 

13def render_ast_task_list_item(children, level, checked): 

14 return { 

15 'type': 'task_list_item', 

16 'children': children, 

17 'level': level, 

18 'checked': checked, 

19 } 

20 

21 

22def render_html_task_list_item(text, level, checked): 

23 checkbox = ( 

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

25 'type="checkbox" disabled' 

26 ) 

27 if checked: 

28 checkbox += ' checked/>' 

29 else: 

30 checkbox += '/>' 

31 

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

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

34 else: 

35 text = checkbox + text 

36 

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

38 

39 

40def plugin_task_lists(md): 

41 md.before_render_hooks.append(task_lists_hook) 

42 

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

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

45 elif md.renderer.NAME == 'ast': 

46 md.renderer.register('task_list_item', render_ast_task_list_item) 

47 

48 

49def _rewrite_all_list_items(tokens): 

50 for tok in tokens: 

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

52 _rewrite_list_item(tok) 

53 if 'children' in tok.keys(): 

54 _rewrite_all_list_items(tok['children']) 

55 return tokens 

56 

57 

58def _rewrite_list_item(item): 

59 children = item['children'] 

60 if children: 

61 first_child = children[0] 

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

63 m = TASK_LIST_ITEM.match(text) 

64 if m: 

65 mark = m.group(1) 

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

67 

68 params = item['params'] 

69 if mark == '[ ]': 

70 params = (params[0], False) 

71 else: 

72 params = (params[0], True) 

73 

74 item['type'] = 'task_list_item' 

75 item['params'] = params