dokuwiki-to-hugo/src/markdown/lists.py

61 lines
2.1 KiB
Python
Raw Permalink Normal View History

2017-01-14 20:56:16 +01:00
import re
from src.markdown_converter import MarkdownConverter
2017-01-30 16:09:23 +01:00
@MarkdownConverter.register
class MarkdownOrderedList:
pattern = re.compile('(^(\s*)-\s)(.*)', re.MULTILINE)
2017-01-14 20:56:16 +01:00
def convert(self, text):
lines = text.split('\n')
last_used_linenrs = []
2017-01-14 20:56:16 +01:00
index = 0
result = text
def deeper_depth(depth):
2017-01-30 16:09:23 +01:00
return list(filter(lambda x: x[0] > depth, last_used_linenrs))
def drop_in_depth_detected(depth):
return len(deeper_depth(depth)) > 0
2017-01-30 16:09:23 +01:00
def remove_deeper_depths(depth):
for itm in deeper_depth(depth):
last_used_linenrs.remove(itm)
2017-01-30 16:09:23 +01:00
def last_used_by_depth(depth):
return list(filter(lambda x: x[0] == depth, last_used_linenrs))
2017-01-30 16:09:23 +01:00
def last_used_index(depth):
return last_used_by_depth(depth)[0][2]
2017-01-30 16:09:23 +01:00
def last_used_linenr(depth):
2017-01-30 16:09:23 +01:00
linenr_result = last_used_by_depth(depth)
if len(linenr_result) == 0:
return 0
2017-01-30 16:09:23 +01:00
return linenr_result[0][1]
2017-01-30 16:09:23 +01:00
def set_last_used_linenr(depth, linenr, the_index):
last_used_result = list(filter(lambda x: x[0] == depth, last_used_linenrs))
if len(last_used_result) > 0:
last_used_linenrs.remove(last_used_result[0])
last_used_linenrs.append((depth, linenr, the_index))
2017-01-14 20:56:16 +01:00
for match in MarkdownOrderedList.pattern.findall(text):
current_line = (match[0] + match[2]).replace('\n', '')
current_depth = len(match[1].replace('\n', ''))
current_linenr = lines.index(current_line)
2017-01-14 20:56:16 +01:00
if last_used_linenr(current_depth) + 1 is current_linenr:
2017-01-30 16:09:23 +01:00
index += 1
elif drop_in_depth_detected(current_depth):
index = last_used_index(current_depth) + 1
remove_deeper_depths(current_depth)
2017-01-14 20:56:16 +01:00
else:
index = 1
set_last_used_linenr(current_depth, current_linenr, index)
2017-01-14 20:56:16 +01:00
result = result.replace(current_line, match[1].replace('\n', '') + str(index) + '. ' + match[2])
2017-01-14 20:56:16 +01:00
2017-01-30 16:09:23 +01:00
return result