Skip to main content

continuity_text/
bidi.rs

1//! Bidi (Unicode Bidirectional Algorithm) helpers.
2//!
3//! Cursor motion in this editor operates in **logical** byte order
4//! always. The bidi level of a position is consulted only by visual
5//! affordances (e.g., caret rendering hints, selection rectangles when
6//! the layout has reversed visual runs). This module exposes the
7//! minimum surface needed by those callers without dragging
8//! `unicode-bidi` into every crate.
9//!
10//! See spec §12: "Bidi text rendering for RTL scripts" and §9 cursor
11//! motion semantics.
12
13use unicode_bidi::{BidiInfo, ParagraphInfo};
14
15/// Bidi paragraph direction inferred from a string's strongly-typed
16/// characters.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ParagraphDirection {
19    /// Left-to-right paragraph base direction.
20    LeftToRight,
21    /// Right-to-left paragraph base direction.
22    RightToLeft,
23    /// No strongly-typed characters; default to LTR per UAX #9.
24    Neutral,
25}
26
27/// Compute the paragraph direction of `text`. Empty / pure-neutral
28/// strings return [`ParagraphDirection::Neutral`].
29#[must_use]
30pub fn paragraph_direction(text: &str) -> ParagraphDirection {
31    let info = BidiInfo::new(text, None);
32    if info.paragraphs.is_empty() {
33        return ParagraphDirection::Neutral;
34    }
35    let p: &ParagraphInfo = &info.paragraphs[0];
36    let level = p.level;
37    if level.is_rtl() {
38        ParagraphDirection::RightToLeft
39    } else if has_strong_ltr(text) {
40        ParagraphDirection::LeftToRight
41    } else {
42        ParagraphDirection::Neutral
43    }
44}
45
46/// Bidi level (0..=126) of the byte at `byte_offset` in `text`. Returns
47/// `None` when the offset is out of bounds. Level 0 means LTR;
48/// odd levels are RTL runs.
49#[must_use]
50pub fn level_at(text: &str, byte_offset: usize) -> Option<u8> {
51    if byte_offset > text.len() {
52        return None;
53    }
54    let info = BidiInfo::new(text, None);
55    info.levels.get(byte_offset).map(|l| l.number())
56}
57
58fn has_strong_ltr(text: &str) -> bool {
59    text.chars().any(|c| {
60        let class = unicode_bidi::bidi_class(c);
61        matches!(class, unicode_bidi::BidiClass::L)
62    })
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn empty_string_is_neutral() {
71        assert_eq!(paragraph_direction(""), ParagraphDirection::Neutral);
72    }
73
74    #[test]
75    fn pure_ascii_is_ltr() {
76        assert_eq!(
77            paragraph_direction("hello"),
78            ParagraphDirection::LeftToRight
79        );
80    }
81
82    #[test]
83    fn arabic_paragraph_is_rtl() {
84        // "Hello" in Arabic ("مرحبا").
85        assert_eq!(
86            paragraph_direction("مرحبا"),
87            ParagraphDirection::RightToLeft
88        );
89    }
90
91    #[test]
92    fn level_at_returns_run_level() {
93        let text = "hello مرحبا";
94        // ASCII prefix is level 0 (LTR).
95        assert_eq!(level_at(text, 0), Some(0));
96        // Arabic suffix is level 1 (RTL run).
97        let arabic_byte = text.find('م').unwrap();
98        let level = level_at(text, arabic_byte).unwrap();
99        assert!(level % 2 == 1, "expected RTL level, got {level}");
100    }
101
102    #[test]
103    fn out_of_bounds_returns_none() {
104        assert_eq!(level_at("abc", 999), None);
105    }
106}