|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +絵文字の置き換え |
| 4 | +========================================= |
| 5 | +
|
| 6 | +絵文字を以下の方針に従って置き換える: |
| 7 | +・表示できない環境を考慮する (アクセシビリティ) |
| 8 | +・絵文字の意味をツールチップで表示する |
| 9 | +
|
| 10 | + >>> text = "GCC: 12.0 [mark noimpl], 13.1 [mark impl], 14.1 [mark verified]" |
| 11 | + >>> md = markdown.Markdown(['mark']) |
| 12 | + >>> print md.convert(text) |
| 13 | + GCC: 12.0 <span role="img" aria-label="未実装" title="未実装">❌</span>, 13.1 <span role="img" aria-label="実装済" title="実装済">⭕</span>, 14.1 <span role="img" aria-label="検証済" title="検証済">✅</span> |
| 14 | +""" |
| 15 | + |
| 16 | +import re |
| 17 | + |
| 18 | +from markdown.extensions import Extension |
| 19 | +from markdown.preprocessors import Preprocessor |
| 20 | + |
| 21 | + |
| 22 | +MARK_DICT = { |
| 23 | + "[mark noimpl]": "<span role=\"img\" aria-label=\"未実装\" title=\"未実装\">❌</span>", |
| 24 | + "[mark impl]": "<span role=\"img\" aria-label=\"実装済\" title=\"実装済\">⭕</span>", |
| 25 | + "[mark verified]": "<span role=\"img\" aria-label=\"検証済\" title=\"検証済\">✅</span>", |
| 26 | +} |
| 27 | + |
| 28 | +class MarkExtension(Extension): |
| 29 | + |
| 30 | + def extendMarkdown(self, md, md_globals): |
| 31 | + markpre = MarkPreprocessor(md) |
| 32 | + |
| 33 | + md.registerExtension(self) |
| 34 | + md.preprocessors.add('meta', markpre, ">normalize_whitespace") |
| 35 | + |
| 36 | + |
| 37 | +class MarkPreprocessor(Preprocessor): |
| 38 | + |
| 39 | + def __init__(self, md): |
| 40 | + Preprocessor.__init__(self, md) |
| 41 | + self._markdown = md |
| 42 | + |
| 43 | + def run(self, lines): |
| 44 | + new_lines = [] |
| 45 | + self._markdown._meta_result = {} |
| 46 | + pattern = re.compile("|".join(map(re.escape, MARK_DICT.keys()))) |
| 47 | + |
| 48 | + for line in lines: |
| 49 | + new_line = pattern.sub(lambda match: MARK_DICT[match.group(0)], line) |
| 50 | + new_lines.append(new_line) |
| 51 | + |
| 52 | + return new_lines |
| 53 | + |
| 54 | + |
| 55 | +def makeExtension(**kwargs): |
| 56 | + return MarkExtension(**kwargs) |
0 commit comments