use alloc::borrow::Cow;
use alloc::string::String;
use alloc::vec::Vec;
use crate::ansi::{leaves_style_open, trim_dangling, Piece, Pieces, RESET};
use crate::grapheme::first_cluster;
use crate::measure::Width;
pub const ELLIPSIS: &str = "…";
impl Width {
pub fn truncate_ellipsis<'a>(&self, s: &'a str, max: usize, ellipsis: &str) -> Cow<'a, str> {
if self.of(s) <= max {
return Cow::Borrowed(s);
}
let e_width = self.of(ellipsis);
if e_width > max {
return Cow::Borrowed(self.truncate(s, max));
}
let head = trim_dangling(self.truncate(s, max - e_width));
let mut out = String::with_capacity(head.len() + ellipsis.len() + RESET.len());
out.push_str(head);
out.push_str(ellipsis);
if self.ansi_enabled() && leaves_style_open(head) {
out.push_str(RESET);
}
Cow::Owned(out)
}
pub fn pad_end<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str> {
self.pad(s, width, Align::Start)
}
pub fn pad_start<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str> {
self.pad(s, width, Align::End)
}
pub fn center<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str> {
self.pad(s, width, Align::Center)
}
fn pad<'a>(&self, s: &'a str, width: usize, align: Align) -> Cow<'a, str> {
let keep = trim_dangling(s).len();
let have = self.of(&s[..keep]);
if have >= width {
return Cow::Borrowed(&s[..keep]);
}
let s = &s[..keep];
let gap = width - have;
let (left, right) = match align {
Align::Start => (0, gap),
Align::End => (gap, 0),
Align::Center => (gap / 2, gap - gap / 2),
};
let mut out = String::with_capacity(s.len() + gap);
for _ in 0..left {
out.push(' ');
}
out.push_str(s);
for _ in 0..right {
out.push(' ');
}
Cow::Owned(out)
}
pub fn cell<'a>(&self, s: &'a str, width: usize) -> Cow<'a, str> {
let fitted = self.truncate_ellipsis(s, width, ELLIPSIS);
let keep = trim_dangling(&fitted).len();
let have = self.of(&fitted[..keep]);
if have >= width && keep == fitted.len() {
return fitted;
}
let mut out = String::with_capacity(keep + width - have);
out.push_str(&fitted[..keep]);
for _ in 0..width - have {
out.push(' ');
}
Cow::Owned(out)
}
pub fn wrap(&self, s: &str, width: usize) -> Vec<String> {
let mut out = Vec::new();
if width == 0 {
return out;
}
let (plain, map) = self.strip_with_offsets(s);
let mut style: Option<String> = None;
let mut line_start = 0; let mut seg_start = 0; let mut col = 0;
let mut wrote = false;
for (end_plain, kind) in crate::linebreak::LineBreaks::new(&plain) {
let end = map_offset(&map, end_plain, s.len());
let seg = &s[seg_start..end];
if seg.is_empty() {
continue;
}
let trimmed_len = trim_end_len(seg);
if col > 0 && col + self.of_at(&seg[..trimmed_len], col) > width {
self.push_line(&mut out, s, line_start, seg_start, &mut style);
line_start = seg_start;
col = 0;
wrote = true;
}
let w_trimmed = self.of_at(&seg[..trimmed_len], col);
if col == 0 && w_trimmed > width {
let limit = seg_start + trimmed_len;
let mut at = line_start;
while at < limit && self.of(&s[at..limit]) > width {
let head = self.truncate(&s[at..limit], width);
let take = head.len().max(first_cluster(&s[at..limit]).len());
let stop = (at + take).min(limit);
self.push_line(&mut out, s, at, stop, &mut style);
wrote = true;
at = stop;
}
line_start = at;
col = self.of(&s[at..end]);
debug_assert!(at <= end);
seg_start = end;
if kind == crate::linebreak::Break::Mandatory {
self.push_line(&mut out, s, line_start, end, &mut style);
line_start = end;
col = 0;
}
continue;
}
col += self.of_at(seg, col);
seg_start = end;
if kind == crate::linebreak::Break::Mandatory {
self.push_line(&mut out, s, line_start, end, &mut style);
line_start = end;
col = 0;
wrote = true;
}
}
if line_start < s.len() || !wrote {
self.push_line(&mut out, s, line_start, s.len(), &mut style);
}
out
}
fn push_line(
&self,
out: &mut Vec<String>,
s: &str,
from: usize,
to: usize,
style: &mut Option<String>,
) {
let raw = &s[from..to.max(from)];
let body = line_body(raw);
let mut line = String::with_capacity(body.len() + 8);
if let Some(open) = style.as_deref() {
line.push_str(open);
}
line.push_str(&body);
self.track_style(raw, style);
if self.ansi_enabled() && leaves_style_open(&line) {
line.push_str(RESET);
}
out.push(line);
}
fn strip_with_offsets(&self, s: &str) -> (String, Vec<usize>) {
let mut plain = String::with_capacity(s.len());
let mut ends = Vec::with_capacity(s.len() + 1);
ends.push(0);
let mut at = 0;
for piece in Pieces::new(s) {
if let Piece::Text(t) = piece {
for (i, ch) in t.char_indices() {
for _ in 0..ch.len_utf8() {
ends.push(at + i + ch.len_utf8());
}
}
plain.push_str(t);
}
at += piece.as_str().len();
}
(plain, ends)
}
}
fn line_body(s: &str) -> Cow<'_, str> {
let mut text_end = 0;
let mut at = 0;
for piece in Pieces::new(s) {
at += piece.as_str().len();
if matches!(piece, Piece::Text(_)) {
text_end = at;
}
}
let head = &s[..text_end];
let keep = trim_end_len(head);
if keep == s.len() {
return Cow::Borrowed(s);
}
if text_end == s.len() {
return Cow::Borrowed(&s[..keep]);
}
let mut out = String::with_capacity(keep + s.len() - text_end);
out.push_str(&s[..keep]);
out.push_str(&s[text_end..]);
Cow::Owned(out)
}
fn trim_end_len(s: &str) -> usize {
let mut n = match () {
_ if s.ends_with("\r\n") => s.len() - 2,
_ => s
.strip_suffix([
'\n', '\r', '\u{0B}', '\u{0C}', '\u{85}', '\u{2028}', '\u{2029}',
])
.map_or(s.len(), str::len),
};
while let Some(stripped) = s[..n].strip_suffix([' ', '\t']) {
n = stripped.len();
}
n
}
fn map_offset(map: &[usize], i: usize, len: usize) -> usize {
if i + 1 >= map.len() {
len
} else {
map[i]
}
}
impl Width {
fn track_style(&self, s: &str, style: &mut Option<String>) {
if !self.ansi_enabled() {
return;
}
for piece in Pieces::new(s) {
if let Piece::Escape(e) = piece {
if leaves_style_open(e) {
*style = Some(String::from(e));
} else if e.ends_with('m') {
*style = None;
}
}
}
}
}
enum Align {
Start,
End,
Center,
}