Skip to main content

Width

Struct Width 

Source
pub struct Width { /* private fields */ }
Expand description

A measurement policy: how to turn text into a number of terminal columns.

The free functions in the crate root use Width::DEFAULT. Build your own when you need CJK ambiguous-width handling or a different tab stop:

use cellwidth::{Ambiguous, Width};

const CJK: Width = Width::DEFAULT.ambiguous(Ambiguous::Wide);
assert_eq!(Width::DEFAULT.of("±"), 1);
assert_eq!(CJK.of("±"), 2);

Implementations§

Source§

impl Width

Source

pub fn truncate_ellipsis<'a>( &self, s: &'a str, max: usize, ellipsis: &str, ) -> Cow<'a, str>

Fit s into max columns, marking a cut with ellipsis.

Returns the input untouched if it already fits. Otherwise the result is at most max columns wide including the ellipsis, and a reset is appended if the cut left styling switched on.

use cellwidth::Width;
let w = Width::DEFAULT;
assert_eq!(w.truncate_ellipsis("日本語テキスト", 7, "…"), "日本語…");
assert_eq!(w.truncate_ellipsis("short", 10, "…"), "short");
Source

pub fn pad_end<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str>

Pad s with spaces on the right to at least width columns.

Text wider than width is returned unchanged; use Width::cell to force an exact width.

Source

pub fn pad_start<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str>

Pad s with spaces on the left to at least width columns.

Source

pub fn center<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str>

Pad s with spaces on both sides to at least width columns.

An odd remainder goes on the right.

Source

pub fn cell<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str>

Fit s into exactly width columns: truncate with … if too long, pad with spaces if too short.

This is the table-cell workhorse. The result is always width columns wide, whatever writing system or emoji the input contains.

use cellwidth::Width;
let w = Width::DEFAULT;
assert_eq!(w.of(&w.cell("日本語テキスト", 8)), 8);
assert_eq!(w.of(&w.cell("👨‍👩‍👧‍👦 family", 8)), 8);
assert_eq!(w.of(&w.cell("ok", 8)), 8);
Source

pub fn wrap(&self, s: &str, width: usize) -> Vec<String>

Break s into lines of at most width columns.

Break opportunities come from the Unicode line breaking algorithm (UAX #14), so this finds the places a reader would accept: between CJK ideographs, after a hyphen, never inside 1,000 or between a bracket and what it encloses. Existing newlines are honoured. A word longer than the line is broken by column.

Styling open at the end of a line is closed and reopened on the next, so each line can be printed on its own.

use cellwidth::Width;
let w = Width::DEFAULT;
assert_eq!(w.wrap("the quick brown fox", 10), ["the quick", "brown fox"]);
// CJK breaks between ideographs, with no spaces in sight.
assert_eq!(w.wrap("\u{65E5}\u{672C}\u{8A9E}\u{30C6}\u{30AD}\u{30B9}\u{30C8}", 6),
           ["\u{65E5}\u{672C}\u{8A9E}", "\u{30C6}\u{30AD}\u{30B9}", "\u{30C8}"]);
// ...but never inside a number.
assert_eq!(w.wrap("cost 1,000 yen", 8), ["cost", "1,000", "yen"]);
Examples found in repository?
examples/table.rs (line 58)
8fn main() {
9    let t = Table::new()
10        .column("host")
11        .column_with("label", Align::Left, Sizing::Max(22))
12        .column_aligned("rps", Align::Right)
13        .column_aligned("status", Align::Center)
14        .row([
15            "nagoya-prod-01",
16            "日本語ログ出力",
17            "1,204",
18            "\x1b[32mhealthy\x1b[0m",
19        ])
20        .row([
21            "berlin-edge-7",
22            "Übermäßig groß",
23            "88",
24            "\x1b[33mdegraded\x1b[0m",
25        ])
26        .row([
27            "crew-alpha",
28            "👨‍👩‍👧‍👦 shared account",
29            "3",
30            "\x1b[32mhealthy\x1b[0m",
31        ])
32        .row([
33            "tokyo-cdn",
34            "🇯🇵 Tōkyō 東京 edge",
35            "17,900",
36            "\x1b[31moffline\x1b[0m",
37        ])
38        .row(["mumbai-2", "क्षि नमस्ते सर्वर", "412", "\x1b[32mhealthy\x1b[0m"]);
39
40    println!("{}\n", t.render(None));
41
42    println!("Squeezed into 46 columns, cells wrap rather than vanish:");
43    println!("{}\n", t.clone().render(Some(46)));
44
45    println!("Markdown, for pasting into an issue:");
46    println!("{}\n", t.clone().border(Border::Markdown).render(None));
47
48    println!("Borderless, for piping into something else:");
49    println!("{}\n", t.clone().border(Border::None).render(None));
50
51    println!("Line breaking finds the places a reader would accept:");
52    for (text, w) in [
53        ("The quick brown fox jumps over the lazy dog", 18),
54        ("日本語のテキストは空白なしで折り返せます", 12),
55        ("total cost 1,200 yen (approximately)", 14),
56    ] {
57        println!("  ┌{}┐", "─".repeat(w));
58        for line in Width::DEFAULT.wrap(text, w) {
59            println!("  │{}│", cellwidth::cell(&line, w));
60        }
61        println!("  └{}┘", "─".repeat(w));
62    }
63}
Source§

impl Width

Source

pub const DEFAULT: Width

Sensible defaults: ambiguous characters are narrow, controls are zero columns, tab stops every 8 columns, escape sequences are skipped, and an emoji ZWJ sequence counts as the single glyph it is meant to render as.

Source

pub const MODERN: Width = Width::DEFAULT

The same as Width::DEFAULT, named for when the contrast with Width::LEGACY is the point.

Source

pub const LEGACY: Width

Matches terminals that count each code point separately, as wcwidth does.

This is VTE (GNOME Terminal, Tilix, Terminator, xfce4-terminal) and Alacritty. Under it a ZWJ family emoji is eight columns, not two, because that is genuinely what those terminals draw.

Source

pub const fn clusters(self, c: Clusters) -> Self

How much of a grapheme cluster counts towards the width.

Source

pub const fn ambiguous(self, a: Ambiguous) -> Self

How to count East Asian Ambiguous characters.

Source

pub const fn control(self, c: Control) -> Self

How to count control characters.

Source

pub const fn tab_stop(self, n: usize) -> Self

Distance between tab stops. 0 makes a tab occupy no columns.

Because a tab’s width depends on where it starts, measurements assume the text begins at column 0.

Source

pub const fn ansi(self, enabled: bool) -> Self

Whether to recognise and skip ANSI escape sequences (default true).

Turn this off to measure escape sequences as the literal characters they are made of, which is what you want when displaying them for debugging.

Source

pub fn of_char(&self, c: char) -> usize

Columns occupied by a single char.

Beware that a char is not a user-perceived character: the width of '\u{301}' (combining acute) is 0, and the width of a flag is only defined for the pair. Prefer Width::of for real text.

Source

pub fn of(&self, s: &str) -> usize

Columns occupied by a string.

Assumes a single line starting at column 0; split on newlines yourself if you have more than one. Escape sequences count as zero unless Width::ansi is off.

use cellwidth::Width;
assert_eq!(Width::DEFAULT.of("日本語"), 6);
Source

pub fn of_at(&self, s: &str, start: usize) -> usize

Columns s occupies when it starts at column start.

Only tabs make this differ from Width::of, but when they do it matters: a tab after four characters advances four columns, and the same tab after eight advances eight. Width is not additive across a tab, so anything laying text out in pieces has to measure each piece where it will actually sit.

use cellwidth::Width;
let w = Width::DEFAULT;
assert_eq!(w.of("\t"), 8);
assert_eq!(w.of_at("\t", 4), 4);
assert_eq!(w.of_at("\t", 8), 8);
Source

pub fn of_grapheme(&self, cluster: &str) -> usize

Columns occupied by one grapheme cluster, as if printed at column 0.

use cellwidth::Width;
assert_eq!(Width::DEFAULT.of_grapheme("👍🏽"), 2);
Source

pub fn truncate<'a>(&self, s: &'a str, max: usize) -> &'a str

Longest prefix of s that fits in max columns.

Borrows: no allocation, ever. Cuts only at cluster boundaries and never inside an escape sequence. Escape sequences already passed are kept, which means the result can leave styling switched on – use Width::truncate_ellipsis or Width::cell if you need the reset handled for you.

use cellwidth::Width;
assert_eq!(Width::DEFAULT.truncate("日本語テキスト", 7), "日本語");
assert_eq!(Width::DEFAULT.truncate("héllo", 3), "hél");

Trait Implementations§

Source§

impl Clone for Width

Source§

fn clone(&self) -> Width

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Width

Source§

impl Debug for Width

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Width

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for Width

Source§

impl PartialEq for Width

Source§

fn eq(&self, other: &Width) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Width

Auto Trait Implementations§

§

impl Freeze for Width

§

impl RefUnwindSafe for Width

§

impl Send for Width

§

impl Sync for Width

§

impl Unpin for Width

§

impl UnsafeUnpin for Width

§

impl UnwindSafe for Width

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.