Skip to content
Back to search

claude-rtl-fix

MarketplaceWorks with Claude CodeGitHub

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.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/rozucci--claude-rtl-fix/badge.svg)](/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
  1. {
  2. "name": "claude-rtl-fix",
  3. "owner": {
  4. "name": "Rozucci"
  5. },
  6. "metadata": {
  7. "description": "Right-to-left (Persian, Arabic, Hebrew, Urdu ...) text fixes for Claude's interfaces"
  8. },
  9. "plugins": [
  10. {
  11. "name": "rtl-fix",
  12. "source": "./claude-code-mod/rtl-fix",
  13. "description": "Fixes mixed right-to-left (Persian, Arabic, Hebrew, Urdu ...) and English text in Claude Code's transcript"
  14. }
  15. ]
  16. }
README.md · README · 345 lines
  1. # Claude-RTL-Fix
  2. Fixes mixed right-to-left and English text in Claude's interfaces: Persian,
  3. Arabic, Hebrew, Urdu and every other language written right to left.
  4. رفع به‌هم‌ریختگی متن راست‌به‌چپ و انگلیسی در رابط‌های Claude، برای فارسی، عربی، عبری، اردو و هر زبان راست‌به‌چپ دیگر.
  5. ![The same Persian, Arabic and Hebrew replies with rtl-fix off and on](docs/demo%20rtl-fix%20off%20and%20on.gif)
  6. [English](#english) · [فارسی](#فارسی) · [العربية](#العربية) · [עברית](#עברית)
  7. ---
  8. ## English
  9. ### The problem
  10. Right-to-left languages are usually written with English words, code, numbers
  11. and units mixed in. Claude's interfaces lay such text out with the plain Unicode
  12. bidi algorithm, and it breaks in the same ways in every right-to-left language:
  13. - A line that starts with an English word is laid out left to right, so its
  14. period jumps to the wrong end and the line sits on the wrong side.
  15. - A number with a unit is reversed: `12.5 USD` shows as `USD 12.5`, `25°C` as
  16. `C°25`, `100 km/h` as `km/h 100`.
  17. - Brackets and dots next to English words move across the line.
  18. The Claude desktop app already picks each paragraph's direction from its first
  19. letter, so lines that start with a right-to-left word mostly look fine. The
  20. cases above still break. The same text, drawn three ways:
  21. ![Raw text, raw text with dir=auto, and text through rtl-fix](docs/comparison%20raw%20vs%20dir-auto%20vs%20rtl-fix.jpg)
  22. ### Languages
  23. It works on the letters, not on a list of languages, so every right-to-left
  24. script is covered:
  25. | Script | Languages | A line it fixes |
  26. | --- | --- | --- |
  27. | Arabic | Persian, Arabic, Urdu, Pashto, Kurdish (Sorani), Sindhi, Uyghur … | `Astro یک فریم‌ورک است.` · `Python لغة برمجة شائعة.` · `یہ منصوبہ Claude Code سے بنایا گیا۔` |
  28. | Hebrew | Hebrew, Yiddish | `React היא ספרייה של JavaScript.` |
  29. | Syriac, Thaana, N'Ko, Adlam, Samaritan, Mandaic, Hanifi Rohingya | Syriac, Dhivehi, Manding, Fula, Rohingya … | detected as right to left |
  30. Western (`0-9`), Arabic-Indic (`٠-٩`) and Persian (`۰-۹`) digits are all
  31. handled. The Persian, Arabic, Hebrew and Urdu cases are in the test suite; the
  32. other scripts are tested for detection.
  33. ### What this does
  34. `rtl-fix` is a Claude Code mod. It changes **only what is drawn**: the stored
  35. message, what the model reads and what you copy stay exactly as written.
  36. It adds invisible Unicode direction marks to each message before it is drawn:
  37. | Where | What it adds |
  38. | --- | --- |
  39. | 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 |
  40. | A Latin run inside it (`Claude Code`, `12.5 USD`, `f(x)`) | `LRI` … `PDI` |
  41. | Inline code, `<autolinks>` | `LRI` … `PDI` around the whole span |
  42. | A table row | the same, cell by cell; pipes and the delimiter row stay |
  43. Left exactly as written: fenced code blocks, HTML lines, link targets, bare
  44. URLs and emails (so they still become links), and lines that are mostly English.
  45. List markers, quote markers, heading hashes, task boxes and hard line breaks stay
  46. where Markdown expects them.
  47. ### Install
  48. At the prompt of a Claude Code terminal session:
  49. ```
  50. /plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
  51. ```
  52. Answer `y` to add the marketplace, then pick a scope (user scope is first).
  53. From a shell:
  54. ```bash
  55. claude plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
  56. ```
  57. An older Claude Code answers `unknown option '--marketplace'`. Then add the
  58. marketplace first, or run `claude update`:
  59. ```bash
  60. claude plugin marketplace add Rozucci/Claude-RTL-Fix
  61. ```
  62. ```bash
  63. claude plugin install rtl-fix@claude-rtl-fix
  64. ```
  65. In the desktop app, where `/plugin` does not run: click **+** next to the prompt
  66. box, then **Plugins**, **Add marketplace** with `Rozucci/Claude-RTL-Fix`,
  67. then **Add plugin**. A mod installed from a terminal at the user scope also loads
  68. in the desktop app's Code tab.
  69. ### Use
  70. It works on its own once installed. Type `/rtl` to turn it off or on again.
  71. ### Develop
  72. ```bash
  73. claude plugin validate claude-code-mod/rtl-fix
  74. ```
  75. ```bash
  76. claude plugin test claude-code-mod/rtl-fix
  77. ```
  78. To run it from this folder: `claude --plugin-dir claude-code-mod/rtl-fix`.
  79. The engine is one file, [`hooks/bidi.ts`](claude-code-mod/rtl-fix/hooks/bidi.ts),
  80. with no dependencies, so it can be reused in a browser extension or anywhere
  81. else that draws Markdown.
  82. The demo above is made from the engine's real output:
  83. `scripts/make-demo.sh` (macOS, needs Google Chrome, bun and ffmpeg).
  84. ### Known limits
  85. - **Terminal.** Not checked by eye yet. The marks are standard Unicode, so how
  86. they look depends on your terminal's own bidi support. Lines stay flush left
  87. there: the mod API offers `dir="rtl"` only on plain `Text`, not on a rendered
  88. Markdown reply.
  89. - **Desktop app alignment** is right, lines that start with English included
  90. (checked by eye with `/rtl` off and on).
  91. - **Table columns** keep left-to-right order; only the text inside each cell is
  92. fixed.
  93. - **Fonts** can't be changed by a mod: the theme API sets colors and a backdrop
  94. only.
  95. - A line with more English words than right-to-left ones is treated as English
  96. and left alone, for example `Say שלום to the new build`.
  97. - Indented (4-space) code blocks outside lists are not detected; fenced blocks are.
  98. ### Roadmap
  99. 1. Claude Code mod (this repository) — v0.2.0.
  100. 2. Browser extension for claude.ai, reusing the same engine. In a browser it can
  101. also give right-to-left text its own font (CSS `unicode-range`), which a mod
  102. can't.
  103. 3. A companion writing skill for the model.
  104. 4. An issue report to Anthropic with this test corpus.
  105. ### Contributing
  106. A line in your language that still draws wrong is the most useful thing you can
  107. send: open an issue with the text as Claude wrote it and a screenshot.
  108. ### License
  109. [MIT](LICENSE)
  110. ---
  111. <div dir="rtl">
  112. ## فارسی
  113. ### مشکل
  114. متن زبان‌های راست‌به‌چپ معمولاً پر از کلمهٔ انگلیسی، کد، عدد و واحد است.
  115. رابط‌های Claude این متن را با الگوریتم سادهٔ bidi یونیکد می‌چینند و در همهٔ
  116. زبان‌های راست‌به‌چپ به یک شکل خراب می‌شود:
  117. - سطری که با کلمهٔ انگلیسی شروع شود چپ‌به‌راست چیده می‌شود؛ نقطه‌اش به سر دیگر
  118. سطر می‌پرد و سطر سمت اشتباه می‌نشیند.
  119. - عدد و واحد برعکس می‌شوند: ‏`12.5 USD` به شکل ‏`USD 12.5` و ‏`25°C` به شکل ‏`C°25`.
  120. - پرانتز و نقطه کنار کلمه‌های انگلیسی جابه‌جا می‌شوند.
  121. اپ دسکتاپ Claude خودش جهت هر پاراگراف را از اولین حرفش تشخیص می‌دهد، برای همین
  122. سطری که با کلمهٔ فارسی شروع شود معمولاً درست دیده می‌شود. ولی موارد بالا هنوز
  123. خراب‌اند. ویدیو و تصویر مقایسه بالای صفحه و در بخش انگلیسی هست.
  124. ### زبان‌ها
  125. افزونه روی حروف کار می‌کند، نه روی فهرست زبان‌ها؛ پس همهٔ خط‌های راست‌به‌چپ را
  126. پوشش می‌دهد:
  127. - **خط عربی:** فارسی، عربی، اردو، پشتو، کردی سورانی، سندی، اویغوری و …
  128. - **خط عبری:** عبری و ییدیش
  129. - **خط‌های دیگر:** سریانی، ثانا (دیوهی/مالدیوی)، اِن‌کو، ادلام، سامری، مندایی و حنیفی روهینگیا
  130. رقم‌های لاتین، عربی (٠-٩) و فارسی (۰-۹) هر سه پشتیبانی می‌شوند.
  131. ### این افزونه چه می‌کند
  132. ‏`rtl-fix` یک mod برای Claude Code است و **فقط نمایش** را عوض می‌کند. پیام
  133. ذخیره‌شده، چیزی که مدل می‌خواند و چیزی که کپی می‌کنید دقیقاً همان می‌ماند که
  134. نوشته شده.
  135. پیش از نمایش هر پیام، نشانه‌های نامرئی جهت یونیکد اضافه می‌کند:
  136. - دور هر سطری که بیشترش راست‌به‌چپ است: ‏`RLM` + `RLI` … `PDI`
  137. - دور هر تکهٔ لاتین داخل آن (مثل ‏`Claude Code`، ‏`12.5 USD`، ‏`f(x)`): ‏`LRI` … `PDI`
  138. - دور کد درون‌خطی و لینک‌های `<…>`: ‏`LRI` … `PDI` روی کل تکه
  139. - در جدول‌ها همین کار خانه‌به‌خانه انجام می‌شود و خط‌های `|` دست نمی‌خورند.
  140. بلوک‌های کد، سطرهای HTML، مقصد لینک‌ها، آدرس‌های اینترنتی و ایمیل‌ها (تا
  141. همچنان لینک شوند) و سطرهایی که بیشترشان انگلیسی است، دست‌نخورده می‌مانند.
  142. نشانهٔ فهرست، نقل‌قول، تیتر، چک‌باکس و شکستن سطر سر جای خودشان می‌مانند.
  143. ### نصب
  144. در خط فرمان یک جلسهٔ Claude Code در ترمینال:
  145. </div>
  146. ```
  147. /plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
  148. ```
  149. <div dir="rtl">
  150. برای افزودن marketplace حرف `y` را بزنید و بعد محدوده را انتخاب کنید (اولی،
  151. یعنی user، پیشنهاد می‌شود).
  152. از shell:
  153. </div>
  154. ```bash
  155. claude plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
  156. ```
  157. <div dir="rtl">
  158. نسخه‌های قدیمی Claude Code جواب می‌دهند `unknown option '--marketplace'`. در این
  159. حالت اول marketplace را اضافه کنید، یا `claude update` را بزنید:
  160. </div>
  161. ```bash
  162. claude plugin marketplace add Rozucci/Claude-RTL-Fix
  163. ```
  164. ```bash
  165. claude plugin install rtl-fix@claude-rtl-fix
  166. ```
  167. <div dir="rtl">
  168. در اپ دسکتاپ، که `/plugin` در آن اجرا نمی‌شود: روی **+** کنار جعبهٔ پیام بزنید،
  169. بعد **Plugins**، بعد **Add marketplace** با `Rozucci/Claude-RTL-Fix` و
  170. در آخر **Add plugin**. افزونه‌ای که از ترمینال در محدودهٔ user نصب شود، در تب
  171. Code اپ دسکتاپ هم بار می‌شود.
  172. ### استفاده
  173. بعد از نصب خودش کار می‌کند. با `/rtl` خاموش و دوباره روشنش کنید.
  174. ### محدودیت‌های فعلی
  175. - **ترمینال:** هنوز با چشم بررسی نشده. نشانه‌ها یونیکد استاندارد هستند و نتیجه
  176. به پشتیبانی خود ترمینال از متن دوجهته بستگی دارد. سطرها آنجا چپ‌چین می‌مانند،
  177. چون API افزونه‌ها `dir="rtl"` را فقط برای متن ساده دارد، نه برای پاسخ Markdown.
  178. - **چینش در اپ دسکتاپ** درست و راست‌چین است، حتی سطری که با انگلیسی شروع می‌شود
  179. (با چشم و با خاموش و روشن کردن `/rtl` بررسی شد).
  180. - **ستون‌های جدول** همچنان از چپ به راست چیده می‌شوند؛ فقط متن داخل هر خانه
  181. درست می‌شود.
  182. - **فونت** را افزونه نمی‌تواند عوض کند؛ API ظاهر فقط رنگ و پس‌زمینه را می‌گیرد.
  183. - سطری که کلمه‌های انگلیسی‌اش بیشتر از کلمه‌های راست‌به‌چپ باشد، انگلیسی حساب
  184. می‌شود و دست نمی‌خورد.
  185. - بلوک کد تورفته (چهار فاصله) بیرون از فهرست‌ها تشخیص داده نمی‌شود؛ بلوک‌های
  186. ` ``` ` تشخیص داده می‌شوند.
  187. ### نقشهٔ راه
  188. 1. افزونهٔ Claude Code (همین مخزن) — نسخهٔ 0.2.0
  189. 2. افزونهٔ مرورگر برای claude.ai با همین موتور؛ در مرورگر می‌تواند برای متن
  190. راست‌به‌چپ فونت جدا هم بگذارد (با `unicode-range` در CSS)، کاری که از mod
  191. برنمی‌آید.
  192. 3. یک skill نوشتاری همراه برای مدل
  193. 4. گزارش مشکل به Anthropic همراه با همین نمونه‌های آزمون
  194. ### مشارکت
  195. اگر سطری به زبان شما هنوز خراب نمایش داده می‌شود، یک issue باز کنید و متن را
  196. همان‌طور که Claude نوشته، همراه با یک اسکرین‌شات بفرستید.
  197. ### مجوز
  198. ‏[MIT](LICENSE)
  199. </div>
  200. ---
  201. <div dir="rtl">
  202. ## العربية
  203. عندما يحتوي ردّ Claude بالعربية على كلمات إنجليزية أو شيفرة أو أرقام مع وحدات،
  204. تظهر الأسطر بترتيب خاطئ: السطر الذي يبدأ بكلمة إنجليزية يُعرض من اليسار إلى
  205. اليمين، وتنقلب الأرقام مع وحداتها (‏`12.5 USD` تظهر ‏`USD 12.5`).
  206. ‏`rtl-fix` إضافة (mod) لـ Claude Code تضيف علامات اتجاه يونيكود غير مرئية قبل عرض
  207. كل رسالة. **العرض فقط هو ما يتغيّر**: الرسالة المحفوظة وما يقرؤه النموذج وما
  208. تنسخه يبقى كما كُتب. تعمل مع العربية والفارسية والأردية والعبرية وكل لغة تُكتب
  209. من اليمين إلى اليسار، ومع الأرقام الهندية (٠-٩).
  210. **التثبيت** في جلسة Claude Code في الطرفية:
  211. </div>
  212. ```
  213. /plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
  214. ```
  215. <div dir="rtl">
  216. اكتب `/rtl` لإيقافها أو تشغيلها. التفاصيل الكاملة في [القسم الإنجليزي](#english).
  217. </div>
  218. ---
  219. <div dir="rtl">
  220. ## עברית
  221. כשתשובה של Claude בעברית כוללת מילים באנגלית, קוד או מספרים עם יחידות, השורות
  222. מוצגות בסדר שגוי: שורה שמתחילה במילה באנגלית מוצגת משמאל לימין, ומספרים עם
  223. יחידות מתהפכים (‏`12.5 USD` מוצג כ־‏`USD 12.5`).
  224. ‏`rtl-fix` הוא מוד (mod) ל־Claude Code שמוסיף סימני כיווניות בלתי נראים של Unicode
  225. לפני שכל הודעה מוצגת. **רק התצוגה משתנה**: ההודעה השמורה, מה שהמודל קורא ומה
  226. שאתם מעתיקים נשארים בדיוק כפי שנכתבו. הוא עובד עם עברית, ערבית, פרסית, אורדו
  227. וכל שפה שנכתבת מימין לשמאל.
  228. **התקנה** בסשן של Claude Code בטרמינל:
  229. </div>
  230. ```
  231. /plugin install rtl-fix --marketplace Rozucci/Claude-RTL-Fix
  232. ```
  233. <div dir="rtl">
  234. הקלידו `/rtl` כדי לכבות או להדליק אותו. הפרטים המלאים ב[חלק האנגלי](#english).
  235. </div>
claude-code-mod/rtl-fix/hooks/bidi.ts · Bundled script · 226 lines · 1 finding marked
  1. /**
  2. * The bidi engine: makes a Markdown text that mixes a right-to-left language
  3. * (Persian, Arabic, Urdu, Hebrew, or any language written in the Arabic,
  4. * Hebrew, Syriac, Thaana or N'Ko script) with English read in the right order.
  5. *
  6. * It works on the text itself, so any renderer benefits, with Unicode's own
  7. * direction marks (all invisible):
  8. *
  9. * - A line that is mostly right-to-left gets RLM + RLI ... PDI around it.
  10. * RLM is a strong right-to-left letter, so a renderer that picks a
  11. * paragraph's direction from its first strong letter (dir="auto") picks RTL.
  12. * RLI ... PDI lays the content out right to left even where the renderer
  13. * forces left-to-right, so punctuation and word order come out right.
  14. * - Inside such a line, every Latin run ("Claude Code", "WebGL 2", "f(x)") and
  15. * every inline code span is wrapped in LRI ... PDI, so it keeps its own order
  16. * and does not pull neighbouring punctuation across.
  17. *
  18. * - In a table row, each mostly right-to-left cell is fixed the same way; the pipes
  19. * and the delimiter row stay as written.
  20. *
  21. * Left untouched: fenced code blocks, HTML lines, link targets, bare URLs and
  22. * email addresses (so they still turn into links), and lines that are mostly
  23. * English.
  24. */
  25. 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
  26. export const RLI = '⁧'
  27. export const PDI = '⁩'
  28. export const RLM = '‏'
  29. // Letters of the right-to-left scripts: Hebrew (Hebrew, Yiddish), Arabic
  30. // (Arabic, Persian, Urdu, Pashto, Kurdish, Sindhi, Uyghur ...), Syriac, Thaana
  31. // (Dhivehi), N'Ko, Samaritan, Mandaic, Hanifi Rohingya and Adlam (Fula).
  32. const RTL_LETTER =
  33. '\\u05D0-\\u05EA\\u05EF-\\u05F2' + // Hebrew
  34. '\\u0620-\\u064A\\u066E-\\u06D3\\u06D5\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF' + // Arabic
  35. '\\u0710-\\u072F\\u074D-\\u074F' + // Syriac
  36. '\\u0750-\\u077F' + // Arabic Supplement
  37. '\\u0780-\\u07A5\\u07B1' + // Thaana
  38. '\\u07CA-\\u07EA' + // N'Ko
  39. '\\u0800-\\u0815' + // Samaritan
  40. '\\u0840-\\u0858' + // Mandaic
  41. '\\u08A0-\\u08FF' + // Arabic Extended-A
  42. '\\uFB1D-\\uFB4F' + // Hebrew presentation forms
  43. '\\uFB50-\\uFDFF\\uFE70-\\uFEFC' + // Arabic presentation forms
  44. '\\u{10D00}-\\u{10D23}' + // Hanifi Rohingya
  45. '\\u{1E900}-\\u{1E943}' // Adlam
  46. const LATIN_LETTER = 'A-Za-z\\u00C0-\\u024F'
  47. // Words, not letters, decide a line's language: Hebrew and Arabic leave most
  48. // vowels unwritten, so their words are short next to English ones. A word
  49. // keeps its combining marks (vowel signs) and, in Persian, the ZWNJ inside it.
  50. const RTL_WORDS = new RegExp(`[${RTL_LETTER}][${RTL_LETTER}\\p{M}\\u200C]*`, 'gu')
  51. const LATIN_WORDS = new RegExp(`[${LATIN_LETTER}][${LATIN_LETTER}\\p{M}'’]*`, 'gu')
  52. const FIRST_STRONG = new RegExp(`[${RTL_LETTER}${LATIN_LETTER}]`, 'u')
  53. const IS_RTL = new RegExp(`[${RTL_LETTER}]`, 'u')
  54. // A Latin run: words that start with a Latin letter, joined by single spaces,
  55. // with inner punctuation kept ("node.js", "C++", "f(x)"). A number written
  56. // right before a Latin unit joins the run ("12.5 USD", "25°C"). Sentence
  57. // punctuation, emphasis underscores and an unmatched ")" at its end are left
  58. // outside the run.
  59. const DIGIT = '0-9\\u0660-\\u0669\\u06F0-\\u06F9' // Western, Arabic-Indic, Persian
  60. const QUANTITY = `(?:[${DIGIT}][${DIGIT}.,٫٬]*(?:[ \\u00A0]|°)?(?=[${LATIN_LETTER}]))?`
  61. const LATIN_WORD = `${QUANTITY}[${LATIN_LETTER}][${LATIN_LETTER}0-9'’+#/@&_.:()\\-–]*`
  62. const LATIN_NEXT = `[${LATIN_LETTER}0-9][${LATIN_LETTER}0-9'’+#/@&_.:()\\-–]*`
  63. const LATIN_RUN = new RegExp(`${LATIN_WORD}(?:[ \\u00A0]${LATIN_NEXT})*`, 'g')
  64. const LATIN_TRAILING = /[.:_\-–]+$/
  65. // Pieces of a line that must not get marks inside them.
  66. // 1. inline code: `x` or ``x``
  67. // 2. a link or image target: ](...)
  68. // 3. an autolink: <https://...>
  69. // 4. a bare URL, or a www. address
  70. // 5. an email address
  71. // Marks next to a bare URL or email would end up inside the link GFM makes of
  72. // it, or stop it becoming a link, so these stay exactly as written.
  73. const PROTECTED =
  74. /(`+)[\s\S]*?\1|\]\([^)]*\)|<https?:\/\/[^>]*>|(?:https?:\/\/|www\.)[^\s<>]+|[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g
  75. // The structural prefix of a Markdown line: indentation, block quotes, a
  76. // heading's hashes, a list marker and an optional task box.
  77. // The trailing part keeps a hard line break (two spaces, or a backslash) at
  78. // the very end, where Markdown looks for it.
  79. const PREFIX =
  80. /^(\s*(?:>\s?)*(?:#{1,6}\s+|[-*+]\s+(?:\[[ xX]\]\s+)?|\d{1,9}[.)]\s+)?)([\s\S]*?)(\\?\s*)$/
  81. const TABLE_ROW = /^\s*\|/
  82. const TABLE_DELIMITER = /^\s*\|?(?:\s*:?-+:?\s*\|)+\s*(?::?-+:?\s*)?$/
  83. const CELL = /^(\s*)([\s\S]*?)(\s*)$/
  84. const FENCE = /^\s{0,3}(`{3,}|~{3,})/
  85. const BIDI_MARK = /[⁦-⁩‎‏‪-‮]/
  86. /** Strips the pieces whose letters should not decide a line's direction. */
  87. function withoutProtected(text: string): string {
  88. return text.replace(PROTECTED, ' ')
  89. }
  90. /** True when a line of text should read right to left. */
  91. export function isRtl(text: string): boolean {
  92. const plain = withoutProtected(text)
  93. const rtl = plain.match(RTL_WORDS)?.length ?? 0
  94. if (rtl === 0) return false
  95. const latin = plain.match(LATIN_WORDS)?.length ?? 0
  96. const first = FIRST_STRONG.exec(plain)?.[0] ?? ''
  97. return rtl >= latin || IS_RTL.test(first)
  98. }
  99. /** Splits a run into what to isolate and what to leave after it. */
  100. function splitTrailing(run: string): [string, string] {
  101. let core = run
  102. let trailing = ''
  103. for (;;) {
  104. const punctuation = LATIN_TRAILING.exec(core)?.[0] ?? ''
  105. if (punctuation) {
  106. core = core.slice(0, -punctuation.length)
  107. trailing = punctuation + trailing
  108. continue
  109. }
  110. // "(با Node 26)": the ")" closes a bracket opened outside the run.
  111. const opened = core.split('(').length - 1
  112. const closed = core.split(')').length - 1
  113. if (core.endsWith(')') && closed > opened) {
  114. core = core.slice(0, -1)
  115. trailing = `)${trailing}`
  116. continue
  117. }
  118. return [core, trailing]
  119. }
  120. }
  121. /** Wraps the Latin runs of a plain (unprotected) stretch of text. */
  122. function isolateLatin(text: string): string {
  123. return text.replace(LATIN_RUN, run => {
  124. const [core, trailing] = splitTrailing(run)
  125. if (!core) return run
  126. return `${LRI}${core}${PDI}${trailing}`
  127. })
  128. }
  129. /** The content of one RTL line, with its Latin runs and code isolated. */
  130. function isolateContent(content: string): string {
  131. let out = ''
  132. let last = 0
  133. for (const match of content.matchAll(PROTECTED)) {
  134. const start = match.index ?? 0
  135. out += isolateLatin(content.slice(last, start))
  136. const piece = match[0]
  137. // Inline code and <autolinks> are isolated as a whole; link targets, bare
  138. // URLs and emails stay exactly as written, so the parser still reads them.
  139. const isWhole = piece.startsWith('`') || piece.startsWith('<')
  140. out += isWhole ? `${LRI}${piece}${PDI}` : piece
  141. last = start + piece.length
  142. }
  143. return out + isolateLatin(content.slice(last))
  144. }
  145. /** Wraps one stretch of text that should read right to left. */
  146. function wrapRtl(content: string): string {
  147. return `${RLM}${RLI}${isolateContent(content)}${PDI}`
  148. }
  149. /** Fixes each mostly right-to-left cell of a table row; pipes stay as written. */
  150. function fixTableRow(line: string): string {
  151. if (TABLE_DELIMITER.test(line)) return line
  152. // Split on unescaped pipes; the pieces between them are the cells.
  153. return line
  154. .split(/(?<!\\)\|/)
  155. .map(cell => {
  156. const [, lead = '', content = '', trail = ''] = CELL.exec(cell) ?? []
  157. if (!content || !isRtl(content)) return cell
  158. return `${lead}${wrapRtl(content)}${trail}`
  159. })
  160. .join('|')
  161. }
  162. /** Fixes one Markdown line (outside a code fence). */
  163. export function fixLine(line: string): string {
  164. if (BIDI_MARK.test(line)) return line // already fixed, or marked by hand
  165. if (/^\s*</.test(line)) return line // HTML
  166. if (TABLE_ROW.test(line)) return fixTableRow(line)
  167. const parts = PREFIX.exec(line)
  168. if (!parts) return line
  169. const [, prefix = '', content = '', trailing = ''] = parts
  170. if (!content || !isRtl(content)) return line
  171. return `${prefix}${wrapRtl(content)}${trailing}`
  172. }
  173. /** Fixes a whole Markdown text, line by line, skipping fenced code. */
  174. export function fixBidi(markdown: string): string {
  175. if (!IS_RTL.test(markdown)) return markdown
  176. let fence: string | null = null
  177. return markdown
  178. .split('\n')
  179. .map(line => {
  180. const opener = FENCE.exec(line)?.[1]
  181. if (fence !== null) {
  182. if (opener && opener[0] === fence[0] && opener.length >= fence.length) fence = null
  183. return line
  184. }
  185. if (opener) {
  186. fence = opener
  187. return line
  188. }
  189. return fixLine(line)
  190. })
  191. .join('\n')
  192. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.