|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +表示崩れを事前修正 |
| 4 | +========================================= |
| 5 | +
|
| 6 | +Markdownライブラリの以下の制限を回避: |
| 7 | +
|
| 8 | +- 箇条書きの前に空行が必要な制限を回避して、自動で空行を挟む |
| 9 | +""" |
| 10 | + |
| 11 | +import re |
| 12 | +import datetime |
| 13 | + |
| 14 | +from markdown.extensions import Extension |
| 15 | +from markdown.preprocessors import Preprocessor |
| 16 | + |
| 17 | +def is_item_line(line: str) -> bool: |
| 18 | + stripped_line = line.strip() |
| 19 | + m = re.match(r'^([0-9]+\.\s)', stripped_line) |
| 20 | + if m: |
| 21 | + return True |
| 22 | + |
| 23 | + m = re.match(r'^([*+-]\s)', stripped_line) |
| 24 | + if m: |
| 25 | + return True |
| 26 | + return False |
| 27 | + |
| 28 | +def is_item_end_line(line: str) -> bool: |
| 29 | + if len(line) == 0: |
| 30 | + return True |
| 31 | + if re.match(r'^#+ ', line): |
| 32 | + return True |
| 33 | + return False |
| 34 | + |
| 35 | +class FixDisplayErrorExtension(Extension): |
| 36 | + |
| 37 | + def extendMarkdown(self, md, md_globals): |
| 38 | + pre = FixDisplayErrorPreprocessor(md) |
| 39 | + |
| 40 | + md.registerExtension(self) |
| 41 | + md.preprocessors.register(pre, 'fix_display_error', 28) |
| 42 | + |
| 43 | + |
| 44 | +class FixDisplayErrorPreprocessor(Preprocessor): |
| 45 | + |
| 46 | + def __init__(self, md): |
| 47 | + Preprocessor.__init__(self, md) |
| 48 | + |
| 49 | + def run(self, lines): |
| 50 | + new_lines = [] |
| 51 | + |
| 52 | + prev_line: str | None = None |
| 53 | + in_item: bool = False |
| 54 | + for line in lines: |
| 55 | + if prev_line == None: |
| 56 | + prev_line = line |
| 57 | + new_lines.append(line) |
| 58 | + continue |
| 59 | + |
| 60 | + if not is_item_line(prev_line) and not in_item and is_item_line(line): |
| 61 | + new_lines.append("") |
| 62 | + |
| 63 | + if not in_item and is_item_line(line): |
| 64 | + in_item = True |
| 65 | + if in_item and is_item_end_line(line): |
| 66 | + in_item = False |
| 67 | + |
| 68 | + prev_line = line |
| 69 | + new_lines.append(line) |
| 70 | + |
| 71 | + return new_lines |
| 72 | + |
| 73 | + |
| 74 | +def makeExtension(**kwargs): |
| 75 | + return FixDisplayErrorExtension(**kwargs) |
0 commit comments