From 13cdb0218c4ba9a0b531f41e49964704932d2510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Mon, 3 May 2021 23:49:41 +0200 Subject: truncate long strings --- src/window.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/window.rs b/src/window.rs index 3714c4c..a2f2b68 100644 --- a/src/window.rs +++ b/src/window.rs @@ -2,6 +2,7 @@ use std::io::Write; use termion::{color, cursor}; +use unicode_segmentation::UnicodeSegmentation; #[derive(Clone, Copy)] pub struct Area { @@ -16,6 +17,15 @@ pub enum Line { Highlight(String), } +pub fn truncate_dots(s: &str, to: usize) -> String { + let graphemes = s.graphemes(true).collect::>(); + if graphemes.len() >= to { + format!("{}...", graphemes.iter().take(to - 3).fold(String::new(), |acc, s| format!("{}{}", acc, s))) + } else { + graphemes.join("") + } +} + pub struct Window { pub lines: Vec, scroll: usize, @@ -37,12 +47,12 @@ impl Window { Some(line) => { write!(out, "{}", cursor::Goto(area.x, y))?; match line { - Line::Normal(s) => write!(out, "{}", s)?, + Line::Normal(s) => write!(out, "{}", truncate_dots(s, area.w as usize))?, Line::Highlight(s) => write!( out, "{}{}{}", color::Fg(color::Red), - s, + truncate_dots(s, area.w as usize), color::Fg(color::Reset), )?, } -- cgit v1.2.1