summaryrefslogtreecommitdiffstats
path: root/src/bat
diff options
context:
space:
mode:
authorDan Davison <dandavison7@gmail.com>2020-03-02 06:32:55 -0600
committerDan Davison <dandavison7@gmail.com>2020-03-02 23:34:03 -0600
commit185dbd5e87e35a625ceaaea7fd36a35e948e44b1 (patch)
tree1032c49b82572c5895ec17dbbbccf9a4442a443f /src/bat
parent299ce3b54c83d8eb27769a189ef1084e5d8d3700 (diff)
Use ansi_term crate and bat's helpers for painting text
Diffstat (limited to 'src/bat')
-rw-r--r--src/bat/mod.rs1
-rw-r--r--src/bat/terminal.rs53
2 files changed, 54 insertions, 0 deletions
diff --git a/src/bat/mod.rs b/src/bat/mod.rs
index 88673f26..04f6dbf7 100644
--- a/src/bat/mod.rs
+++ b/src/bat/mod.rs
@@ -1,3 +1,4 @@
pub mod assets;
pub mod dirs;
pub mod output;
+pub mod terminal;
diff --git a/src/bat/terminal.rs b/src/bat/terminal.rs
new file mode 100644
index 00000000..50351c48
--- /dev/null
+++ b/src/bat/terminal.rs
@@ -0,0 +1,53 @@
+extern crate ansi_colours;
+
+use ansi_term::Colour::{Fixed, RGB};
+use ansi_term::{self, Style};
+
+use syntect::highlighting::{self, FontStyle};
+
+pub fn to_ansi_color(color: highlighting::Color, true_color: bool) -> ansi_term::Colour {
+ if color.a == 0 {
+ // Themes can specify one of the user-configurable terminal colors by
+ // encoding them as #RRGGBBAA with AA set to 00 (transparent) and RR set
+ // to the color palette number. The built-in themes ansi-light,
+ // ansi-dark, and base16 use this.
+ Fixed(color.r)
+ } else if true_color {
+ RGB(color.r, color.g, color.b)
+ } else {
+ Fixed(ansi_colours::ansi256_from_rgb((color.r, color.g, color.b)))
+ }
+}
+
+#[allow(dead_code)]
+pub fn as_terminal_escaped(
+ style: highlighting::Style,
+ text: &str,
+ true_color: bool,
+ colored: bool,
+ italics: bool,
+ background_color: Option<highlighting::Color>,
+) -> String {
+ if text.is_empty() {
+ return text.to_string();
+ }
+
+ let mut style = if !colored {
+ Style::default()
+ } else {
+ let color = to_ansi_color(style.foreground, true_color);
+
+ if style.font_style.contains(FontStyle::BOLD) {
+ color.bold()
+ } else if style.font_style.contains(FontStyle::UNDERLINE) {
+ color.underline()
+ } else if italics && style.font_style.contains(FontStyle::ITALIC) {
+ color.italic()
+ } else {
+ color.normal()
+ }
+ };
+
+ style.background = background_color.map(|c| to_ansi_color(c, true_color));
+ style.paint(text).to_string()
+}