From c1b6c382d8b020238e64c811bcc6f905f0f5390d Mon Sep 17 00:00:00 2001 From: jao Date: Fri, 4 Feb 2022 02:12:32 +0000 Subject: Refactoring: Xmobar.Text.{Ansi,Pango,Output} --- src/Xmobar/Text/Ansi.hs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/Xmobar/Text/Ansi.hs (limited to 'src/Xmobar/Text/Ansi.hs') diff --git a/src/Xmobar/Text/Ansi.hs b/src/Xmobar/Text/Ansi.hs new file mode 100644 index 0000000..2f1c2c4 --- /dev/null +++ b/src/Xmobar/Text/Ansi.hs @@ -0,0 +1,44 @@ +------------------------------------------------------------------------------ +-- | +-- Module: Xmobar.Text.Ansi +-- Copyright: (c) 2022 Jose Antonio Ortega Ruiz +-- License: BSD3-style (see LICENSE) +-- +-- Maintainer: jao@gnu.org +-- Stability: unstable +-- Portability: portable +-- Created: Fri Feb 4, 2022 01:10 +-- +-- +-- Codification with ANSI (color) escape codes +-- +------------------------------------------------------------------------------ + +module Xmobar.Text.Ansi (withAnsiColor) where + +import Data.List (intercalate) + +asInt :: String -> String +asInt x = case (reads $ "0x" ++ x) :: [(Integer, String)] of + [(v, "") ] -> show v + _ -> "" + +namedColor :: String -> String +namedColor c = + case c of + "black" -> "0"; "red" -> "1"; "green" -> "2"; "yellow" -> "3"; "blue" -> "4"; + "magenta" -> "5"; "cyan" -> "6"; "white" -> "7"; _ -> "" + +ansiCode :: String -> String +ansiCode ('#':r:g:[b]) = ansiCode ['#', '0', r, '0', g, '0', b] +ansiCode ('#':r0:r1:g0:g1:b0:[b1]) = + "2;" ++ intercalate ";" (map asInt [[r0,r1], [g0,g1], [b0,b1]]) +ansiCode ('#':n) = ansiCode n +ansiCode c = "5;" ++ if null i then namedColor c else i where i = asInt c + +withAnsiColor :: (String, String) -> String -> String +withAnsiColor (fg, bg) s = wrap "38;" fg (wrap "48;" bg s) + where wrap cd cl w = + if null cl + then w + else "\x1b[" ++ cd ++ ansiCode cl ++ "m" ++ w ++ "\x1b[0m" -- cgit v1.2.3