{- | 
General and hledger-specific input/output-related helpers for
pretty-printing haskell values, error reporting, time, files, command line parsing,
terminals, pager output, ANSI colour/styles, etc.
-}

{-# LANGUAGE ImplicitParams      #-}
{-# LANGUAGE LambdaCase          #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE PackageImports      #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

module Hledger.Utils.IO (

  -- * Pretty showing/printing
  pshow,
  pshow',
  pprint,
  pprint',

  -- * Errors
  error',
  usageError,
  warn,
  warnIO,
  setWarningHandler,
  ansiFormatError,
  ansiFormatWarning,
  printError,
  exitWithErrorMessage,
  handleExit,

  -- * Time
  getCurrentLocalTime,
  getCurrentZonedTime,

  -- * Files
  dataDirName,
  rulesDirName,
  getHomeSafe,
  embedFileRelative,
  embedFileRelativeBytes,
  expandHomePath,
  expandPath,
  expandGlob,
  expandPathOrGlob,
  sortByModTime,
  openFileOrStdin,
  withFileOrStdout,
  ensureFilesystemCanAppend,
  readFileOrStdinPortably,
  readFileOrStdinPortably',
  readFileStrictly,
  readFilePortably,
  hGetContentsPortably,
  -- hereFileRelative,
  textToHandle,

  -- * Command line parsing
  progArgs,
  getFlag,
  getOpt,
  parseYN,
  parseYNA,
  YNA(..),
  -- hasOutputFile,
  -- outputFileOption,

  -- * Terminal size
  getTerminalHeightWidth,
  getTerminalHeight,
  getTerminalWidth,
  insideEmacsNotVterm,

  -- * Pager output
  findPager,
  runPager,
  lessVarValue,
  lessIsWorking,

  -- * ANSI colour/styles

  -- ** hledger-specific

  colorOption,
  useColorOnStdout,
  useColorOnStderr,
  useColorOnStdoutUnsafe,
  useColorOnStderrUnsafe,
  supportsTrueColor,
  supportsTrueColorUnsafe,
  bold',
  faint',
  black',
  red',
  green',
  yellow',
  blue',
  magenta',
  cyan',
  white',
  brightBlack',
  brightRed',
  brightGreen',
  brightYellow',
  brightBlue',
  brightMagenta',
  brightCyan',
  brightWhite',
  rgb',
  sgrresetall,
  accent,
  gradientStr,
  titleLine,
  titleAndVersionLine,

  -- ** Generic

  color,
  bgColor,
  colorB,
  bgColorB,
  -- XXX Types used with color/bgColor/colorB/bgColorB,
  -- not re-exported because clashing with UIUtils:
  -- Color(..),
  -- ColorIntensity(..),

  terminalIsLight,
  terminalLightness,
  terminalFgColor,
  terminalBgColor,

  )
where

import           Control.Concurrent (forkIO)
import           Control.Exception
import           Control.Monad (when, forM, guard, void)
import           Data.Char (toLower, isSpace)
import Data.ByteString qualified as BS
import           Data.Colour.RGBSpace (RGB(RGB))
import           Data.Colour.RGBSpace.HSL (lightness)
import           Data.Colour.SRGB (sRGB)
import           Data.Encoding (DynEncoding)
import           Data.FileEmbed (makeRelativeToProject, embedFile, embedStringFile)
import           Data.Functor ((<&>))
import           Data.IORef (IORef, newIORef, readIORef, writeIORef)
import           Data.List hiding (uncons)
import           Data.Maybe (isJust, catMaybes)
import Data.Text qualified as T
import           Data.Text.Encoding.Error (UnicodeException)
import Data.Text.IO qualified as T
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as TB
import           Data.Time.Clock (getCurrentTime)
import           Data.Time.LocalTime (LocalTime, ZonedTime, getCurrentTimeZone, utcToLocalTime, utcToZonedTime)
import           Data.Word (Word16)
import           Debug.Trace
import           Foreign.C.Error (Errno(..), ePIPE)
import           GHC.IO.Encoding (getLocaleEncoding, textEncodingName)
import           GHC.IO.Exception (IOException(..), IOErrorType (ResourceVanished))
import           Language.Haskell.TH.Syntax (Q, Exp)
import           Safe (headMay, maximumDef)
import           System.Console.ANSI (Color(..),ColorIntensity(..), ConsoleLayer(..), SGR(..), hSupportsANSIColor, setSGRCode, getLayerColor, ConsoleIntensity (..), xterm6LevelRGB)
import           System.Console.Terminal.Size (Window (Window), size)
import           System.Directory (getHomeDirectory, getModificationTime, findExecutable)
import           System.Environment (getArgs, getEnvironment, lookupEnv, getProgName)
import           System.Exit (ExitCode(ExitSuccess), exitFailure)
import           System.FilePath (isRelative, (</>), takeBaseName)
import "Glob"    System.FilePath.Glob (glob)
import           System.Info (os)
import           System.IO (Handle, IOMode (..), hClose, hGetEncoding, hIsTerminalDevice, hPutStr, hPutStrLn, hSetNewlineMode, hSetEncoding, openFile, stderr, stdin, stdout, universalNewlineMode, utf8_bom, utf8, withFile)
import System.IO.Encoding qualified as Enc
import           System.IO.Temp (withTempFile)
import           System.IO.Unsafe (unsafePerformIO)
import           System.Process (CreateProcess(..), StdStream(CreatePipe), createPipe, proc, readCreateProcessWithExitCode, shell, waitForProcess, withCreateProcess)
import           System.Timeout (timeout)
import           Text.Pretty.Simple (CheckColorTty(..), OutputOptions(..), defaultOutputOptionsDarkBg, defaultOutputOptionsNoColor, pShowOpt, pPrintOpt)

import Hledger.Utils.Text (WideBuilder(WideBuilder))
import Control.Monad.IO.Class (MonadIO, liftIO)


-- Pretty showing/printing
-- using pretty-simple

-- https://hackage.haskell.org/package/pretty-simple/docs/Text-Pretty-Simple.html#t:OutputOptions

-- | pretty-simple options with colour enabled if allowed.
prettyopts :: OutputOptions
prettyopts =
  (if Bool
useColorOnStderrUnsafe then OutputOptions
defaultOutputOptionsDarkBg else OutputOptions
defaultOutputOptionsNoColor)
    { outputOptionsIndentAmount = 2
    -- , outputOptionsCompact      = True  -- fills lines, but does not respect page width (https://github.com/cdepillabout/pretty-simple/issues/126)
    -- , outputOptionsPageWidth    = fromMaybe 80 $ unsafePerformIO getTerminalWidth
    }

-- | pretty-simple options with colour disabled.
prettyoptsNoColor :: OutputOptions
prettyoptsNoColor =
  OutputOptions
defaultOutputOptionsNoColor
    { outputOptionsIndentAmount=2
    }

-- | Pretty show. An easier alias for pretty-simple's pShow.
-- This will probably show in colour if useColorOnStderrUnsafe is true.
pshow :: Show a => a -> String
pshow :: forall a. Show a => a -> String
pshow = Text -> String
TL.unpack (Text -> String) -> (a -> Text) -> a -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OutputOptions -> a -> Text
forall a. Show a => OutputOptions -> a -> Text
pShowOpt OutputOptions
prettyopts

-- | Monochrome version of pshow. This will never show in colour.
pshow' :: Show a => a -> String
pshow' :: forall a. Show a => a -> String
pshow' = Text -> String
TL.unpack (Text -> String) -> (a -> Text) -> a -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OutputOptions -> a -> Text
forall a. Show a => OutputOptions -> a -> Text
pShowOpt OutputOptions
prettyoptsNoColor

-- | Pretty print a showable value. An easier alias for pretty-simple's pPrint.
-- This will print in colour if useColorOnStderrUnsafe is true.
pprint :: Show a => a -> IO ()
pprint :: forall a. Show a => a -> IO ()
pprint = CheckColorTty -> OutputOptions -> a -> IO ()
forall (m :: * -> *) a.
(MonadIO m, Show a) =>
CheckColorTty -> OutputOptions -> a -> m ()
pPrintOpt (if Bool
useColorOnStderrUnsafe then CheckColorTty
CheckColorTty else CheckColorTty
NoCheckColorTty) OutputOptions
prettyopts

-- | Monochrome version of pprint. This will never print in colour.
pprint' :: Show a => a -> IO ()
pprint' :: forall a. Show a => a -> IO ()
pprint' = CheckColorTty -> OutputOptions -> a -> IO ()
forall (m :: * -> *) a.
(MonadIO m, Show a) =>
CheckColorTty -> OutputOptions -> a -> m ()
pPrintOpt CheckColorTty
NoCheckColorTty OutputOptions
prettyoptsNoColor

-- "Avoid using pshow, pprint, dbg* in the code below to prevent infinite loops." (?)



-- Errors

-- | Call errorWithoutStackTrace, prepending a "Error:" label.
error' :: String -> a
error' :: forall a. String -> a
error' = String -> a
forall a. String -> a
errorWithoutStackTrace (String -> a) -> (String -> String) -> String -> a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String
"Error: "String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)

-- | Like error', but add a hint about using -h
-- (on its own line, if the message has several lines).
usageError :: String -> a
usageError :: forall a. String -> a
usageError String
msg = String -> a
forall a. String -> a
error' (String -> a) -> String -> a
forall a b. (a -> b) -> a -> b
$ String
msg' String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
sep String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"(use -h to see usage)"
  where
    msg' :: String
msg' = (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\n') String
msg
    sep :: String
sep  = if Char
'\n' Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` String
msg' then String
"\n" else String
" "

-- | Apply standard ANSI SGR formatting (red, bold) suitable for console error text.
ansiFormatError :: String -> String
ansiFormatError :: String -> String
ansiFormatError = (String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
sgrresetall) (String -> String) -> (String -> String) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((String
sgrbrightred String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
sgrbold) String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)

-- | Show a warning message on stderr before returning the given value.
-- Like trace, but prepends a "Warning:" label, and does some ANSI styling of the first line when allowed (using unsafe IO).
-- Currently we use this very sparingly in hledger; we prefer to either quietly work, or loudly raise an error.
-- Varying output can make scripting harder. But on stderr, it shouldn't cause much hassle.
warn :: String -> a -> a
warn :: forall a. String -> a -> a
warn = String -> a -> a
forall a. String -> a -> a
trace (String -> a -> a) -> (String -> String) -> String -> a -> a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String
formatWarning

-- | The action warnIO uses to emit a warning message:
-- by default, print it to stderr with a "Warning:" prefix and ANSI styling when supported.
{-# NOINLINE warningHandler #-}
warningHandler :: IORef (String -> IO ())
warningHandler :: IORef (String -> IO ())
warningHandler = IO (IORef (String -> IO ())) -> IORef (String -> IO ())
forall a. IO a -> a
unsafePerformIO (IO (IORef (String -> IO ())) -> IORef (String -> IO ()))
-> IO (IORef (String -> IO ())) -> IORef (String -> IO ())
forall a b. (a -> b) -> a -> b
$ (String -> IO ()) -> IO (IORef (String -> IO ()))
forall a. a -> IO (IORef a)
newIORef ((String -> IO ()) -> IO (IORef (String -> IO ())))
-> (String -> IO ()) -> IO (IORef (String -> IO ()))
forall a b. (a -> b) -> a -> b
$ String -> IO ()
traceIO (String -> IO ()) -> (String -> String) -> String -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String
formatWarning

-- | Replace the action warnIO uses to emit warning messages (which receives
-- the message with no "Warning:" prefix or styling). Eg TUI apps can collect
-- warnings for in-app display, instead of disrupting the terminal with stderr output.
setWarningHandler :: (String -> IO ()) -> IO ()
setWarningHandler :: (String -> IO ()) -> IO ()
setWarningHandler = IORef (String -> IO ()) -> (String -> IO ()) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef (String -> IO ())
warningHandler

-- | Like warn, but take extra care to sequence properly in IO.
-- Emits the warning with the current warning handler (see setWarningHandler).
warnIO :: MonadIO m => String -> m ()
warnIO :: forall (m :: * -> *). MonadIO m => String -> m ()
warnIO String
msg = IO () -> m ()
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ IORef (String -> IO ()) -> IO (String -> IO ())
forall a. IORef a -> IO a
readIORef IORef (String -> IO ())
warningHandler IO (String -> IO ()) -> ((String -> IO ()) -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ((String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
msg)

formatWarning :: String -> String
formatWarning =
  (if Bool
useColorOnStderrUnsafe then (String -> String) -> String -> String
modifyFirstLine String -> String
ansiFormatWarning else String -> String
forall a. a -> a
id) (String -> String) -> (String -> String) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
  (String
"Warning: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)

-- | Apply standard ANSI SGR formatting (yellow, bold) suitable for console warning text.
ansiFormatWarning :: String -> String
ansiFormatWarning :: String -> String
ansiFormatWarning = (String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
sgrresetall) (String -> String) -> (String -> String) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((String
sgrbrightyellow String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
sgrbold) String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)

-- Transform a string's first line.
-- Note, this won't add a trailing newline if there isn't one,
-- and it will remove one if there is one or more.
modifyFirstLine :: (String -> String) -> String -> String
modifyFirstLine :: (String -> String) -> String -> String
modifyFirstLine String -> String
f String
s = String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"\n" ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
f [String]
l [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String]
ls where ([String]
l,[String]
ls) = Int -> [String] -> ([String], [String])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
1 ([String] -> ([String], [String]))
-> [String] -> ([String], [String])
forall a b. (a -> b) -> a -> b
$ String -> [String]
lines String
s  -- total

-- | Print an error message to stderr, with a consistent "programname: " prefix,
-- and applying ANSI styling (bold bright red) to the first line if that is supported and allowed.
printError :: String -> IO ()
printError :: String -> IO ()
printError String
msg = do
  progname <- IO String
getProgName
  usecolor <- useColorOnStderr
  let
    style = if Bool
usecolor then (String -> String) -> String -> String
modifyFirstLine String -> String
ansiFormatError else String -> String
forall a. a -> a
id
    prefix =
      String
progname
        String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": "
        -- error' prepends an "Error: " prefix. But that seems to have been removed when I catch the ErrorCall exception - unless I'm running in GHCI.
        -- Is it possible something in GHC or base is removing it ?
        -- Use a stupid heuristic for now: add it again unless already there.
        String -> String -> String
forall a. Semigroup a => a -> a -> a
<> (if String
"Error:" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` String
msg then String
"" else String
"Error: ")
  hPutStrLn stderr $ style $ prefix <> msg

-- | Print an error message with printError,
-- then exit the program with a non-zero exit code.
exitWithErrorMessage :: String -> IO ()
exitWithErrorMessage :: String -> IO ()
exitWithErrorMessage String
msg = String -> IO ()
printError String
msg IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> IO ()
forall a. IO a
exitFailure

-- | This wraps a program's main routine so as to display more consistent,
-- useful, and GHC-version-independent error output when the program exits
-- because of certain common exceptions. It
--
-- 1. disables SIGPIPE errors, which are usually harmless,
--    caused when our output is truncated in a piped command.
--
-- 2. catches these common exceptions:
--
--    - UnicodeException, caused eg by text decoding errors in pure code
--
--    - IOException, caused by I/O errors, including text decoding errors during I/O
--
--    - ErrorCall - @error@ / @errorWithoutStackTrace@ calls
--
-- 3. compensates for GHC output bugs:
--
--    - removes the trailing newlines added by some GHC 9.10.* versions
--
--    - removes "uncaught exception" output added by some GHC 9.12.* versions
--
--    - ensures a consistent "PROGNAME: " prefix
--
-- 4. applies bold bright red ANSI styling to the first line of error output,
--    if that is supported and allowed
--
-- 5. for unicode exceptions and I/O exceptions which look like they were
--    unicode-related, it adds a message (in english) explaining the problem and what to do.
--
-- Some exceptions this does not catch are ExitCode (exitSuccess/exitFailure/exitWith)
-- and UserInterrupt (control-C).
--
handleExit :: IO () -> IO ()
handleExit :: IO () -> IO ()
handleExit = (IO () -> [Handler ()] -> IO ()) -> [Handler ()] -> IO () -> IO ()
forall a b c. (a -> b -> c) -> b -> a -> c
flip IO () -> [Handler ()] -> IO ()
forall a. IO a -> [Handler a] -> IO a
catches [
   -- Handler (\(e::SomeException) -> error' $ pshow e),  -- debug
   (UnicodeException -> IO ()) -> Handler ()
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\(UnicodeException
e::UnicodeException) -> UnicodeException -> IO ()
forall e. Exception e => e -> IO ()
exitUnicode UnicodeException
e)
  ,(IOException -> IO ()) -> Handler ()
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\(IOException
e::IOException) -> if
    | IOException -> Bool
forall e. Exception e => e -> Bool
isUnicodeError IOException
e    -> IOException -> IO ()
forall e. Exception e => e -> IO ()
exitUnicode IOException
e
    | Bool
otherwise           -> IOException -> IO ()
forall e. Exception e => e -> IO ()
exitOther IOException
e)
  ,(ErrorCall -> IO ()) -> Handler ()
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\(ErrorCall
e::ErrorCall) -> ErrorCall -> IO ()
forall e. Exception e => e -> IO ()
exitOther ErrorCall
e)
  ] (IO () -> IO ()) -> (IO () -> IO ()) -> IO () -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IO () -> IO ()
ignoreSigPipe

  where
    -- | Ignore SIGPIPE errors.
    -- This is copied from System.Process.Internals in process 1.6.20.0+,
    -- since that version of process comes only with ghc 9.10.2+.
    ignoreSigPipe :: IO () -> IO ()
    ignoreSigPipe :: IO () -> IO ()
ignoreSigPipe = (IOException -> IO ()) -> IO () -> IO ()
forall e a. Exception e => (e -> IO a) -> IO a -> IO a
handle ((IOException -> IO ()) -> IO () -> IO ())
-> (IOException -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ \IOException
e -> case IOException
e of
      IOError { ioe_type :: IOException -> IOErrorType
ioe_type  = IOErrorType
ResourceVanished
              , ioe_errno :: IOException -> Maybe CInt
ioe_errno = Just CInt
ioe }
        | CInt -> Errno
Errno CInt
ioe Errno -> Errno -> Bool
forall a. Eq a => a -> a -> Bool
== Errno
ePIPE -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      IOException
_ -> IOException -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO IOException
e

    -- Many decoding failures do not produce a UnicodeException, unfortunately.
    -- So this fragile hack detects them from the error message.
    -- But there are many variant wordings and they probably change over time.
    -- It's not ideal.
    isUnicodeError :: Exception e => e -> Bool
    isUnicodeError :: forall e. Exception e => e -> Bool
isUnicodeError e
ex =
      let msg :: String
msg = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower (e -> String
forall a. Show a => a -> String
show e
ex) in (String -> Bool) -> [String] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` String
msg) [
          String
"illegal byte sequence"
        , String
"invalid byte sequence"
        , String
"cannot decode byte sequence"
        , String
"invalid character"
        , String
"invalid or incomplete multibyte"
        , String
"mkTextEncoding: invalid argument"
        ]

    exitUnicode :: Exception e => e -> IO ()
    exitUnicode :: forall e. Exception e => e -> IO ()
exitUnicode e
ex = do
      enc <- IO String
getSystemEncoding
      let
        noencoding = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower String
enc String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"ascii"
        msg = [String] -> String
unlines ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ [
            String -> String
rstrip (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ e -> String
forall a. Show a => a -> String
show e
ex
          , String
"Some text could not be decoded with the system's text encoding, " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
enc
          , String
"(or, the text encoding specified by CSV rules)."
          ] [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++
          if Bool
noencoding
          then [
            String
"Please configure a system locale which can decode this text."
          ]
          else [
            String
"Please either convert the text to this encoding,"
          , String
"or configure a system locale which can decode this text."
          ]
      exitWithErrorMessage msg

    exitOther :: Exception e => e -> IO ()
    exitOther :: forall e. Exception e => e -> IO ()
exitOther = String -> IO ()
exitWithErrorMessage (String -> IO ()) -> (e -> String) -> e -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String
rstrip (String -> String) -> (e -> String) -> e -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. e -> String
forall a. Show a => a -> String
show

    rstrip :: String -> String
rstrip = String -> String
forall a. [a] -> [a]
reverse (String -> String) -> (String -> String) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace (String -> String) -> (String -> String) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String
forall a. [a] -> [a]
reverse

-- I18n

-- encoding has a similar getSystemEncoding :: IO (Maybe DynEncoding)
-- but it returns Nothing on Windows or if there's an error.

-- | Get the name of the text encoding used by the current locale, using GHC's API.
getSystemEncoding :: IO String
getSystemEncoding :: IO String
getSystemEncoding = do
  localeEncoding <- IO TextEncoding
getLocaleEncoding
  return $ textEncodingName localeEncoding

-- -- | Get the name of the text encoding currently configured for stdout, using GHC's API.
-- getStdoutEncoding :: IO (Maybe String)
-- getStdoutEncoding = do
--   mEncoding <- hGetEncoding stdout
--   return $ fmap textEncodingName mEncoding

-- Time

getCurrentLocalTime :: IO LocalTime
getCurrentLocalTime :: IO LocalTime
getCurrentLocalTime = do
  t <- IO UTCTime
getCurrentTime
  tz <- getCurrentTimeZone
  return $ utcToLocalTime tz t

getCurrentZonedTime :: IO ZonedTime
getCurrentZonedTime :: IO ZonedTime
getCurrentZonedTime = do
  t <- IO UTCTime
getCurrentTime
  tz <- getCurrentTimeZone
  return $ utcToZonedTime tz t



-- Files

-- | Like getHomeDirectory, but in case of IO error (home directory not found, not understood, etc.), returns "".
getHomeSafe :: IO (Maybe FilePath)
getHomeSafe :: IO (Maybe String)
getHomeSafe = (String -> Maybe String) -> IO String -> IO (Maybe String)
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> Maybe String
forall a. a -> Maybe a
Just IO String
getHomeDirectory IO (Maybe String)
-> (IOException -> IO (Maybe String)) -> IO (Maybe String)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(IOException
_ :: IOException) -> Maybe String -> IO (Maybe String)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing)

-- | Expand a single tilde (representing home directory) at the start of a file path.
-- ~username is not supported. This can raise an IO error.
expandHomePath :: FilePath -> IO FilePath
expandHomePath :: String -> IO String
expandHomePath = \case
    String
"~"          -> IO String
getHomeDirectory
    (Char
'~':Char
'/':String
p)  -> (String -> String -> String
</> String
p) (String -> String) -> IO String -> IO String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO String
getHomeDirectory
    (Char
'~':Char
'\\':String
p) -> (String -> String -> String
</> String
p) (String -> String) -> IO String -> IO String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO String
getHomeDirectory
    (Char
'~':String
_)      -> IOException -> IO String
forall a. HasCallStack => IOException -> IO a
ioError (IOException -> IO String) -> IOException -> IO String
forall a b. (a -> b) -> a -> b
$ String -> IOException
userError String
"~USERNAME in paths is not supported"
    String
p            -> String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
p

-- | Given a current directory, convert a possibly relative, possibly tilde-prefixed
-- file path to an absolute one.
-- ~username is not supported.
-- If the file path is "-", it is left as-is.
-- This can an raise an IO error.
expandPath :: FilePath -> FilePath -> IO FilePath -- general type sig for use in reader parsers
expandPath :: String -> String -> IO String
expandPath String
_ String
"-" = String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
"-"
expandPath String
curdir String
p = (if String -> Bool
isRelative String
p then (String
curdir String -> String -> String
</>) else String -> String
forall a. a -> a
id) (String -> String) -> IO String -> IO String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO String
expandHomePath String
p  -- PARTIAL:

-- | The name of the data directory used by hledger commands and rules that
-- read or write CSV files (located next to the main journal file).
-- This is where the get command saves downloaded transactions data,
-- where the CSV source rule looks for input files,
-- and where the CSV archive rule saves imported files.
dataDirName :: FilePath
dataDirName :: String
dataDirName = String
"data"

-- | The name of the rules directory used by `hledger import`
-- (located next to the main journal file).
-- This is where import looks for .rules files when invoked with no arguments.
rulesDirName :: FilePath
rulesDirName :: String
rulesDirName = String
"rules"

-- | Like @expandPath@, but treats the expanded path as a glob, and returns
-- zero or more matched absolute file paths, alphabetically sorted.
-- Can raise an error.
-- For a more elaborate glob expander, see 'findMatchedFiles' (used by the include directive).
expandGlob :: FilePath -> FilePath -> IO [FilePath]
expandGlob :: String -> String -> IO [String]
expandGlob String
curdir String
p = String -> String -> IO String
expandPath String
curdir String
p IO String -> (String -> IO [String]) -> IO [String]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> IO [String]
glob IO [String] -> ([String] -> [String]) -> IO [String]
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> [String] -> [String]
forall a. Ord a => [a] -> [a]
sort  -- PARTIAL:

-- | Like expandPath, but if the path contains glob metacharacters (* ? [ {),
-- treats it as a glob pattern and expands it, returning the first match.
-- Raises an error if the glob pattern matches no files.
-- If the path contains no glob metacharacters, just expands ~ and returns the path,
-- even if the file doesn't exist yet.
-- This is useful for options like -f and LEDGER_FILE that should:
-- - accept non-existent files (for commands like add/import that create them)
-- - expand glob patterns and error if they don't match anything
expandPathOrGlob :: FilePath -> FilePath -> IO FilePath
expandPathOrGlob :: String -> String -> IO String
expandPathOrGlob String
curdir String
p = do
  let hasGlobChars :: Bool
hasGlobChars = (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` String
p) (String
"*?[{" :: [Char])
  if Bool
hasGlobChars
    then do
      matches <- String -> String -> IO [String]
expandGlob String
curdir String
p IO [String] -> (IOException -> IO [String]) -> IO [String]
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(IOException
_::IOException) -> [String] -> IO [String]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [])
      case headMay matches of
        Just String
f -> String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
f
        Maybe String
Nothing -> String -> IO String
forall a. String -> a
error' (String -> IO String) -> String -> IO String
forall a b. (a -> b) -> a -> b
$ String
"glob pattern \"" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
p String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"\" matched no files"
    else
      String -> String -> IO String
expandPath String
curdir String
p

-- | Given a list of existing file paths, sort them by modification time (from oldest to newest).
sortByModTime :: [FilePath] -> IO [FilePath]
sortByModTime :: [String] -> IO [String]
sortByModTime [String]
fs = do
  ftimes <- [String]
-> (String -> IO (UTCTime, String)) -> IO [(UTCTime, String)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM [String]
fs ((String -> IO (UTCTime, String)) -> IO [(UTCTime, String)])
-> (String -> IO (UTCTime, String)) -> IO [(UTCTime, String)]
forall a b. (a -> b) -> a -> b
$ \String
f -> do {t <- String -> IO UTCTime
getModificationTime String
f; return (t,f)}
  return $ map snd $ sort ftimes

-- | Like readFilePortably, but read all of the file before proceeding.
readFileStrictly :: FilePath -> IO T.Text
readFileStrictly :: String -> IO Text
readFileStrictly String
f = String -> IO Text
readFilePortably String
f IO Text -> (Text -> IO Text) -> IO Text
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Text
t -> Int -> IO Int
forall a. a -> IO a
evaluate (Text -> Int
T.length Text
t) IO Int -> IO Text -> IO Text
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Text -> IO Text
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Text
t

-- | Read text from a file,
-- converting any \r\n line endings to \n,,
-- using the system locale's text encoding,
-- ignoring any utf8 BOM prefix (as seen in paypal's 2018 CSV, eg) if that encoding is utf8.
readFilePortably :: FilePath -> IO T.Text
readFilePortably :: String -> IO Text
readFilePortably String
f = String -> IOMode -> IO Handle
openFile String
f IOMode
ReadMode IO Handle -> (Handle -> IO Text) -> IO Text
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Maybe DynEncoding -> Handle -> IO Text
hGetContentsPortably Maybe DynEncoding
forall a. Maybe a
Nothing

-- | Like readFilePortably, but read from standard input if the path is "-".
readFileOrStdinPortably :: String -> IO T.Text
readFileOrStdinPortably :: String -> IO Text
readFileOrStdinPortably = Maybe DynEncoding -> String -> IO Text
readFileOrStdinPortably' Maybe DynEncoding
forall a. Maybe a
Nothing

-- | Like readFileOrStdinPortably, but take an optional converter.
readFileOrStdinPortably' :: Maybe DynEncoding -> String -> IO T.Text
readFileOrStdinPortably' :: Maybe DynEncoding -> String -> IO Text
readFileOrStdinPortably' Maybe DynEncoding
c String
f = String -> IO Handle
openFileOrStdin String
f IO Handle -> (Handle -> IO Text) -> IO Text
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Maybe DynEncoding -> Handle -> IO Text
hGetContentsPortably Maybe DynEncoding
c

-- | Open a file for reading, using the standard System.IO.openFile.
-- This opens the handle in text mode, using the initial system locale's text encoding.
openFileOrStdin :: String -> IO Handle
openFileOrStdin :: String -> IO Handle
openFileOrStdin String
"-" = Handle -> IO Handle
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Handle
stdin
openFileOrStdin String
f' = String -> IOMode -> IO Handle
openFile String
f' IOMode
ReadMode

-- | Run an action with a handle for writing, opening the given file path in
-- the given mode, or returning 'stdout' if the path is "-". When opening a
-- real file, the handle is closed at the end (like 'withFile'); when using
-- stdout, it is left open for the rest of the program.
withFileOrStdout :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withFileOrStdout :: forall r. String -> IOMode -> (Handle -> IO r) -> IO r
withFileOrStdout String
"-" IOMode
_    Handle -> IO r
action = Handle -> IO r
action Handle
stdout
withFileOrStdout String
f   IOMode
mode Handle -> IO r
action = String -> IOMode -> (Handle -> IO r) -> IO r
forall r. String -> IOMode -> (Handle -> IO r) -> IO r
withFile String
f IOMode
mode Handle -> IO r
action

-- | Verify that the filesystem at 'dir' honors O_APPEND, by doing a
-- quick test with a dummy file there (.hledger-append-test*).
-- Returns True if writes opened in 'AppendMode' actually land at end-of-file,
-- False if they don't.
-- This is needed because some filesystems (FAT/exFAT, Android shared-storage
-- and some FUSE mounts) silently drop O_APPEND, so 'appendFile' actually
-- overwrites the file, potentially causing severe data loss (#2577).
ensureFilesystemCanAppend :: FilePath -> IO Bool
ensureFilesystemCanAppend :: String -> IO Bool
ensureFilesystemCanAppend String
dir =
  String -> String -> (String -> Handle -> IO Bool) -> IO Bool
forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
String -> String -> (String -> Handle -> m a) -> m a
withTempFile String
dir String
".hledger-append-test-" ((String -> Handle -> IO Bool) -> IO Bool)
-> (String -> Handle -> IO Bool) -> IO Bool
forall a b. (a -> b) -> a -> b
$ \String
path Handle
h -> do
    let chunk1 :: ByteString
chunk1 = ByteString
"can this filesystem\n"
        chunk2 :: ByteString
chunk2 = ByteString
"append ?\n"
        expected :: ByteString
expected = ByteString
chunk1 ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
chunk2
    Handle -> ByteString -> IO ()
BS.hPut Handle
h ByteString
chunk1
    Handle -> IO ()
hClose Handle
h
    String -> IOMode -> (Handle -> IO ()) -> IO ()
forall r. String -> IOMode -> (Handle -> IO r) -> IO r
withFile String
path IOMode
AppendMode ((Handle -> IO ()) -> IO ()) -> (Handle -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Handle
h2 -> Handle -> ByteString -> IO ()
BS.hPut Handle
h2 ByteString
chunk2
    actual <- String -> IO ByteString
BS.readFile String
path
    return (actual == expected)

-- | Read text from a handle, perhaps using a specified encoding from the encoding package.
-- Or if no encoding is specified, using the handle's current encoding,
-- changing it to UTF-8BOM if it was UTF-8, to ignore any Byte Order Mark at the start.
-- Also it converts Windows line endings to newlines.
-- If decoding fails, this throws an IOException (or possibly a UnicodeException or something else from the encoding package).
hGetContentsPortably :: Maybe DynEncoding -> Handle -> IO T.Text
hGetContentsPortably :: Maybe DynEncoding -> Handle -> IO Text
hGetContentsPortably Maybe DynEncoding
Nothing Handle
h = do
  Handle -> NewlineMode -> IO ()
hSetNewlineMode Handle
h NewlineMode
universalNewlineMode
  menc <- Handle -> IO (Maybe TextEncoding)
hGetEncoding Handle
h
  when (fmap show menc == Just "UTF-8") $ hSetEncoding h utf8_bom
  T.hGetContents h
hGetContentsPortably (Just DynEncoding
e) Handle
h =
  -- convert newlines manually, because Enc.hGetContents uses bytestring's hGetContents
  HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"\r\n" Text
"\n" (Text -> Text) -> (String -> Text) -> String -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack (String -> Text) -> IO String -> IO Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> let ?enc = DynEncoding
e in Handle -> IO String
forall e. (Encoding e, ?enc::e) => Handle -> IO String
Enc.hGetContents Handle
h

-- | Create a handle from which the given text can be read. Its encoding will be UTF-8.
textToHandle :: T.Text -> IO Handle
textToHandle :: Text -> IO Handle
textToHandle Text
t = do
  (r, w) <- IO (Handle, Handle)
createPipe
  hSetEncoding r utf8
  hSetEncoding w utf8
  -- use a separate thread so that we don't deadlock if we can't write all of the text at once
  forkIO $ T.hPutStr w t >> hClose w
  return r

-- | Like embedFile, but takes a path relative to the package directory.
embedFileRelative :: FilePath -> Q Exp
embedFileRelative :: String -> Q Exp
embedFileRelative String
f = String -> Q String
makeRelativeToProject String
f Q String -> (String -> Q Exp) -> Q Exp
forall a b. Q a -> (a -> Q b) -> Q b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> Q Exp
embedStringFile

-- | Like embedFileRelative, but embeds the file's raw bytes as a ByteString,
-- so that its encoding does not depend on the build machine's locale.
embedFileRelativeBytes :: FilePath -> Q Exp
embedFileRelativeBytes :: String -> Q Exp
embedFileRelativeBytes String
f = String -> Q String
makeRelativeToProject String
f Q String -> (String -> Q Exp) -> Q Exp
forall a b. Q a -> (a -> Q b) -> Q b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> Q Exp
embedFile

-- -- | Like hereFile, but takes a path relative to the package directory.
-- -- Similar to embedFileRelative ?
-- hereFileRelative :: FilePath -> Q Exp
-- hereFileRelative f = makeRelativeToProject f >>= hereFileExp
--   where
--     QuasiQuoter{quoteExp=hereFileExp} = hereFile



-- Command line parsing

-- | The program's command line arguments.
-- Uses unsafePerformIO; tends to stick in GHCI until reloaded,
-- and may or may not detect args provided by a hledger config file.
{-# NOINLINE progArgs #-}
progArgs :: [String]
progArgs :: [String]
progArgs = IO [String] -> [String]
forall a. IO a -> a
unsafePerformIO IO [String]
getArgs
-- XX currently this affects:
--  the enabling of orderdates and assertions checks in journalFinalise
--  a few cases involving --color (see useColorOnStdoutUnsafe)
--  --debug

-- | Given one or more long or short flag names,
-- report whether this flag is present in the command line.
-- Concatenated short flags (-a -b written as -ab) are not supported.
getFlag :: [String] -> IO Bool
getFlag :: [String] -> IO Bool
getFlag [String]
names = do
  let flags :: [String]
flags = (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
toFlag [String]
names
  args <- IO [String]
getArgs
  return $ any (`elem` args) flags

-- | Given one or more long or short option names, read the rightmost value of this option from the command line arguments.
-- If the value is missing raise an error.
-- Concatenated short flags (-a -b written as -ab) are not supported.
getOpt :: [String] -> IO (Maybe String)
getOpt :: [String] -> IO (Maybe String)
getOpt [String]
names = do
  rargs <- [String] -> [String]
forall a. [a] -> [a]
reverse ([String] -> [String])
-> ([String] -> [String]) -> [String] -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> [String]
splitFlagsAndVals ([String] -> [String]) -> IO [String] -> IO [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO [String]
getArgs
  let flags = (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
toFlag [String]
names
  return $
    case break ((`elem` flags)) rargs of
      ([String]
_,[])        -> Maybe String
forall a. Maybe a
Nothing
      ([],String
flag:[String]
_)   -> String -> Maybe String
forall a. String -> a
error' (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
flag String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" requires a value"
      ([String]
argsafter,[String]
_) -> String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ [String] -> String
forall a. HasCallStack => [a] -> a
last [String]
argsafter

-- | Given a list of command line arguments, split any of the form --flag=VAL or -fVAL into two list items.
-- Concatenated short flags (-a -b written as -ab) are not supported.
splitFlagsAndVals :: [String] -> [String]
splitFlagsAndVals :: [String] -> [String]
splitFlagsAndVals = (String -> [String]) -> [String] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ((String -> [String]) -> [String] -> [String])
-> (String -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$
  \case
    a :: String
a@(Char
'-':Char
'-':String
_) | Char
'=' Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` String
a -> let (String
x,String
y) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
'=') String
a in [String
x, Int -> String -> String
forall a. Int -> [a] -> [a]
drop Int
1 String
y]
    a :: String
a@(Char
'-':Char
f:Char
_:String
_) | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Char
fChar -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
'-' -> [Int -> String -> String
forall a. Int -> [a] -> [a]
take Int
2 String
a, Int -> String -> String
forall a. Int -> [a] -> [a]
drop Int
2 String
a]
    String
a -> [String
a]

-- | Convert a short or long flag name to a flag with leading hyphen(s).
toFlag :: String -> String
toFlag [Char
c] = [Char
'-',Char
c]
toFlag String
s   = Char
'-'Char -> String -> String
forall a. a -> [a] -> [a]
:Char
'-'Char -> String -> String
forall a. a -> [a] -> [a]
:String
s

-- | Parse y/yes/always or n/no/never to true or false, or return an error message.
parseYN :: String -> Either String Bool
parseYN :: String -> Either String Bool
parseYN String
s
  | String
l String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String
"y",String
"yes",String
"always"] = Bool -> Either String Bool
forall a b. b -> Either a b
Right Bool
True
  | String
l String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String
"n",String
"no",String
"never"]   = Bool -> Either String Bool
forall a b. b -> Either a b
Right Bool
False
  | Bool
otherwise = String -> Either String Bool
forall a b. a -> Either a b
Left (String -> Either String Bool) -> String -> Either String Bool
forall a b. (a -> b) -> a -> b
$ String
"value should be one of " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> (String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " [String
"y",String
"yes",String
"n",String
"no"])
  where l :: String
l = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower String
s

data YNA = Yes | No | Auto deriving (YNA -> YNA -> Bool
(YNA -> YNA -> Bool) -> (YNA -> YNA -> Bool) -> Eq YNA
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: YNA -> YNA -> Bool
== :: YNA -> YNA -> Bool
$c/= :: YNA -> YNA -> Bool
/= :: YNA -> YNA -> Bool
Eq,Int -> YNA -> String -> String
[YNA] -> String -> String
YNA -> String
(Int -> YNA -> String -> String)
-> (YNA -> String) -> ([YNA] -> String -> String) -> Show YNA
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> YNA -> String -> String
showsPrec :: Int -> YNA -> String -> String
$cshow :: YNA -> String
show :: YNA -> String
$cshowList :: [YNA] -> String -> String
showList :: [YNA] -> String -> String
Show)

-- | Parse y/yes/always or n/no/never or a/auto to a YNA choice, or return an error message.
parseYNA :: String -> Either String YNA
parseYNA :: String -> Either String YNA
parseYNA String
s
  | String
l String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String
"y",String
"yes",String
"always"] = YNA -> Either String YNA
forall a b. b -> Either a b
Right YNA
Yes
  | String
l String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String
"n",String
"no",String
"never"]   = YNA -> Either String YNA
forall a b. b -> Either a b
Right YNA
No
  | String
l String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String
"a",String
"auto"]         = YNA -> Either String YNA
forall a b. b -> Either a b
Right YNA
Auto
  | Bool
otherwise = String -> Either String YNA
forall a b. a -> Either a b
Left (String -> Either String YNA) -> String -> Either String YNA
forall a b. (a -> b) -> a -> b
$ String
"value should be one of " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> (String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " [String
"y",String
"yes",String
"n",String
"no",String
"a",String
"auto"])
  where l :: String
l = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower String
s

-- | Is there a --output-file or -o option in the command line arguments ?
-- Uses getOpt; sticky in GHCI until reloaded, may not always be affected by a hledger config file, etc.
hasOutputFile :: IO Bool
hasOutputFile :: IO Bool
hasOutputFile = do
  mv <- [String] -> IO (Maybe String)
getOpt [String
"output-file",String
"o"]
  return $
    case mv of
      Maybe String
Nothing  -> Bool
False
      Just String
"-" -> Bool
False
      Maybe String
_        -> Bool
True

-- -- | Get the -o/--output-file option's value, if any, from the command line arguments.
-- -- Uses getOpt; sticky in GHCI until reloaded, may not always be affected by a hledger config file, etc.
-- outputFileOption :: IO (Maybe String)
-- outputFileOption = getOpt ["output-file","o"]



-- Terminal size

-- [NOTE: Alternative methods of getting the terminal size]
-- terminal-size uses the TIOCGWINSZ ioctl to get the window size on Unix
-- systems, which may not be completely portable according to people in
-- #linux@liberachat.
--
-- If this turns out to be the case, supplementary coverage can be given by
-- using the terminfo package.
--
-- Conversely, terminfo on its own is not a full solution, firstly because it
-- only works on Unix (not Windows), and secondly since in some scenarios (eg
-- stripped-down build systems) the terminfo database may be limited and lack
-- the correct entries. (A hack that sometimes works but which isn't robust
-- enough to be relied upon is to set TERM=dumb -- while this advice does appear
-- in some places, it's not guaranteed to work)
--
-- In any case, $LINES/$COLUMNS should not be used as a source for the terminal
-- size - they are not available or do not update reliably in all shells.
--
-- See #2332 for details

-- | An alternative to ansi-terminal's getTerminalSize, based on
-- the more robust-looking terminal-size package.
--
-- Tries to get stdout's terminal's current height and width.
getTerminalHeightWidth :: IO (Maybe (Int,Int))
getTerminalHeightWidth :: IO (Maybe (Int, Int))
getTerminalHeightWidth = (Maybe (Window Int) -> Maybe (Int, Int))
-> IO (Maybe (Window Int)) -> IO (Maybe (Int, Int))
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((Window Int -> (Int, Int))
-> Maybe (Window Int) -> Maybe (Int, Int)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Window Int -> (Int, Int)
forall {b}. Window b -> (b, b)
unwindow) IO (Maybe (Window Int))
forall n. Integral n => IO (Maybe (Window n))
size
  where unwindow :: Window b -> (b, b)
unwindow (Window b
h b
w) = (b
h,b
w)

getTerminalHeight :: IO (Maybe Int)
getTerminalHeight :: IO (Maybe Int)
getTerminalHeight = ((Int, Int) -> Int) -> Maybe (Int, Int) -> Maybe Int
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Int, Int) -> Int
forall a b. (a, b) -> a
fst (Maybe (Int, Int) -> Maybe Int)
-> IO (Maybe (Int, Int)) -> IO (Maybe Int)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO (Maybe (Int, Int))
getTerminalHeightWidth

getTerminalWidth :: IO (Maybe Int)
getTerminalWidth :: IO (Maybe Int)
getTerminalWidth  = ((Int, Int) -> Int) -> Maybe (Int, Int) -> Maybe Int
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Int, Int) -> Int
forall a b. (a, b) -> b
snd (Maybe (Int, Int) -> Maybe Int)
-> IO (Maybe (Int, Int)) -> IO (Maybe Int)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO (Maybe (Int, Int))
getTerminalHeightWidth

-- | Are we running inside an Emacs subprocess other than vterm ?
-- Terminals like Emacs's M-x shell (comint) advertise a full xterm terminal
-- but only partially emulate it (SGR colours render, but cursor movement and
-- terminal queries do not), so interactive line editing, paging and background
-- colour detection tend to misbehave there.
-- vterm is excluded because it emulates a terminal fully.
-- Emacs sets INSIDE_EMACS to eg "30.1,comint" or "30.1,vterm", so we look for a
-- "vterm" component rather than an exact match.
insideEmacsNotVterm :: IO Bool
insideEmacsNotVterm :: IO Bool
insideEmacsNotVterm = Bool -> (String -> Bool) -> Maybe String -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String
"vterm" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf`)) (Maybe String -> Bool) -> IO (Maybe String) -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO (Maybe String)
lookupEnv String
"INSIDE_EMACS"



-- Pager output
-- somewhat hledger-specific

-- | Try to find a pager executable robustly, safely handling various error conditions
-- like an unset PATH var or the specified pager not being found as an executable.
-- The pager can be specified by a path or program name in the PAGER environment variable.
-- If that is unset or has a problem, "less" is tried, then "more".
-- If successful, the pager's path or program name is returned.
findPager :: IO (Maybe String)  -- XXX probably a ByteString in fact ?
findPager :: IO (Maybe String)
findPager = do
  mpagervar <- String -> IO (Maybe String)
lookupEnv String
"PAGER"
  let pagers = [String
p | Just String
p <- [Maybe String
mpagervar]] [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String
"less", String
"more"]
  headMay . catMaybes <$> mapM findExecutable pagers

-- | Should a pager be used for displaying the given text on stdout, and if so, which one ?
-- Uses a pager if findPager finds one and none of the following conditions are true:
-- We're running in a native MS Windows environment like cmd or powershell.
-- Or the --pager=n|no option is in effect.
-- Or the -o/--output-file option is in effect.
-- Or INSIDE_EMACS is set, to something other than "vterm".
-- Or the terminal's current height and width can't be detected.
-- Or the output text is less wide and less tall than the terminal.
-- Throws an error if the --pager option's value could not be parsed.
maybePagerFor :: String -> IO (Maybe String)
maybePagerFor :: String -> IO (Maybe String)
maybePagerFor String
output = do
  let
    ls :: [String]
ls = String -> [String]
lines String
output
    oh :: Int
oh = [String] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [String]
ls
    ow :: Int
ow = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumDef Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (String -> Int) -> [String] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [String]
ls
    windows :: Bool
windows = String
os String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"mingw32"
  pagerno    <- Bool -> (String -> Bool) -> Maybe String -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> Bool) -> (Bool -> Bool) -> Either String Bool -> Bool
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> Bool
forall a. String -> a
error' Bool -> Bool
forall a. a -> a
id (Either String Bool -> Bool)
-> (String -> Either String Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Either String Bool
parseYN) (Maybe String -> Bool) -> IO (Maybe String) -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [String] -> IO (Maybe String)
getOpt [String
"pager"]
  outputfile <- hasOutputFile
  emacsterm  <- insideEmacsNotVterm
  mhw        <- getTerminalHeightWidth
  mpager     <- findPager
  return $ do
    guard $ not $ windows || pagerno || outputfile || emacsterm
    (th,tw) <- mhw
    guard $ oh > th || ow > tw
    mpager

-- | Display the given text on the terminal, trying to use a pager ($PAGER, less, or more)
-- when appropriate (see maybePagerFor), otherwise printing to standard output.
-- Also, if the pager is less, we modify the LESS environment variable (see lessVarValue)
-- and check for problems which could cause confusing output (see lessIsWorking).
runPager :: String -> IO ()
runPager :: String -> IO ()
runPager String
s = do
  mpager <- String -> IO (Maybe String)
maybePagerFor String
s
  case mpager of
    Maybe String
Nothing -> String -> IO ()
putStr String
s
    Just String
pager -> do

      -- If using less, customise the LESS environment variable and check if it works
      let pagerIsLess :: Bool
pagerIsLess = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower (String -> String
takeBaseName String
pager) String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"less"
      (mCustomEnv, shouldUsePager) <- if Bool -> Bool
not Bool
pagerIsLess
        then (Maybe [(String, String)], Bool)
-> IO (Maybe [(String, String)], Bool)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe [(String, String)]
forall a. Maybe a
Nothing, Bool
True)
        else do
          mHLEDGER_LESS <- String -> IO (Maybe String)
lookupEnv String
"HLEDGER_LESS"
          mLESS         <- lookupEnv "LESS"
          usecolor      <- useColorOnStdout
          let newlessvar = Maybe String -> Maybe String -> Bool -> String
lessVarValue Maybe String
mHLEDGER_LESS Maybe String
mLESS Bool
usecolor
          env <- getEnvironment
          let customEnv = (String
"LESS", String
newlessvar) (String, String) -> [(String, String)] -> [(String, String)]
forall a. a -> [a] -> [a]
: ((String, String) -> Bool)
-> [(String, String)] -> [(String, String)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
"LESS") (String -> Bool)
-> ((String, String) -> String) -> (String, String) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String, String) -> String
forall a b. (a, b) -> a
fst) [(String, String)]
env
          -- Check that less --version is working (using our custom LESS) (#2544)
          lessHasError <- lessIsWorking (Just customEnv) `catch` \(IOException
_::IOException) -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
          when lessHasError $ warnIO $
            "less --version fails with current LESS settings; disabling. Check 'hledger setup' for details.\n"
          return (Just customEnv, not lessHasError)

      -- Run the pager, providing the text as input. Or if we found a problem already, just print.
      if not shouldUsePager
        then putStr s
        else (withCreateProcess (shell pager){std_in=CreatePipe, env=mCustomEnv} $
          \Maybe Handle
mhin Maybe Handle
_ Maybe Handle
_ ProcessHandle
p -> do
            case Maybe Handle
mhin of
              Maybe Handle
Nothing  -> String -> IO ()
forall a. HasCallStack => String -> IO a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
String -> m a
fail String
"Failed to create pipe to pager"
              Just Handle
hin -> IO ThreadId -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ThreadId -> IO ()) -> IO ThreadId -> IO ()
forall a b. (a -> b) -> a -> b
$ IO () -> IO ThreadId
forkIO (IO () -> IO ThreadId) -> IO () -> IO ThreadId
forall a b. (a -> b) -> a -> b
$   -- Write from another thread to avoid deadlock ? Maybe unneeded, but just in case.
                (Handle -> String -> IO ()
hPutStr Handle
hin String
s IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Handle -> IO ()
hClose Handle
hin)  -- Be sure to close the pipe so the pager knows we're done.
                  -- If the pager quits early, we'll receive an EPIPE error; hide that.
                  IO () -> (IOException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(IOException
e::IOException) -> case IOException
e of
                    IOError{ioe_type :: IOException -> IOErrorType
ioe_type=IOErrorType
ResourceVanished, ioe_errno :: IOException -> Maybe CInt
ioe_errno=Just CInt
ioe, ioe_handle :: IOException -> Maybe Handle
ioe_handle=Just Handle
hdl} | CInt -> Errno
Errno CInt
ioeErrno -> Errno -> Bool
forall a. Eq a => a -> a -> Bool
==Errno
ePIPE, Handle
hdlHandle -> Handle -> Bool
forall a. Eq a => a -> a -> Bool
==Handle
hin -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                    IOException
_ -> IOException -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO IOException
e
            IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ ProcessHandle -> IO ExitCode
waitForProcess ProcessHandle
p)
          `catch` \(IOException
_::IOException) -> String -> IO ()
putStr String
s

-- | Test @less@, by running less --version and looking for a nonzero exit, timeout, or stderr output.
-- Uses the provided environment, containing a LESS variable, if any.
-- We do this because various LESS settings can cause some less versions to fail or cause confusing output without failing.
lessIsWorking :: Maybe [(String, String)] -> IO Bool
lessIsWorking :: Maybe [(String, String)] -> IO Bool
lessIsWorking Maybe [(String, String)]
mCustomEnv = do
  result <- Int
-> IO (ExitCode, String, String)
-> IO (Maybe (ExitCode, String, String))
forall a. Int -> IO a -> IO (Maybe a)
timeout Int
300000 (IO (ExitCode, String, String)
 -> IO (Maybe (ExitCode, String, String)))
-> IO (ExitCode, String, String)
-> IO (Maybe (ExitCode, String, String))
forall a b. (a -> b) -> a -> b
$ CreateProcess -> String -> IO (ExitCode, String, String)
readCreateProcessWithExitCode (String -> [String] -> CreateProcess
proc String
"less" [String
"--version"]){env=mCustomEnv} String
""
  return $ case result of
    Maybe (ExitCode, String, String)
Nothing -> Bool
True  -- Timeout
    Just (ExitCode
exitCode, String
_, String
stderrOut) -> ExitCode
exitCode ExitCode -> ExitCode -> Bool
forall a. Eq a => a -> a -> Bool
/= ExitCode
ExitSuccess Bool -> Bool -> Bool
|| Bool -> Bool
not (String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
stderrOut)

-- | Compute the LESS environment variable value that hledger will use for the less pager.
-- This used in runPager when invoking less, and also in the setup command for display.
-- It takes the current HLEDGER_LESS and LESS env var values, and whether we are showing colour on stdout,
-- and returns the adjusted LESS value that should be used. Specifically:
--
-- - If HLEDGER_LESS is defined, we use it in place of the LESS environment variable.
--
-- - Otherwise, if LESS is defined, append some preferred options (lessOptions and maybe lessColourOptions) to it.
--
-- - Otherwise, we set LESS to just use those preferred options.
--
lessVarValue :: Maybe String -> Maybe String -> Bool -> String
lessVarValue :: Maybe String -> Maybe String -> Bool -> String
lessVarValue Maybe String
mHLEDGER_LESS Maybe String
mLESS Bool
usecolor =
  let extraopts :: [String]
extraopts = String -> [String]
words String
lessOptions [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String
lessColourOptions | Bool
usecolor]
  in case (Maybe String
mHLEDGER_LESS, Maybe String
mLESS) of
       (Just String
hledgerlessvar, Maybe String
_) -> String
hledgerlessvar
       (Maybe String
_, Just String
lessvar) ->
         let existing :: [String]
existing = String -> [String]
words String
lessvar
             new :: [String]
new = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String -> [String] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [String]
existing) [String]
extraopts
         in if [String] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
new then String
lessvar else [String] -> String
unwords (String
lessvar String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String]
new)
       (Maybe String, Maybe String)
_ -> [String] -> String
unwords [String]
extraopts

-- keep synced: hledger.m4.md > Paging
-- | hledger's preferred less options, which it will append to the user's LESS environment variable.
-- The thinking here is: "Many people don't have their LESS optimised to get the best experience from modern less, as I didn't.
-- Also as they use hledger on different machines, LESS is likely not consistent. 
-- So let's add some settings that I have found reasonably robust, compatible, and good for usability.
-- That will help provide a consistent good experience when viewing hledger's long outputs.
-- And power users can prevent this by setting exactly the options they want in HLEDGER_LESS."
-- Here's what they mean: https://manned.org/man/less#head5
--
-- Flags that might break older less versions (causing hledger to fall back to unpaged output) are avoided here.
-- Such as --mouse and --wheel-lines (less >=530, 2018) and --use-color (less >=551, 2019).
-- --hilite-unread (less >=443, 2011) is useful and considered old enough.
--
lessOptions :: String
lessOptions = [String] -> String
unwords [
   String
"--chop-long-lines"
  ,String
"--hilite-unread"
  ,String
"--ignore-case"
  ,String
"--no-init"
  ,String
"--quit-if-one-screen"
  ,String
"--shift=8"
  ,String
"--squeeze-blank-lines"
  ,String
"--use-backslash"
  ] 

-- | Additional less options to use if we are showing colour on stdout.
lessColourOptions :: String
lessColourOptions = [String] -> String
unwords [
   String
"--RAW-CONTROL-CHARS"
  ]


-- ANSI colour/styles
-- Some of these use unsafePerformIO to read info.

-- hledger-specific:

-- | Get the value of the rightmost --color or --colour option from the program's command line arguments.
-- Throws an error if the option's value could not be parsed.
colorOption :: IO YNA
colorOption :: IO YNA
colorOption = YNA -> (String -> YNA) -> Maybe String -> YNA
forall b a. b -> (a -> b) -> Maybe a -> b
maybe YNA
Auto ((String -> YNA) -> (YNA -> YNA) -> Either String YNA -> YNA
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> YNA
forall a. String -> a
error' YNA -> YNA
forall a. a -> a
id (Either String YNA -> YNA)
-> (String -> Either String YNA) -> String -> YNA
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Either String YNA
parseYNA) (Maybe String -> YNA) -> IO (Maybe String) -> IO YNA
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [String] -> IO (Maybe String)
getOpt [String
"color",String
"colour"]

-- | Should ANSI color and styles be used with this output handle ?
-- Considers the --color/--colour option, and in auto mode the NO_COLOR and TERM
-- environment variables and whether the handle is an ANSI-capable terminal.
-- In auto mode we never use colour when TERM=dumb (the conventional request for
-- plain output); otherwise we use it when ansi-terminal's hSupportsANSIColor says
-- the handle supports colour. Note hSupportsANSIColor reports colour support for an
-- Emacs subshell even on a captured pipe when TERM=dumb, which would leak escape
-- codes into redirected output (eg shelltest); the TERM=dumb check prevents that.
useColorOnHandle :: Handle -> IO Bool
useColorOnHandle :: Handle -> IO Bool
useColorOnHandle Handle
h = do
  no_color       <- Maybe String -> Bool
forall a. Maybe a -> Bool
isJust (Maybe String -> Bool) -> IO (Maybe String) -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO (Maybe String)
lookupEnv String
"NO_COLOR"
  dumbterminal   <- (== Just "dumb") . fmap (map toLower) <$> lookupEnv "TERM"
  supports_color <- hSupportsANSIColor h
  yna            <- colorOption
  return $ yna==Yes || (yna==Auto && not no_color && not dumbterminal && supports_color)

-- | Should ANSI color and styles be used for standard output ?
-- Considers useColorOnHandle stdout and hasOutputFile.
useColorOnStdout :: IO Bool
useColorOnStdout :: IO Bool
useColorOnStdout = do
  nooutputfile <- Bool -> Bool
not (Bool -> Bool) -> IO Bool -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO Bool
hasOutputFile
  usecolor <- useColorOnHandle stdout
  return $ nooutputfile && usecolor

-- | Should ANSI color and styles be used for standard error output ?
-- Considers useColorOnHandle stderr; is not affected by an --output-file option.
useColorOnStderr :: IO Bool
useColorOnStderr :: IO Bool
useColorOnStderr = Handle -> IO Bool
useColorOnHandle Handle
stderr

-- | Like useColorOnStdout, but using unsafePerformIO. Useful eg for low-level debug code.
-- Sticky in GHCI until reloaded, may not always be affected by --color in a hledger config file, etc.
useColorOnStdoutUnsafe :: Bool
useColorOnStdoutUnsafe :: Bool
useColorOnStdoutUnsafe = IO Bool -> Bool
forall a. IO a -> a
unsafePerformIO IO Bool
useColorOnStdout

-- | Like useColorOnStdoutUnsafe, but for stderr.
useColorOnStderrUnsafe :: Bool
useColorOnStderrUnsafe :: Bool
useColorOnStderrUnsafe = IO Bool -> Bool
forall a. IO a -> a
unsafePerformIO IO Bool
useColorOnStderr

-- | Does the terminal appear to support 24-bit "true colour" ?
-- Detected from the COLORTERM environment variable being "truecolor" or "24bit",
-- the de-facto convention. This errs conservative: it can miss truecolor terminals
-- that don't set COLORTERM (eg across ssh/tmux/sudo), in which case we fall back to
-- 256-colour; and it can't help terminals that set it but don't actually render
-- truecolor. When false, 'rgb'' downgrades to the nearest xterm 256-colour.
supportsTrueColor :: IO Bool
supportsTrueColor :: IO Bool
supportsTrueColor = Bool -> (String -> Bool) -> Maybe String -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String
"truecolor",String
"24bit"]) (Maybe String -> Bool) -> IO (Maybe String) -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO (Maybe String)
lookupEnv String
"COLORTERM"

-- | Like 'supportsTrueColor', but using unsafePerformIO.
supportsTrueColorUnsafe :: Bool
supportsTrueColorUnsafe :: Bool
supportsTrueColorUnsafe = IO Bool -> Bool
forall a. IO a -> a
unsafePerformIO IO Bool
supportsTrueColor

-- | Detect whether ANSI should be used on stdout using useColorOnStdoutUnsafe,
-- and if so prepend and append the given SGR codes to a string.
-- Currently used in a few places (the commands list, the recentassertions error message, add);
-- see useColorOnStdoutUnsafe's limitations.
ansiWrapUnsafe :: SGRString -> SGRString -> String -> String
ansiWrapUnsafe :: String -> String -> String -> String
ansiWrapUnsafe String
pre String
post String
s = if Bool
useColorOnStdoutUnsafe then String
preString -> String -> String
forall a. Semigroup a => a -> a -> a
<>String
sString -> String -> String
forall a. Semigroup a => a -> a -> a
<>String
post else String
s

type SGRString = String

sgrbold :: String
sgrbold          = [SGR] -> String
setSGRCode [ConsoleIntensity -> SGR
SetConsoleIntensity ConsoleIntensity
BoldIntensity]
sgrfaint :: String
sgrfaint         = [SGR] -> String
setSGRCode [ConsoleIntensity -> SGR
SetConsoleIntensity ConsoleIntensity
FaintIntensity]
sgrnormal :: String
sgrnormal        = [SGR] -> String
setSGRCode [ConsoleIntensity -> SGR
SetConsoleIntensity ConsoleIntensity
NormalIntensity]
sgrresetfg :: String
sgrresetfg       = [SGR] -> String
setSGRCode [ConsoleLayer -> SGR
SetDefaultColor ConsoleLayer
Foreground]
sgrresetbg :: String
sgrresetbg       = [SGR] -> String
setSGRCode [ConsoleLayer -> SGR
SetDefaultColor ConsoleLayer
Background]
sgrresetall :: String
sgrresetall      = String
sgrresetfg String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
sgrresetbg String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
sgrnormal
sgrblack :: String
sgrblack         = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Dull Color
Black]
sgrred :: String
sgrred           = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Dull Color
Red]
sgrgreen :: String
sgrgreen         = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Dull Color
Green]
sgryellow :: String
sgryellow        = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Dull Color
Yellow]
sgrblue :: String
sgrblue          = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Dull Color
Blue]
sgrmagenta :: String
sgrmagenta       = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Dull Color
Magenta]
sgrcyan :: String
sgrcyan          = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Dull Color
Cyan]
sgrwhite :: String
sgrwhite         = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Dull Color
White]
sgrbrightblack :: String
sgrbrightblack   = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
Black]
sgrbrightred :: String
sgrbrightred     = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
Red]
sgrbrightgreen :: String
sgrbrightgreen   = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
Green]
sgrbrightyellow :: String
sgrbrightyellow  = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
Yellow]
sgrbrightblue :: String
sgrbrightblue    = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
Blue]
sgrbrightmagenta :: String
sgrbrightmagenta = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
Magenta]
sgrbrightcyan :: String
sgrbrightcyan    = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
Cyan]
sgrbrightwhite :: String
sgrbrightwhite   = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
White]
-- Emit a 24-bit truecolor foreground code, or if the terminal doesn't advertise
-- truecolor support (see supportsTrueColorUnsafe), the nearest xterm 256-colour.
sgrrgb :: Float -> Float -> Float -> String
sgrrgb Float
r Float
g Float
b
  | Bool
supportsTrueColorUnsafe = [SGR] -> String
setSGRCode [ConsoleLayer -> Colour Float -> SGR
SetRGBColor ConsoleLayer
Foreground (Colour Float -> SGR) -> Colour Float -> SGR
forall a b. (a -> b) -> a -> b
$ Float -> Float -> Float -> Colour Float
forall b. (Ord b, Floating b) => b -> b -> b -> Colour b
sRGB Float
r Float
g Float
b]
  | Bool
otherwise               = [SGR] -> String
setSGRCode [ConsoleLayer -> Word8 -> SGR
SetPaletteColor ConsoleLayer
Foreground (Word8 -> SGR) -> Word8 -> SGR
forall a b. (a -> b) -> a -> b
$ Int -> Int -> Int -> Word8
xterm6LevelRGB (Float -> Int
forall {a} {b}. (RealFrac a, Integral b) => a -> b
lvl Float
r) (Float -> Int
forall {a} {b}. (RealFrac a, Integral b) => a -> b
lvl Float
g) (Float -> Int
forall {a} {b}. (RealFrac a, Integral b) => a -> b
lvl Float
b)]
  where lvl :: a -> b
lvl a
v = b -> b -> b
forall a. Ord a => a -> a -> a
max b
0 (b -> b) -> b -> b
forall a b. (a -> b) -> a -> b
$ b -> b -> b
forall a. Ord a => a -> a -> a
min b
5 (b -> b) -> b -> b
forall a b. (a -> b) -> a -> b
$ a -> b
forall b. Integral b => a -> b
forall a b. (RealFrac a, Integral b) => a -> b
round (a
v a -> a -> a
forall a. Num a => a -> a -> a
* a
5)  -- map a 0..1 intensity to a 0..5 colour-cube level

-- | Set various ANSI styles/colours in a string, only if useColorOnStdoutUnsafe says we should.
bold' :: String -> String
bold' :: String -> String
bold'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbold String
sgrnormal

faint' :: String -> String
faint' :: String -> String
faint'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrfaint String
sgrnormal

black' :: String -> String
black' :: String -> String
black'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrblack String
sgrresetfg

red' :: String -> String
red' :: String -> String
red'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrred String
sgrresetfg

green' :: String -> String
green' :: String -> String
green'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrgreen String
sgrresetfg

yellow' :: String -> String
yellow' :: String -> String
yellow'  = String -> String -> String -> String
ansiWrapUnsafe String
sgryellow String
sgrresetfg

blue' :: String -> String
blue' :: String -> String
blue'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrblue String
sgrresetfg

magenta' :: String -> String
magenta' :: String -> String
magenta'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrmagenta String
sgrresetfg

cyan' :: String -> String
cyan' :: String -> String
cyan'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrcyan String
sgrresetfg

white' :: String -> String
white' :: String -> String
white'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrwhite String
sgrresetfg

brightBlack' :: String -> String
brightBlack' :: String -> String
brightBlack'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbrightblack String
sgrresetfg

brightRed' :: String -> String
brightRed' :: String -> String
brightRed'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbrightred String
sgrresetfg

brightGreen' :: String -> String
brightGreen' :: String -> String
brightGreen'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbrightgreen String
sgrresetfg

brightYellow' :: String -> String
brightYellow' :: String -> String
brightYellow'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbrightyellow String
sgrresetfg

brightBlue' :: String -> String
brightBlue' :: String -> String
brightBlue'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbrightblue String
sgrresetfg

brightMagenta' :: String -> String
brightMagenta' :: String -> String
brightMagenta'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbrightmagenta String
sgrresetfg

brightCyan' :: String -> String
brightCyan' :: String -> String
brightCyan'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbrightcyan String
sgrresetfg

brightWhite' :: String -> String
brightWhite' :: String -> String
brightWhite'  = String -> String -> String -> String
ansiWrapUnsafe String
sgrbrightwhite String
sgrresetfg

rgb' :: Float -> Float -> Float -> String -> String
rgb' :: Float -> Float -> Float -> String -> String
rgb' Float
r Float
g Float
b  = String -> String -> String -> String
ansiWrapUnsafe (Float -> Float -> Float -> String
sgrrgb Float
r Float
g Float
b) String
sgrresetfg

-- | Choose and apply an accent color for hledger output, if possible
-- picking one that will contrast with the current terminal background colour.
accent :: String -> String
accent :: String -> String
accent
  | Bool -> Bool
not Bool
useColorOnStdoutUnsafe    = String -> String
forall a. a -> a
id  -- XXX unsafe accenting the title banner - seems to work, even respecting config file
  | Maybe Bool
terminalIsLight Maybe Bool -> Maybe Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
False = String -> String
brightWhite'
  | Maybe Bool
terminalIsLight Maybe Bool -> Maybe Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
True  = String -> String
brightBlack'
  | Bool
otherwise                     = String -> String
forall a. a -> a
id

-- | Colour a string with hledger's diagonal blue-to-green gradient: each
-- character's colour depends on its position (@row@, and column counting from
-- @col0@) within a grid @h@ rows tall and @w@ columns wide, fading blue at the
-- top-left to green at the bottom-right. The gradient is brighter on a dark
-- terminal background and darker on a light one. The whole string is wrapped in
-- the given intensity style (eg 'bold'' or 'faint''); the per-character colour
-- codes only touch the foreground, so the intensity is kept across the string.
-- When the background lightness can't be detected (eg inside emacs, where the
-- background-colour query doesn't work), it uses the light-background palette,
-- whose deeper shades stay legible on both light and dark backgrounds; only a
-- background known to be dark gets the brighter dark-background palette.
-- Colouring is skipped entirely only when colour is off.
gradientStr :: (String -> String) -> Int -> Int -> Int -> Int -> String -> String
gradientStr :: (String -> String) -> Int -> Int -> Int -> Int -> String -> String
gradientStr String -> String
intensity Int
h Int
w Int
row Int
col0 String
s
  | Bool -> Bool
not Bool
useColorOnStdoutUnsafe = String
s
  | Bool
otherwise =
      let light :: Bool
light      = Maybe Bool
terminalIsLight Maybe Bool -> Maybe Bool -> Bool
forall a. Eq a => a -> a -> Bool
/= Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
False  -- deep palette unless the background is known dark
          (Float
r1,Float
g1,Float
b1) = if Bool
light then (Float
0.12,Float
0.44,Float
0.69) else (Float
0.16,Float
0.71,Float
0.85)  -- start (blue)
          (Float
r2,Float
g2,Float
b2) = if Bool
light then (Float
0.25,Float
0.49,Float
0.12) else (Float
0.48,Float
0.75,Float
0.26)  -- end   (green)
          fullspan :: Float
fullspan   = Int -> Float
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
1 (Int
h Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
w Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
2)) :: Float
          paint :: Int -> Char -> String
paint Int
c Char
ch
            | Char
ch Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' ' = String
" "  -- leave gaps uncoloured, and out of the escape-code noise
            | Bool
otherwise = Float -> Float -> Float -> String -> String
rgb' (Float -> Float -> Float
mix Float
r1 Float
r2) (Float -> Float -> Float
mix Float
g1 Float
g2) (Float -> Float -> Float
mix Float
b1 Float
b2) [Char
ch]
            where t :: Float
t     = Int -> Float
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int
row Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
c) Float -> Float -> Float
forall a. Fractional a => a -> a -> a
/ Float
fullspan  -- 0 at top-left, 1 at bottom-right
                  mix :: Float -> Float -> Float
mix Float
a Float
b = Float
a Float -> Float -> Float
forall a. Num a => a -> a -> a
+ (Float
b Float -> Float -> Float
forall a. Num a => a -> a -> a
- Float
a) Float -> Float -> Float
forall a. Num a => a -> a -> a
* Float
t
      in String -> String
intensity (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ [String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ (Int -> Char -> String) -> [Int] -> String -> [String]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> Char -> String
paint [Int
col0..] String
s

-- | Render a title heading coloured with hledger's blue-to-green bold gradient,
-- when colour is enabled.
titleLine :: String -> String
titleLine :: String -> String
titleLine String
title = (String -> String) -> Int -> Int -> Int -> Int -> String -> String
gradientStr String -> String
bold' Int
1 (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
title) Int
0 Int
0 String
title

-- | Render a one-line heading with a title at the left and a version (or other
-- short annotation) right-aligned to the given width, both coloured with
-- hledger's blue-to-green gradient (bold title, faint version) when colour is
-- enabled.
titleAndVersionLine :: Int -> String -> String -> String
titleAndVersionLine :: Int -> String -> String -> String
titleAndVersionLine Int
width String
title String
version = String
styledtitle String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
pad String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
styledversion
  where
    styledtitle :: String
styledtitle   = (String -> String) -> Int -> Int -> Int -> Int -> String -> String
gradientStr String -> String
bold'  Int
1 (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
title)   Int
0 Int
0 String
title
    styledversion :: String
styledversion = (String -> String) -> Int -> Int -> Int -> Int -> String -> String
gradientStr String -> String
faint' Int
1 (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
version) Int
0 Int
0 String
version
    pad :: String
pad = Int -> Char -> String
forall a. Int -> a -> [a]
replicate (Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
1 (Int -> Int) -> Int -> Int
forall a b. (a -> b) -> a -> b
$ Int
width Int -> Int -> Int
forall a. Num a => a -> a -> a
- String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
title Int -> Int -> Int
forall a. Num a => a -> a -> a
- String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
version) Char
' '

-- Generic:

-- | Wrap a string in ANSI codes to set and reset foreground colour.
-- ColorIntensity is @Dull@ or @Vivid@ (ie normal and bold).
-- Color is one of @Black@, @Red@, @Green@, @Yellow@, @Blue@, @Magenta@, @Cyan@, @White@.
-- Eg: @color Dull Red "text"@.
color :: ColorIntensity -> Color -> String -> String
color :: ColorIntensity -> Color -> String -> String
color ColorIntensity
int Color
col String
s = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
int Color
col] String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
s String -> String -> String
forall a. [a] -> [a] -> [a]
++ [SGR] -> String
setSGRCode []

-- | Wrap a string in ANSI codes to set and reset background colour.
bgColor :: ColorIntensity -> Color -> String -> String
bgColor :: ColorIntensity -> Color -> String -> String
bgColor ColorIntensity
int Color
col String
s = [SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Background ColorIntensity
int Color
col] String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
s String -> String -> String
forall a. [a] -> [a] -> [a]
++ [SGR] -> String
setSGRCode []

-- | Wrap a WideBuilder in ANSI codes to set and reset foreground colour.
colorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder
colorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder
colorB ColorIntensity
int Color
col (WideBuilder Builder
s Int
w) =
    Builder -> Int -> WideBuilder
WideBuilder (String -> Builder
TB.fromString ([SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
int Color
col]) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
s Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> String -> Builder
TB.fromString ([SGR] -> String
setSGRCode [])) Int
w

-- | Wrap a WideBuilder in ANSI codes to set and reset background colour.
bgColorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder
bgColorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder
bgColorB ColorIntensity
int Color
col (WideBuilder Builder
s Int
w) =
    Builder -> Int -> WideBuilder
WideBuilder (String -> Builder
TB.fromString ([SGR] -> String
setSGRCode [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Background ColorIntensity
int Color
col]) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
s Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> String -> Builder
TB.fromString ([SGR] -> String
setSGRCode [])) Int
w


-- | Detect whether the terminal currently has a light background colour,
-- if possible, using unsafePerformIO.
-- If the terminal is transparent, its apparent light/darkness may be different.
terminalIsLight :: Maybe Bool
terminalIsLight :: Maybe Bool
terminalIsLight = (Float -> Float -> Bool
forall a. Ord a => a -> a -> Bool
> Float
0.5) (Float -> Bool) -> Maybe Float -> Maybe Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Float
terminalLightness

-- | Detect the terminal's current background lightness (0..1), if possible, using unsafePerformIO.
-- If the terminal is transparent, its apparent lightness may be different.
terminalLightness :: Maybe Float
terminalLightness :: Maybe Float
terminalLightness = RGB Float -> Float
forall a. (Fractional a, Ord a) => RGB a -> a
lightness (RGB Float -> Float) -> Maybe (RGB Float) -> Maybe Float
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ConsoleLayer -> Maybe (RGB Float)
terminalColor ConsoleLayer
Background

-- | Detect the terminal's current background colour, if possible, using unsafePerformIO.
terminalBgColor :: Maybe (RGB Float)
terminalBgColor :: Maybe (RGB Float)
terminalBgColor = ConsoleLayer -> Maybe (RGB Float)
terminalColor ConsoleLayer
Background

-- | Detect the terminal's current foreground colour, if possible, using unsafePerformIO.
terminalFgColor :: Maybe (RGB Float)
terminalFgColor :: Maybe (RGB Float)
terminalFgColor = ConsoleLayer -> Maybe (RGB Float)
terminalColor ConsoleLayer
Foreground

-- | Detect the terminal's current foreground or background colour, if possible, using unsafePerformIO.
{-# NOINLINE terminalColor #-}
terminalColor :: ConsoleLayer -> Maybe (RGB Float)
terminalColor :: ConsoleLayer -> Maybe (RGB Float)
terminalColor = IO (Maybe (RGB Float)) -> Maybe (RGB Float)
forall a. IO a -> a
unsafePerformIO (IO (Maybe (RGB Float)) -> Maybe (RGB Float))
-> (ConsoleLayer -> IO (Maybe (RGB Float)))
-> ConsoleLayer
-> Maybe (RGB Float)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ConsoleLayer -> IO (Maybe (RGB Float))
getLayerColor'

-- A version of ansi-terminal's getLayerColor that is less likely to leak escape sequences to output,
-- and that returns a RGB of Floats (0..1) that is more compatible with the colour package.
-- This does nothing in a non-interactive context (eg when piping stdout to another command,
-- or when stdin, where the terminal's answer is read, is not the terminal, eg with -f -),
-- inside emacs (comint shell buffers show the query's escape sequence instead of answering it,
-- and vterm doesn't answer the query at all), or in a non-colour-supporting terminal.
-- If the query fails for some other reason, the colour is unknown.
getLayerColor' :: ConsoleLayer -> IO (Maybe (RGB Float))
getLayerColor' :: ConsoleLayer -> IO (Maybe (RGB Float))
getLayerColor' ConsoleLayer
l = do
  inemacs       <- Bool -> Bool
not (Bool -> Bool) -> (Maybe String -> Bool) -> Maybe String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe String -> Bool
forall a. Maybe a -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Maybe String -> Bool) -> IO (Maybe String) -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO (Maybe String)
lookupEnv String
"INSIDE_EMACS"
  interactive   <- (&&) <$> hIsTerminalDevice stdout <*> hIsTerminalDevice stdin
  supportscolor <- hSupportsANSIColor stdout
  if inemacs || not interactive || not supportscolor then return Nothing
  else (fmap fractionalRGB <$> getLayerColor l) `catch` \(IOException
_ :: IOException) -> Maybe (RGB Float) -> IO (Maybe (RGB Float))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (RGB Float)
forall a. Maybe a
Nothing
  where
    fractionalRGB :: (Fractional a) => RGB Word16 -> RGB a
    fractionalRGB :: forall a. Fractional a => RGB Word16 -> RGB a
fractionalRGB (RGB Word16
r Word16
g Word16
b) = a -> a -> a -> RGB a
forall a. a -> a -> a -> RGB a
RGB (Word16 -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
r a -> a -> a
forall a. Fractional a => a -> a -> a
/ a
65535) (Word16 -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
g a -> a -> a
forall a. Fractional a => a -> a -> a
/ a
65535) (Word16 -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
b a -> a -> a
forall a. Fractional a => a -> a -> a
/ a
65535)  -- chatgpt