From 8963749e6aea4ee03589e9ed4967d841f0856971 Mon Sep 17 00:00:00 2001 From: Denis Isidoro Date: Sat, 8 Apr 2023 20:53:25 -0300 Subject: [PATCH] Correctly calculate character widths (#820) --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + src/deser/mod.rs | 16 +++++++++++++--- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e0f3fa5..824684b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -446,6 +446,7 @@ dependencies = [ "shellwords", "strip-ansi-escapes", "thiserror", + "unicode-width", "walkdir", ] @@ -973,6 +974,12 @@ version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" +[[package]] +name = "unicode-width" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" + [[package]] name = "unicode-xid" version = "0.2.2" diff --git a/Cargo.toml b/Cargo.toml index dacbc1a..25e5d1d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ serde = { version = "1.0.159", features = ["derive"] } serde_yaml = "0.9.21" dns_common_derive = { version = "0.2.1" } dns_common = { version = "0.2.1", default-features = false, features = ["yaml", "json"] } +unicode-width = "0.1.10" [lib] name = "navi" diff --git a/src/deser/mod.rs b/src/deser/mod.rs index c97f7f2..7b2662e 100644 --- a/src/deser/mod.rs +++ b/src/deser/mod.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use unicode_width::UnicodeWidthStr; pub mod raycast; pub mod terminal; @@ -26,9 +27,18 @@ pub fn fix_newlines(txt: &str) -> String { } fn limit_str(text: &str, length: usize) -> String { - if text.len() > length { - format!("{}…", text.chars().take(length - 1).collect::()) + let len = UnicodeWidthStr::width(text); + if len <= length { + format!("{}{}", text, " ".repeat(length - len)) } else { - format!("{:width$}", text, width = length) + let mut new_length = length; + let mut actual_length = 9999; + let mut txt = text.to_owned(); + while actual_length > length { + txt = txt.chars().take(new_length - 1).collect::(); + actual_length = UnicodeWidthStr::width(txt.as_str()); + new_length -= 1; + } + format!("{}…", txt) } }