Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docling/backend/md_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -770,7 +770,9 @@ def _iterate_elements( # noqa: C901
isinstance(element, marko.block.CodeBlock | marko.block.FencedCode)
and len(element.children) > 0
and isinstance((child := element.children[0]), marko.inline.RawText)
and len(snippet_text := (child.children.strip())) > 0
# Drop blank lines around the code but keep the first line's
# indentation, which is part of the code.
and len(snippet_text := child.children.lstrip("\n").rstrip()) > 0
):
self._close_table(doc)
_log.debug(" - Code Block: %s", element.children)
Expand Down
33 changes: 33 additions & 0 deletions tests/test_backend_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,39 @@ def test_code_block_language_detection():
]


def test_code_block_keeps_first_line_indentation():
"""Indentation on a code block's first line is content, not padding.

Stripping the whole snippet removed it from the first line only, so the
lines no longer lined up: YAML changed structure and Python stopped parsing.
"""
markdown = (
"```yaml\n"
" key: 1\n"
" sub:\n"
" x: 2\n"
"```\n\n"
"Indented block:\n\n"
" deeper\n"
" base\n\n"
"```\n"
"\n"
" after blank line\n"
"```\n"
)
conv_result = get_converter().convert_string(markdown, format=InputFormat.MD)
assert conv_result.status == ConversionStatus.SUCCESS

code_texts = [
item.text for item in conv_result.document.texts if isinstance(item, CodeItem)
]
assert code_texts == [
" key: 1\n sub:\n x: 2",
" deeper\nbase",
" after blank line",
]


def test_convert_table_keeps_inline_code_spans():
"""A code span inside a GFM table cell is part of that cell.

Expand Down
Loading