MCPcopy Create free account
hub / github.com/Python-Markdown/markdown / nest_toc_tokens

Function nest_toc_tokens

markdown/extensions/toc.py:196–258  ·  view source on GitHub ↗

Given an unsorted list with errors and skips, return a nested one. [{'level': 1}, {'level': 2}] => [{'level': 1, 'children': [{'level': 2, 'children': []}]}] A wrong list is also converted: [{'level': 2}, {'level': 1}] => [{'level': 2, 'children

(toc_list)

Source from the content-addressed store, hash-verified

194
195
196def nest_toc_tokens(toc_list):
197 """Given an unsorted list with errors and skips, return a nested one.
198
199 [{'level': 1}, {'level': 2}]
200 =>
201 [{'level': 1, 'children': [{'level': 2, 'children': []}]}]
202
203 A wrong list is also converted:
204
205 [{'level': 2}, {'level': 1}]
206 =>
207 [{'level': 2, 'children': []}, {'level': 1, 'children': []}]
208 """
209
210 ordered_list = []
211 if len(toc_list):
212 # Initialize everything by processing the first entry
213 last = toc_list.pop(0)
214 last['children'] = []
215 levels = [last['level']]
216 ordered_list.append(last)
217 parents = []
218
219 # Walk the rest nesting the entries properly
220 while toc_list:
221 t = toc_list.pop(0)
222 current_level = t['level']
223 t['children'] = []
224
225 # Reduce depth if current level < last item's level
226 if current_level < levels[-1]:
227 # Pop last level since we know we are less than it
228 levels.pop()
229
230 # Pop parents and levels we are less than or equal to
231 to_pop = 0
232 for p in reversed(parents):
233 if current_level <= p['level']:
234 to_pop += 1
235 else: # pragma: no cover
236 break
237 if to_pop:
238 levels = levels[:-to_pop]
239 parents = parents[:-to_pop]
240
241 # Note current level as last
242 levels.append(current_level)
243
244 # Level is the same, so append to
245 # the current parent (if available)
246 if current_level == levels[-1]:
247 (parents[-1]['children'] if parents
248 else ordered_list).append(t)
249
250 # Current level is > last item's level,
251 # So make last item a parent and append current as child
252 else:
253 last['children'].append(t)

Callers 1

runMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected