Skip to content

Commit

Permalink
Replace nu-ansi-term with the anstyle crate
Browse files Browse the repository at this point in the history
The `anstyle` crate is already used by `clap` to print ANSI text styles.
  • Loading branch information
nickelc committed May 12, 2023
1 parent 1074adc commit e0b3ddc
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 87 deletions.
11 changes: 1 addition & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ regex-onig = ["syntect/regex-onig"] # Use the "oniguruma" regex engine
regex-fancy = ["syntect/regex-fancy"] # Use the rust-only "fancy-regex" engine

[dependencies]
anstyle = "1.0.0"
anstyle-query = "1.0.0"
is-terminal = { version = "0.4.4", optional = true }
nu-ansi-term = "0.47.0"
ansi_colours = "^1.2"
bincode = "1.0"
console = "0.15.5"
Expand Down
21 changes: 15 additions & 6 deletions src/bin/bat/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ use std::io::{BufReader, Write};
use std::path::Path;
use std::process;

use nu_ansi_term::Color::Green;
use nu_ansi_term::Style;
use anstyle::AnsiColor::Green;
use anstyle::Style;

use crate::{
app::App,
Expand Down Expand Up @@ -149,7 +149,7 @@ pub fn get_languages(config: &Config, cache_dir: &Path) -> Result<String> {
let desired_width = config.term_width - longest - separator.len();

let style = if config.colored_output {
Green.normal()
Green.on_default()
} else {
Style::default()
};
Expand All @@ -170,7 +170,14 @@ pub fn get_languages(config: &Config, cache_dir: &Path) -> Result<String> {
}

num_chars += new_chars;
write!(result, "{}", style.paint(&word[..])).ok();
write!(
result,
"{}{}{}",
style.render(),
&word[..],
style.render_reset()
)
.ok();
if extension.peek().is_some() {
result += comma_separator;
}
Expand Down Expand Up @@ -198,11 +205,13 @@ pub fn list_themes(cfg: &Config, config_dir: &Path, cache_dir: &Path) -> Result<
let mut stdout = stdout.lock();

if config.colored_output {
let bold = Style::new().bold();
for theme in assets.themes() {
writeln!(
stdout,
"Theme: {}\n",
Style::new().bold().paint(theme.to_string())
"Theme: {}{theme}{}\n",
bold.render(),
bold.render_reset(),
)?;
config.theme = theme.to_string();
Controller::new(&config, &assets)
Expand Down
14 changes: 8 additions & 6 deletions src/decorations.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use anstyle::Style;

#[cfg(feature = "git")]
use crate::diff::LineChange;
use crate::printer::{Colors, InteractivePrinter};
use nu_ansi_term::Style;
use crate::terminal::StyledExt;

#[derive(Debug, Clone)]
pub(crate) struct DecorationText {
Expand Down Expand Up @@ -31,7 +33,7 @@ impl LineNumberDecoration {
color: colors.line_number,
cached_wrap_invalid_at: 10000,
cached_wrap: DecorationText {
text: colors.line_number.paint(" ".repeat(4)).to_string(),
text: " ".repeat(4).styled(colors.line_number).to_string(),
width: 4,
},
}
Expand All @@ -49,7 +51,7 @@ impl Decoration for LineNumberDecoration {
if line_number > self.cached_wrap_invalid_at {
let new_width = self.cached_wrap.width + 1;
return DecorationText {
text: self.color.paint(" ".repeat(new_width)).to_string(),
text: " ".repeat(new_width).styled(self.color).to_string(),
width: new_width,
};
}
Expand All @@ -59,7 +61,7 @@ impl Decoration for LineNumberDecoration {
let plain: String = format!("{:4}", line_number);
DecorationText {
width: plain.len(),
text: self.color.paint(plain).to_string(),
text: plain.styled(self.color).to_string(),
}
}
}
Expand All @@ -83,7 +85,7 @@ impl LineChangesDecoration {
#[inline]
fn generate_cached(style: Style, text: &str) -> DecorationText {
DecorationText {
text: style.paint(text).to_string(),
text: text.styled(style).to_string(),
width: text.chars().count(),
}
}
Expand Down Expand Up @@ -135,7 +137,7 @@ impl GridBorderDecoration {
pub(crate) fn new(colors: &Colors) -> Self {
GridBorderDecoration {
cached: DecorationText {
text: colors.grid.paint("│").to_string(),
text: "│".styled(colors.grid).to_string(),
width: 1,
},
}
Expand Down
14 changes: 11 additions & 3 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::io::Write;
use thiserror::Error;

use crate::terminal::StyledExt;

#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
Expand Down Expand Up @@ -43,7 +45,7 @@ impl From<String> for Error {
pub type Result<T> = std::result::Result<T, Error>;

pub fn default_error_handler(error: &Error, output: &mut dyn Write) {
use nu_ansi_term::Color::Red;
use anstyle::AnsiColor::Red;

match error {
Error::Io(ref io_error) if io_error.kind() == ::std::io::ErrorKind::BrokenPipe => {
Expand All @@ -53,13 +55,19 @@ pub fn default_error_handler(error: &Error, output: &mut dyn Write) {
writeln!(
output,
"{}: Error while parsing metadata.yaml file: {}",
Red.paint("[bat error]"),
"[bat error]".styled(Red.on_default()),
error
)
.ok();
}
_ => {
writeln!(output, "{}: {}", Red.paint("[bat error]"), error).ok();
writeln!(
output,
"{}: {}",
"[bat error]".styled(Red.on_default()),
error
)
.ok();
}
};
}
4 changes: 2 additions & 2 deletions src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[macro_export]
macro_rules! bat_warning {
($($arg:tt)*) => ({
use nu_ansi_term::Color::Yellow;
eprintln!("{}: {}", Yellow.paint("[bat warning]"), format!($($arg)*));
let style = anstyle::AnsiColor::Yellow.on_default();
eprintln!("{}[bat warning]{}: {}", style.render(), style.render_reset(), format!($($arg)*));
})
}
66 changes: 27 additions & 39 deletions src/printer.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::io::Write;
use std::vec::Vec;

use nu_ansi_term::Color::{Fixed, Green, Red, Yellow};
use nu_ansi_term::Style;
use anstyle::{AnsiColor, Style};

use bytesize::ByteSize;

Expand Down Expand Up @@ -32,7 +31,7 @@ use crate::input::OpenedInput;
use crate::line_range::RangeCheckResult;
use crate::preprocessor::{expand_tabs, replace_nonprintable};
use crate::style::StyleComponent;
use crate::terminal::{as_terminal_escaped, to_ansi_color};
use crate::terminal::{as_terminal_escaped, to_ansi_color, StyledExt};
use crate::vscreen::AnsiStyle;
use crate::wrapping::WrappingMode;

Expand Down Expand Up @@ -222,7 +221,7 @@ impl<'a> InteractivePrinter<'a> {
writeln!(
handle,
"{}",
style.paint("─".repeat(self.config.term_width))
"─".repeat(self.config.term_width).styled(style),
)?;
Ok(())
}
Expand All @@ -233,7 +232,7 @@ impl<'a> InteractivePrinter<'a> {
} else {
let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
writeln!(handle, "{}", self.colors.grid.paint(hline))?;
writeln!(handle, "{}", hline.styled(self.colors.grid))?;
}

Ok(())
Expand Down Expand Up @@ -263,9 +262,7 @@ impl<'a> InteractivePrinter<'a> {
handle,
"{}{}",
" ".repeat(self.panel_width),
self.colors
.grid
.paint(if self.panel_width > 0 { "│ " } else { "" }),
if self.panel_width > 0 { "│ " } else { "" }.styled(self.colors.grid),
)
} else {
write!(handle, "{}", " ".repeat(self.panel_width))
Expand Down Expand Up @@ -300,7 +297,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
"{}: Binary content from {} will not be printed to the terminal \
(but will be present if the output of 'bat' is piped). You can use 'bat -A' \
to show the binary file contents.",
Yellow.paint("[bat warning]"),
"[bat warning]".styled(AnsiColor::Yellow.on_default()),
input.description.summary(),
)?;
} else if self.config.style_components.grid() {
Expand Down Expand Up @@ -358,7 +355,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
.kind()
.map(|kind| format!("{}: ", kind))
.unwrap_or_else(|| "".into()),
self.colors.header_value.paint(description.title()),
description.title().styled(self.colors.header_value),
mode
),

Expand All @@ -367,7 +364,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
.size
.map(|s| format!("{}", ByteSize(s)))
.unwrap_or_else(|| "-".into());
writeln!(handle, "Size: {}", self.colors.header_value.paint(bsize))
writeln!(handle, "Size: {}", bsize.styled(self.colors.header_value))
}
_ => Ok(()),
}
Expand Down Expand Up @@ -410,9 +407,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
writeln!(
handle,
"{}",
self.colors
.grid
.paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
format!("{}{}{}{}", panel, snip_left, title, snip_right).styled(self.colors.grid),
)?;

Ok(())
Expand Down Expand Up @@ -549,17 +544,15 @@ impl<'a> Printer for InteractivePrinter<'a> {

if text.len() != text_trimmed.len() {
if let Some(background_color) = background_color {
let ansi_style = Style {
background: to_ansi_color(background_color, true_color),
..Default::default()
};
let ansi_style = Style::new()
.bg_color(to_ansi_color(background_color, true_color));

let width = if cursor_total <= cursor_max {
cursor_max - cursor_total + 1
} else {
0
};
write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
write!(handle, "{}", " ".repeat(width).styled(ansi_style))?;
}
write!(handle, "{}", &text[text_trimmed.len()..])?;
}
Expand Down Expand Up @@ -668,15 +661,13 @@ impl<'a> Printer for InteractivePrinter<'a> {
}

if let Some(background_color) = background_color {
let ansi_style = Style {
background: to_ansi_color(background_color, self.config.true_color),
..Default::default()
};
let ansi_style =
Style::new().bg_color(to_ansi_color(background_color, self.config.true_color));

write!(
handle,
"{}",
ansi_style.paint(" ".repeat(cursor_max - cursor))
" ".repeat(cursor_max - cursor).styled(ansi_style),
)?;
}
writeln!(handle)?;
Expand Down Expand Up @@ -710,26 +701,23 @@ impl Colors {
}

fn colored(theme: &Theme, true_color: bool) -> Self {
let gutter_style = Style {
foreground: match theme.settings.gutter_foreground {
// If the theme provides a gutter foreground color, use it.
// Note: It might be the special value #00000001, in which case
// to_ansi_color returns None and we use an empty Style
// (resulting in the terminal's default foreground color).
Some(c) => to_ansi_color(c, true_color),
// Otherwise, use a specific fallback color.
None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
},
..Style::default()
};
let gutter_style = Style::new().fg_color(match theme.settings.gutter_foreground {
// If the theme provides a gutter foreground color, use it.
// Note: It might be the special value #00000001, in which case
// to_ansi_color returns None and we use an empty Style
// (resulting in the terminal's default foreground color).
Some(c) => to_ansi_color(c, true_color),
// Otherwise, use a specific fallback color.
None => Some(anstyle::Color::from(DEFAULT_GUTTER_COLOR)),
});

Colors {
grid: gutter_style,
rule: gutter_style,
header_value: Style::new().bold(),
git_added: Green.normal(),
git_removed: Red.normal(),
git_modified: Yellow.normal(),
git_added: AnsiColor::Green.on_default(),
git_removed: AnsiColor::Red.on_default(),
git_modified: AnsiColor::Yellow.on_default(),
line_number: gutter_style,
}
}
Expand Down
Loading

0 comments on commit e0b3ddc

Please sign in to comment.