Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃憣 IMPROVE: DocutilsRenderer.create_highlighted_code_block #488

Merged
merged 1 commit into from Jan 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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