Skip to content

Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.

fix(docx): preserve inline tabs and breaks (#239)

Stamina980ae087784dd
diff --git a/book_to_skill/parsers/docx.py b/book_to_skill/parsers/docx.py
index 49f2962..a8e3a6c 100644
--- a/book_to_skill/parsers/docx.py
+++ b/book_to_skill/parsers/docx.py
@@ -55,6 +55,18 @@ def extract_docx_with_zipfile(docx_path: str) -> str | None:
ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
parts: list[str] = []
+ def inline_text(elem) -> str:
+ """Rebuild text runs without dropping explicit DOCX separators."""
+ text_parts: list[str] = []
+ for node in elem.iter():
+ if node.tag == f"{ns}t" and node.text:
+ text_parts.append(node.text)
+ elif node.tag == f"{ns}tab":
+ text_parts.append("\t")
+ elif node.tag in {f"{ns}br", f"{ns}cr"}:
+ text_parts.append("\n")
+ return "".join(text_parts)
+
def emit_block(elem) -> None:
# Walk block content in document order. Paragraphs join their runs;
# tables emit one tab-joined line per row (same row format as the
@@ -68,15 +80,14 @@ def extract_docx_with_zipfile(docx_path: str) -> str | None:
for child in elem:
tag = child.tag
if tag == f"{ns}p":
- texts = [t.text for t in child.iter(f"{ns}t") if t.text]
- if texts:
- parts.append("".join(texts))
+ paragraph = inline_text(child)
+ if paragraph:
+ parts.append(paragraph)
elif tag == f"{ns}tbl":
for row in child.iter(f"{ns}tr"):
cells = []
for cell in row.iter(f"{ns}tc"):
- cell_texts = [t.text for t in cell.iter(f"{ns}t") if t.text]
- cells.append("".join(cell_texts).strip())
+ cells.append(inline_text(cell).strip())
if any(cells):
parts.append("\t".join(cells))
else:
diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.py
index 610021c..933114e 100644
--- a/tests/test_book_to_skill.py
+++ b/tests/test_book_to_skill.py
@@ -1819,6 +1819,22 @@ class TestDocxTableReconstruction:
out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))
assert out == "Just a paragraph\nAnd another"
+ def test_inline_tabs_are_preserved(self, tmp_path):
+ body = (
+ "<w:p><w:r><w:t>Term</w:t><w:tab/><w:t>Definition</w:t>"
+ "</w:r></w:p>"
+ )
+ out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))
+ assert out == "Term\tDefinition"
+
+ def test_inline_breaks_are_preserved(self, tmp_path):
+ body = (
+ "<w:p><w:r><w:t>First line</w:t><w:br/><w:t>Second line</w:t>"
+ "<w:cr/><w:t>Third line</w:t></w:r></w:p>"
+ )
+ out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))
+ assert out == "First line\nSecond line\nThird line"
+
def test_empty_cell_still_tab_joined(self, tmp_path):
body = (
"<w:tbl><w:tr>" + self._cell("A")