|
| 1 | +# Converts inline <pre lang="langcode">code</pre> blocks to pygments-highlighted html |
| 2 | +# Custom hook to highlight and format <pre lang="langcode">code</br>code</pre> blocks |
| 3 | +# |
| 4 | +# This is used for <pre/> blocks embedded in tables, as these otherwise are skipped by pygments |
| 5 | +# |
| 6 | +# Note: It's possible this can be done better with Python-markdown inline patterns (https://python-markdown.github.io/reference/markdown/inlinepatterns), |
| 7 | +# but the below works For Now |
| 8 | + |
| 9 | +import re |
| 10 | +import markdown |
| 11 | + |
| 12 | +import mkdocs |
| 13 | +from mkdocs.structure.pages import Page |
| 14 | +from mkdocs.config.defaults import MkDocsConfig |
| 15 | +from mkdocs.structure.files import Files |
| 16 | + |
| 17 | +from pymdownx.highlight import HighlightExtension |
| 18 | + |
| 19 | +# Get current mkdocs config |
| 20 | +user_extensions = MkDocsConfig.markdown_extensions.__dict__.get('configdata'); |
| 21 | +highlight_config = dict() |
| 22 | + |
| 23 | +if 'pymdownx.highlight' in user_extensions: |
| 24 | + highlight_config = user_extensions.get('pymdownx.highlight') |
| 25 | + |
| 26 | +ExistingHighlighter = HighlightExtension().get_pymdownx_highlighter()(**highlight_config) |
| 27 | + |
| 28 | +def on_page_content(html: str, page: Page, config: MkDocsConfig, files: Files, **kwargs): |
| 29 | + def inline_pre_to_code_fence(match): |
| 30 | + raw = match.group() |
| 31 | + |
| 32 | + ## Check for language |
| 33 | + lang = '' |
| 34 | + langmatch = re.search('lang="(.*?)"', raw) |
| 35 | + |
| 36 | + if langmatch: |
| 37 | + lang = langmatch.group(1) |
| 38 | + |
| 39 | + ## Remove first tag |
| 40 | + pre = re.sub('<pre( lang=(".+"))?>', '', raw) |
| 41 | + |
| 42 | + ## Strip end tag |
| 43 | + pre = re.sub('</pre>', '', pre) |
| 44 | + |
| 45 | + ## Swap html linebreaks |
| 46 | + pre = re.sub('<br/>', '\n', pre) |
| 47 | + |
| 48 | + return ExistingHighlighter.highlight(pre, lang) |
| 49 | + |
| 50 | + result = re.sub('<pre( lang=(".+"))?>(.+)</pre>', inline_pre_to_code_fence, html) |
| 51 | + |
| 52 | + return result |
0 commit comments