haskellfunctional-programmingansi-escapeterminal-emulatoransi-colors

How do I use System.Console.ANSI to wrap a String in escape sequences for getting it colored in the terminal?


Here I've learned about System.Console.ANSI, and at that doc page I read of the "strawberry" flavour functions, of which I read that

has a String type and just consists of an escape code which can be added to any other bit of text before being output.

which feels just what I want in pure code, a way to take a String and wrap it somehow in escape sequences, so that when that String finds its way in the IO monad and will printed in the terminal, it gets printed, say, in red.

How can I use the aforementioned module for this?

Clicking on the Example.hs link gives a 404.


Solution

  • The "strawberry" functions are the ones that end in the Code suffix.

    Note that they don't transform String values. They simply produce String values that, when output to an ANSI terminal, perform the desired action (changing the color, moving the cursor, whatever). So, for example, you can define a pure String value by concatenating codes and plain text:

    redHelloWorld :: String
    redHelloWorld
      = setSGRCode [SetColor Foreground Vivid Red]
      ++ "hello world"
      ++ setSGRCode [Reset]
    

    and write it to the console in main or some other IO function:

    main :: IO ()
    main = do
      putStrLn redHelloWorld
    

    A full sample program:

    import System.Console.ANSI
    
    redHelloWorld :: String
    redHelloWorld
      = setSGRCode [SetColor Foreground Vivid Red]
      ++ "hello world"
      ++ setSGRCode [Reset]
    
    main :: IO ()
    main = do
      putStrLn redHelloWorld