Skip to content

Commit

Permalink
feat: Allow passing extra opts like title to source code blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed May 1, 2022
1 parent 32078ab commit bb3252a
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 4 deletions.
1 change: 1 addition & 0 deletions src/markdown_exec/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def validator(
options["exec"] = exec_value
options["isolate"] = isolate_value
options["show_source"] = show_source_value
options["extra"] = inputs
return True


Expand Down
6 changes: 4 additions & 2 deletions src/markdown_exec/markdown_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@
from textwrap import indent


def code_block(language: str, source: str) -> str:
def code_block(language: str, source: str, **options: str) -> str:
"""Format source as a code block.
Parameters:
language: The code block language.
source: The source code to format.
**options: Additional options passed from the source, to add back to the generated code block.
Returns:
The formatted code block.
"""
return f"```{language}\n{source}\n```"
opts = " ".join(f'{opt_name}="{opt_value}"' for opt_name, opt_value in options.items())
return f"```{language} {opts}\n{source}\n```"


def tabbed(*tabs: tuple[str, str]) -> str:
Expand Down
5 changes: 3 additions & 2 deletions src/markdown_exec/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,17 @@ def exec_python( # noqa: WPS231
exec_source = f"def _function():\n{indent(source, prefix=' ' * 4)}\n_function()\n"
else:
exec_source = source
extra = options.get("extra", {})
try:
exec(exec_source) # noqa: S102
except MarkdownOutput as raised_output:
output = str(raised_output)
except HTMLOutput as raised_output:
output = f'<div markdown="0">{str(raised_output)}</div>'
except Exception:
output = code_block("python", traceback.format_exc())
output = code_block("python", traceback.format_exc(), **extra)
if show_source:
source_block = code_block("python", source)
source_block = code_block("python", source, **extra)
if show_source == "above":
output = source_block + "\n\n" + output
elif show_source == "below":
Expand Down

0 comments on commit bb3252a

Please sign in to comment.