claude-rtl-fix
Fixes mixed right-to-left (Persian, Arabic, Hebrew, Urdu …) and English text in Claude's interfaces. A Claude Code mod with a dependency-free bidi engine.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/rozucci--claude-rtl-fix)HTML
<a href="/listings/rozucci--claude-rtl-fix"><img src="/api/listings/rozucci--claude-rtl-fix/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
At the prompt of a Claude Code terminal session:
/plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
Answer `y` to add the marketplace, then pick a scope (user scope is first).
From a shell:
claude plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
An older Claude Code answers `unknown option '--marketplace'`. Then add the marketplace first, or run `claude update`:
claude plugin marketplace add Rozucci/Claude-RTL-Fix
claude plugin install rtl-fix@claude-rtl-fix
In the desktop app, where `/plugin` does not run: click **+** next to the prompt box, then **Plugins**, **Add marketplace** with `Rozucci/Claude-RTL-Fix`, then **Add plugin**. A mod installed from a terminal at the user scope also loads in the desktop app's Code tab.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 16 lines
- {
- "name": "claude-rtl-fix",
- "owner": {
- "name": "Rozucci"
- },
- "metadata": {
- "description": "Right-to-left (Persian, Arabic, Hebrew, Urdu ...) text fixes for Claude's interfaces"
- },
- "plugins": [
- {
- "name": "rtl-fix",
- "source": "./claude-code-mod/rtl-fix",
- "description": "Fixes mixed right-to-left (Persian, Arabic, Hebrew, Urdu ...) and English text in Claude Code's transcript"
- }
- ]
- }
README.md · README · 345 lines
- # Claude-RTL-Fix
- Fixes mixed right-to-left and English text in Claude's interfaces: Persian,
- Arabic, Hebrew, Urdu and every other language written right to left.
- رفع بههمریختگی متن راستبهچپ و انگلیسی در رابطهای Claude، برای فارسی، عربی، عبری، اردو و هر زبان راستبهچپ دیگر.
- 
- [English](#english) · [فارسی](#فارسی) · [العربية](#العربية) · [עברית](#עברית)
- ---
- ## English
- ### The problem
- Right-to-left languages are usually written with English words, code, numbers
- and units mixed in. Claude's interfaces lay such text out with the plain Unicode
- bidi algorithm, and it breaks in the same ways in every right-to-left language:
- - A line that starts with an English word is laid out left to right, so its
- period jumps to the wrong end and the line sits on the wrong side.
- - A number with a unit is reversed: `12.5 USD` shows as `USD 12.5`, `25°C` as
- `C°25`, `100 km/h` as `km/h 100`.
- - Brackets and dots next to English words move across the line.
- The Claude desktop app already picks each paragraph's direction from its first
- letter, so lines that start with a right-to-left word mostly look fine. The
- cases above still break. The same text, drawn three ways:
- 
- ### Languages
- It works on the letters, not on a list of languages, so every right-to-left
- script is covered:
- | Script | Languages | A line it fixes |
- | --- | --- | --- |
- | Arabic | Persian, Arabic, Urdu, Pashto, Kurdish (Sorani), Sindhi, Uyghur … | `Astro یک فریمورک است.` · `Python لغة برمجة شائعة.` · `یہ منصوبہ Claude Code سے بنایا گیا۔` |
- | Hebrew | Hebrew, Yiddish | `React היא ספרייה של JavaScript.` |
- | Syriac, Thaana, N'Ko, Adlam, Samaritan, Mandaic, Hanifi Rohingya | Syriac, Dhivehi, Manding, Fula, Rohingya … | detected as right to left |
- Western (`0-9`), Arabic-Indic (`٠-٩`) and Persian (`۰-۹`) digits are all
- handled. The Persian, Arabic, Hebrew and Urdu cases are in the test suite; the
- other scripts are tested for detection.
- ### What this does
- `rtl-fix` is a Claude Code mod. It changes **only what is drawn**: the stored
- message, what the model reads and what you copy stay exactly as written.
- It adds invisible Unicode direction marks to each message before it is drawn:
- | Where | What it adds |
- | --- | --- |
- | A line that is mostly right-to-left (at least as many right-to-left words as English ones, or a right-to-left first letter) | `RLM` + `RLI` … `PDI` around its content |
- | A Latin run inside it (`Claude Code`, `12.5 USD`, `f(x)`) | `LRI` … `PDI` |
- | Inline code, `<autolinks>` | `LRI` … `PDI` around the whole span |
- | A table row | the same, cell by cell; pipes and the delimiter row stay |
- Left exactly as written: fenced code blocks, HTML lines, link targets, bare
- URLs and emails (so they still become links), and lines that are mostly English.
- List markers, quote markers, heading hashes, task boxes and hard line breaks stay
- where Markdown expects them.
- ### Install
- At the prompt of a Claude Code terminal session:
- ```
- /plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
- ```
- Answer `y` to add the marketplace, then pick a scope (user scope is first).
- From a shell:
- ```bash
- claude plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
- ```
- An older Claude Code answers `unknown option '--marketplace'`. Then add the
- marketplace first, or run `claude update`:
- ```bash
- claude plugin marketplace add Rozucci/Claude-RTL-Fix
- ```
- ```bash
- claude plugin install rtl-fix@claude-rtl-fix
- ```
- In the desktop app, where `/plugin` does not run: click **+** next to the prompt
- box, then **Plugins**, **Add marketplace** with `Rozucci/Claude-RTL-Fix`,
- then **Add plugin**. A mod installed from a terminal at the user scope also loads
- in the desktop app's Code tab.
- ### Use
- It works on its own once installed. Type `/rtl` to turn it off or on again.
- ### Develop
- ```bash
- claude plugin validate claude-code-mod/rtl-fix
- ```
- ```bash
- claude plugin test claude-code-mod/rtl-fix
- ```
- To run it from this folder: `claude --plugin-dir claude-code-mod/rtl-fix`.
- The engine is one file, [`hooks/bidi.ts`](claude-code-mod/rtl-fix/hooks/bidi.ts),
- with no dependencies, so it can be reused in a browser extension or anywhere
- else that draws Markdown.
- The demo above is made from the engine's real output:
- `scripts/make-demo.sh` (macOS, needs Google Chrome, bun and ffmpeg).
- ### Known limits
- - **Terminal.** Not checked by eye yet. The marks are standard Unicode, so how
- they look depends on your terminal's own bidi support. Lines stay flush left
- there: the mod API offers `dir="rtl"` only on plain `Text`, not on a rendered
- Markdown reply.
- - **Desktop app alignment** is right, lines that start with English included
- (checked by eye with `/rtl` off and on).
- - **Table columns** keep left-to-right order; only the text inside each cell is
- fixed.
- - **Fonts** can't be changed by a mod: the theme API sets colors and a backdrop
- only.
- - A line with more English words than right-to-left ones is treated as English
- and left alone, for example `Say שלום to the new build`.
- - Indented (4-space) code blocks outside lists are not detected; fenced blocks are.
- ### Roadmap
- 1. Claude Code mod (this repository) — v0.2.0.
- 2. Browser extension for claude.ai, reusing the same engine. In a browser it can
- also give right-to-left text its own font (CSS `unicode-range`), which a mod
- can't.
- 3. A companion writing skill for the model.
- 4. An issue report to Anthropic with this test corpus.
- ### Contributing
- A line in your language that still draws wrong is the most useful thing you can
- send: open an issue with the text as Claude wrote it and a screenshot.
- ### License
- [MIT](LICENSE)
- ---
- <div dir="rtl">
- ## فارسی
- ### مشکل
- متن زبانهای راستبهچپ معمولاً پر از کلمهٔ انگلیسی، کد، عدد و واحد است.
- رابطهای Claude این متن را با الگوریتم سادهٔ bidi یونیکد میچینند و در همهٔ
- زبانهای راستبهچپ به یک شکل خراب میشود:
- - سطری که با کلمهٔ انگلیسی شروع شود چپبهراست چیده میشود؛ نقطهاش به سر دیگر
- سطر میپرد و سطر سمت اشتباه مینشیند.
- - عدد و واحد برعکس میشوند: `12.5 USD` به شکل `USD 12.5` و `25°C` به شکل `C°25`.
- - پرانتز و نقطه کنار کلمههای انگلیسی جابهجا میشوند.
- اپ دسکتاپ Claude خودش جهت هر پاراگراف را از اولین حرفش تشخیص میدهد، برای همین
- سطری که با کلمهٔ فارسی شروع شود معمولاً درست دیده میشود. ولی موارد بالا هنوز
- خراباند. ویدیو و تصویر مقایسه بالای صفحه و در بخش انگلیسی هست.
- ### زبانها
- افزونه روی حروف کار میکند، نه روی فهرست زبانها؛ پس همهٔ خطهای راستبهچپ را
- پوشش میدهد:
- - **خط عربی:** فارسی، عربی، اردو، پشتو، کردی سورانی، سندی، اویغوری و …
- - **خط عبری:** عبری و ییدیش
- - **خطهای دیگر:** سریانی، ثانا (دیوهی/مالدیوی)، اِنکو، ادلام، سامری، مندایی و حنیفی روهینگیا
- رقمهای لاتین، عربی (٠-٩) و فارسی (۰-۹) هر سه پشتیبانی میشوند.
- ### این افزونه چه میکند
- `rtl-fix` یک mod برای Claude Code است و **فقط نمایش** را عوض میکند. پیام
- ذخیرهشده، چیزی که مدل میخواند و چیزی که کپی میکنید دقیقاً همان میماند که
- نوشته شده.
- پیش از نمایش هر پیام، نشانههای نامرئی جهت یونیکد اضافه میکند:
- - دور هر سطری که بیشترش راستبهچپ است: `RLM` + `RLI` … `PDI`
- - دور هر تکهٔ لاتین داخل آن (مثل `Claude Code`، `12.5 USD`، `f(x)`): `LRI` … `PDI`
- - دور کد درونخطی و لینکهای `<…>`: `LRI` … `PDI` روی کل تکه
- - در جدولها همین کار خانهبهخانه انجام میشود و خطهای `|` دست نمیخورند.
- بلوکهای کد، سطرهای HTML، مقصد لینکها، آدرسهای اینترنتی و ایمیلها (تا
- همچنان لینک شوند) و سطرهایی که بیشترشان انگلیسی است، دستنخورده میمانند.
- نشانهٔ فهرست، نقلقول، تیتر، چکباکس و شکستن سطر سر جای خودشان میمانند.
- ### نصب
- در خط فرمان یک جلسهٔ Claude Code در ترمینال:
- </div>
- ```
- /plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
- ```
- <div dir="rtl">
- برای افزودن marketplace حرف `y` را بزنید و بعد محدوده را انتخاب کنید (اولی،
- یعنی user، پیشنهاد میشود).
- از shell:
- </div>
- ```bash
- claude plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
- ```
- <div dir="rtl">
- نسخههای قدیمی Claude Code جواب میدهند `unknown option '--marketplace'`. در این
- حالت اول marketplace را اضافه کنید، یا `claude update` را بزنید:
- </div>
- ```bash
- claude plugin marketplace add Rozucci/Claude-RTL-Fix
- ```
- ```bash
- claude plugin install rtl-fix@claude-rtl-fix
- ```
- <div dir="rtl">
- در اپ دسکتاپ، که `/plugin` در آن اجرا نمیشود: روی **+** کنار جعبهٔ پیام بزنید،
- بعد **Plugins**، بعد **Add marketplace** با `Rozucci/Claude-RTL-Fix` و
- در آخر **Add plugin**. افزونهای که از ترمینال در محدودهٔ user نصب شود، در تب
- Code اپ دسکتاپ هم بار میشود.
- ### استفاده
- بعد از نصب خودش کار میکند. با `/rtl` خاموش و دوباره روشنش کنید.
- ### محدودیتهای فعلی
- - **ترمینال:** هنوز با چشم بررسی نشده. نشانهها یونیکد استاندارد هستند و نتیجه
- به پشتیبانی خود ترمینال از متن دوجهته بستگی دارد. سطرها آنجا چپچین میمانند،
- چون API افزونهها `dir="rtl"` را فقط برای متن ساده دارد، نه برای پاسخ Markdown.
- - **چینش در اپ دسکتاپ** درست و راستچین است، حتی سطری که با انگلیسی شروع میشود
- (با چشم و با خاموش و روشن کردن `/rtl` بررسی شد).
- - **ستونهای جدول** همچنان از چپ به راست چیده میشوند؛ فقط متن داخل هر خانه
- درست میشود.
- - **فونت** را افزونه نمیتواند عوض کند؛ API ظاهر فقط رنگ و پسزمینه را میگیرد.
- - سطری که کلمههای انگلیسیاش بیشتر از کلمههای راستبهچپ باشد، انگلیسی حساب
- میشود و دست نمیخورد.
- - بلوک کد تورفته (چهار فاصله) بیرون از فهرستها تشخیص داده نمیشود؛ بلوکهای
- ` ``` ` تشخیص داده میشوند.
- ### نقشهٔ راه
- 1. افزونهٔ Claude Code (همین مخزن) — نسخهٔ 0.2.0
- 2. افزونهٔ مرورگر برای claude.ai با همین موتور؛ در مرورگر میتواند برای متن
- راستبهچپ فونت جدا هم بگذارد (با `unicode-range` در CSS)، کاری که از mod
- برنمیآید.
- 3. یک skill نوشتاری همراه برای مدل
- 4. گزارش مشکل به Anthropic همراه با همین نمونههای آزمون
- ### مشارکت
- اگر سطری به زبان شما هنوز خراب نمایش داده میشود، یک issue باز کنید و متن را
- همانطور که Claude نوشته، همراه با یک اسکرینشات بفرستید.
- ### مجوز
- [MIT](LICENSE)
- </div>
- ---
- <div dir="rtl">
- ## العربية
- عندما يحتوي ردّ Claude بالعربية على كلمات إنجليزية أو شيفرة أو أرقام مع وحدات،
- تظهر الأسطر بترتيب خاطئ: السطر الذي يبدأ بكلمة إنجليزية يُعرض من اليسار إلى
- اليمين، وتنقلب الأرقام مع وحداتها (`12.5 USD` تظهر `USD 12.5`).
- `rtl-fix` إضافة (mod) لـ Claude Code تضيف علامات اتجاه يونيكود غير مرئية قبل عرض
- كل رسالة. **العرض فقط هو ما يتغيّر**: الرسالة المحفوظة وما يقرؤه النموذج وما
- تنسخه يبقى كما كُتب. تعمل مع العربية والفارسية والأردية والعبرية وكل لغة تُكتب
- من اليمين إلى اليسار، ومع الأرقام الهندية (٠-٩).
- **التثبيت** في جلسة Claude Code في الطرفية:
- </div>
- ```
- /plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
- ```
- <div dir="rtl">
- اكتب `/rtl` لإيقافها أو تشغيلها. التفاصيل الكاملة في [القسم الإنجليزي](#english).
- </div>
- ---
- <div dir="rtl">
- ## עברית
- כשתשובה של Claude בעברית כוללת מילים באנגלית, קוד או מספרים עם יחידות, השורות
- מוצגות בסדר שגוי: שורה שמתחילה במילה באנגלית מוצגת משמאל לימין, ומספרים עם
- יחידות מתהפכים (`12.5 USD` מוצג כ־`USD 12.5`).
- `rtl-fix` הוא מוד (mod) ל־Claude Code שמוסיף סימני כיווניות בלתי נראים של Unicode
- לפני שכל הודעה מוצגת. **רק התצוגה משתנה**: ההודעה השמורה, מה שהמודל קורא ומה
- שאתם מעתיקים נשארים בדיוק כפי שנכתבו. הוא עובד עם עברית, ערבית, פרסית, אורדו
- וכל שפה שנכתבת מימין לשמאל.
- **התקנה** בסשן של Claude Code בטרמינל:
- </div>
- ```
- /plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
- ```
- <div dir="rtl">
- הקלידו `/rtl` כדי לכבות או להדליק אותו. הפרטים המלאים ב[חלק האנגלי](#english).
- </div>
claude-code-mod/rtl-fix/hooks/bidi.ts · Bundled script · 226 lines · 1 finding marked
- /**
- * The bidi engine: makes a Markdown text that mixes a right-to-left language
- * (Persian, Arabic, Urdu, Hebrew, or any language written in the Arabic,
- * Hebrew, Syriac, Thaana or N'Ko script) with English read in the right order.
- *
- * It works on the text itself, so any renderer benefits, with Unicode's own
- * direction marks (all invisible):
- *
- * - A line that is mostly right-to-left gets RLM + RLI ... PDI around it.
- * RLM is a strong right-to-left letter, so a renderer that picks a
- * paragraph's direction from its first strong letter (dir="auto") picks RTL.
- * RLI ... PDI lays the content out right to left even where the renderer
- * forces left-to-right, so punctuation and word order come out right.
- * - Inside such a line, every Latin run ("Claude Code", "WebGL 2", "f(x)") and
- * every inline code span is wrapped in LRI ... PDI, so it keeps its own order
- * and does not pull neighbouring punctuation across.
- *
- * - In a table row, each mostly right-to-left cell is fixed the same way; the pipes
- * and the delimiter row stay as written.
- *
- * Left untouched: fenced code blocks, HTML lines, link targets, bare URLs and
- * email addresses (so they still turn into links), and lines that are mostly
- * English.
- */
- export const LRI = ''
- Note: Usual in code (characters a sanitizer strips): Contains 7 bidirectional-override character(s), which make text display in a different order from how it's read
- Line 26 on GitHub
- export const RLI = ''
- export const PDI = ''
- export const RLM = ''
- // Letters of the right-to-left scripts: Hebrew (Hebrew, Yiddish), Arabic
- // (Arabic, Persian, Urdu, Pashto, Kurdish, Sindhi, Uyghur ...), Syriac, Thaana
- // (Dhivehi), N'Ko, Samaritan, Mandaic, Hanifi Rohingya and Adlam (Fula).
- const RTL_LETTER =
- '\\u05D0-\\u05EA\\u05EF-\\u05F2' + // Hebrew
- '\\u0620-\\u064A\\u066E-\\u06D3\\u06D5\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF' + // Arabic
- '\\u0710-\\u072F\\u074D-\\u074F' + // Syriac
- '\\u0750-\\u077F' + // Arabic Supplement
- '\\u0780-\\u07A5\\u07B1' + // Thaana
- '\\u07CA-\\u07EA' + // N'Ko
- '\\u0800-\\u0815' + // Samaritan
- '\\u0840-\\u0858' + // Mandaic
- '\\u08A0-\\u08FF' + // Arabic Extended-A
- '\\uFB1D-\\uFB4F' + // Hebrew presentation forms
- '\\uFB50-\\uFDFF\\uFE70-\\uFEFC' + // Arabic presentation forms
- '\\u{10D00}-\\u{10D23}' + // Hanifi Rohingya
- '\\u{1E900}-\\u{1E943}' // Adlam
- const LATIN_LETTER = 'A-Za-z\\u00C0-\\u024F'
- // Words, not letters, decide a line's language: Hebrew and Arabic leave most
- // vowels unwritten, so their words are short next to English ones. A word
- // keeps its combining marks (vowel signs) and, in Persian, the ZWNJ inside it.
- const RTL_WORDS = new RegExp(`[${RTL_LETTER}][${RTL_LETTER}\\p{M}\\u200C]*`, 'gu')
- const LATIN_WORDS = new RegExp(`[${LATIN_LETTER}][${LATIN_LETTER}\\p{M}'’]*`, 'gu')
- const FIRST_STRONG = new RegExp(`[${RTL_LETTER}${LATIN_LETTER}]`, 'u')
- const IS_RTL = new RegExp(`[${RTL_LETTER}]`, 'u')
- // A Latin run: words that start with a Latin letter, joined by single spaces,
- // with inner punctuation kept ("node.js", "C++", "f(x)"). A number written
- // right before a Latin unit joins the run ("12.5 USD", "25°C"). Sentence
- // punctuation, emphasis underscores and an unmatched ")" at its end are left
- // outside the run.
- const DIGIT = '0-9\\u0660-\\u0669\\u06F0-\\u06F9' // Western, Arabic-Indic, Persian
- const QUANTITY = `(?:[${DIGIT}][${DIGIT}.,٫٬]*(?:[ \\u00A0]|°)?(?=[${LATIN_LETTER}]))?`
- const LATIN_WORD = `${QUANTITY}[${LATIN_LETTER}][${LATIN_LETTER}0-9'’+#/@&_.:()\\-–]*`
- const LATIN_NEXT = `[${LATIN_LETTER}0-9][${LATIN_LETTER}0-9'’+#/@&_.:()\\-–]*`
- const LATIN_RUN = new RegExp(`${LATIN_WORD}(?:[ \\u00A0]${LATIN_NEXT})*`, 'g')
- const LATIN_TRAILING = /[.:_\-–]+$/
- // Pieces of a line that must not get marks inside them.
- // 1. inline code: `x` or ``x``
- // 2. a link or image target: ](...)
- // 3. an autolink: <https://...>
- // 4. a bare URL, or a www. address
- // 5. an email address
- // Marks next to a bare URL or email would end up inside the link GFM makes of
- // it, or stop it becoming a link, so these stay exactly as written.
- const PROTECTED =
- /(`+)[\s\S]*?\1|\]\([^)]*\)|<https?:\/\/[^>]*>|(?:https?:\/\/|www\.)[^\s<>]+|[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g
- // The structural prefix of a Markdown line: indentation, block quotes, a
- // heading's hashes, a list marker and an optional task box.
- // The trailing part keeps a hard line break (two spaces, or a backslash) at
- // the very end, where Markdown looks for it.
- const PREFIX =
- /^(\s*(?:>\s?)*(?:#{1,6}\s+|[-*+]\s+(?:\[[ xX]\]\s+)?|\d{1,9}[.)]\s+)?)([\s\S]*?)(\\?\s*)$/
- const TABLE_ROW = /^\s*\|/
- const TABLE_DELIMITER = /^\s*\|?(?:\s*:?-+:?\s*\|)+\s*(?::?-+:?\s*)?$/
- const CELL = /^(\s*)([\s\S]*?)(\s*)$/
- const FENCE = /^\s{0,3}(`{3,}|~{3,})/
- const BIDI_MARK = /[--]/
- /** Strips the pieces whose letters should not decide a line's direction. */
- function withoutProtected(text: string): string {
- return text.replace(PROTECTED, ' ')
- }
- /** True when a line of text should read right to left. */
- export function isRtl(text: string): boolean {
- const plain = withoutProtected(text)
- const rtl = plain.match(RTL_WORDS)?.length ?? 0
- if (rtl === 0) return false
- const latin = plain.match(LATIN_WORDS)?.length ?? 0
- const first = FIRST_STRONG.exec(plain)?.[0] ?? ''
- return rtl >= latin || IS_RTL.test(first)
- }
- /** Splits a run into what to isolate and what to leave after it. */
- function splitTrailing(run: string): [string, string] {
- let core = run
- let trailing = ''
- for (;;) {
- const punctuation = LATIN_TRAILING.exec(core)?.[0] ?? ''
- if (punctuation) {
- core = core.slice(0, -punctuation.length)
- trailing = punctuation + trailing
- continue
- }
- // "(با Node 26)": the ")" closes a bracket opened outside the run.
- const opened = core.split('(').length - 1
- const closed = core.split(')').length - 1
- if (core.endsWith(')') && closed > opened) {
- core = core.slice(0, -1)
- trailing = `)${trailing}`
- continue
- }
- return [core, trailing]
- }
- }
- /** Wraps the Latin runs of a plain (unprotected) stretch of text. */
- function isolateLatin(text: string): string {
- return text.replace(LATIN_RUN, run => {
- const [core, trailing] = splitTrailing(run)
- if (!core) return run
- return `${LRI}${core}${PDI}${trailing}`
- })
- }
- /** The content of one RTL line, with its Latin runs and code isolated. */
- function isolateContent(content: string): string {
- let out = ''
- let last = 0
- for (const match of content.matchAll(PROTECTED)) {
- const start = match.index ?? 0
- out += isolateLatin(content.slice(last, start))
- const piece = match[0]
- // Inline code and <autolinks> are isolated as a whole; link targets, bare
- // URLs and emails stay exactly as written, so the parser still reads them.
- const isWhole = piece.startsWith('`') || piece.startsWith('<')
- out += isWhole ? `${LRI}${piece}${PDI}` : piece
- last = start + piece.length
- }
- return out + isolateLatin(content.slice(last))
- }
- /** Wraps one stretch of text that should read right to left. */
- function wrapRtl(content: string): string {
- return `${RLM}${RLI}${isolateContent(content)}${PDI}`
- }
- /** Fixes each mostly right-to-left cell of a table row; pipes stay as written. */
- function fixTableRow(line: string): string {
- if (TABLE_DELIMITER.test(line)) return line
- // Split on unescaped pipes; the pieces between them are the cells.
- return line
- .split(/(?<!\\)\|/)
- .map(cell => {
- const [, lead = '', content = '', trail = ''] = CELL.exec(cell) ?? []
- if (!content || !isRtl(content)) return cell
- return `${lead}${wrapRtl(content)}${trail}`
- })
- .join('|')
- }
- /** Fixes one Markdown line (outside a code fence). */
- export function fixLine(line: string): string {
- if (BIDI_MARK.test(line)) return line // already fixed, or marked by hand
- if (/^\s*</.test(line)) return line // HTML
- if (TABLE_ROW.test(line)) return fixTableRow(line)
- const parts = PREFIX.exec(line)
- if (!parts) return line
- const [, prefix = '', content = '', trailing = ''] = parts
- if (!content || !isRtl(content)) return line
- return `${prefix}${wrapRtl(content)}${trailing}`
- }
- /** Fixes a whole Markdown text, line by line, skipping fenced code. */
- export function fixBidi(markdown: string): string {
- if (!IS_RTL.test(markdown)) return markdown
- let fence: string | null = null
- return markdown
- .split('\n')
- .map(line => {
- const opener = FENCE.exec(line)?.[1]
- if (fence !== null) {
- if (opener && opener[0] === fence[0] && opener.length >= fence.length) fence = null
- return line
- }
- if (opener) {
- fence = opener
- return line
- }
- return fixLine(line)
- })
- .join('\n')
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.