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
impl Width
Sourcepub fn truncate_ellipsis<'a>(
&self,
s: &'a str,
max: usize,
ellipsis: &str,
) -> Cow<'a, str>
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");Sourcepub fn pad_end<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str>
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.
Sourcepub fn pad_start<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str>
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.
Sourcepub fn center<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str>
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.
Sourcepub fn cell<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str>
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);Sourcepub fn wrap(&self, s: &str, width: usize) -> Vec<String>
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?
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
impl Width
Sourcepub const DEFAULT: Width
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.
Sourcepub const MODERN: Width = Width::DEFAULT
pub const MODERN: Width = Width::DEFAULT
The same as Width::DEFAULT, named for when the contrast with
Width::LEGACY is the point.
Sourcepub const LEGACY: Width
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.
Sourcepub const fn clusters(self, c: Clusters) -> Self
pub const fn clusters(self, c: Clusters) -> Self
How much of a grapheme cluster counts towards the width.
Sourcepub const fn ambiguous(self, a: Ambiguous) -> Self
pub const fn ambiguous(self, a: Ambiguous) -> Self
How to count East Asian Ambiguous characters.
Sourcepub const fn tab_stop(self, n: usize) -> Self
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.
Sourcepub const fn ansi(self, enabled: bool) -> Self
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.
Sourcepub fn of_char(&self, c: char) -> usize
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.
Sourcepub fn of(&self, s: &str) -> usize
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);Sourcepub fn of_at(&self, s: &str, start: usize) -> usize
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);Sourcepub fn of_grapheme(&self, cluster: &str) -> usize
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);Sourcepub fn truncate<'a>(&self, s: &'a str, max: usize) -> &'a str
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");