Skip to main content

vtcode_commons/
display_width.rs

1//! Authoritative terminal display-cell width ("variable column width") math.
2//!
3//! A terminal cell is not one byte, nor even one character: combining marks
4//! occupy no cell, East-Asian wide glyphs occupy two, and East-Asian-ambiguous
5//! glyphs occupy one or two depending on terminal configuration. Every
6//! wrap/truncate/pad/hit-test decision must use the same verdict or frames,
7//! links and tool output drift out of alignment.
8//!
9//! On a terminal configured to render East-Asian-ambiguous glyphs (UAX #11)
10//! as two cells (`ui.ambiguous_width = "wide"`), the CJK width table is used
11//! so the math matches what the terminal actually shows.
12//!
13//! The halfwidth voiced sound marks `U+FF9E` (dakuten) and `U+FF9F`
14//! (handakuten) are the one correction `unicode-width` tables have disagreed
15//! on: older tables report them as zero width even though a terminal draws
16//! them in one cell, so wrap and truncation math would otherwise credit one
17//! cell for a two-cell glyph. Only the *missing* width is credited, so newer
18//! tables that already count the mark are not double-counted.
19
20use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
21
22use crate::terminal_capabilities::ambiguous_width_wide;
23
24/// Terminal display width of `text` in cells.
25#[must_use]
26pub fn display_width(text: &str) -> usize {
27    let missing_mark_width: usize = text.chars().map(missing_sound_mark_width).sum();
28    let width = if ambiguous_width_wide() {
29        UnicodeWidthStr::width_cjk(text)
30    } else {
31        UnicodeWidthStr::width(text)
32    };
33    width.saturating_add(missing_mark_width)
34}
35
36/// Width older `unicode-width` tables leave out for a halfwidth sound mark.
37fn missing_sound_mark_width(ch: char) -> usize {
38    if matches!(ch, '\u{FF9E}' | '\u{FF9F}') {
39        1usize.saturating_sub(UnicodeWidthChar::width(ch).unwrap_or(0))
40    } else {
41        0
42    }
43}
44
45/// Terminal display width of one character under the resolved
46/// ambiguous-width verdict, for char-by-char column mapping.
47#[must_use]
48pub fn char_display_width(ch: char) -> usize {
49    char_display_width_or(ch, 0)
50}
51
52/// Terminal display width of one character, with `fallback` for characters
53/// the width tables do not classify (control characters), matching call
54/// sites that treat unknown widths as one cell.
55#[must_use]
56pub fn char_display_width_or(ch: char, fallback: usize) -> usize {
57    let width = if ambiguous_width_wide() {
58        UnicodeWidthChar::width_cjk(ch).unwrap_or(fallback)
59    } else {
60        UnicodeWidthChar::width(ch).unwrap_or(fallback)
61    };
62    width.saturating_add(missing_sound_mark_width(ch))
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    use crate::ui_protocol::AmbiguousWidthMode;
69
70    #[test]
71    fn counts_halfwidth_sound_marks_without_double_counting() {
72        assert_eq!(display_width(""), 0);
73        assert_eq!(display_width("hello"), 5);
74        assert_eq!(display_width("日本"), 4);
75        assert_eq!(display_width("ガ"), 2);
76        assert_eq!(display_width("パ"), 2);
77        assert_eq!(display_width("\u{FF9E}"), 1);
78        assert_eq!(display_width("aガ"), 3);
79        assert_eq!(char_display_width('\u{FF9E}'), 1);
80        assert_eq!(char_display_width('\u{FF9F}'), 1);
81    }
82
83    #[test]
84    fn counts_ambiguous_glyphs_narrow_by_default() {
85        assert_eq!(display_width("├──"), 3);
86        assert_eq!(display_width("│ α"), 3);
87        assert_eq!(char_display_width('│'), 1);
88        assert_eq!(char_display_width('α'), 1);
89    }
90
91    #[test]
92    fn counts_ambiguous_glyphs_wide_when_configured() {
93        // nextest runs each test in its own process, so the one-time verdict
94        // override is isolated here. Ideographs are unambiguous in both
95        // tables; only the ambiguous set changes.
96        crate::terminal_capabilities::set_ambiguous_width(AmbiguousWidthMode::Wide);
97        assert_eq!(display_width("├──"), 6);
98        assert_eq!(display_width("│ α"), 4);
99        assert_eq!(char_display_width('│'), 2);
100        assert_eq!(char_display_width('α'), 1); // cjk table keeps Greek narrow
101        assert_eq!(display_width("日本"), 4);
102        assert_eq!(display_width("ガ"), 2);
103    }
104
105    #[test]
106    fn char_width_fallback_applies_to_unclassified_characters() {
107        assert_eq!(char_display_width_or('\n', 1), 1);
108        assert_eq!(char_display_width_or('日', 1), 2);
109    }
110}