Skip to content

Commit 3c9e38e

Browse files
Expand tabs to spaces; add ProgressStyle::with_tab_width
Tab width in terminals is not standardized (though 4 or 8 spaces seems common) but this provides an escape hatch. This should fix console-rs#150.
1 parent 3bdc77d commit 3c9e38e

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/style.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ pub struct ProgressStyle {
2323
// how unicode-big each char in progress_chars is
2424
char_width: usize,
2525
format_map: HashMap<&'static str, fn(&ProgressState) -> String>,
26+
tab_width: usize,
2627
}
2728

2829
#[cfg(feature = "unicode-segmentation")]
@@ -91,6 +92,7 @@ impl ProgressStyle {
9192
char_width,
9293
template,
9394
format_map: HashMap::default(),
95+
tab_width: 4,
9496
}
9597
}
9698

@@ -140,6 +142,12 @@ impl ProgressStyle {
140142
self
141143
}
142144

145+
/// Sets the number of spaces to which tabs will be expanded. Default: 4
146+
pub fn with_tab_width(mut self, tab_width: usize) -> ProgressStyle {
147+
self.tab_width = tab_width;
148+
self
149+
}
150+
143151
/// Sets the template string for the progress bar
144152
///
145153
/// Review the [list of template keys](./index.html#templates) for more information.
@@ -327,6 +335,8 @@ impl ProgressStyle {
327335
continue;
328336
}
329337

338+
buf = buf.replace('\t', &" ".repeat(self.tab_width));
339+
330340
match width {
331341
Some(width) => {
332342
let padded = PaddedStringDisplay {
@@ -348,7 +358,9 @@ impl ProgressStyle {
348358
},
349359
}
350360
}
351-
TemplatePart::Literal(s) => cur.push_str(s),
361+
TemplatePart::Literal(s) => {
362+
cur.push_str(&s.replace('\t', &" ".repeat(self.tab_width)))
363+
}
352364
TemplatePart::NewLine => lines.push(match wide {
353365
Some(inner) => {
354366
inner.expand(mem::take(&mut cur), self, state, &mut buf, target_width)
@@ -398,7 +410,7 @@ impl<'a> WideElement<'a> {
398410
buf.write_fmt(format_args!(
399411
"{}",
400412
PaddedStringDisplay {
401-
str: &style.message,
413+
str: &style.message.replace('\t', &" ".repeat(style.tab_width)),
402414
width: left,
403415
align: *align,
404416
truncate: true,

0 commit comments

Comments
 (0)