-
Notifications
You must be signed in to change notification settings - Fork 111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Helper function for slicing strings with ansi codes in them. #135
Comments
something like this fn split_long_word(allowed_width: usize, word: &str) -> (String, String) {
let mut iter = console::AnsiCodeIterator::new(word);
let mut current_len = 0;
let mut escapes = Vec::new();
let mut head = String::with_capacity(word.len());
let mut tail = String::with_capacity(word.len());
#[allow(clippy::while_let_on_iterator)]
while let Some((val,is_esc)) = iter.next(){
if is_esc {
escapes.push(val);
if val == crossterm::style::Attribute::Reset.to_string() {
tail.clear();
}
}
let len = match is_esc {
true => 0,
false => val.chars().count(),
};
if current_len + len <= allowed_width {
head.push_str(val);
current_len += len;
}else{
assert!(! is_esc);
let split = val.split_at(allowed_width - current_len);
head.push_str(split.0);
head.push_str(crossterm::style::Attribute::Reset.to_string().as_str());
for esc in escapes{
tail.push_str(esc);
}
tail.push_str(split.1);
break;
}
}
iter.for_each(|s| tail.push_str(s.0));
(head, tail)
}
fn main() {
let a = split_long_word(10,
&format!(r"asdf12{}", console::style(".device").bold().red())
);
println!("{}|newline\n{}|stuff", a.0,a.1);
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The library currently has helper functions for stripping escape codes, and measuring string length with them removed.
It would be useful to have a helper function which can break up a string, inserting escape codes to terminate and resume the styling. This would in particular be useful for multi-line strings being formatted into columned outputs. Like I am trying to do here: Nukesor/comfy-table#91
The text was updated successfully, but these errors were encountered: