Skip to content

Commit

Permalink
feat: Add console source integration option
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed May 1, 2022
1 parent 5fce814 commit 62dfd74
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 11 deletions.
13 changes: 2 additions & 11 deletions src/markdown_exec/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from markdown.core import Markdown

from markdown_exec.rendering import code_block, markdown, tabbed
from markdown_exec.rendering import add_source, code_block, markdown


def buffer_print(buffer: StringIO, *text: str, end: str = "\n", **kwargs: Any) -> None:
Expand Down Expand Up @@ -68,14 +68,5 @@ def exec_python( # noqa: WPS231
output = f'<div markdown="0">{str(output)}</div>'

if source:
source_block = code_block("python", code, **extra)
if source == "above":
output = source_block + "\n\n" + output
elif source == "below":
output = output + "\n\n" + source_block
elif source == "tabbed-left":
output = tabbed((source_tab_title, source_block), (result_tab_title, output))
elif source == "tabbed-right":
output = tabbed((result_tab_title, output), (source_tab_title, source_block))

output = add_source(source=code, location=source, output=output, language="python", tabs=tabs, **extra)
return markdown.convert(output)
35 changes: 35 additions & 0 deletions src/markdown_exec/rendering.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,41 @@ def tabbed(*tabs: tuple[str, str]) -> str:
return "\n".join(parts)


def add_source(*, source: str, location: str, output: str, language: str, tabs: tuple[str, str], **extra: str) -> str:
"""Add source code block to the output.
Parameters:
source: The source code block.
location: Where to add the source (above, below, tabbed-left, tabbed-right, console).
output: The current output.
language: The code language.
tabs: Tabs titles (if used).
**extra: Extra options added back to source code block.
Raises:
ValueError: When the given location is not supported.
Returns:
The updated output.
"""
if location == "console":
return code_block(language, source + "\n" + output, **extra)

source_block = code_block(language, source, **extra)
if location == "above":
return source_block + "\n\n" + output
if location == "below":
return output + "\n\n" + source_block

source_tab_title, result_tab_title = tabs
if location == "tabbed-left":
return tabbed((source_tab_title, source_block), (result_tab_title, output))
if location == "tabbed-right":
return tabbed((result_tab_title, output), (source_tab_title, source_block))

raise ValueError(f"unsupported location for sources: {location}")


# code taken from mkdocstrings, credits to @oprypin
class _IdPrependingTreeprocessor(Treeprocessor):
"""Prepend the configured prefix to IDs of all HTML elements."""
Expand Down

0 comments on commit 62dfd74

Please sign in to comment.