{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
module System.Console.Pretty
( Color(..) , Pretty(..) , Section(..) , Style(..)
, supportsPretty)
where
import qualified Data.Char as C
import Data.Monoid ((<>))
import qualified Data.Text as T
import GHC.IO.Handle (Handle)
import System.Environment (lookupEnv)
import System.IO (hIsTerminalDevice, stdout)
data Section = Foreground | Background
data Color = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White | Default
deriving (Enum)
data Style
= Normal | Bold | Faint | Italic
| Underline | SlowBlink | ColoredNormal | Reverse
deriving (Enum)
class Pretty a where
color :: Color -> a -> a
color = colorize Foreground
bgColor :: Color -> a -> a
bgColor = colorize Background
colorize :: Section -> Color -> a -> a
style :: Style -> a -> a
instance Pretty T.Text where
colorize section col str =
"\x1b[" <>
sectionNum <>
(T.singleton $ C.intToDigit $ fromEnum col)
<> "m" <>
str <>
"\x1b[0m"
where
sectionNum :: T.Text
sectionNum = case section of
Foreground -> "9"
Background -> "4"
style sty str =
"\x1b[" <>
(T.singleton $ C.intToDigit $ fromEnum sty)
<> "m" <>
str <>
"\x1b[0m"
instance Pretty String where
colorize section col str =
"\x1b[" <>
sectionNum <>
show (fromEnum col)
<> "m" <>
str <>
"\x1b[0m"
where
sectionNum :: String
sectionNum = case section of
Foreground -> "9"
Background -> "4"
style sty str =
"\x1b[" <>
show (fromEnum sty)
<> "m" <>
str <>
"\x1b[0m"
supportsPretty :: IO Bool
supportsPretty =
hSupportsANSI stdout
where
hSupportsANSI :: Handle -> IO Bool
hSupportsANSI h = (&&) <$> hIsTerminalDevice h <*> (not <$> isDumb)
where
isDumb = (== Just "dumb") <$> lookupEnv "TERM"