Arabic paragraphs in Markdown render left to right: a rehype plugin fix
Markdown has no syntax for text direction, so an Arabic paragraph inside an English page inherits dir="ltr" unless the renderer adds a direction. On my site I fixed it with a small rehype plugin that sets dir="rtl" when
Markdown has no syntax for text direction, so an Arabic paragraph inside an English page inherits dir="ltr" unless the renderer adds a direction. On my site I fixed it with a small rehype plugin that sets dir="rtl" when a block starts in Arabic and has more Arabic letters than Latin ones. Checking only one of those two conditions gets some paragraphs wrong.
My app pages are written in English and carry lists of Arabic links. Each Arabic run already had lang="ar", so a screen reader picked the right voice. Direction is a separate attribute, and nothing set it. The words themselves were shaped correctly, but the block was left-aligned and its separators and final full stop sat at the wrong end.
Why not dir="auto"?
dir="auto" takes the direction of the first strongly directional character. That works for a comment field, where each block is in one language. In mixed prose it flips an English paragraph that happens to open with an Arabic name.
Why not count letters?
Counting was my first attempt: more Arabic letters than Latin means right to left. An existing test failed on this line:
Masareef (مصاريف) is an app. [تحميل مصاريف بالعربي](https://www.mohamedgado.com/x)
It is an English sentence followed by a long Arabic link. The Arabic letters win the count, and the English sentence flips. Requiring the first letter to be Arabic as well fixes it.
The plugin
function rehypeArabicBlocks() {
return (tree: HastRoot) => {
visit(tree, 'element', (node: Element) => {
if (!/^(p|li|h[2-6])$/.test(node.tagName)) return
let text = ''
visit(node, 'text', (t: { value: string }) => {
text += t.value
})
const arabic = text.match(/\p{Script=Arabic}/gu)?.length ?? 0
const latin = text.match(/\p{Script=Latin}/gu)?.length ?? 0
const first = text.match(/\p{L}/u)?.[0] ?? ''
if (arabic <= latin || !/\p{Script=Arabic}/u.test(first)) return
node.properties = {
...node.properties,
dir: 'rtl',
style: 'text-align:right',
}
})
}
}
It runs after remark-rehype, so it sees the final HTML elements. \p{Script=...} needs the u flag.
The test
Keep both cases in one test, so a later change can't fix one and break the other:
const { html } = await renderMarkdown('بالعربية: [محفظة الذهب](https://www.mohamedgado.com/x)\n\nHadeed (حديد) is a workout planner.')
assert.match(html, /<p dir="rtl" style="text-align:right"><span lang="ar">بالعربية/)
assert.match(html, /<p>Hadeed/)
The rule has a limit: a Latin-heavy block that opens in Arabic stays left to right. If your content has those, set the direction by hand.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.