tasklist.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. """
  2. Tasklist.
  3. pymdownx.tasklist
  4. An extension for Python Markdown.
  5. Github style tasklists
  6. MIT license.
  7. Copyright (c) 2014 - 2017 Isaac Muse <isaacmuse@gmail.com>
  8. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  9. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  10. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  11. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  13. of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  15. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  16. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  17. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  18. DEALINGS IN THE SOFTWARE.
  19. """
  20. from markdown import Extension
  21. from markdown.treeprocessors import Treeprocessor
  22. import re
  23. RE_CHECKBOX = re.compile(r"^(?P<checkbox> *\[(?P<state>(?:x|X| ){1})\] +)(?P<line>.*)", re.DOTALL)
  24. def get_checkbox(state, custom_checkbox=False, clickable_checkbox=False):
  25. """Get checkbox tag."""
  26. if custom_checkbox:
  27. return (
  28. '<label class="task-list-control">' +
  29. '<input type="checkbox"%s%s/>' % (
  30. ' disabled' if not clickable_checkbox else '',
  31. ' checked' if state.lower() == 'x' else '') +
  32. '<span class="task-list-indicator"></span></label> '
  33. )
  34. return '<input type="checkbox"%s%s/> ' % (
  35. ' disabled' if not clickable_checkbox else '',
  36. ' checked' if state.lower() == 'x' else '')
  37. class TasklistTreeprocessor(Treeprocessor):
  38. """Tasklist tree processor that finds lists with checkboxes."""
  39. def __init__(self, md):
  40. """Initialize."""
  41. super(TasklistTreeprocessor, self).__init__(md)
  42. def inline(self, li):
  43. """Search for checkbox directly in `li` tag."""
  44. found = False
  45. m = RE_CHECKBOX.match(li.text)
  46. if m is not None:
  47. li.text = self.md.htmlStash.store(
  48. get_checkbox(m.group('state'), self.custom_checkbox, self.clickable_checkbox)
  49. ) + m.group('line')
  50. found = True
  51. return found
  52. def sub_paragraph(self, li):
  53. """Search for checkbox in sub-paragraph."""
  54. found = False
  55. if len(li):
  56. first = list(li)[0]
  57. if first.tag == "p" and first.text is not None:
  58. m = RE_CHECKBOX.match(first.text)
  59. if m is not None:
  60. first.text = self.md.htmlStash.store(
  61. get_checkbox(m.group('state'), self.custom_checkbox, self.clickable_checkbox)
  62. ) + m.group('line')
  63. found = True
  64. return found
  65. def run(self, root):
  66. """Find list items that start with [ ] or [x] or [X]."""
  67. self.custom_checkbox = bool(self.config["custom_checkbox"])
  68. self.clickable_checkbox = bool(self.config["clickable_checkbox"])
  69. parent_map = dict((c, p) for p in root.iter() for c in p)
  70. task_items = []
  71. lilinks = root.iter('li')
  72. for li in lilinks:
  73. if li.text is None or li.text == "":
  74. if not self.sub_paragraph(li):
  75. continue
  76. elif not self.inline(li):
  77. continue
  78. # Checkbox found
  79. c = li.attrib.get("class", "")
  80. classes = [] if c == "" else c.split()
  81. classes.append("task-list-item")
  82. li.attrib["class"] = ' '.join(classes)
  83. task_items.append(li)
  84. for li in task_items:
  85. parent = parent_map[li]
  86. c = parent.attrib.get("class", "")
  87. classes = [] if c == "" else c.split()
  88. if "task-list" not in classes:
  89. classes.append("task-list")
  90. parent.attrib["class"] = ' '.join(classes)
  91. return root
  92. class TasklistExtension(Extension):
  93. """Tasklist extension."""
  94. def __init__(self, *args, **kwargs):
  95. """Initialize."""
  96. self.config = {
  97. 'custom_checkbox': [
  98. False,
  99. "Add an empty label tag after the input tag to allow for custom styling - Default: False"
  100. ],
  101. 'clickable_checkbox': [
  102. False,
  103. "Allow user to check/uncheck the checkbox - Default: False"
  104. ],
  105. 'delete': [True, "Enable delete - Default: True"],
  106. 'subscript': [True, "Enable subscript - Default: True"]
  107. }
  108. super(TasklistExtension, self).__init__(*args, **kwargs)
  109. def extendMarkdown(self, md):
  110. """Add checklist tree processor to Markdown instance."""
  111. tasklist = TasklistTreeprocessor(md)
  112. tasklist.config = self.getConfigs()
  113. md.treeprocessors.register(tasklist, "task-list", 25)
  114. md.registerExtension(self)
  115. def makeExtension(*args, **kwargs):
  116. """Return extension."""
  117. return TasklistExtension(*args, **kwargs)