uncurses 0.0.8

A Rust terminal rendering library
Documentation
//! Width-measurement and wrapping policy, plus grapheme-cell iteration.
//!
//! Strings are always segmented into extended grapheme clusters by
//! [`grapheme_cells`]. [`WidthMode`] changes only how each cluster's cell width
//! is computed: by summing its code points (`Wc`) or by cluster-aware Unicode
//! presentation rules (`Grapheme`). [`WrapMode`] controls what happens when a
//! cluster would run past the right edge of a clip rectangle.

use crate::unicode::graphemes;

use super::width::{char_width, grapheme_width};

/// How grapheme clusters are measured for terminal-cell layout.
///
/// This enum does not control segmentation: [`grapheme_cells`] always
/// segments by extended grapheme cluster. It controls only width calculation
/// for each cluster. The East-Asian Ambiguous policy is orthogonal and is
/// passed as a separate `eaw_wide` boolean to [`char_width`] and
/// [`grapheme_width`].
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WidthMode {
    /// Measure each cluster by summing the widths of its code points.
    ///
    /// This models a terminal that has no grapheme segmentation and advances
    /// the cursor once per code point, which is what POSIX `wcswidth`
    /// describes: the sum of `wcwidth` over the string. Combining marks,
    /// joiners, and variation selectors are themselves zero-width, so they
    /// add nothing and a cluster like `e` + combining acute still measures
    /// one cell. A code point that owns cells does add, which is why a
    /// regional-indicator pair measures two.
    ///
    /// A long joined sequence measures the sum of its parts, so a
    /// four-person family emoji is eight columns and a skin-toned thumbs-up
    /// is four. Use this when matching older or simpler terminal width
    /// behavior is more important than cluster-aware emoji presentation.
    #[default]
    Wc,
    /// Measure the whole grapheme cluster.
    ///
    /// This mode accounts for variation selectors, regional indicators,
    /// zero-width-joiner sequences, and pictographic presentation when
    /// deciding whether a cluster occupies zero, one, or two cells. Use it for
    /// modern terminal rendering that treats emoji and joined clusters as a
    /// single displayed unit.
    Grapheme,
}

impl WidthMode {
    /// Measure one extended grapheme cluster under this mode.
    ///
    /// In [`WidthMode::Wc`] mode, the width is the sum of [`char_width`] over
    /// every code point in `g`; an empty string is `0`. In
    /// [`WidthMode::Grapheme`] mode, the width is [`grapheme_width`] for the
    /// whole cluster.
    ///
    /// # Parameters
    ///
    /// * `g` — an extended grapheme cluster. Passing a longer string is
    ///   accepted, and in `Wc` mode every code point in it counts toward the
    ///   sum.
    /// * `eaw_wide` — East-Asian Ambiguous policy; see [`char_width`].
    ///
    /// # Returns
    ///
    /// The cluster width in terminal cells. [`WidthMode::Grapheme`] returns
    /// `0`, `1`, or `2`; [`WidthMode::Wc`] sums code points and can return
    /// more, saturating at [`u8::MAX`].
    ///
    /// # Errors and panics
    ///
    /// This method does not fail or intentionally panic.
    pub fn grapheme_width(self, g: &str, eaw_wide: bool) -> u8 {
        match self {
            Self::Wc => g.chars().fold(0u8, |total, c| {
                total.saturating_add(char_width(c, eaw_wide))
            }),
            Self::Grapheme => grapheme_width(g, eaw_wide),
        }
    }
}

/// Iterate `s` as `(grapheme_cluster, width)` pairs.
///
/// Segmentation is always by extended grapheme cluster. Width calculation uses
/// [`WidthMode::grapheme_width`] with the supplied East-Asian Ambiguous policy.
/// The string slice in each yielded pair borrows from `s`.
///
/// # Parameters
///
/// * `s` — UTF-8 string to segment and measure.
/// * `mode` — cluster-width policy.
/// * `eaw_wide` — East-Asian Ambiguous policy.
///
/// # Returns
///
/// An iterator yielding borrowed cluster slices and their display widths.
///
/// # Errors and panics
///
/// This function does not fail or intentionally panic.
pub fn grapheme_cells(
    s: &str,
    mode: WidthMode,
    eaw_wide: bool,
) -> impl Iterator<Item = (&str, u8)> {
    graphemes(s).map(move |g| (g, mode.grapheme_width(g, eaw_wide)))
}

/// Behavior when a cluster would extend past the right edge of the clip
/// rectangle.
///
/// Newlines and carriage returns are handled independently of this setting:
/// `\n` advances to the next row at the clip rectangle's left edge, and `\r`
/// returns to that left edge on the current row.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum WrapMode {
    /// Stop painting at the right edge of the current row.
    ///
    /// The cluster that would cross the edge is not written, and the returned
    /// cursor position is where painting stopped.
    #[default]
    Truncate,
    /// Continue on the next row at the left edge of the clip rectangle.
    ///
    /// Wrapping stops when the bottom edge is reached. If a cluster is wider
    /// than the clip rectangle itself, it is not written.
    Wrap,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wc_mode_sums_codepoint_widths() {
        // 'e' + combining acute: 1 + 0. A zero-width tail adds nothing, so
        // the common accented-letter case still measures one cell.
        assert_eq!(WidthMode::Wc.grapheme_width("e\u{0301}", false), 1);
        // Lone combining mark cluster: nothing to add up.
        assert_eq!(WidthMode::Wc.grapheme_width("\u{0301}", false), 0);
        // Empty string.
        assert_eq!(WidthMode::Wc.grapheme_width("", false), 0);
    }

    #[test]
    fn wc_mode_counts_codepoints_past_the_first() {
        // A regional-indicator pair is two code points of one cell each, and
        // a terminal without grapheme segmentation advances two columns for
        // it. Measuring only the first code point would report one and leave
        // every later column on the row off by one.
        assert_eq!(WidthMode::Wc.grapheme_width("\u{1f1fa}\u{1f1f8}", false), 2);
        // A lone regional indicator is genuinely one column.
        assert_eq!(WidthMode::Wc.grapheme_width("\u{1f1ef}", false), 1);
        // A zero-width code point followed by a printable one: the cluster
        // occupies the printable one's cell, not zero.
        assert_eq!(WidthMode::Wc.grapheme_width("\u{200d}a", false), 1);
    }

    #[test]
    fn wc_mode_reports_the_full_sum_for_joined_sequences() {
        // A terminal measuring per code point advances two columns for each
        // emoji in the sequence and none for the joiners.
        assert_eq!(WidthMode::Wc.grapheme_width("\u{1f44d}\u{1f3fd}", false), 4);
        let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}";
        assert_eq!(WidthMode::Wc.grapheme_width(family, false), 8);
    }

    #[test]
    fn grapheme_mode_uses_cluster_width() {
        // ✋ + VS15: Grapheme honours VS15 → text presentation, width 1.
        assert_eq!(
            WidthMode::Grapheme.grapheme_width("\u{270b}\u{fe0e}", false),
            1
        );
        // Wc reads no presentation meaning in VS15; it is a zero-width code
        // point, so the sum is '✋' alone (width 2 under the default
        // emoji-presentation tables).
        assert_eq!(WidthMode::Wc.grapheme_width("\u{270b}\u{fe0e}", false), 2);
    }

    #[test]
    fn east_asian_width_flag_applies_to_both_modes() {
        assert_eq!(WidthMode::Wc.grapheme_width("…", false), 1);
        assert_eq!(WidthMode::Wc.grapheme_width("…", true), 2);
        assert_eq!(WidthMode::Grapheme.grapheme_width("…", false), 1);
        assert_eq!(WidthMode::Grapheme.grapheme_width("…", true), 2);
    }

    #[test]
    fn grapheme_cells_segments_both_modes_by_cluster() {
        let g: Vec<_> = grapheme_cells("Aé中", WidthMode::Grapheme, false).collect();
        assert_eq!(g.len(), 3);
        assert_eq!(g[2], ("中", 2));

        // Wc mode also segments by cluster; widths sum the code points.
        let w: Vec<_> = grapheme_cells("e\u{0301}A", WidthMode::Wc, false).collect();
        assert_eq!(w.len(), 2);
        assert_eq!(w[0], ("e\u{0301}", 1));
        assert_eq!(w[1], ("A", 1));
    }
}