Skip to main content

parley_engine/
break_overrides.rs

1// Copyright 2026 the Parley Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Overrides for line-break opportunities.
5
6use core::ops::RangeInclusive;
7
8/// Context for a potential line break opportunity between two adjacent code points.
9#[derive(Clone, Copy, Debug)]
10#[non_exhaustive]
11pub struct LineBreakContext {
12    /// The code point before the `before` code point, if any.
13    pub before_before: Option<char>,
14    /// The code point before the potential break.
15    pub before: char,
16    /// The code point after the potential break.
17    pub after: char,
18}
19
20/// Line break opportunity override.
21///
22/// Called for each adjacent pair of Unicode code points in the text, in order, except for pairs
23/// containing a mandatory break character. The [`LineBreakContext`] describes the potential break.
24///
25/// Returning:
26///    - `Some(true)`  : forces a line break opportunity between the pair
27///    - `Some(false)` : suppresses any opportunity
28///    - `None`        : defers to the default (ICU) behavior
29///
30/// Note that pairs with a mandatory break aren't soft wrap opportunities. Mandatory breaks are
31/// reported as [`Whitespace`][crate::shape::Whitespace].
32///
33/// This is typically used to force preferential line breaking decisions when it
34/// comes to ASCII punctuation like `/`, `-`, etc. For example, to prevent break
35/// opportunities within "1/2".
36///
37/// A separate use case is to match the line breaking behavior of existing systems
38/// such as web browsers. See [`CHROMIUM_LINE_BREAK_OVERRIDE`] for a ready-made
39/// override function that mirrors Chromium's behavior.
40pub type LineBreakOverrideFn = dyn Fn(LineBreakContext) -> Option<bool> + Send + Sync;
41
42/// A line break override function mirroring Chromium's preferred line breaking behavior.
43///
44/// See: <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/character_property_data_generator.cc;l=449-495>
45///
46/// # Differences from other browsers
47///
48/// ## Compared to Safari
49///
50/// Chromium (and this table) differs from Safari in 9 cases:
51///  - A "-" followed by one of "!|$|)|/|:|;|?|]|}" is suppressed in Chromium, but broken in Safari.
52///
53/// ## Compared to Firefox
54///
55/// Firefox always defers to the default ICU behavior.
56pub static CHROMIUM_LINE_BREAK_OVERRIDE: &LineBreakOverrideFn =
57    &(chromium_override as fn(LineBreakContext) -> Option<bool>);
58
59fn chromium_override(cx: LineBreakContext) -> Option<bool> {
60    let LineBreakContext {
61        before_before,
62        before,
63        after,
64        ..
65    } = cx;
66    // CSS "does not fully define where soft wrap opportunities occur".
67    // (https://www.w3.org/TR/css-text-3/#line-breaking)
68    // We find that Chrome always treats the position after a space sequence
69    // as a line break opportunity, despite this not matching UAX-14
70    // (see LB13: https://www.unicode.org/reports/tr14/#LB13; we're not currently
71    // aware of any others).
72    //
73    // See also https://github.com/linebender/parley/pull/485, and https://github.com/linebender/parley/issues/619.
74    //
75    // See `LazyLineBreakIterator::NextBreakablePosition`
76    // <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/text_break_iterator.cc;l=282-303>
77    if before == ' ' && after != ' ' {
78        return Some(true);
79    }
80    // Before consulting 'before' / 'after' pair table, check for the special "-" case.
81    //
82    // Chromium doesn't allow breaking when it looks like the minus sign is for a negative
83    // number like "Subtract -5 from X". But, Chromium does allow breaking when the minus
84    // sign is part of a long URL like "AAAA-2222".
85    //
86    // See <https://github.com/chromium/chromium/blob/c6bee15e8f336c8feabf539d8bbb540c134ec20a/third_party/blink/renderer/platform/text/text_break_iterator.cc#L224-L240>
87    if before == '-' && after.is_ascii_digit() {
88        return Some(before_before.is_some_and(|c| c.is_ascii_alphanumeric()));
89    }
90    CHROMIUM_LINE_BREAK_TABLE.lookup(before, after)
91}
92
93/// A static table mirroring Chromium's preferred line breaking behavior for `before` / `after`
94/// printable ASCII code points.
95static CHROMIUM_LINE_BREAK_TABLE: AsciiLineBreakTable<5> =
96    AsciiLineBreakTableBuilder::chromium().build::<5>();
97
98/// A line break override table for ASCII character pairs.
99///
100/// See [`LineBreakOverrideFn`] for more details.
101///
102/// All table operations are `const`, which means that derived tables don't
103/// need a runtime construction step.
104///
105/// The table is row-deduplicated. Each `before` character maps to
106/// one of `N` distinct rows, so tables can be kept tiny.
107///
108/// # Example
109///
110/// ```
111/// # use parley_engine::break_overrides::CHROMIUM_LINE_BREAK_OVERRIDE;
112/// # use parley_engine::{Analysis, AnalysisOptions, Analyzer};
113/// # let mut analyzer = Analyzer::new();
114/// # let mut analysis = Analysis::new();
115/// let text = "Hello there!";
116/// let options = AnalysisOptions {
117///     // Emulate Chromium:
118///     line_break_override: Some(CHROMIUM_LINE_BREAK_OVERRIDE),
119///     ..AnalysisOptions::default()
120/// };
121/// analyzer.analyze(text, &options, &mut analysis, &parley_engine::AnalysisDataSources::default());
122/// ```
123#[derive(Clone, Debug)]
124pub struct AsciiLineBreakTable<const N: usize> {
125    /// Maps each `before` character (`0..128`) to a row in `rows`.
126    row_of: [u8; 128],
127    /// The distinct rows.
128    rows: [Row; N],
129}
130
131impl<const N: usize> AsciiLineBreakTable<N> {
132    /// Look up the break override for a `(before, after)` pair.
133    ///
134    /// Return semantics copied from [`LineBreakOverrideFn`].
135    pub const fn lookup(&self, before: char, after: char) -> Option<bool> {
136        let (b, a) = (before as u32, after as u32);
137        if b >= 128 || a >= 128 {
138            return None;
139        }
140        let row = &self.rows[self.row_of[b as usize] as usize];
141        if row.overridden & (1_u128 << a) == 0 {
142            return None;
143        }
144        Some(row.allow & (1_u128 << a) != 0)
145    }
146}
147
148/// A single deduplicated row of a [`AsciiLineBreakTable`].
149#[derive(Clone, Copy, Debug)]
150struct Row {
151    /// Bits set means the pair has an override.
152    overridden: u128,
153    /// Bits set means a break is allowed.
154    allow: u128,
155}
156
157/// A builder for an [`AsciiLineBreakTable`].
158///
159/// Construction is `const`. We create a dense `128 x 128` grid of overrides,
160/// then compress it into a row-deduplicated table via [`AsciiLineBreakTableBuilder::build`].
161#[derive(Clone, Debug)]
162pub struct AsciiLineBreakTableBuilder {
163    /// Bit `after` set in row `before` means the pair has an explicit override.
164    overridden: [u128; 128],
165    /// Bit `after` set in row `before` means a break is allowed for that pair.
166    allow: [u128; 128],
167}
168
169impl AsciiLineBreakTableBuilder {
170    /// A builder that defers every pair to the default ICU behavior.
171    pub const fn new() -> Self {
172        Self {
173            overridden: [0; 128],
174            allow: [0; 128],
175        }
176    }
177
178    /// Override every pair in the cartesian product of the two inclusive ASCII
179    /// ranges.
180    ///
181    /// # Panics
182    ///
183    /// All range bounds must be printable ASCII (`<= '\u{7f}'`).
184    pub const fn with_pairs(
185        mut self,
186        before: RangeInclusive<char>,
187        after: RangeInclusive<char>,
188        allow_break: bool,
189    ) -> Self {
190        assert!(
191            *before.end() as u32 <= 0x7f && *after.end() as u32 <= 0x7f,
192            "only printable ASCII is supported",
193        );
194        let mut before_pos = *before.start() as u32;
195        while before_pos <= *before.end() as u32 {
196            let mut after_pos = *after.start() as u32;
197            while after_pos <= *after.end() as u32 {
198                let bit = 1_u128 << after_pos;
199                self.overridden[before_pos as usize] |= bit;
200                if allow_break {
201                    self.allow[before_pos as usize] |= bit;
202                } else {
203                    self.allow[before_pos as usize] &= !bit;
204                }
205                after_pos += 1;
206            }
207            before_pos += 1;
208        }
209        self
210    }
211
212    /// Compress the dense grid into a row-deduplicated [`AsciiLineBreakTable`]
213    /// with at most `N` distinct rows.
214    ///
215    /// # Panics
216    ///
217    /// Panics if `N` does not exactly match the number of distinct rows required.
218    pub const fn build<const N: usize>(&self) -> AsciiLineBreakTable<N> {
219        // Row 0 is reserved as the "defer everything" row.
220        let mut rows = [Row {
221            overridden: 0,
222            allow: 0,
223        }; N];
224        let mut len = 1_usize;
225        let mut row_of = [0_u8; 128];
226
227        let mut b = 0;
228        while b < 128 {
229            let (ov, al) = (self.overridden[b], self.allow[b]);
230            let mut idx = 0;
231            let mut found = usize::MAX;
232            while idx < len {
233                if rows[idx].overridden == ov && rows[idx].allow == al {
234                    found = idx;
235                    break;
236                }
237                idx += 1;
238            }
239            let r = if found != usize::MAX {
240                found
241            } else {
242                assert!(
243                    len < N,
244                    "N is too small to contain table. Repeat with a larger N."
245                );
246                rows[len] = Row {
247                    overridden: ov,
248                    allow: al,
249                };
250                len += 1;
251                len - 1
252            };
253            row_of[b] = r as u8;
254            b += 1;
255        }
256
257        assert!(
258            len == N,
259            "N is larger than required. Repeat with a smaller N."
260        );
261
262        AsciiLineBreakTable { row_of, rows }
263    }
264
265    /// See [`CHROMIUM_LINE_BREAK_TABLE`] for more details.
266    const fn chromium() -> Self {
267        // The printable ASCII range `'!'..=0x7F`.
268        const ALL: RangeInclusive<char> = '!'..='\u{7f}';
269
270        Self::new()
271            .with_pairs(ALL, ALL, false)
272            .with_pairs(ALL, '('..='(', true)
273            .with_pairs(ALL, '<'..='<', true)
274            .with_pairs(ALL, '['..='[', true)
275            .with_pairs(ALL, '{'..='{', true)
276            .with_pairs('-'..='-', ALL, true)
277            .with_pairs('?'..='?', ALL, true)
278            .with_pairs('-'..='-', '$'..='$', false)
279            .with_pairs(ALL, '!'..='!', false)
280            .with_pairs('?'..='?', '"'..='"', false)
281            .with_pairs('?'..='?', '\''..='\'', false)
282            .with_pairs(ALL, ')'..=')', false)
283            .with_pairs(ALL, ','..=',', false)
284            .with_pairs(ALL, '.'..='.', false)
285            .with_pairs(ALL, '/'..='/', false)
286            .with_pairs('-'..='-', '0'..='9', false)
287            .with_pairs(ALL, ':'..=':', false)
288            .with_pairs(ALL, ';'..=';', false)
289            .with_pairs(ALL, '?'..='?', false)
290            .with_pairs(ALL, ']'..=']', false)
291            .with_pairs(ALL, '}'..='}', false)
292            .with_pairs('$'..='$', ALL, false)
293            .with_pairs('\''..='\'', ALL, false)
294            .with_pairs('('..='(', ALL, false)
295            .with_pairs('/'..='/', ALL, false)
296            .with_pairs('0'..='9', ALL, false)
297            .with_pairs('<'..='<', ALL, false)
298            .with_pairs('@'..='@', ALL, false)
299            .with_pairs('A'..='Z', ALL, false)
300            .with_pairs('['..='[', ALL, false)
301            .with_pairs('^'..='`', ALL, false)
302            .with_pairs('a'..='z', ALL, false)
303            .with_pairs('{'..='{', ALL, false)
304            .with_pairs('\u{7f}'..='\u{7f}', ALL, false)
305    }
306}
307
308impl Default for AsciiLineBreakTableBuilder {
309    fn default() -> Self {
310        Self::new()
311    }
312}
313
314#[cfg(test)]
315mod tests {
316    use super::AsciiLineBreakTableBuilder;
317    use super::CHROMIUM_LINE_BREAK_TABLE;
318    use super::LineBreakContext;
319    use super::chromium_override;
320
321    fn cx(before_before: Option<char>, before: char, after: char) -> LineBreakContext {
322        LineBreakContext {
323            before_before,
324            before,
325            after,
326        }
327    }
328
329    #[test]
330    fn chromium_hyphen_digit_depends_on_preceding_char() {
331        // A break between '-' and a digit is allowed only when the character
332        // preceding the '-' is ASCII alphanumeric.
333        assert_eq!(chromium_override(cx(Some('D'), '-', '1')), Some(true));
334        assert_eq!(chromium_override(cx(Some('4'), '-', '5')), Some(true));
335        // Otherwise the '-' may be a minus sign, so the break is suppressed.
336        assert_eq!(chromium_override(cx(Some(' '), '-', '1')), Some(false));
337        assert_eq!(chromium_override(cx(Some('('), '-', '1')), Some(false));
338        // No preceding character (start of text) behaves like a non-alphanumeric
339        // context, matching Chromium's `last_last_ch == 0`.
340        assert_eq!(chromium_override(cx(None, '-', '1')), Some(false));
341    }
342
343    #[test]
344    fn chromium_ignores_uax_14_lb13() {
345        // Blink allows a break after a space run unconditionally.
346        // See comment in non-test code for more details.
347        for after in ['}', ')', ']', '!', '.', ',', '/', ':', ';', '?', 'b', '('] {
348            assert_eq!(
349                chromium_override(cx(None, ' ', after)),
350                Some(true),
351                "expected a break after the space, before {after:?}"
352            );
353        }
354    }
355
356    #[test]
357    fn chromium_hyphen_non_digit_defers_to_table() {
358        // '-' followed by a non-digit ignores `before_before` and uses the table.
359        assert_eq!(chromium_override(cx(Some('D'), '-', 'b')), Some(true));
360        assert_eq!(chromium_override(cx(None, '-', 'b')), Some(true));
361        // Non-ASCII after '-' defers to ICU.
362        assert_eq!(chromium_override(cx(Some('D'), '-', 'é')), None);
363    }
364
365    #[test]
366    fn chromium_suppresses_ascii_punctuation_breaks() {
367        let t = &CHROMIUM_LINE_BREAK_TABLE;
368        // No break before or after a slash.
369        assert_eq!(t.lookup('a', '/'), Some(false));
370        assert_eq!(t.lookup('/', 'b'), Some(false));
371        // No break around other punctuation.
372        assert_eq!(t.lookup('a', '.'), Some(false));
373        assert_eq!(t.lookup('a', ':'), Some(false));
374        // No break between letters.
375        assert_eq!(t.lookup('a', 'b'), Some(false));
376    }
377
378    #[test]
379    fn chromium_allows_some_breaks() {
380        let t = &CHROMIUM_LINE_BREAK_TABLE;
381        // Break allowed before opening punctuation, but only when the preceding
382        // character's row was not later suppressed.
383        assert_eq!(t.lookup(')', '('), Some(true));
384        assert_eq!(t.lookup(')', '<'), Some(true));
385        assert_eq!(t.lookup('a', '('), Some(false));
386        // Break allowed after '-' and '?' except when...
387        assert_eq!(t.lookup('-', 'b'), Some(true));
388        assert_eq!(t.lookup('?', 'b'), Some(true));
389        // ...break not allowed after '-' before a digit, or '?' before a quote.
390        assert_eq!(t.lookup('-', '5'), Some(false));
391        assert_eq!(t.lookup('?', '"'), Some(false));
392    }
393
394    #[test]
395    fn non_ascii_pairs_defer_to_icu() {
396        let t = &CHROMIUM_LINE_BREAK_TABLE;
397        assert_eq!(t.lookup('a', 'é'), None);
398        assert_eq!(t.lookup('é', 'a'), None);
399        // Space (0x20) is below the printable range, so it defers too.
400        assert_eq!(t.lookup('a', ' '), None);
401    }
402
403    #[test]
404    fn empty_table_defers_to_icu() {
405        let t = AsciiLineBreakTableBuilder::new().build::<1>();
406        assert_eq!(t.lookup('a', '/'), None);
407        assert_eq!(t.lookup('a', '('), None);
408    }
409
410    #[test]
411    fn dedup_matches_dense_for_chromium() {
412        let builder = AsciiLineBreakTableBuilder::chromium();
413        for b in 0..128_u32 {
414            for a in 0..128_u32 {
415                let bit = 1_u128 << a;
416                let dense = if builder.overridden[b as usize] & bit == 0 {
417                    None
418                } else {
419                    Some(builder.allow[b as usize] & bit != 0)
420                };
421                let (before, after) = (char::from_u32(b).unwrap(), char::from_u32(a).unwrap());
422                assert_eq!(
423                    CHROMIUM_LINE_BREAK_TABLE.lookup(before, after),
424                    dense,
425                    "mismatch at (before={b:#04x}, after={a:#04x})",
426                );
427            }
428        }
429    }
430}