Skip to content

Commit

Permalink
Expand tabs to spaces; add ProgressStyle::with_tab_width
Browse files Browse the repository at this point in the history
Tab width in terminals is not standardized (though 4 or 8 spaces seems common)
but this provides an escape hatch.

This should fix #150.
  • Loading branch information
chris-laplante committed Mar 31, 2022
1 parent 3bdc77d commit 3c9e38e
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub struct ProgressStyle {
// how unicode-big each char in progress_chars is
char_width: usize,
format_map: HashMap<&'static str, fn(&ProgressState) -> String>,
tab_width: usize,
}

#[cfg(feature = "unicode-segmentation")]
Expand Down Expand Up @@ -91,6 +92,7 @@ impl ProgressStyle {
char_width,
template,
format_map: HashMap::default(),
tab_width: 4,
}
}

Expand Down Expand Up @@ -140,6 +142,12 @@ impl ProgressStyle {
self
}

/// Sets the number of spaces to which tabs will be expanded. Default: 4
pub fn with_tab_width(mut self, tab_width: usize) -> ProgressStyle {
self.tab_width = tab_width;
self
}

/// Sets the template string for the progress bar
///
/// Review the [list of template keys](./index.html#templates) for more information.
Expand Down Expand Up @@ -327,6 +335,8 @@ impl ProgressStyle {
continue;
}

buf = buf.replace('\t', &" ".repeat(self.tab_width));

match width {
Some(width) => {
let padded = PaddedStringDisplay {
Expand All @@ -348,7 +358,9 @@ impl ProgressStyle {
},
}
}
TemplatePart::Literal(s) => cur.push_str(s),
TemplatePart::Literal(s) => {
cur.push_str(&s.replace('\t', &" ".repeat(self.tab_width)))
}
TemplatePart::NewLine => lines.push(match wide {
Some(inner) => {
inner.expand(mem::take(&mut cur), self, state, &mut buf, target_width)
Expand Down Expand Up @@ -398,7 +410,7 @@ impl<'a> WideElement<'a> {
buf.write_fmt(format_args!(
"{}",
PaddedStringDisplay {
str: &style.message,
str: &style.message.replace('\t', &" ".repeat(style.tab_width)),
width: left,
align: *align,
truncate: true,
Expand Down

0 comments on commit 3c9e38e

Please sign in to comment.