flm_core/layout/width.rs
1//! Display width: how many columns a string occupies when printed.
2//!
3//! The engine never counts columns with `str::len()` or `chars().count()`. The
4//! width of a string is the **sum, over its extended grapheme clusters, of the
5//! display width of each cluster**, where a grapheme cluster is what a reader
6//! sees as one character (`e` followed by a combining accent, or a whole family
7//! emoji joined by zero-width joiners). The clusters come from the crate
8//! `unicode-segmentation`; each cluster's width comes from the crate
9//! `unicode-width`.
10//!
11//! The width is summed cluster by cluster, rather than computed by
12//! `unicode-width` on the whole string, because the whole-string function
13//! applies rules that depend on the neighboring characters across cluster
14//! boundaries: with it, the width of two strings joined can differ from the
15//! sum of their widths, and a longer string can measure narrower than its
16//! beginning. The printer keeps a running column, and the fitting scan adds up
17//! widths node by node; both need the width of a join to be the sum of the
18//! widths, and a longer string never to be narrower. Measuring one cluster at
19//! a time and adding the results gives both properties, and agrees with the
20//! whole-string width on ordinary text.
21//!
22//! Control characters, including `'\t'` and `'\n'`, count as one column each
23//! under `unicode-width`, which is one reason a text atom may not contain them
24//! (see [`DocBuf::text`](super::DocBuf::text)).
25//!
26//! # The measure the engine uses
27//!
28//! The engine measures with [`UnicodeMeasure`], which counts the East-Asian
29//! *Ambiguous* characters (`…`, `→`, `•`, the em dash) as one column, as
30//! terminals configured for Western languages draw them.
31//! [`Profile`](super::Profile) has no setting for the measure: a caller needs
32//! the measure to align text by hand ([`display_width`]) but not the ability
33//! to replace it, and keeping the measure's interface ([`WidthMeasure`])
34//! inside the crate leaves the choice of measure free to change. The
35//! [`WidthMeasure`] trait and two other measures are kept for the crate's own
36//! use and for the tests: for output read where ambiguous characters are drawn
37//! two columns wide, the crate could switch the printer to
38//! [`UnicodeCjkMeasure`] with a change of one line, and the tests check
39//! that the measure changes the layout (the same list document hangs its item
40//! at column 4 under one measure and at column 5 under the other).
41
42use unicode_segmentation::UnicodeSegmentation;
43use unicode_width::UnicodeWidthStr;
44
45/// Returns the display width of `s` in columns, as the layout engine measures
46/// it: the sum, over the extended grapheme clusters of `s`, of each cluster's
47/// Unicode display width, with East-Asian *Ambiguous* characters counted as
48/// one column.
49///
50/// A *grapheme cluster* is what a reader sees as one character (`e` followed
51/// by a combining accent, or a whole family emoji joined by zero-width
52/// joiners), as Unicode's text segmentation rules delimit it. *East-Asian
53/// Ambiguous* characters are those a terminal configured for Western languages
54/// draws one column wide and one configured for East-Asian languages two (`…`,
55/// `→`, `•`, the em dash); the engine counts them as one column.
56///
57/// The printer wraps against this width, and an emitter uses it for anything
58/// it aligns by hand (a rule of `=` under a heading, a label padded to a
59/// column). `"Über Bäume — 日本語"` measures 19 (the three East-Asian
60/// characters are two columns each); a family emoji measures 2; a combining
61/// accent adds nothing.
62pub fn display_width(s: &str) -> u32 {
63 UnicodeMeasure.str_width(s)
64}
65
66/// A width measure: how many columns a string occupies where the output is
67/// read.
68///
69/// An implementation gives the width of one grapheme cluster; the width of a
70/// string is the provided sum, which an implementation must not override,
71/// because the printer's column arithmetic relies on the width of a join being
72/// the sum of the widths and on a longer string never being narrower.
73pub(crate) trait WidthMeasure {
74 /// The width of one extended grapheme cluster.
75 fn cluster_width(&self, cluster: &str) -> u32;
76
77 /// The width of any string: the sum of
78 /// [`cluster_width`](Self::cluster_width) over its extended grapheme
79 /// clusters.
80 fn str_width(&self, s: &str) -> u32 {
81 s.graphemes(true).map(|g| self.cluster_width(g)).sum()
82 }
83}
84
85/// Unicode display width, with East-Asian *Ambiguous* characters counted as
86/// **narrow** (one column): the measure the engine uses.
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88pub(crate) struct UnicodeMeasure;
89
90impl WidthMeasure for UnicodeMeasure {
91 #[inline]
92 fn cluster_width(&self, cluster: &str) -> u32 {
93 UnicodeWidthStr::width(cluster) as u32
94 }
95}
96
97/// Unicode display width, with East-Asian *Ambiguous* characters counted as
98/// **wide** (two columns): the measure for output read where `—`, `…`, `°` and
99/// box-drawing characters are drawn two columns wide. Used by the tests; not
100/// reachable from the public interface.
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
102#[cfg_attr(not(test), allow(dead_code))]
103pub(crate) struct UnicodeCjkMeasure;
104
105impl WidthMeasure for UnicodeCjkMeasure {
106 #[inline]
107 fn cluster_width(&self, cluster: &str) -> u32 {
108 UnicodeWidthStr::width_cjk(cluster) as u32
109 }
110}
111
112/// The length in bytes as the width: not a Unicode measure. It stands for a
113/// reader that counts bytes (or an ASCII-only output, where bytes are
114/// columns) and gives the tests a third, simple measure. Used by the tests;
115/// not reachable from the public interface.
116#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
117#[cfg_attr(not(test), allow(dead_code))]
118pub(crate) struct AsciiMeasure;
119
120impl WidthMeasure for AsciiMeasure {
121 #[inline]
122 fn cluster_width(&self, cluster: &str) -> u32 {
123 cluster.len() as u32
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 //! Grapheme clusters, East-Asian width, and the additivity the engine
130 //! relies on.
131
132 use unicode_segmentation::UnicodeSegmentation;
133
134 use super::{display_width, AsciiMeasure, UnicodeCjkMeasure, UnicodeMeasure, WidthMeasure};
135
136 /// A string with combining-capable Latin, an East-Asian *Ambiguous*
137 /// character (the em dash) and three East-Asian *Wide* characters.
138 const MIXED: &str = "Über Bäume — 日本語";
139
140 /// A ZWJ emoji sequence: four emoji joined by three zero-width joiners,
141 /// which renders as a single glyph.
142 const FAMILY: &str = "👨👩👧👦";
143
144 fn measures() -> Vec<Box<dyn WidthMeasure>> {
145 vec![
146 Box::new(UnicodeMeasure),
147 Box::new(UnicodeCjkMeasure),
148 Box::new(AsciiMeasure),
149 ]
150 }
151
152 #[test]
153 fn mixed_string_widths_across_the_three_measures() {
154 // 11 narrow columns ("Über Bäume " = 11), the em dash, a space, then
155 // 3 wide CJK characters.
156 assert_eq!(UnicodeMeasure.str_width(MIXED), 19);
157 // U+2014 EM DASH is East-Asian Ambiguous: wide in a CJK context.
158 assert_eq!(UnicodeCjkMeasure.str_width(MIXED), 20);
159 // AsciiMeasure counts bytes: 4 two-byte and 1 three-byte character
160 // among 17 characters.
161 assert_eq!(MIXED.len(), 26);
162 assert_eq!(AsciiMeasure.str_width(MIXED), 26);
163 }
164
165 #[test]
166 fn ambiguous_width_ellipsis() {
167 assert_eq!(UnicodeMeasure.str_width("…"), 1);
168 assert_eq!(UnicodeCjkMeasure.str_width("…"), 2);
169 assert_eq!(UnicodeMeasure.cluster_width("…"), 1);
170 assert_eq!(UnicodeCjkMeasure.cluster_width("…"), 2);
171 }
172
173 #[test]
174 fn zwj_family_emoji_is_one_cluster_of_width_two() {
175 let clusters: Vec<&str> = FAMILY.graphemes(true).collect();
176 assert_eq!(clusters.len(), 1, "clusters: {clusters:?}");
177 assert_eq!(clusters[0], FAMILY);
178
179 assert_eq!(UnicodeMeasure.cluster_width(FAMILY), 2);
180 assert_eq!(UnicodeMeasure.str_width(FAMILY), 2);
181 // Chars would say 7, bytes 25 — neither is a column count.
182 assert_eq!(FAMILY.chars().count(), 7);
183 }
184
185 #[test]
186 fn combining_marks_do_not_add_width() {
187 // "e" + U+0301 COMBINING ACUTE ACCENT is one cluster, one column.
188 let decomposed = "e\u{301}";
189 assert_eq!(decomposed.graphemes(true).count(), 1);
190 assert_eq!(UnicodeMeasure.str_width(decomposed), 1);
191 assert_eq!(UnicodeMeasure.str_width("é"), 1);
192 }
193
194 /// The provided `str_width` is exactly the per-cluster accumulator the
195 /// printer runs, so measuring a whole atom and accumulating cluster by
196 /// cluster agree — the measure is additive.
197 #[test]
198 fn str_width_is_the_per_cluster_accumulator() {
199 for s in [MIXED, FAMILY, "…", "e\u{301}", "plain ascii", ""] {
200 for m in measures() {
201 let summed: u32 = s.graphemes(true).map(|g| m.cluster_width(g)).sum();
202 assert_eq!(m.str_width(s), summed, "{s:?}");
203 }
204 }
205 }
206
207 /// Additivity at an arbitrary cluster boundary: split anywhere between
208 /// clusters and the parts still sum to the whole.
209 #[test]
210 fn width_is_additive_across_cluster_boundaries() {
211 for m in measures() {
212 let clusters: Vec<&str> = MIXED.graphemes(true).collect();
213 for k in 0..=clusters.len() {
214 let head: String = clusters[..k].concat();
215 let tail: String = clusters[k..].concat();
216 assert_eq!(
217 m.str_width(&head) + m.str_width(&tail),
218 m.str_width(MIXED),
219 "split at cluster {k}"
220 );
221 }
222 }
223 }
224
225 /// The measure is part of the layout contract, not a cosmetic setting:
226 /// U+2022 BULLET is East-Asian *Ambiguous*, so the same list item hangs at
227 /// column 4 under [`UnicodeMeasure`] and column 5 under
228 /// [`UnicodeCjkMeasure`].
229 #[test]
230 fn bullet_is_ambiguous_width() {
231 assert_eq!(UnicodeMeasure.str_width(" • "), 4);
232 assert_eq!(UnicodeCjkMeasure.str_width(" • "), 5);
233 }
234
235 /// The public function is the engine's measure.
236 #[test]
237 fn display_width_is_the_unicode_measure() {
238 for s in [MIXED, FAMILY, "…", "e\u{301}", " • ", ""] {
239 assert_eq!(display_width(s), UnicodeMeasure.str_width(s), "{s:?}");
240 }
241 assert_eq!(display_width(MIXED), 19);
242 }
243}