module Data.Text.Format
(
Format
, Only(..)
, Fast(..)
, Shown(..)
, format
, print
, hprint
, build
, left
, right
, hex
, expt
, expt_
, fixed
, fixed_
) where
import Control.Monad.IO.Class (MonadIO(liftIO))
import Data.Text.Format.Functions ((<>))
import Data.Text.Format.Params (Params(..))
import Data.Text.Format.Types.Internal (FPControl(..), FPFormat(..), Fast(..))
import Data.Text.Format.Types.Internal (Format(..), Hex(..), Only(..), Shown(..))
import Data.Text.Lazy.Builder
import Prelude hiding (exp, print)
import System.IO (Handle)
import qualified Data.Text as ST
import qualified Data.Text.Buildable as B
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.IO as LT
build :: Params ps => Format -> ps -> Builder
build (Format fmt) ps = zipParams (map fromText . ST.splitOn "{}" $ fmt) xs
where zipParams (f:fs) (y:ys) = f <> y <> zipParams fs ys
zipParams [f] [] = f
zipParams _ _ = error . LT.unpack $ format
"Data.Text.Format.build: {} sites, but {} parameters"
(ST.count "{}" fmt, length xs)
xs = buildParams ps
format :: Params ps => Format -> ps -> LT.Text
format fmt ps = toLazyText $ build fmt ps
print :: (MonadIO m, Params ps) => Format -> ps -> m ()
print fmt ps = liftIO . LT.putStr . toLazyText $ build fmt ps
hprint :: (MonadIO m, Params ps) => Handle -> Format -> ps -> m ()
hprint h fmt ps = liftIO . LT.hPutStr h . toLazyText $ build fmt ps
left :: B.Buildable a => Int -> Char -> a -> Builder
left k c =
fromLazyText . LT.justifyRight (fromIntegral k) c . toLazyText . B.build
right :: B.Buildable a => Int -> Char -> a -> Builder
right k c =
fromLazyText . LT.justifyLeft (fromIntegral k) c . toLazyText . B.build
fixed :: (B.Buildable a, RealFloat a) =>
Int
-> a -> Builder
fixed decs = B.build . FPControl Fixed (Just decs)
fixed_ :: (B.Buildable a, RealFloat a) => a -> Builder
fixed_ = B.build . FPControl Fixed Nothing
expt :: (B.Buildable a, RealFloat a) =>
Int
-> a -> Builder
expt decs = B.build . FPControl Exponent (Just decs)
expt_ :: (B.Buildable a, RealFloat a) => a -> Builder
expt_ = B.build . FPControl Exponent Nothing
hex :: Integral a => a -> Builder
hex = B.build . Hex