#![doc(html_root_url = "https://docs.rs/cli-truncate/0.1.0")]
use unicode_width::UnicodeWidthChar;
const RESET: &str = "\u{1b}[0m";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Position {
Start,
Middle,
#[default]
End,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Options {
ellipsis: String,
position: Position,
}
impl Default for Options {
fn default() -> Self {
Self {
ellipsis: String::from("\u{2026}"),
position: Position::End,
}
}
}
impl Options {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn ellipsis(mut self, ellipsis: &str) -> Self {
ellipsis.clone_into(&mut self.ellipsis);
self
}
#[must_use]
pub fn position(mut self, position: Position) -> Self {
self.position = position;
self
}
#[must_use]
pub fn truncate(&self, text: &str, max_width: usize) -> String {
if max_width == 0 {
return String::new();
}
if width(text) <= max_width {
return text.to_owned();
}
let toks = tokenize(text);
let ellipsis_width = width(&self.ellipsis);
if ellipsis_width >= max_width {
return clamp_visible(&self.ellipsis, max_width);
}
let avail = max_width - ellipsis_width;
match self.position {
Position::End => {
let cut = prefix_cut(&toks, avail);
let mut out = String::new();
let mut open = false;
emit(&mut out, &toks[..cut], &mut open);
push_tracked(&mut out, &self.ellipsis, &mut open);
close(&mut out, open);
out
}
Position::Start => {
let keep = drop_leading_zero_width(&toks, suffix_start(&toks, avail));
let mut out = String::new();
let mut open = false;
push_tracked(&mut out, &self.ellipsis, &mut open);
emit(&mut out, &toks[keep..], &mut open);
close(&mut out, open);
out
}
Position::Middle => {
let left = avail / 2;
let right = avail - left;
let cut = prefix_cut(&toks, left);
let keep = drop_leading_zero_width(&toks, suffix_start(&toks, right).max(cut));
let mut out = String::new();
let mut open = false;
emit(&mut out, &toks[..cut], &mut open);
push_tracked(&mut out, &self.ellipsis, &mut open);
emit(&mut out, &toks[keep..], &mut open);
close(&mut out, open);
out
}
}
}
}
#[must_use]
pub fn truncate(text: &str, max_width: usize) -> String {
Options::new().truncate(text, max_width)
}
#[must_use]
pub fn width(text: &str) -> usize {
let chars: Vec<char> = text.chars().collect();
let mut total = 0;
let mut i = 0;
while i < chars.len() {
let (scanned, next) = scan(&chars, i);
if let Scanned::Visible(c) = scanned {
total += char_width(c);
}
i = next;
}
total
}
enum Tok {
Esc(String),
Ch(char, usize),
}
fn tokenize(text: &str) -> Vec<Tok> {
let chars: Vec<char> = text.chars().collect();
let mut toks = Vec::new();
let mut i = 0;
while i < chars.len() {
let (scanned, next) = scan(&chars, i);
match scanned {
Scanned::Escape(seq) => toks.push(Tok::Esc(seq)),
Scanned::Visible(c) => toks.push(Tok::Ch(c, char_width(c))),
Scanned::Control => {}
}
i = next;
}
toks
}
fn char_width(c: char) -> usize {
UnicodeWidthChar::width(c).unwrap_or(0)
}
enum Scanned {
Escape(String),
Visible(char),
Control,
}
fn scan(chars: &[char], i: usize) -> (Scanned, usize) {
let c = chars[i];
if c == '\u{1b}' {
return scan_escape(chars, i);
}
match c {
'\u{9b}' => return scan_csi(chars, i + 1, i),
'\u{90}' | '\u{9d}' | '\u{98}' | '\u{9e}' | '\u{9f}' => {
return scan_string_sequence(chars, i + 1, i);
}
_ => {}
}
if c.is_control() {
return (Scanned::Control, i + 1);
}
(Scanned::Visible(c), i + 1)
}
fn scan_escape(chars: &[char], i: usize) -> (Scanned, usize) {
match chars.get(i + 1).copied() {
Some('[') => scan_csi(chars, i + 2, i),
Some(']' | 'P' | 'X' | '^' | '_') => scan_string_sequence(chars, i + 2, i),
Some(c) if ('\u{20}'..='\u{2f}').contains(&c) => {
let mut j = i + 2;
while j < chars.len() && ('\u{20}'..='\u{2f}').contains(&chars[j]) {
j += 1;
}
if j < chars.len() && ('\u{30}'..='\u{7e}').contains(&chars[j]) {
j += 1;
}
(Scanned::Escape(slice(chars, i, j)), j)
}
Some(c) if ('\u{30}'..='\u{7e}').contains(&c) => {
(Scanned::Escape(slice(chars, i, i + 2)), i + 2)
}
_ => (Scanned::Escape(slice(chars, i, i + 1)), i + 1),
}
}
fn scan_csi(chars: &[char], body: usize, start: usize) -> (Scanned, usize) {
let mut j = body;
while j < chars.len() && ('\u{30}'..='\u{3f}').contains(&chars[j]) {
j += 1;
}
while j < chars.len() && ('\u{20}'..='\u{2f}').contains(&chars[j]) {
j += 1;
}
if j < chars.len() && ('\u{40}'..='\u{7e}').contains(&chars[j]) {
j += 1;
}
(Scanned::Escape(slice(chars, start, j)), j)
}
fn scan_string_sequence(chars: &[char], body: usize, start: usize) -> (Scanned, usize) {
let mut j = body;
while j < chars.len() {
let c = chars[j];
if c == '\u{07}' || c == '\u{9c}' {
j += 1;
break;
}
if c == '\u{1b}' && chars.get(j + 1) == Some(&'\\') {
j += 2;
break;
}
j += 1;
}
(Scanned::Escape(slice(chars, start, j)), j)
}
fn slice(chars: &[char], start: usize, end: usize) -> String {
chars[start..end].iter().collect()
}
fn prefix_cut(toks: &[Tok], avail: usize) -> usize {
let mut used = 0;
let mut cut = 0;
for (idx, t) in toks.iter().enumerate() {
if let Tok::Ch(_, w) = t {
if used + w > avail {
break;
}
used += w;
cut = idx + 1;
}
}
cut
}
fn suffix_start(toks: &[Tok], avail: usize) -> usize {
let mut used = 0;
let mut keep_from = toks.len();
for (idx, t) in toks.iter().enumerate().rev() {
match t {
Tok::Ch(_, w) => {
if used + w > avail {
break;
}
used += w;
keep_from = idx;
}
Tok::Esc(_) => keep_from = idx,
}
}
keep_from
}
fn drop_leading_zero_width(toks: &[Tok], mut from: usize) -> usize {
while let Some(Tok::Ch(_, 0)) = toks.get(from) {
from += 1;
}
from
}
fn emit(out: &mut String, toks: &[Tok], open: &mut bool) {
for t in toks {
match t {
Tok::Ch(c, _) => out.push(*c),
Tok::Esc(s) => {
out.push_str(s);
update_style(open, s);
}
}
}
}
fn push_tracked(out: &mut String, s: &str, open: &mut bool) {
out.push_str(s);
for t in tokenize(s) {
if let Tok::Esc(seq) = t {
update_style(open, &seq);
}
}
}
fn close(out: &mut String, open: bool) {
if open {
out.push_str(RESET);
}
}
fn update_style(open: &mut bool, seq: &str) {
if let Some(is_reset) = sgr_is_reset(seq) {
*open = !is_reset;
}
}
fn sgr_is_reset(seq: &str) -> Option<bool> {
let body = match seq.strip_prefix('\u{1b}') {
Some(rest) => rest.strip_prefix('[')?,
None => seq.strip_prefix('\u{9b}')?,
};
let params = body.strip_suffix('m')?;
Some(
params
.split(';')
.all(|p| p.is_empty() || p.bytes().all(|b| b == b'0')),
)
}
fn clamp_visible(s: &str, max: usize) -> String {
let mut out = String::new();
let mut used = 0;
let mut open = false;
for t in tokenize(s) {
match t {
Tok::Ch(c, w) => {
if used + w > max {
break;
}
out.push(c);
used += w;
}
Tok::Esc(seq) => {
out.push_str(&seq);
update_style(&mut open, &seq);
}
}
}
close(&mut out, open);
out
}