scroll-1.20250228.2: unix/Pager.hs
{-# LANGUAGE CPP #-}
module Pager where
import System.IO
import System.Posix.IO
import System.Posix.Terminal
import Control.Applicative
import Prelude
-- If stdin is not connected to a tty, we're being used as a pager with
-- output piped in. The content of stdin is sucked in and returned for
-- paging, and stdin is re-opened from the terminal device.
stdinPager :: IO (Maybe String)
stdinPager = go =<< queryTerminal stdInput
where
go True = return Nothing
go False = do
stdoutisterm <- queryTerminal stdOutput
if stdoutisterm
then do
term <- getTerminalName stdOutput
oldstdin <- dup stdInput
closeFd stdInput
#if MIN_VERSION_unix(2,8,0)
newstdin <- openFd term ReadOnly defaultFileFlags
#else
newstdin <- openFd term ReadOnly Nothing defaultFileFlags
#endif
_ <- dupTo newstdin stdInput
Just <$> (hGetContents =<< fdToHandle oldstdin)
else error "stdout is not a terminal"