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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve markdown list handling #244

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 14 additions & 16 deletions monty/utils/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,37 +210,35 @@ def list(self, text: str, ordered: bool, level: int, start: Any = None) -> str:
# todo: figure out how this should actually work
if level == 1:
return text.lstrip("\n") + "\n"
return text
else:
# inner lists need a newline prefix to show separately from parent item
return "\n" + text

def list_item(self, text: str, level: int) -> str:
"""Show the list, indented to its proper level."""
lines = text.rstrip().splitlines()
indent = "\u2001" * (level - 1)

result: list[str] = [f"{indent}- {lines[0]}"]
in_codeblock = False

in_codeblock = "```" in lines[0]
for line in lines[1:]:
if "`" * 3 in line: # very very very rudimentary codeblock detection
if in_codeblock:
in_codeblock = False
if line.endswith("\n"):
line = line[:-1]
result.append(line)
continue
else:
in_codeblock = True
line = line.lstrip()
if not line.strip():
if in_codeblock:
continue
# whitespace-only lines can be rendered as empty
result.append("")
elif in_codeblock:
result.append(line)
continue

if in_codeblock:
# don't indent lines inside codeblocks
result.append(line)
else:
# the space here should be about the same width as `- `
result.append(f"{indent}\u2007{line}")

# check this at the end, since the first codeblock line should generally be indented
if "```" in line:
in_codeblock = not in_codeblock

return "\n".join(result) + "\n"

def task_list_item(self, text: Any, level: int, checked: bool = False, **attrs) -> str:
Expand Down