SEO & Content

Translating Technical Documentation & Markdown Without Losing Formatting

Ankit Rathor
Ankit Rathor
Founder & Editor, Witoni
Jan 27, 2026•6 min read
In-depth analysis of translating technical documentation & markdown without losing formatting. Discover production patterns, benchmarks, and actionable workflows.

Translating technical documentation across multiple languages is rarely a matter of sending a string to an API and pasting the response back into your repository. Technical documentation is not plain text; it is an interconnected structural format. When you pass raw Markdown through a machine translation engine or large language model (LLM), things break quickly. Tables lose column alignments, indentation in nested ordered lists collapses, inline code variables get translated into literal target words, and YAML frontmatter keys get corrupted. Preserving layout integrity and syntactic correctness requires a deliberate parsing pipeline that treats structure and translatable content as distinct concerns.

Why Naive Translation Pipelines Break Markdown

Most modern translation APIs operate on natural language strings. They evaluate sentence flow, semantic context, and syntactic grammar. However, Markdown syntax relies heavily on whitespace, special characters, and structural delimiters that language models often interpret as disposable punctuation or grammatical markers.

Here are three primary failure modes encountered when feeding raw Markdown directly into an engine:

1
Inline Syntax Mutilation: Translating `"Use the "find_or_create_by" helper"" to Spanish often yields ""Usa el ayudante "encontrar_o_crear_por" "" or breaks backtick pairs into typographic quotes ("" " `" becomes "“" or "'`).
2
Frontmatter Destruction: Static site generators like Docusaurus, VitePress, and Hugo rely on YAML/TOML frontmatter at the top of Markdown files. Naive translation translates keys like "title:", "sidebar_position:", and "slug:", breaking routing and builds.
3
Whitespace and Indentation Drift: In standard CommonMark, nested lists require exact 2-space or 4-space indentations. A translation engine attempting to normalize spacing often collapses tabs to single spaces or expands blank lines, turning code fences into indented blockquotes or flat lists.

To prevent these issues in production, we need a translation architecture that isolates syntax from content before translation and reconstructs the document afterward.

The Core Architecture: AST Parsing vs. Token Masking

When designing an automated localization pipeline, two architectural patterns stand out: Token Masking (Regex/Placeholder replacement) and Abstract Syntax Tree (AST) Parsing.

```

Raw Markdown Document

│

▼

[ Unified / Remark Parser ] ───> Extracts Syntax Tree (mdast)

│

├──> Leaves Non-Translatable Nodes Untouched (YAML, CodeBlock, InlineCode)

│

└──> Batches Translatable Nodes (Paragraph, Heading, List Item Text)

│

▼

[ Translation Engine / LLM ]

│

▼

[ Tree Mutator & Serializer ] <─── Replaces Text Nodes with Translated Output

│

▼

Localized Markdown Document

```

1. Token Masking (Placeholder Substitution)

In this approach, a pre-processor scans the document with regular expressions, replaces non-translatable tokens (code blocks, inline code, URLs, variables) with unique XML-like delimiters (e.g., "__CODE_BLOCK_0__"), sends the masked text to the translation engine, and unmasks the placeholders in post-processing.

While simple to prototype, masking suffers from context contamination. Translators and LLMs frequently drop, duplicate, or translate placeholder keys (e.g., turning "__VAR_1__" into "__VARIABLE_1__"). It also fails on deeply nested structures like tables containing inline code and hyperlinked text.

2. AST-Based Extraction and Traversal

The reliable production method parses Markdown into an Abstract Syntax Tree (AST) using tools like "remark" (JavaScript/TypeScript) or "mistune"/"markdown-it" (Python/Node). In an AST, every element—paragraphs, headings, table cells, code fences, HTML blocks—is represented as an explicit node.

With an AST, your localization worker iterates through the tree, collects only translatable text nodes, batches them to preserve sentence context, passes them to the translation service, replaces the node values, and serializes the AST back to valid Markdown. Non-translatable blocks (like code snippets and frontmatter keys) remain completely isolated from the translation pipeline.

A Worked Implementation: The AST Traversal Pattern

The following Node.js script demonstrates how to parse a Markdown document using "remark", isolate translatable leaf nodes while protecting code fences and inline syntax, and safely recompile the document.

```javascript

import { unified } from 'unified';

import remarkParse from 'remark-parse';

import remarkStringify from 'remark-stringify';

import remarkFrontmatter from 'remark-frontmatter';

import { visit } from 'unist-util-visit';

// Dummy translation function representing your translation API

async function translateText(text, targetLang) {

if (!text.trim()) return text;

// Replace this mock with your LLM or MT API call

return `[${targetLang.toUpperCase()}] ${text}`;

}

export async function translateMarkdown(sourceContent, targetLang) {

// 1. Parse source into an AST

const processor = unified()

.use(remarkParse)

.use(remarkFrontmatter, ['yaml', 'toml'])

.use(remarkStringify, { bullet: '-', fence: '`', rule: '-' });

const tree = processor.parse(sourceContent);

// 2. Identify and batch translatable nodes

const translatableNodes = [];

visit(tree, (node, index, parent) => {

// Skip code fences, inline code, and raw YAML blocks

if (

node.type === 'code' ||

node.type === 'inlineCode' ||

node.type === 'yaml'

) {

return;

}

// Target pure text nodes inside paragraphs, headings, list items

if (node.type === 'text' && node.value.trim().length > 0) {

translatableNodes.push(node);

}

});

// 3. Process translations (in real systems, batch these to reduce latency)

for (const node of translatableNodes) {

node.value = await translateText(node.value, targetLang);

}

// 4. Compile the AST back to Markdown

const result = processor.stringify(tree);

return String(result);

}

```

By operating strictly at the node level, the language model never sees the code fence wrappers, language tags (```` ```typescript ````), or YAML structural keys. The formatting remains syntactically identical to the source file.

Handling Edge Cases: Tables, Anchors, and Frontmatter

Even with an AST, specific documentation features require custom handling rules:

Table Syntax and Cell Delimiters

Markdown tables rely on pipe characters (`|`) and hyphens (`-`). If cell contents expand significantly during translation (for example, German translations often expand by 20% to 35% compared to English), raw line-wrapping can corrupt the table structure. Ensure your serialization step re-aligns table columns using formatters like Prettier or remark-gfm rather than relying on raw string concatenation.

Links and Cross-References

Documentation links typically look like `[Installation Guide](/docs/install#prerequisites)`. You must translate the link text (`Installation Guide`), but you should never translate the anchor path (`#prerequisites`) unless you have already translated the heading ID in the target document. If your target language heading renders with a localized slug, update the anchor reference simultaneously to avoid dead internal links.

Selective Frontmatter Translation

Frontmatter must be parsed separately into an object (using libraries like `js-yaml`). Apply a strict allowlist for translation:

  • Translate: `title`, `description`, `summary`
  • Do Not Translate: `id`, `slug`, `sidebar_position`, `tags`, `image`, `layout`

After translation, serialize the YAML back into the header before running the AST compiler.

Common Mistakes in Markdown Localization

1
Translating Code Block Annotations: Accidental translation of language flags (e.g., turning ```` ```bash ```` into localized text) breaks syntax highlighting in doc generators.
2
Fragmenting Sentences Across Inline Tags: If a sentence contains a bold or italic tag, some naive splitters translate each segment independently. For example, splitting "Click " and "Submit" and " to continue." into three distinct API calls ruins grammar and inflection in inflected languages.
3
Translating Variable Placeholders: Leaving variables like "{userName}" or "%d" unprotected allows engines to insert spaces ("{ user name }"), breaking templating engines.
4
Ignoring Escaped Characters: Markdown relies on backslashes to escape characters (e.g., "\*" or "\["). Translators frequently strip these escape slashes, causing unexpected rendering glitches.

Pre-Flight and Post-Translation Checklist

Run your automated documentation workflows through this verification checklist:

  • [ ] Pre-translation Validation: Ensure the source Markdown conforms to CommonMark and passes linter checks (such as "markdownlint").
  • [ ] Frontmatter Whitelisting: Verify that only approved human-facing keys are marked for localization.
  • [ ] Code Fence Isolation: Confirm all triple-backtick blocks and inline backtick tokens are fully excluded from engine queries.
  • [ ] Anchor and Link Verification: Run an automated link checker across translated outputs to detect broken internal hashes or translated paths.
  • [ ] Automated Re-rendering Test: Feed generated Markdown files through your static site generator build process (e.g., Docusaurus build) in CI/CD to catch structural parsing errors immediately.

If you need a ready-made, reliable interface for transforming technical documents while keeping tags, formatting, and code intact, test your input against the [Yapay Zeka Markdown Çevirmeni](/tool/yapay-zeka-markdown-cevirmeni) tool, which handles syntax isolation automatically.

Conclusion

Maintaining multilingual technical documentation does not require compromising on build stability or visual layout. Treating Markdown as arbitrary strings leads to fragile pipelines, broken links, and corrupted formatting. By isolating non-translatable constructs using an AST, whitelisting frontmatter properties, and batching context-aware text nodes, you can run localized technical documentation updates with the same confidence and automation you expect from your core code repositories.

#ai#tools#technology#seo-content#guide