Skip to content

Commit 96f789e

Browse files
authored
Merge pull request #134 from steppi/literal-blocks
Add processing of literal blocks in try examples directive
2 parents 2582889 + b1586fa commit 96f789e

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

jupyterlite_sphinx/_try_examples.py

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def _append_code_cell_and_clear_lines(code_lines, output_lines, notebook):
133133
def _append_markdown_cell_and_clear_lines(markdown_lines, notebook):
134134
"""Append new markdown cell to notebook, clearing lines."""
135135
markdown_text = "\n".join(markdown_lines)
136-
# Convert blocks of LaTeX equations
136+
markdown_text = _process_literal_blocks(markdown_text)
137137
markdown_text = _process_latex(markdown_text)
138138
markdown_text = _strip_ref_identifiers(markdown_text)
139139
markdown_text = _convert_links(markdown_text)
@@ -216,6 +216,50 @@ def _process_latex(md_text):
216216
return "\n".join(wrapped_lines)
217217

218218

219+
def _process_literal_blocks(md_text):
220+
md_lines = md_text.split("\n")
221+
new_lines = []
222+
in_literal_block = False
223+
literal_block_accumulator = []
224+
225+
for line in md_lines:
226+
indent_level = len(line) - len(line.lstrip())
227+
228+
if in_literal_block and (indent_level > 0 or line.strip() == ""):
229+
literal_block_accumulator.append(line.lstrip())
230+
elif in_literal_block:
231+
new_lines.extend(["```"] + literal_block_accumulator + ["```"])
232+
literal_block_accumulator = []
233+
if line.endswith("::"):
234+
# If the line endswith ::, a new literal block is starting.
235+
line = line[:-2] # Strip off the :: from the end
236+
if not line:
237+
# If the line contains only ::, we ignore it.
238+
continue
239+
else:
240+
# Only set in_literal_block to False if not starting new
241+
# literal block.
242+
in_literal_block = False
243+
# We've appended the entire literal block which just ended, but
244+
# still need to append the current line.
245+
new_lines.append(line)
246+
else:
247+
if line.endswith("::"):
248+
# A literal block is starting.
249+
in_literal_block = True
250+
line = line[:-2]
251+
if not line:
252+
# As above, if the line contains only ::, ignore it.
253+
continue
254+
new_lines.append(line)
255+
256+
if literal_block_accumulator:
257+
# Handle case where a literal block ends the markdown cell.
258+
new_lines.extend(["```"] + literal_block_accumulator + ["```"])
259+
260+
return "\n".join(new_lines)
261+
262+
219263
# https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#docstring-sections
220264
_non_example_docstring_section_headers = (
221265
"Args",

0 commit comments

Comments
 (0)