Skip to main content

Right-to-left text in an ASP.NET Core rich text editor

The editor with a formatted document

Arabic, Hebrew, Persian and Urdu run right to left. An editor that cannot say so produces text with its punctuation on the wrong side. In RichTextBox, each paragraph can have its own direction, which is saved with it.

Add the buttons

<richtextbox name="Body" toolbar="{bold,italic}|{ltr,rtl}|{undo,redo}"></richtextbox>

Put the caret in a paragraph and press rtl or ltr. The office toolbar already has them. They work from the release after 1.0.24; before that, use the calls below.

Set the direction from code

Each editor has these methods:

var editor = window.richTextBoxEditors.Body;

editor.setBaseDirection("rtl");     // the document, while editing
editor.setTextDirection("rtl");     // the selected paragraphs
editor.toggleTextDirection();
editor.autoDetectTextDirection();   // decide from the text itself
editor.getBaseDirection();

To follow the page's language, call setBaseDirection as the page loads:

<richtextbox id="Body" name="Body" toolbar="default"></richtextbox>
<script>
    window.addEventListener("load", function () {
        if (document.documentElement.lang === "ar") {
            window.richTextBoxEditors.Body.setBaseDirection("rtl");
        }
    });
</script>

What is saved

A paragraph's direction is stored in the HTML as a dir attribute, so it stays when the document is saved and shown again:

<p dir="rtl">...</p>

Changing it also swaps an explicit left or right alignment, the way Word does. The document's base direction is not in the saved HTML, so set it each time the page loads, as above, and put dir on the element that shows the content.

Automatic detection

Automatic detection looks at a paragraph's first strongly directional character, the same rule browsers use for dir="auto". That suits sites where people may write in either direction.

Show it on your page

Your page's CSS should use logical properties such as margin-inline-start, or list markers and quote borders will stay on the left. Also check that the sanitizer policy you use keeps dir.

Read next