Skip to content

Commit

Permalink
馃憣 IMPROVE: DocutilsRenderer.create_highlighted_code_block
Browse files Browse the repository at this point in the history
Minor improvement, to handle null lexer_name,
and allow for the use of an alternative node class.
  • Loading branch information
chrisjsewell committed Jan 2, 2022
1 parent 885651f commit d380224
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
17 changes: 8 additions & 9 deletions myst_parser/docutils_renderer.py
Expand Up @@ -16,6 +16,7 @@
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
)
Expand Down Expand Up @@ -432,12 +433,13 @@ def render_code_inline(self, token: SyntaxTreeNode) -> None:
def create_highlighted_code_block(
self,
text: str,
lexer_name: str,
lexer_name: Optional[str],
number_lines: bool = False,
lineno_start: int = 1,
source: Optional[str] = None,
line: Optional[int] = None,
) -> nodes.literal_block:
node_cls: Type[nodes.Element] = nodes.literal_block,
) -> nodes.Element:
"""Create a literal block with syntax highlighting.
This mimics the behaviour of the `code-block` directive.
Expand All @@ -450,19 +452,19 @@ def create_highlighted_code_block(
Note, this function does not add the literal block to the document.
"""
if self.sphinx_env is not None:
node = nodes.literal_block(text, text, language=lexer_name)
node = node_cls(text, text, language=lexer_name or "none")
if number_lines:
node["linenos"] = True
if lineno_start != 1:
node["highlight_args"] = {"linenostart": lineno_start}
else:
node = nodes.literal_block(
node = node_cls(
text, classes=["code"] + ([lexer_name] if lexer_name else [])
)
try:
lex_tokens = Lexer(
text,
lexer_name,
lexer_name or "",
"short"
if self.config.get("myst_highlight_code_blocks", True)
else "none",
Expand All @@ -476,7 +478,7 @@ def create_highlighted_code_block(
if value is not None
},
)
lex_tokens = Lexer(text, lexer_name, "none")
lex_tokens = Lexer(text, lexer_name or "", "none")

if number_lines:
lex_tokens = NumberLines(
Expand All @@ -497,10 +499,7 @@ def create_highlighted_code_block(
return node

def render_code_block(self, token: SyntaxTreeNode) -> None:
# this should never have a language, since it is just indented text, however,
# creating a literal_block with no language will raise a warning in sphinx
lexer = token.info.split()[0] if token.info else None
lexer = lexer or "none"
node = self.create_highlighted_code_block(
token.content,
lexer,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_renderers/fixtures/docutil_syntax_elements.md
Expand Up @@ -127,7 +127,7 @@ Block Code:
foo
.
<document source="notset">
<literal_block classes="code none" xml:space="preserve">
<literal_block classes="code" xml:space="preserve">
foo
.

Expand Down

0 comments on commit d380224

Please sign in to comment.