If you translate an EPUB by pulling out the text and building a new book, you lose the things readers notice: images, the publisher's CSS, the table of contents, footnote links. The approach that keeps them is to translate text nodes in place, with a map from every translated line back to the exact DOM slot it came from. That map breaks on one kind of markup more than any other: a paragraph where every word sits in its own <i> or <span>. I merge those into one line only when nine conditions hold, and I write the translation back into the first word's text node.
I built NovelVerba, a tool that translates long Chinese, Japanese and Korean novels from EPUB or TXT files. This post is about the EPUB part: what the extractor sees, the rules for merging, and how I kept it linear on chapters with hundreds of thousands of text nodes.
One line per text node, and a receipt for each
The extractor walks the spine documents. Every block element (p, h1 to h6, li, div, td and a few more) opens a block context. Every non-empty text node inside it becomes a "slot", and every slot becomes one source line. For each line I store a part reference:
// simplified: the real type also records which kind of text node the slot is interface EpubPartRef { path: string; // "/html[1]/body[1]/p[3]", tag name plus sibling index index: number; // which slot inside that block } Plus a SHA-1 digest of all slot texts. The translation pipeline keeps a strict contract: one source line in, one translated line out. At export, the writer opens the original XHTML again, finds each block by path, finds the slot by index, and replaces only the text. Every <i>, <a href>, <img> and class around it stays where the publisher put it.
That works well for normal prose. Then a book converted through Calibre showed up.
What a shredded paragraph looks like
Here is the shape, rebuilt with the opening line of Pride and Prejudice (public domain). The real sources are Chinese, Japanese or Korean, but an English sentence makes the word boundaries easy to see while reading:
<p class="block8" id="p1"><i class="calibre3">It</i> <i class="calibre3">is</i> <i class="calibre3">a</i> <i class="calibre3">truth</i> <i class="calibre3">universally</i> <i class="calibre3">acknowledged</i>, <i class="calibre3">that</i> <i class="calibre3">a</i> ... Every word is its own italic element. Punctuation is a bare text node of the <p>. The spaces are whitespace-only text nodes between tags. In a reader app it looks like a normal italic paragraph. Word processors and conversion chains produce this when formatting gets applied word by word, and Calibre's index_split_NNN.html files keep it intact.
With slot-per-line, this one sentence becomes 26 slots, so 26 source lines: It, is, a, truth, and so on. The translation follows the contract and comes back as 26 lines of one word each. Nothing failed, no error was raised, and the chapter read as a vertical column of single words.
Merge only when the paragraph is clearly shredded
The obvious fix is "if a block has many small inline tags, join them". That breaks real formatting. A sentence with one emphasized word, a poem with one <i> per verse line, a stats line like HP 100 MP 50 in alternating spans: all of these carry meaning in their markup.
So the merge is a whitelist with nine conditions. A leaf block is merged into one line only if all of them hold:
| # | Condition | What it keeps out |
|---|---|---|
| a | Every element inside is a pure formatting tag: b strong i em u s strike del ins span font small big mark nobr | <br>, links, footnote <sup>, images, ruby, math, svg, code |
| b | At least 3 slots, at least one containing a letter | Two-slot drop caps, lines of digits |
| c | Every slot with a letter or digit is wrapped, and every wrapped slot has the same wrapper signature (tag plus attributes, ignoring id and xml:id) | Sparse emphasis, mixed bold and italic, a hidden prefix span |
| d1 | Two adjacent word slots always have collapsible whitespace between them | Words glued by CSS letter-spacing tricks |
| d2 | No gap contains NBSP, U+2007, U+202F, U+3000, form feed or other non-collapsible whitespace | Layout that depends on fixed spacing |
| g | At least 80% of word slots are a single token | Poems and Google Docs style runs of several words |
| h | No gap contains a line break | One tag per source line under white-space: pre-wrap |
| i | No element declares display or white-space in its style | Flex or grid layouts where each span is its own cell |
| f | The merged line is at most 2,000 characters | Lines the pipeline could not split later |
Running the extractor on a few synthetic cases shows the split:
shredded sentence -> ["It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife."] sparse emphasis -> ["It is a", "truth", "universally", "acknowledged", ", that a single man."] poem lines in <i> -> ["Tyger Tyger, burning bright,", "In the forests of the night;", "What immortal hand or eye,"] <br> in the middle -> ["It", "is", "a", "truth", "universally", "acknowledged"]   between -> ["It", "is", "a", "truth"] glued <i>It</i><i>is</i> -> ["It", "is", "a", "truth"] The sparse emphasis case is the honest cost of this design. The sentence stays in five pieces, because merging it would mean deciding where truth and acknowledged land in a translated sentence with different word order. I have no safe answer for that yet, so the extractor keeps the old behavior and the formatting survives.
The rule for wrappers (c) compares a signature, not a tag name. Two <i class="calibre3"> match. <i class="calibre3"> and <i class="lead"> do not. id and xml:id are excluded from the signature on purpose: converters often give every word its own id, and that should not block the merge.
Writing one translated line back into 26 slots
At export, the merged block gets exactly one translated line. The writer puts the whole line into the first slot that contains a letter, then removes every other text node in the block. It also removes every element that does not contain the target and does not carry an id or xml:id.
The id part matters. Same example, with an anchor on one word and a link pointing at it from elsewhere in the file:
<!-- source --> <p id="p1"><i class="c3">It</i> <i class="c3">is</i> <i class="c3" id="truth">truth</i>, <i class="c3">universally</i> <i class="c3">acknowledged</i>.</p> <p><a href="#truth">back</a></p> <!-- after write-back --> <p id="p1"><i class="c3">C'est une vérité universellement reconnue.</i><i class="c3" id="truth"></i></p> <p><a href="#truth">back</a></p> The translated line keeps the italic wrapper and its class. The anchor survives as an empty element, so #truth still resolves. The trade-off: the anchor now points at the end of the paragraph instead of the original word. For footnote back-links and TOC targets that sit on a paragraph or heading, that is fine. For an anchor on a single word in the middle of a sentence, there is no exact position left to point at once the word order changes.
After every document is written, a validator compares source and output before anything goes into the zip:
- no new duplicate
id(anidthat appears more often than in the source) - every
hrefandsrcfrom the source still exists in the output, except same-file links whose target was removed on purpose with stripped ruby (see below) - every same-file fragment
href="#x"whose target existed in the source still has a target
If any of these fail, the export stops with an error for that chapter. It does not quietly ship a chapter that is still in the source language, or one with a dead link the writer created.
The same decision at extract time and at export time
A project can sit for weeks between upload and export, and the code changes in between. If the merge rules change, a block that was one line at extract time could be 26 slots at export time, and the line counts would no longer add up.
Two guards handle that:
- The parser and the writer import the same
is_fragmented_blockfunction. At export, every block listed as merged is checked again on the current DOM before anything is modified. If it no longer qualifies, the export refuses with "recreate the project", instead of guessing. - The digest is recomputed from the current file, including the merged text of each merged block, in the same order as at extract time. A mismatch means the source changed, and the export refuses again.
The line count check runs after the digest check. A merged block with 26 parts counts as one expected line, so the formula is parts - (parts_per_merged_block - 1) summed over merged blocks.
Keeping it linear
Chapters can be large. A single XHTML file can hold thousands of paragraphs, and shredded ones multiply the text node count by twenty or more. Several naive steps were quadratic:
- Wrapper signatures. The first version built a string of all ancestor tags and attributes for every slot. With a long attribute on an outer wrapper, that string gets copied once per slot. Signatures are now interned: each element gets a numeric id keyed by
parentId/tag[attrs], and a slot only stores the number. There is a test with 20,000 slots under a 256 KiB attribute. - Edge whitespace. Reading trailing whitespace with a regex like
/[\s]*$/is quadratic on a text node with a long run of spaces in the middle, because the engine retries from every position. A plain loop from the end fixes it. The test uses a text node with 200,000 spaces. - Finding blocks by path. Resolving
/html[1]/body[1]/p[2931]by scanning siblings for every part is O(n²) on long documents. The writer builds a finder that groups children by tag name once per parent and caches results per path. - Inserting bilingual copies. In bilingual export, each translated block gets a copy of the original inserted before it. Splicing one clone at a time into a parent with thousands of children is quadratic, so clones are grouped by parent and the children array is rebuilt once.
On my dev machine (Node 22, Windows), parse plus extraction on synthetic chapters gave:
2,000 shredded paragraphs, 44,000 text nodes -> 2,000 lines, ~200 ms 20,000 shredded paragraphs, 440,000 text nodes -> 20,000 lines, ~1.4 s Ten times the input, about seven times the time. The test suite pins the shape: 2,000 valid paragraphs of 20 words each (40,000 slots) must merge into exactly 2,000 lines, and a single <p> with 50,000 per-word spans must not merge at all, because it would exceed the 2,000 character line limit.
Smaller things that broke write-back along the way
None of these deserve a whole post, but each one produced a broken file at some point:
- Entities. Slot text is decoded before it goes to translation. If the raw
A & Bgoes through, the translation echoes the entity and the serializer escapes it again, and the reader shows&amp;. - Leading and trailing whitespace. Translated lines come back trimmed. The writer re-attaches the original whitespace of each slot, otherwise
<b>Published:</b> 1903turns intoPublished:1903. - Ruby. For targets other than Japanese,
<rt>and<rp>are stripped, since furigana next to a translated word is noise. Any same-filehrefpointing at anidinside the stripped ruby loses itshref, so it does not become a dead link. - Right-to-left targets. For Arabic output the root
<html>getsdir="rtl", and a block that pinneddir="ltr"itself is overridden. A drop cap wrapped in its own span is unwrapped, because an enlarged Arabic letter in a separate span loses its joining with the next letter. - Bilingual copies and ids. The copy of the original has every
idremoved across its whole subtree. The translated block keeps the ids, so the table of contents jumps to the translation. - Serializing XHTML. The serializer runs with self-closing tags on (
<br/>) but without XML mode, because XML mode turns every non-ASCII character into a numeric entity and a Chinese chapter grows to nearly three times its size. - The OPF file.
dc:languageis changed by editing byte offsets inside the original string, located with a namespace-aware parse. Everything outside the edit stays byte for byte, including the publisher's formatting and the XML declaration. - The zip.
mimetypeis stored uncompressed as the first entry, as the EPUB spec requires, and already compressed media (JPEG, PNG, WOFF fonts, audio) are stored instead of deflated again.
What is still open
Two things I would like to solve better:
- Paragraphs with a few emphasized words stay split into several lines. The formatting is preserved, but the translation sees the sentence in pieces.
- Word-level anchors inside a merged paragraph move to the end of the paragraph.
If you have worked on EPUB round trips, I am curious how you handle the first one. Do you translate the whole paragraph and then try to re-apply emphasis by alignment, or do you accept losing the inline formatting?
If you want to check a book before doing anything like this, I made a free EPUB checker that looks for common structure problems (package, metadata, table of contents, internal links). It runs in the browser and the file never leaves your device. It is not a replacement for EPUBCheck.


