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 newstdin <- openFd term ReadOnly Nothing defaultFileFlags _ <- dupTo newstdin stdInput Just <$> (hGetContents =<< fdToHandle oldstdin) else error "stdout is not a terminal"