Correctly calculate character widths (#820)

This commit is contained in:
Denis Isidoro 2023-04-08 20:53:25 -03:00 committed by GitHub
parent 2b03c89034
commit 8963749e6a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 3 deletions

7
Cargo.lock generated
View file

@ -446,6 +446,7 @@ dependencies = [
"shellwords", "shellwords",
"strip-ansi-escapes", "strip-ansi-escapes",
"thiserror", "thiserror",
"unicode-width",
"walkdir", "walkdir",
] ]
@ -973,6 +974,12 @@ version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4"
[[package]]
name = "unicode-width"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.2" version = "0.2.2"

View file

@ -35,6 +35,7 @@ serde = { version = "1.0.159", features = ["derive"] }
serde_yaml = "0.9.21" serde_yaml = "0.9.21"
dns_common_derive = { version = "0.2.1" } dns_common_derive = { version = "0.2.1" }
dns_common = { version = "0.2.1", default-features = false, features = ["yaml", "json"] } dns_common = { version = "0.2.1", default-features = false, features = ["yaml", "json"] }
unicode-width = "0.1.10"
[lib] [lib]
name = "navi" name = "navi"

View file

@ -1,4 +1,5 @@
use crate::prelude::*; use crate::prelude::*;
use unicode_width::UnicodeWidthStr;
pub mod raycast; pub mod raycast;
pub mod terminal; pub mod terminal;
@ -26,9 +27,18 @@ pub fn fix_newlines(txt: &str) -> String {
} }
fn limit_str(text: &str, length: usize) -> String { fn limit_str(text: &str, length: usize) -> String {
if text.len() > length { let len = UnicodeWidthStr::width(text);
format!("{}", text.chars().take(length - 1).collect::<String>()) if len <= length {
format!("{}{}", text, " ".repeat(length - len))
} else { } 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::<String>();
actual_length = UnicodeWidthStr::width(txt.as_str());
new_length -= 1;
}
format!("{}", txt)
} }
} }