refactor: let textwrap handle long words

The textwrap crate can handle long words fine. By default they're
broken to avoid lines longer than the specified width, but this can be
disabled.
This commit is contained in:
Martin Geisler 2017-02-08 20:33:40 +01:00 committed by Kevin K
parent f89a012d09
commit 88f26e083e

View file

@ -25,18 +25,6 @@ mod term_size {
pub fn dimensions() -> Option<(usize, usize)> { None }
}
macro_rules! find_longest {
($help:expr) => {{
let mut lw = 0;
for l in $help.split(' ').map(|s| str_width(s)) {
if l > lw {
lw = l;
}
}
lw
}};
}
fn str_width(s: &str) -> usize { UnicodeWidthStr::width(s) }
const TAB: &'static str = " ";
@ -407,9 +395,8 @@ impl<'a> Help<'a> {
// Determine how many newlines we need to insert
debugln!("Help::write_before_after_help: Usable space: {}",
self.term_w);
let longest_w = find_longest!(help);
help = help.replace("{n}", "\n");
wrap_help(&mut help, longest_w, self.term_w);
wrap_help(&mut help, self.term_w);
} else {
sdebugln!("No");
}
@ -450,9 +437,8 @@ impl<'a> Help<'a> {
// Determine how many newlines we need to insert
let avail_chars = self.term_w - spcs;
debugln!("Help::help: Usable space...{}", avail_chars);
let longest_w = find_longest!(help);
help = help.replace("{n}", "\n");
wrap_help(&mut help, longest_w, avail_chars);
wrap_help(&mut help, avail_chars);
} else {
sdebugln!("No");
}
@ -629,9 +615,8 @@ impl<'a> Help<'a> {
macro_rules! write_name {
() => {{
let mut name = parser.meta.name.clone();
let longest_w = find_longest!(name);
name = name.replace("{n}", "\n");
wrap_help(&mut name, longest_w, self.term_w);
wrap_help(&mut name, self.term_w);
try!(color!(self, &*name, good));
}};
}
@ -659,9 +644,8 @@ impl<'a> Help<'a> {
macro_rules! write_thing {
($thing:expr) => {{
let mut owned_thing = $thing.to_owned();
let longest_w = find_longest!(owned_thing);
owned_thing = owned_thing.replace("{n}", "\n");
wrap_help(&mut owned_thing, longest_w, self.term_w);
wrap_help(&mut owned_thing, self.term_w);
try!(write!(self.writer, "{}\n", &*owned_thing))
}};
}
@ -923,15 +907,12 @@ impl<'a> Help<'a> {
}
}
fn wrap_help(help: &mut String, longest_w: usize, avail_chars: usize) {
// Keep previous behavior of not wrapping at all if one of the
// words would overflow the line.
if longest_w < avail_chars {
*help = help.lines()
.map(|line| textwrap::fill(line, avail_chars))
.collect::<Vec<String>>()
.join("\n");
}
fn wrap_help(help: &mut String, avail_chars: usize) {
let wrapper = textwrap::Wrapper::new(avail_chars).break_words(false);
*help = help.lines()
.map(|line| wrapper.fill(line))
.collect::<Vec<String>>()
.join("\n");
}
#[cfg(test)]
@ -941,7 +922,7 @@ mod test {
#[test]
fn wrap_help_last_word() {
let mut help = String::from("foo bar baz");
wrap_help(&mut help, 3, 5);
wrap_help(&mut help, 5);
assert_eq!(help, "foo\nbar\nbaz");
}
}