[cad161]: / docs / scripts / cards.py

Download this file

277 lines (228 with data), 9.1 kB

  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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""
Adapted from pymdownx.tabbed (https://github.com/facelessuser/pymdown-extensions/)
"""
import re
import xml.etree.ElementTree as etree
from markdown import Extension
from markdown.blockprocessors import BlockProcessor
from markdown.extensions.attr_list import AttrListTreeprocessor, get_attrs
def assign_attrs(elem, attrs):
"""Assign `attrs` to element."""
for k, v in get_attrs(attrs):
if k == ".":
# add to class
cls = elem.get("class")
if cls:
elem.set("class", "{} {}".format(cls, v))
else:
elem.set("class", v)
else:
# assign attribute `k` with `v`
elem.set(AttrListTreeprocessor.NAME_RE.sub("_", k), v)
class CardProcessor(BlockProcessor):
"""card block processor."""
START = re.compile(r"(?:^|\n)={3} *(card)?(?: +({:.*?}) *(?:\n|$))?")
COMPRESS_SPACES = re.compile(r" {2,}")
def __init__(self, parser, config):
"""Initialize."""
super().__init__(parser)
self.card_group_count = 0
self.current_sibling = None
self.content_indention = 0
def detab_by_length(self, text, length):
"""Remove a card from the front of each line of the given text."""
newtext = []
lines = text.split("\n")
for line in lines:
if line.startswith(" " * length):
newtext.append(line[length:])
elif not line.strip():
newtext.append("") # pragma: no cover
else:
break
return "\n".join(newtext), "\n".join(lines[len(newtext) :])
def parse_content(self, parent, block):
"""
Get sibling card.
Retrieve the appropriate sibling element. This can get tricky when
dealing with lists.
"""
old_block = block
non_cards = ""
card_set = "card-set"
# We already acquired the block via test
if self.current_sibling is not None:
sibling = self.current_sibling
block, non_cards = self.detab_by_length(block, self.content_indent)
self.current_sibling = None
self.content_indent = 0
return sibling, block, non_cards
sibling = self.lastChild(parent)
if (
sibling is None
or sibling.tag.lower() != "div"
or sibling.attrib.get("class", "") != card_set
):
sibling = None
else:
# If the last child is a list and the content is indented sufficient
# to be under it, then the content's is sibling is in the list.
last_child = self.lastChild(sibling)
card_content = "card-content"
child_class = (
last_child.attrib.get("class", "") if last_child is not None else ""
)
indent = 0
while last_child is not None:
if (
sibling is not None
and block.startswith(" " * self.tab_length * 2)
and last_child is not None
and (
last_child.tag in ("ul", "ol", "dl")
or (last_child.tag == "div" and child_class == card_content)
)
):
# Handle nested card content
if last_child.tag == "div" and child_class == card_content:
temp_child = self.lastChild(last_child)
if temp_child is None or temp_child.tag not in (
"ul",
"ol",
"dl",
):
break
last_child = temp_child
# The expectation is that we'll find an `<li>`.
# We should get it's last child as well.
sibling = self.lastChild(last_child)
last_child = (
self.lastChild(sibling) if sibling is not None else None
)
child_class = (
last_child.attrib.get("class", "")
if last_child is not None
else ""
)
# Context has been lost at this point, so we must adjust the
# text's indentation level so it will be evaluated correctly
# under the list.
block = block[self.tab_length :]
indent += self.tab_length
else:
last_child = None
if not block.startswith(" " * self.tab_length):
sibling = None
if sibling is not None:
indent += self.tab_length
block, non_cards = self.detab_by_length(old_block, indent)
self.current_sibling = sibling
self.content_indent = indent
return sibling, block, non_cards
def test(self, parent, block):
"""Test block."""
if self.START.search(block):
return True
else:
return self.parse_content(parent, block)[0] is not None
def run(self, parent, blocks):
"""Convert to card block."""
block = blocks.pop(0)
m = self.START.search(block)
card_set = "card-set"
if m:
# removes the first line
if m.start() > 0:
self.parser.parseBlocks(parent, [block[: m.start()]])
block = block[m.end() :]
sibling = self.lastChild(parent)
block, non_cards = self.detab(block)
else:
sibling, block, non_cards = self.parse_content(parent, block)
if m:
if (
sibling is not None
and sibling.tag.lower() == "div"
and sibling.attrib.get("class", "") == card_set
):
card_group = sibling
else:
self.card_group_count += 1
card_group = etree.SubElement(
parent,
"div",
{
"class": card_set,
"data-cards": "%d:0" % self.card_group_count,
},
)
data = card_group.attrib["data-cards"].split(":")
card_set = int(data[0])
card_count = int(data[1]) + 1
div = etree.SubElement(
card_group,
"div",
{
"class": "card-content",
},
)
attributes = m.group(2)
if attributes:
attr_m = AttrListTreeprocessor.INLINE_RE.search(attributes)
if attr_m:
assign_attrs(div, attr_m.group(1))
if div.get("href"):
div.tag = "a"
card_group.attrib["data-cards"] = "%d:%d" % (card_set, card_count)
else:
if sibling.tag in ("li", "dd") and sibling.text:
# Sibling is a list item, but we need to wrap it's content should be
# wrapped in <p>
text = sibling.text
sibling.text = ""
p = etree.SubElement(sibling, "p")
p.text = text
div = sibling
elif sibling.tag == "div" and sibling.attrib.get("class", "") == card_set:
# Get `card-content` under `card-set`
div = self.lastChild(sibling)
else:
# Pass anything else as the parent
div = sibling
self.parser.parseChunk(div, block)
if non_cards:
# Insert the card content back into blocks
blocks.insert(0, non_cards)
class CardExtension(Extension):
"""Add card extension."""
def __init__(self, *args, **kwargs):
"""Initialize."""
self.config = {
"slugify": [
0,
"Slugify function used to create card specific IDs - Default: None",
],
"combine_header_slug": [
False,
"Combine the card slug with the slug of the parent header - "
"Default: False",
],
"separator": ["-", "Slug separator - Default: '-'"],
}
super(CardExtension, self).__init__(*args, **kwargs)
def extendMarkdown(self, md):
"""Add card to Markdown instance."""
md.registerExtension(self)
config = self.getConfigs()
self.card_processor = CardProcessor(md.parser, config)
md.parser.blockprocessors.register(
self.card_processor,
"card",
105,
)
def reset(self):
"""Reset."""
self.card_processor.card_group_count = 0
def makeExtension(*args, **kwargs):
"""Return extension."""
return CardExtension(*args, **kwargs)