-
Notifications
You must be signed in to change notification settings - Fork 45
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
Option to preserve trailing whitespace #503
Comments
Hi @heiskane,
Interesting! Since you're doing something custom, have you considered using the All the wrapping logic operates on fragments: the "upper layer" simply splits the text into fragments using different options. I think your use case could be handled by
Today, the string
I'm suggesting instead turning it into
That should do the trick. You should be able to do this with the |
Thanks for the reply. I experimented a bit with what you suggested but i am still having some issues. The issue with this is that WordSeparator::Custom takes a closure that returns iterator over If Update: the method: impl<'a> Word<'a> {
// snip....
pub fn no_trim(word: &str) -> Word<'_> {
Word {
word,
width: display_width(word),
whitespace: "",
penalty: "",
}
}
} my (quick and dirty) solution to the issue: use textwrap::{core::Word, Options, WordSeparator};
fn main() {
let text = "as a hello";
let opts = Options::new(5).word_separator(WordSeparator::Custom(|line| {
let mut start = 0;
let mut prev_char = ' ';
let mut char_indices = line.char_indices();
println!("line: {:?}", line);
Box::new(std::iter::from_fn(move || {
for (idx, ch) in char_indices.by_ref() {
if prev_char == ' ' && start != 0 {
let word = Word::no_trim(" ");
println!("word0: {:?}", word);
prev_char = ch;
start = idx;
return Some(word);
}
if prev_char != ' ' && ch == ' ' {
let word = Word::from(&line[start..idx]);
println!("word1: {:?}", word);
start = idx;
prev_char = ch;
return Some(word);
}
prev_char = ch;
}
if start < line.len() {
let word = Word::no_trim(&line[start..]);
println!("word2: {:?}", word);
start = line.len();
return Some(word);
}
None
}))
}));
let wrapped = textwrap::wrap(text, opts);
println!("{wrapped:?}");
} prints:
Could this method (or something similar) be added to the crate so that wrapping without trimming would be possible? I can submit a PR if the method i created is fine (and maybe create a new |
Currently working on something that requires me to keep track of a cursor in a message and wrap the message in a textbox with the cursor in the right place. This currently is not possible as wrapping trims the trailing whitespace making wrapped text different length from the original message misaligning any position i might track in the message.
Trimming trailing whitespace could be disabled in the options?
wanted behavior.
The text was updated successfully, but these errors were encountered: