2024-03-04 01:15:23 +08:00
|
|
|
# CodeHilite Extension for Python-Markdown
|
|
|
|
# ========================================
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# Adds code/syntax highlighting to standard Python-Markdown code blocks.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# See https://Python-Markdown.github.io/extensions/code_hilite
|
|
|
|
# for documentation.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# Original code Copyright 2006-2008 [Waylan Limberg](http://achinghead.com/).
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# All changes Copyright 2008-2014 The Python Markdown Project
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# License: [BSD](https://opensource.org/licenses/bsd-license.php)
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
Adds code/syntax highlighting to standard Python-Markdown code blocks.
|
|
|
|
|
|
|
|
See the [documentation](https://Python-Markdown.github.io/extensions/code_hilite)
|
|
|
|
for details.
|
|
|
|
"""
|
|
|
|
|
|
|
|
from __future__ import annotations
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
from . import Extension
|
|
|
|
from ..treeprocessors import Treeprocessor
|
2022-01-24 12:07:52 +08:00
|
|
|
from ..util import parseBoolValue
|
2024-03-04 01:15:23 +08:00
|
|
|
from typing import TYPE_CHECKING, Callable, Any
|
|
|
|
|
|
|
|
if TYPE_CHECKING: # pragma: no cover
|
|
|
|
import xml.etree.ElementTree as etree
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
try: # pragma: no cover
|
2018-09-17 08:27:00 +08:00
|
|
|
from pygments import highlight
|
|
|
|
from pygments.lexers import get_lexer_by_name, guess_lexer
|
|
|
|
from pygments.formatters import get_formatter_by_name
|
2022-11-08 02:06:49 +08:00
|
|
|
from pygments.util import ClassNotFound
|
2018-09-17 08:27:00 +08:00
|
|
|
pygments = True
|
2022-01-24 12:07:52 +08:00
|
|
|
except ImportError: # pragma: no cover
|
2018-09-17 08:27:00 +08:00
|
|
|
pygments = False
|
|
|
|
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def parse_hl_lines(expr: str) -> list[int]:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""Support our syntax for emphasizing certain lines of code.
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
`expr` should be like '1 2' to emphasize lines 1 and 2 of a code block.
|
|
|
|
Returns a list of integers, the line numbers to emphasize.
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
|
|
|
if not expr:
|
|
|
|
return []
|
|
|
|
|
|
|
|
try:
|
|
|
|
return list(map(int, expr.split()))
|
2022-01-24 12:07:52 +08:00
|
|
|
except ValueError: # pragma: no cover
|
2018-09-17 08:27:00 +08:00
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
|
|
# ------------------ The Main CodeHilite Class ----------------------
|
2022-01-24 12:07:52 +08:00
|
|
|
class CodeHilite:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
2022-01-24 12:07:52 +08:00
|
|
|
Determine language of source code, and pass it on to the Pygments highlighter.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
Usage:
|
2022-11-08 02:06:49 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
```python
|
|
|
|
code = CodeHilite(src=some_code, lang='python')
|
|
|
|
html = code.hilite()
|
|
|
|
```
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Arguments:
|
|
|
|
src: Source string or any object with a `.readline` attribute.
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
lang (str): String name of Pygments lexer to use for highlighting. Default: `None`.
|
|
|
|
guess_lang (bool): Auto-detect which lexer to use.
|
|
|
|
Ignored if `lang` is set to a valid value. Default: `True`.
|
|
|
|
use_pygments (bool): Pass code to Pygments for code highlighting. If `False`, the code is
|
|
|
|
instead wrapped for highlighting by a JavaScript library. Default: `True`.
|
|
|
|
pygments_formatter (str): The name of a Pygments formatter or a formatter class used for
|
|
|
|
highlighting the code blocks. Default: `html`.
|
|
|
|
linenums (bool): An alias to Pygments `linenos` formatter option. Default: `None`.
|
|
|
|
css_class (str): An alias to Pygments `cssclass` formatter option. Default: 'codehilite'.
|
|
|
|
lang_prefix (str): Prefix prepended to the language. Default: "language-".
|
2022-01-24 12:07:52 +08:00
|
|
|
|
|
|
|
Other Options:
|
2024-03-04 01:15:23 +08:00
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
Any other options are accepted and passed on to the lexer and formatter. Therefore,
|
|
|
|
valid options include any options which are accepted by the `html` formatter or
|
|
|
|
whichever lexer the code's language uses. Note that most lexers do not have any
|
|
|
|
options. However, a few have very useful options, such as PHP's `startinline` option.
|
|
|
|
Any invalid options are ignored without error.
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
* **Formatter options**: <https://pygments.org/docs/formatters/#HtmlFormatter>
|
|
|
|
* **Lexer Options**: <https://pygments.org/docs/lexers/>
|
2022-01-24 12:07:52 +08:00
|
|
|
|
2022-11-08 02:06:49 +08:00
|
|
|
Additionally, when Pygments is enabled, the code's language is passed to the
|
|
|
|
formatter as an extra option `lang_str`, whose value being `{lang_prefix}{lang}`.
|
2024-03-04 01:15:23 +08:00
|
|
|
This option has no effect to the Pygments' builtin formatters.
|
2022-11-08 02:06:49 +08:00
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
Advanced Usage:
|
2024-03-04 01:15:23 +08:00
|
|
|
|
|
|
|
```python
|
|
|
|
code = CodeHilite(
|
|
|
|
src = some_code,
|
|
|
|
lang = 'php',
|
|
|
|
startinline = True, # Lexer option. Snippet does not start with `<?php`.
|
|
|
|
linenostart = 42, # Formatter option. Snippet starts on line 42.
|
|
|
|
hl_lines = [45, 49, 50], # Formatter option. Highlight lines 45, 49, and 50.
|
|
|
|
linenos = 'inline' # Formatter option. Avoid alignment problems.
|
|
|
|
)
|
|
|
|
html = code.hilite()
|
|
|
|
```
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __init__(self, src: str, **options):
|
2018-09-17 08:27:00 +08:00
|
|
|
self.src = src
|
2024-03-04 01:15:23 +08:00
|
|
|
self.lang: str | None = options.pop('lang', None)
|
|
|
|
self.guess_lang: bool = options.pop('guess_lang', True)
|
|
|
|
self.use_pygments: bool = options.pop('use_pygments', True)
|
|
|
|
self.lang_prefix: str = options.pop('lang_prefix', 'language-')
|
|
|
|
self.pygments_formatter: str | Callable = options.pop('pygments_formatter', 'html')
|
2022-01-24 12:07:52 +08:00
|
|
|
|
|
|
|
if 'linenos' not in options:
|
|
|
|
options['linenos'] = options.pop('linenums', None)
|
|
|
|
if 'cssclass' not in options:
|
|
|
|
options['cssclass'] = options.pop('css_class', 'codehilite')
|
|
|
|
if 'wrapcode' not in options:
|
2024-03-04 01:15:23 +08:00
|
|
|
# Override Pygments default
|
2022-01-24 12:07:52 +08:00
|
|
|
options['wrapcode'] = True
|
|
|
|
# Disallow use of `full` option
|
|
|
|
options['full'] = False
|
|
|
|
|
|
|
|
self.options = options
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def hilite(self, shebang: bool = True) -> str:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
Pass code to the [Pygments](https://pygments.org/) highlighter with
|
|
|
|
optional line numbers. The output should then be styled with CSS to
|
2018-09-17 08:27:00 +08:00
|
|
|
your liking. No styles are applied by default - only styling hooks
|
2024-03-04 01:15:23 +08:00
|
|
|
(i.e.: `<span class="k">`).
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
returns : A string of html.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
self.src = self.src.strip('\n')
|
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
if self.lang is None and shebang:
|
2018-09-17 08:27:00 +08:00
|
|
|
self._parseHeader()
|
|
|
|
|
|
|
|
if pygments and self.use_pygments:
|
|
|
|
try:
|
2022-01-24 12:07:52 +08:00
|
|
|
lexer = get_lexer_by_name(self.lang, **self.options)
|
2018-09-17 08:27:00 +08:00
|
|
|
except ValueError:
|
|
|
|
try:
|
|
|
|
if self.guess_lang:
|
2022-01-24 12:07:52 +08:00
|
|
|
lexer = guess_lexer(self.src, **self.options)
|
2018-09-17 08:27:00 +08:00
|
|
|
else:
|
2022-01-24 12:07:52 +08:00
|
|
|
lexer = get_lexer_by_name('text', **self.options)
|
|
|
|
except ValueError: # pragma: no cover
|
|
|
|
lexer = get_lexer_by_name('text', **self.options)
|
2022-11-08 02:06:49 +08:00
|
|
|
if not self.lang:
|
|
|
|
# Use the guessed lexer's language instead
|
|
|
|
self.lang = lexer.aliases[0]
|
|
|
|
lang_str = f'{self.lang_prefix}{self.lang}'
|
|
|
|
if isinstance(self.pygments_formatter, str):
|
|
|
|
try:
|
|
|
|
formatter = get_formatter_by_name(self.pygments_formatter, **self.options)
|
|
|
|
except ClassNotFound:
|
|
|
|
formatter = get_formatter_by_name('html', **self.options)
|
|
|
|
else:
|
|
|
|
formatter = self.pygments_formatter(lang_str=lang_str, **self.options)
|
2018-09-17 08:27:00 +08:00
|
|
|
return highlight(self.src, lexer, formatter)
|
|
|
|
else:
|
2024-03-04 01:15:23 +08:00
|
|
|
# just escape and build markup usable by JavaScript highlighting libraries
|
2018-09-17 08:27:00 +08:00
|
|
|
txt = self.src.replace('&', '&')
|
|
|
|
txt = txt.replace('<', '<')
|
|
|
|
txt = txt.replace('>', '>')
|
|
|
|
txt = txt.replace('"', '"')
|
|
|
|
classes = []
|
|
|
|
if self.lang:
|
2022-01-24 12:07:52 +08:00
|
|
|
classes.append('{}{}'.format(self.lang_prefix, self.lang))
|
|
|
|
if self.options['linenos']:
|
2018-09-17 08:27:00 +08:00
|
|
|
classes.append('linenums')
|
|
|
|
class_str = ''
|
|
|
|
if classes:
|
2022-01-24 12:07:52 +08:00
|
|
|
class_str = ' class="{}"'.format(' '.join(classes))
|
|
|
|
return '<pre class="{}"><code{}>{}\n</code></pre>\n'.format(
|
|
|
|
self.options['cssclass'],
|
|
|
|
class_str,
|
|
|
|
txt
|
|
|
|
)
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def _parseHeader(self) -> None:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
2022-01-24 12:07:52 +08:00
|
|
|
Determines language of a code block from shebang line and whether the
|
2024-03-04 01:15:23 +08:00
|
|
|
said line should be removed or left in place. If the shebang line
|
2022-01-24 12:07:52 +08:00
|
|
|
contains a path (even a single /) then it is assumed to be a real
|
|
|
|
shebang line and left alone. However, if no path is given
|
2024-03-04 01:15:23 +08:00
|
|
|
(e.i.: `#!python` or `:::python`) then it is assumed to be a mock shebang
|
2022-01-24 12:07:52 +08:00
|
|
|
for language identification of a code fragment and removed from the
|
|
|
|
code block prior to processing for code highlighting. When a mock
|
2024-03-04 01:15:23 +08:00
|
|
|
shebang (e.i: `#!python`) is found, line numbering is turned on. When
|
|
|
|
colons are found in place of a shebang (e.i.: `:::python`), line
|
2022-01-24 12:07:52 +08:00
|
|
|
numbering is left in the current state - off by default.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
Also parses optional list of highlight lines, like:
|
|
|
|
|
|
|
|
:::python hl_lines="1 3"
|
|
|
|
"""
|
|
|
|
|
|
|
|
import re
|
|
|
|
|
|
|
|
# split text into lines
|
|
|
|
lines = self.src.split("\n")
|
|
|
|
# pull first line to examine
|
|
|
|
fl = lines.pop(0)
|
|
|
|
|
|
|
|
c = re.compile(r'''
|
|
|
|
(?:(?:^::+)|(?P<shebang>^[#]!)) # Shebang or 2 or more colons
|
|
|
|
(?P<path>(?:/\w+)*[/ ])? # Zero or 1 path
|
|
|
|
(?P<lang>[\w#.+-]*) # The language
|
|
|
|
\s* # Arbitrary whitespace
|
|
|
|
# Optional highlight lines, single- or double-quote-delimited
|
|
|
|
(hl_lines=(?P<quot>"|')(?P<hl_lines>.*?)(?P=quot))?
|
|
|
|
''', re.VERBOSE)
|
|
|
|
# search first line for shebang
|
|
|
|
m = c.search(fl)
|
|
|
|
if m:
|
|
|
|
# we have a match
|
|
|
|
try:
|
|
|
|
self.lang = m.group('lang').lower()
|
2022-01-24 12:07:52 +08:00
|
|
|
except IndexError: # pragma: no cover
|
2018-09-17 08:27:00 +08:00
|
|
|
self.lang = None
|
|
|
|
if m.group('path'):
|
|
|
|
# path exists - restore first line
|
|
|
|
lines.insert(0, fl)
|
2022-01-24 12:07:52 +08:00
|
|
|
if self.options['linenos'] is None and m.group('shebang'):
|
2018-09-17 08:27:00 +08:00
|
|
|
# Overridable and Shebang exists - use line numbers
|
2022-01-24 12:07:52 +08:00
|
|
|
self.options['linenos'] = True
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
self.options['hl_lines'] = parse_hl_lines(m.group('hl_lines'))
|
2018-09-17 08:27:00 +08:00
|
|
|
else:
|
|
|
|
# No match
|
|
|
|
lines.insert(0, fl)
|
|
|
|
|
|
|
|
self.src = "\n".join(lines).strip("\n")
|
|
|
|
|
|
|
|
|
|
|
|
# ------------------ The Markdown Extension -------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
class HiliteTreeprocessor(Treeprocessor):
|
2022-11-08 02:06:49 +08:00
|
|
|
""" Highlight source code in code blocks. """
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
config: dict[str, Any]
|
|
|
|
|
|
|
|
def code_unescape(self, text: str) -> str:
|
2022-01-24 12:07:52 +08:00
|
|
|
"""Unescape code."""
|
|
|
|
text = text.replace("<", "<")
|
|
|
|
text = text.replace(">", ">")
|
|
|
|
# Escaped '&' should be replaced at the end to avoid
|
|
|
|
# conflicting with < and >.
|
|
|
|
text = text.replace("&", "&")
|
|
|
|
return text
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def run(self, root: etree.Element) -> None:
|
|
|
|
""" Find code blocks and store in `htmlStash`. """
|
2018-09-17 08:27:00 +08:00
|
|
|
blocks = root.iter('pre')
|
|
|
|
for block in blocks:
|
|
|
|
if len(block) == 1 and block[0].tag == 'code':
|
2022-11-08 02:06:49 +08:00
|
|
|
local_config = self.config.copy()
|
2024-03-04 01:15:23 +08:00
|
|
|
text = block[0].text
|
|
|
|
if text is None:
|
|
|
|
continue
|
2018-09-17 08:27:00 +08:00
|
|
|
code = CodeHilite(
|
2024-03-04 01:15:23 +08:00
|
|
|
self.code_unescape(text),
|
2022-01-24 12:07:52 +08:00
|
|
|
tab_length=self.md.tab_length,
|
2022-11-08 02:06:49 +08:00
|
|
|
style=local_config.pop('pygments_style', 'default'),
|
|
|
|
**local_config
|
2018-09-17 08:27:00 +08:00
|
|
|
)
|
2022-01-24 12:07:52 +08:00
|
|
|
placeholder = self.md.htmlStash.store(code.hilite())
|
2024-03-04 01:15:23 +08:00
|
|
|
# Clear code block in `etree` instance
|
2018-09-17 08:27:00 +08:00
|
|
|
block.clear()
|
2024-03-04 01:15:23 +08:00
|
|
|
# Change to `p` element which will later
|
2018-09-17 08:27:00 +08:00
|
|
|
# be removed when inserting raw html
|
|
|
|
block.tag = 'p'
|
|
|
|
block.text = placeholder
|
|
|
|
|
|
|
|
|
|
|
|
class CodeHiliteExtension(Extension):
|
2024-03-04 01:15:23 +08:00
|
|
|
""" Add source code highlighting to markdown code blocks. """
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
def __init__(self, **kwargs):
|
2018-09-17 08:27:00 +08:00
|
|
|
# define default configs
|
|
|
|
self.config = {
|
2024-03-04 01:15:23 +08:00
|
|
|
'linenums': [
|
|
|
|
None, "Use lines numbers. True|table|inline=yes, False=no, None=auto. Default: `None`."
|
|
|
|
],
|
|
|
|
'guess_lang': [
|
|
|
|
True, "Automatic language detection - Default: `True`."
|
|
|
|
],
|
|
|
|
'css_class': [
|
|
|
|
"codehilite", "Set class name for wrapper <div> - Default: `codehilite`."
|
|
|
|
],
|
|
|
|
'pygments_style': [
|
|
|
|
'default', 'Pygments HTML Formatter Style (Colorscheme). Default: `default`.'
|
|
|
|
],
|
|
|
|
'noclasses': [
|
|
|
|
False, 'Use inline styles instead of CSS classes - Default `False`.'
|
|
|
|
],
|
|
|
|
'use_pygments': [
|
|
|
|
True, 'Highlight code blocks with pygments. Disable if using a JavaScript library. Default: `True`.'
|
|
|
|
],
|
2022-01-24 12:07:52 +08:00
|
|
|
'lang_prefix': [
|
2024-03-04 01:15:23 +08:00
|
|
|
'language-', 'Prefix prepended to the language when `use_pygments` is false. Default: `language-`.'
|
|
|
|
],
|
|
|
|
'pygments_formatter': [
|
|
|
|
'html', 'Use a specific formatter for Pygments highlighting. Default: `html`.'
|
2022-11-08 02:06:49 +08:00
|
|
|
],
|
2024-03-04 01:15:23 +08:00
|
|
|
}
|
|
|
|
""" Default configuration options. """
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
for key, value in kwargs.items():
|
|
|
|
if key in self.config:
|
|
|
|
self.setConfig(key, value)
|
|
|
|
else:
|
|
|
|
# manually set unknown keywords.
|
|
|
|
if isinstance(value, str):
|
|
|
|
try:
|
2024-03-04 01:15:23 +08:00
|
|
|
# Attempt to parse `str` as a boolean value
|
2022-01-24 12:07:52 +08:00
|
|
|
value = parseBoolValue(value, preserve_none=True)
|
|
|
|
except ValueError:
|
2024-03-04 01:15:23 +08:00
|
|
|
pass # Assume it's not a boolean value. Use as-is.
|
2022-01-24 12:07:52 +08:00
|
|
|
self.config[key] = [value, '']
|
|
|
|
|
|
|
|
def extendMarkdown(self, md):
|
2024-03-04 01:15:23 +08:00
|
|
|
""" Add `HilitePostprocessor` to Markdown instance. """
|
2018-09-17 08:27:00 +08:00
|
|
|
hiliter = HiliteTreeprocessor(md)
|
|
|
|
hiliter.config = self.getConfigs()
|
2022-01-24 12:07:52 +08:00
|
|
|
md.treeprocessors.register(hiliter, 'hilite', 30)
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
md.registerExtension(self)
|
|
|
|
|
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
def makeExtension(**kwargs): # pragma: no cover
|
|
|
|
return CodeHiliteExtension(**kwargs)
|