{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-|

Embedded documentation files in various formats, and helpers for viewing them.

|-}

module Hledger.Cli.DocFiles (

   Topic
  ,TopicResolution(..)
  ,manualTitle
  ,manualHeadings
  ,manualTopicsMatching
  ,resolveManualTopic
  ,printHelpForTopic
  ,runManForTopic
  ,runInfoForTopic
  ,runPagerForTopic
  ,runTldrForPage

  ) where

import Control.Exception
import Data.ByteString (ByteString)
import Data.Char (isUpper, isLower, toLower)
import Data.ByteString.Char8 qualified as BC
import Data.List (dropWhileEnd, isInfixOf, isPrefixOf, nub)
import Data.Maybe (fromMaybe, maybeToList)
import Data.String
import System.Directory (findExecutable)
import System.Environment (setEnv)
import System.IO
import System.IO.Temp
import System.Process

import Hledger.Utils (first3, second3, third3, embedFileRelative, error', shellQuoteIfNeeded)
import Text.Printf (printf)
import System.Environment (lookupEnv)
import Hledger.Utils.Debug

-- The name of any hledger executable.
type Tool = String

-- Any heading in the hledger user manual (and perhaps later the hledger-ui/hledger-web manuals).
type Topic = String

-- Any name of a hledger tldr page (hledger, hledger-ui, hledger-print etc.)
type TldrPage = String

-- | All hledger-related pages from the tldr-pages project.
-- All are symlinked into the hledger package directory to allow embeddeding.
tldrs :: [(TldrPage, ByteString)]
tldrs :: [(Tool, ByteString)]
tldrs = [
   (Tool
"hledger-accounts",        $(embedFileRelative "embeddedfiles/hledger-accounts.md"))
  ,(Tool
"hledger-add",             $(embedFileRelative "embeddedfiles/hledger-add.md"))
  ,(Tool
"hledger-aregister",       $(embedFileRelative "embeddedfiles/hledger-aregister.md"))
  ,(Tool
"hledger-balance",         $(embedFileRelative "embeddedfiles/hledger-balance.md"))
  ,(Tool
"hledger-balancesheet",    $(embedFileRelative "embeddedfiles/hledger-balancesheet.md"))
  ,(Tool
"hledger-import",          $(embedFileRelative "embeddedfiles/hledger-import.md"))
  ,(Tool
"hledger-incomestatement", $(embedFileRelative "embeddedfiles/hledger-incomestatement.md"))
  ,(Tool
"hledger-print",           $(embedFileRelative "embeddedfiles/hledger-print.md"))
  ,(Tool
"hledger-ui",              $(embedFileRelative "embeddedfiles/hledger-ui.md"))
  ,(Tool
"hledger-web",             $(embedFileRelative "embeddedfiles/hledger-web.md"))
  ,(Tool
"hledger",                 $(embedFileRelative "embeddedfiles/hledger.md"))
  ]

-- | The main hledger manuals as source for man, info and as plain text.
-- All are symlinked into the hledger package directory to allow embeddeding.
manuals :: [(Tool, (ByteString, ByteString, ByteString))]
manuals :: [(Tool, (ByteString, ByteString, ByteString))]
manuals = [
   (Tool
"hledger",
    ($(embedFileRelative "embeddedfiles/hledger.1")
    ,$(embedFileRelative "embeddedfiles/hledger.txt")
    ,$(embedFileRelative "embeddedfiles/hledger.info")
    ))
  ,(Tool
"hledger-ui",
    ($(embedFileRelative "embeddedfiles/hledger-ui.1")
    ,$(embedFileRelative "embeddedfiles/hledger-ui.txt")
    ,$(embedFileRelative "embeddedfiles/hledger-ui.info")
    ))
  ,(Tool
"hledger-web",
    ($(embedFileRelative "embeddedfiles/hledger-web.1")
    ,$(embedFileRelative "embeddedfiles/hledger-web.txt")
    ,$(embedFileRelative "embeddedfiles/hledger-web.info")
    ))
  ]

-- | Get the manual as plain text for this tool, or a not found message.
manualTxt :: Tool -> ByteString
manualTxt :: Tool -> ByteString
manualTxt Tool
name = ByteString
-> ((ByteString, ByteString, ByteString) -> ByteString)
-> Maybe (ByteString, ByteString, ByteString)
-> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Tool -> ByteString
forall a. IsString a => Tool -> a
fromString (Tool -> ByteString) -> Tool -> ByteString
forall a b. (a -> b) -> a -> b
$ Tool
"No text manual found for tool: "Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
name) (ByteString, ByteString, ByteString) -> ByteString
forall {a} {b} {c}. (a, b, c) -> b
second3 (Maybe (ByteString, ByteString, ByteString) -> ByteString)
-> Maybe (ByteString, ByteString, ByteString) -> ByteString
forall a b. (a -> b) -> a -> b
$ Tool
-> [(Tool, (ByteString, ByteString, ByteString))]
-> Maybe (ByteString, ByteString, ByteString)
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Tool
name [(Tool, (ByteString, ByteString, ByteString))]
manuals

-- | This tool's manual title, taken from the top running-header line
-- (eg "HLEDGER(1)  hledger User Manuals  HLEDGER(1)"), with the "(N)" section
-- number stripped (eg "HLEDGER"). Nothing if the manual has no such header.
-- Note this title is not itself a line the viewers can scroll to, so callers
-- resolving a topic to it should show the manual from the top.
manualTitle :: Tool -> Maybe Topic
manualTitle :: Tool -> Maybe Tool
manualTitle Tool
tool = case (Tool -> Bool) -> [Tool] -> [Tool]
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Tool -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([Tool] -> [Tool])
-> (ByteString -> [Tool]) -> ByteString -> [Tool]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tool -> [Tool]
lines (Tool -> [Tool]) -> (ByteString -> Tool) -> ByteString -> [Tool]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Tool
BC.unpack (ByteString -> [Tool]) -> ByteString -> [Tool]
forall a b. (a -> b) -> a -> b
$ Tool -> ByteString
manualTxt Tool
tool of
  (Tool
l:[Tool]
_) | (Tool
w:[Tool]
_) <- Tool -> [Tool]
words Tool
l, Char
'(' Char -> Tool -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Tool
w -> Tool -> Maybe Tool
forall a. a -> Maybe a
Just (Tool -> Maybe Tool) -> Tool -> Maybe Tool
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Tool -> Tool
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'(') Tool
w
  [Tool]
_                                       -> Maybe Tool
forall a. Maybe a
Nothing

-- | The section headings in this tool's manual, each with its hierarchy level,
-- usable as help topics. Some heading hierarchy is lost in the rendered plain
-- text, but we recover an approximate level for each: the manual title (see
-- 'manualTitle') is level 1; an all-caps column-0 heading (eg OPTIONS,
-- PART 1: ...) is level 2; any other column-0 heading (eg Options, Journal) is
-- level 3; and a heading indented three spaces is level 4. Headings are
-- non-blank lines at the left margin or indented exactly three spaces,
-- containing no run of two or more spaces (which would indicate wrapped prose,
-- a table, an option entry, or a running header). The standard man-page
-- headings NAME, SYNOPSIS and DESCRIPTION are dropped, as they aren't useful
-- topics and their generic names could clash with real ones.
manualHeadings :: Tool -> [(Topic, Int)]
manualHeadings :: Tool -> [(Tool, Int)]
manualHeadings Tool
tool = Maybe (Tool, Int) -> [(Tool, Int)]
forall a. Maybe a -> [a]
maybeToList ((Tool -> (Tool, Int)) -> Maybe Tool -> Maybe (Tool, Int)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\Tool
t -> (Tool
t, Int
1)) (Maybe Tool -> Maybe (Tool, Int))
-> Maybe Tool -> Maybe (Tool, Int)
forall a b. (a -> b) -> a -> b
$ Tool -> Maybe Tool
manualTitle Tool
tool) [(Tool, Int)] -> [(Tool, Int)] -> [(Tool, Int)]
forall a. [a] -> [a] -> [a]
++ [(Tool, Int)]
sections
  where
    sections :: [(Tool, Int)]
sections =
      [ (Tool, Int)
hl
      | Tool
l <- Tool -> [Tool]
lines (Tool -> [Tool]) -> (ByteString -> Tool) -> ByteString -> [Tool]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Tool
BC.unpack (ByteString -> [Tool]) -> ByteString -> [Tool]
forall a b. (a -> b) -> a -> b
$ Tool -> ByteString
manualTxt Tool
tool
      , hl :: (Tool, Int)
hl@(Tool
h, Int
_) <- Maybe (Tool, Int) -> [(Tool, Int)]
forall a. Maybe a -> [a]
maybeToList (Maybe (Tool, Int) -> [(Tool, Int)])
-> Maybe (Tool, Int) -> [(Tool, Int)]
forall a b. (a -> b) -> a -> b
$ Tool -> Maybe (Tool, Int)
forall {b}. Num b => Tool -> Maybe (Tool, b)
headingOf Tool
l
      , (Char -> Char) -> Tool -> Tool
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower Tool
h Tool -> [Tool] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Tool
"name", Tool
"synopsis", Tool
"description"]
      ]
    headingOf :: Tool -> Maybe (Tool, b)
headingOf Tool
l = case (Char -> Bool) -> Tool -> (Tool, Tool)
forall a. (a -> Bool) -> [a] -> ([a], [a])
span (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
' ') Tool
l of
      (Tool
"",    Tool
rest) -> (\Tool
h -> (Tool
h, if Tool -> Bool
forall {t :: * -> *}.
(Foldable t, Eq (t Char), IsString (t Char)) =>
t Char -> Bool
level2Caps Tool
h then b
2 else b
3)) (Tool -> (Tool, b)) -> Maybe Tool -> Maybe (Tool, b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Tool -> Maybe Tool
headingText Tool
rest
      (Tool
"   ", Tool
rest) -> (\Tool
h -> (Tool
h, b
4))                             (Tool -> (Tool, b)) -> Maybe Tool -> Maybe (Tool, b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Tool -> Maybe Tool
headingText Tool
rest
      (Tool, Tool)
_             -> Maybe (Tool, b)
forall a. Maybe a
Nothing
    headingText :: Tool -> Maybe Tool
headingText Tool
s
      | Tool -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Tool
s' Bool -> Bool -> Bool
|| Tool
"  " Tool -> Tool -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` Tool
s' = Maybe Tool
forall a. Maybe a
Nothing
      | Bool
otherwise                      = Tool -> Maybe Tool
forall a. a -> Maybe a
Just Tool
s'
      where s' :: Tool
s' = (Char -> Bool) -> Tool -> Tool
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
' ') Tool
s
    -- An all-caps column-0 heading is normally a level-2 section, except for a
    -- few that are really level-3 subsections, eg CSV (a data format, sibling of
    -- the Journal/Timeclock/Timedot sections).
    level2Caps :: t Char -> Bool
level2Caps t Char
h = t Char -> Bool
forall {t :: * -> *}. Foldable t => t Char -> Bool
allCaps t Char
h Bool -> Bool -> Bool
&& t Char
h t Char -> [t Char] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [t Char
"CSV"]
    allCaps :: t Char -> Bool
allCaps t Char
s = (Char -> Bool) -> t Char -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Char -> Bool
isUpper t Char
s Bool -> Bool -> Bool
&& Bool -> Bool
not ((Char -> Bool) -> t Char -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Char -> Bool
isLower t Char
s)

-- | Every matchable help topic as (name, tool, heading): every manual's headings
-- (each with the tool whose manual it belongs to), given a unique name for
-- matching and listing. The name is the heading, but with "-ui"/"-web" appended
-- for a hledger-ui/hledger-web heading whose bare name also occurs in another
-- manual (so eg OPTIONS becomes OPTIONS-ui / OPTIONS-web, keeping every name
-- unique and unambiguously matchable). hledger headings always keep their bare
-- name, as does any section name unique to one manual.
manualTopics :: [(Topic, Tool, Topic, Int)]
manualTopics :: [(Tool, Tool, Tool, Int)]
manualTopics = [(Tool -> Tool -> Tool
forall {a}. (Eq a, IsString a) => a -> Tool -> Tool
topicName Tool
tool Tool
h, Tool
tool, Tool
h, Int
lvl) | (Tool
tool, (Tool
h, Int
lvl)) <- [(Tool, (Tool, Int))]
rawpairs]
  where
    rawpairs :: [(Tool, (Tool, Int))]
rawpairs = [(Tool
tool, (Tool, Int)
hl) | Tool
tool <- ((Tool, (ByteString, ByteString, ByteString)) -> Tool)
-> [(Tool, (ByteString, ByteString, ByteString))] -> [Tool]
forall a b. (a -> b) -> [a] -> [b]
map (Tool, (ByteString, ByteString, ByteString)) -> Tool
forall a b. (a, b) -> a
fst [(Tool, (ByteString, ByteString, ByteString))]
manuals, (Tool, Int)
hl <- Tool -> [(Tool, Int)]
manualHeadings Tool
tool]
    manualsWith :: Tool -> [Tool]
manualsWith Tool
lch = [Tool] -> [Tool]
forall a. Eq a => [a] -> [a]
nub [Tool
tool | (Tool
tool, (Tool
h, Int
_)) <- [(Tool, (Tool, Int))]
rawpairs, (Char -> Char) -> Tool -> Tool
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower Tool
h Tool -> Tool -> Bool
forall a. Eq a => a -> a -> Bool
== Tool
lch]
    topicName :: a -> Tool -> Tool
topicName a
tool Tool
h = case a
tool of
      a
"hledger-ui"  | Bool
shared -> Tool
h Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool
"-ui"
      a
"hledger-web" | Bool
shared -> Tool
h Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool
"-web"
      a
_                      -> Tool
h
      where shared :: Bool
shared = [Tool] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (Tool -> [Tool]
manualsWith ((Char -> Char) -> Tool -> Tool
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower Tool
h)) Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1

-- | The result of resolving a user-supplied topic against all the manuals'
-- topics. A found match carries the tool whose manual it belongs to and the
-- heading to scroll to; an ambiguous match carries the matching topic names,
-- each with its manual heading level (for hierarchical listing).
data TopicResolution = TopicNotFound | TopicFound Tool Topic | TopicAmbiguous [(Topic, Int)]

-- | Resolve a topic to a manual section, searching all the manuals' topic names.
-- A case-insensitive exact match wins; otherwise a unique prefix match is used;
-- otherwise a unique infix match is used. Resolving to a heading (and its tool)
-- lets all viewers (including info and the web anchor) locate the section
-- reliably, and lets callers respond to a bad topic. When the match is
-- ambiguous, all matches of any kind (ie all infix matches) are listed.
resolveManualTopic :: Topic -> TopicResolution
resolveManualTopic :: Tool -> TopicResolution
resolveManualTopic Tool
topic =
  case [(Tool, Tool, Tool, Int)]
exacts of
    [(Tool, Tool, Tool, Int)
tp] -> (Tool, Tool, Tool, Int) -> TopicResolution
forall {a} {d}. (a, Tool, Tool, d) -> TopicResolution
found (Tool, Tool, Tool, Int)
tp
    []   -> case ([(Tool, Tool, Tool, Int)]
prefixes, [(Tool, Tool, Tool, Int)]
infixes) of
      ([(Tool, Tool, Tool, Int)
tp], [(Tool, Tool, Tool, Int)]
_)  -> (Tool, Tool, Tool, Int) -> TopicResolution
forall {a} {d}. (a, Tool, Tool, d) -> TopicResolution
found (Tool, Tool, Tool, Int)
tp
      ([], [(Tool, Tool, Tool, Int)
tp]) -> (Tool, Tool, Tool, Int) -> TopicResolution
forall {a} {d}. (a, Tool, Tool, d) -> TopicResolution
found (Tool, Tool, Tool, Int)
tp
      ([], [])   -> TopicResolution
TopicNotFound
      ([(Tool, Tool, Tool, Int)]
_,  [(Tool, Tool, Tool, Int)]
tps)  -> [(Tool, Int)] -> TopicResolution
TopicAmbiguous (((Tool, Tool, Tool, Int) -> (Tool, Int))
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Int)]
forall a b. (a -> b) -> [a] -> [b]
map (Tool, Tool, Tool, Int) -> (Tool, Int)
forall {a} {b} {c} {b}. (a, b, c, b) -> (a, b)
nameLevel [(Tool, Tool, Tool, Int)]
tps)
    [(Tool, Tool, Tool, Int)]
_    -> [(Tool, Int)] -> TopicResolution
TopicAmbiguous (((Tool, Tool, Tool, Int) -> (Tool, Int))
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Int)]
forall a b. (a -> b) -> [a] -> [b]
map (Tool, Tool, Tool, Int) -> (Tool, Int)
forall {a} {b} {c} {b}. (a, b, c, b) -> (a, b)
nameLevel [(Tool, Tool, Tool, Int)]
infixes)
  where
    exacts :: [(Tool, Tool, Tool, Int)]
exacts   = [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a. Eq a => [a] -> [a]
nub ([(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)])
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a b. (a -> b) -> a -> b
$ ((Tool, Tool, Tool, Int) -> Bool)
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Tool -> Tool -> Bool
forall a. Eq a => a -> a -> Bool
== Tool
t)          (Tool -> Bool)
-> ((Tool, Tool, Tool, Int) -> Tool)
-> (Tool, Tool, Tool, Int)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tool -> Tool
lc (Tool -> Tool)
-> ((Tool, Tool, Tool, Int) -> Tool)
-> (Tool, Tool, Tool, Int)
-> Tool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Tool, Tool, Tool, Int) -> Tool
forall {a} {b} {c} {d}. (a, b, c, d) -> a
name) [(Tool, Tool, Tool, Int)]
manualTopics
    prefixes :: [(Tool, Tool, Tool, Int)]
prefixes = [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a. Eq a => [a] -> [a]
nub ([(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)])
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a b. (a -> b) -> a -> b
$ ((Tool, Tool, Tool, Int) -> Bool)
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Tool
t Tool -> Tool -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) (Tool -> Bool)
-> ((Tool, Tool, Tool, Int) -> Tool)
-> (Tool, Tool, Tool, Int)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tool -> Tool
lc (Tool -> Tool)
-> ((Tool, Tool, Tool, Int) -> Tool)
-> (Tool, Tool, Tool, Int)
-> Tool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Tool, Tool, Tool, Int) -> Tool
forall {a} {b} {c} {d}. (a, b, c, d) -> a
name) [(Tool, Tool, Tool, Int)]
manualTopics
    infixes :: [(Tool, Tool, Tool, Int)]
infixes  = [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a. Eq a => [a] -> [a]
nub ([(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)])
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a b. (a -> b) -> a -> b
$ ((Tool, Tool, Tool, Int) -> Bool)
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Tool
t Tool -> Tool -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf`)  (Tool -> Bool)
-> ((Tool, Tool, Tool, Int) -> Tool)
-> (Tool, Tool, Tool, Int)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tool -> Tool
lc (Tool -> Tool)
-> ((Tool, Tool, Tool, Int) -> Tool)
-> (Tool, Tool, Tool, Int)
-> Tool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Tool, Tool, Tool, Int) -> Tool
forall {a} {b} {c} {d}. (a, b, c, d) -> a
name) [(Tool, Tool, Tool, Int)]
manualTopics
    found :: (a, Tool, Tool, d) -> TopicResolution
found (a
_, Tool
tool, Tool
h, d
_) = Tool -> Tool -> TopicResolution
TopicFound Tool
tool Tool
h
    name :: (a, b, c, d) -> a
name (a
n, b
_, c
_, d
_) = a
n
    nameLevel :: (a, b, c, b) -> (a, b)
nameLevel (a
n, b
_, c
_, b
lvl) = (a
n, b
lvl)
    lc :: Tool -> Tool
lc = (Char -> Char) -> Tool -> Tool
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower
    t :: Tool
t  = Tool -> Tool
lc (Tool -> Tool) -> (Tool -> Tool) -> Tool -> Tool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> Tool -> Tool
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
' ') (Tool -> Tool) -> Tool -> Tool
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Tool -> Tool
forall a. (a -> Bool) -> [a] -> [a]
dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
' ') Tool
topic

-- | The topic names (each with its manual heading level, for hierarchical
-- listing) that contain the given topic as a case-insensitive substring (all
-- topics if the topic is empty). Used by help's -l list mode.
manualTopicsMatching :: Topic -> [(Topic, Int)]
manualTopicsMatching :: Tool -> [(Tool, Int)]
manualTopicsMatching Tool
topic = [(Tool, Int)] -> [(Tool, Int)]
forall a. Eq a => [a] -> [a]
nub ([(Tool, Int)] -> [(Tool, Int)]) -> [(Tool, Int)] -> [(Tool, Int)]
forall a b. (a -> b) -> a -> b
$ ((Tool, Tool, Tool, Int) -> (Tool, Int))
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Int)]
forall a b. (a -> b) -> [a] -> [b]
map (Tool, Tool, Tool, Int) -> (Tool, Int)
forall {a} {b} {c} {b}. (a, b, c, b) -> (a, b)
nameLevel ([(Tool, Tool, Tool, Int)] -> [(Tool, Int)])
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Int)]
forall a b. (a -> b) -> a -> b
$ ((Tool, Tool, Tool, Int) -> Bool)
-> [(Tool, Tool, Tool, Int)] -> [(Tool, Tool, Tool, Int)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Tool
t Tool -> Tool -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf`) (Tool -> Bool)
-> ((Tool, Tool, Tool, Int) -> Tool)
-> (Tool, Tool, Tool, Int)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tool -> Tool
lc (Tool -> Tool)
-> ((Tool, Tool, Tool, Int) -> Tool)
-> (Tool, Tool, Tool, Int)
-> Tool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Tool, Tool, Tool, Int) -> Tool
forall {a} {b} {c} {d}. (a, b, c, d) -> a
name) [(Tool, Tool, Tool, Int)]
manualTopics
  where
    name :: (a, b, c, d) -> a
name (a
n, b
_, c
_, d
_) = a
n
    nameLevel :: (a, b, c, b) -> (a, b)
nameLevel (a
n, b
_, c
_, b
lvl) = (a
n, b
lvl)
    lc :: Tool -> Tool
lc = (Char -> Char) -> Tool -> Tool
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower
    t :: Tool
t  = Tool -> Tool
lc (Tool -> Tool) -> (Tool -> Tool) -> Tool -> Tool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> Tool -> Tool
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
' ') (Tool -> Tool) -> Tool -> Tool
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Tool -> Tool
forall a. (a -> Bool) -> [a] -> [a]
dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
' ') Tool
topic

-- | Get the manual as man source (nroff) for this tool, or a not found message.
manualMan :: Tool -> ByteString
manualMan :: Tool -> ByteString
manualMan Tool
name = ByteString
-> ((ByteString, ByteString, ByteString) -> ByteString)
-> Maybe (ByteString, ByteString, ByteString)
-> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Tool -> ByteString
forall a. IsString a => Tool -> a
fromString (Tool -> ByteString) -> Tool -> ByteString
forall a b. (a -> b) -> a -> b
$ Tool
"No man page found for tool: "Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
name) (ByteString, ByteString, ByteString) -> ByteString
forall {a} {b} {c}. (a, b, c) -> a
first3 (Maybe (ByteString, ByteString, ByteString) -> ByteString)
-> Maybe (ByteString, ByteString, ByteString) -> ByteString
forall a b. (a -> b) -> a -> b
$ Tool
-> [(Tool, (ByteString, ByteString, ByteString))]
-> Maybe (ByteString, ByteString, ByteString)
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Tool
name [(Tool, (ByteString, ByteString, ByteString))]
manuals

-- | Get the manual as info source (texinfo) for this tool, or a not found message.
manualInfo :: Tool -> ByteString
manualInfo :: Tool -> ByteString
manualInfo Tool
name = ByteString
-> ((ByteString, ByteString, ByteString) -> ByteString)
-> Maybe (ByteString, ByteString, ByteString)
-> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Tool -> ByteString
forall a. IsString a => Tool -> a
fromString (Tool -> ByteString) -> Tool -> ByteString
forall a b. (a -> b) -> a -> b
$ Tool
"No info manual found for tool: "Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
name) (ByteString, ByteString, ByteString) -> ByteString
forall {a} {b} {c}. (a, b, c) -> c
third3 (Maybe (ByteString, ByteString, ByteString) -> ByteString)
-> Maybe (ByteString, ByteString, ByteString) -> ByteString
forall a b. (a -> b) -> a -> b
$ Tool
-> [(Tool, (ByteString, ByteString, ByteString))]
-> Maybe (ByteString, ByteString, ByteString)
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Tool
name [(Tool, (ByteString, ByteString, ByteString))]
manuals

-- | Print plain text help for this tool. This is the fallback "viewer" used
-- for non-interactive output or a dumb terminal, where no pager is available.
-- To avoid dumping the whole (large) manual, when no topic is requested we print
-- only the introduction: everything up to and including the DESCRIPTION section
-- (ie stopping at the first all-caps top-level heading after it, such as PART 1),
-- followed by a note on how to read the rest.
-- If a topic is requested, or there's no DESCRIPTION heading (eg the
-- hledger-ui/hledger-web manuals), the whole manual is printed.
printHelpForTopic :: Tool -> Maybe Topic -> IO ()
printHelpForTopic :: Tool -> Maybe Tool -> IO ()
printHelpForTopic Tool
tool Maybe Tool
mtopic = do
  let manual :: ByteString
manual = Tool -> ByteString
manualTxt Tool
tool
  case Maybe Tool
mtopic of
    Just Tool
_  -> ByteString -> IO ()
BC.putStr ByteString
manual  -- topic requested: show all, so it isn't hidden
    Maybe Tool
Nothing ->
      case (ByteString -> Bool)
-> [ByteString] -> ([ByteString], [ByteString])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
"DESCRIPTION") (ByteString -> [ByteString]
BC.lines ByteString
manual) of
        ([ByteString]
_, [])              -> ByteString -> IO ()
BC.putStr ByteString
manual  -- no DESCRIPTION heading: show all
        ([ByteString]
before, ByteString
desc:[ByteString]
after) ->
          case (ByteString -> Bool)
-> [ByteString] -> ([ByteString], [ByteString])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break ByteString -> Bool
isTopHeading [ByteString]
after of
            ([ByteString]
_, [])       -> ByteString -> IO ()
BC.putStr ByteString
manual  -- no following heading: show all
            ([ByteString]
body, [ByteString]
_)     -> do
              ByteString -> IO ()
BC.putStr (ByteString -> IO ()) -> ByteString -> IO ()
forall a b. (a -> b) -> a -> b
$ [ByteString] -> ByteString
BC.unlines ([ByteString] -> ByteString) -> [ByteString] -> ByteString
forall a b. (a -> b) -> a -> b
$ [ByteString]
before [ByteString] -> [ByteString] -> [ByteString]
forall a. [a] -> [a] -> [a]
++ ByteString
desc ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: [ByteString]
body
              ByteString -> IO ()
BC.putStrLn ByteString
helpTruncationNote

-- | Is this a top-level manual heading: a non-empty line starting in column 0
-- with an uppercase letter and containing no lowercase letters (eg NAME, PART 1: ...)?
isTopHeading :: ByteString -> Bool
isTopHeading :: ByteString -> Bool
isTopHeading ByteString
l = case ByteString -> Maybe (Char, ByteString)
BC.uncons ByteString
l of
  Just (Char
c, ByteString
_) -> Char -> Bool
isUpper Char
c Bool -> Bool -> Bool
&& Bool -> Bool
not ((Char -> Bool) -> ByteString -> Bool
BC.any Char -> Bool
isLower ByteString
l)
  Maybe (Char, ByteString)
Nothing     -> Bool
False

-- | Note appended to the truncated plain-text help.
helpTruncationNote :: ByteString
helpTruncationNote :: ByteString
helpTruncationNote =
  ByteString
"(This is just the introduction. To read the full manual, run `hledger help`\n\
  \in a more capable terminal, or `hledger help -p` (pager), `-m` (man) or `-i`\n\
  \(info), or see https://hledger.org.)"

-- | Display an info manual for this topic, opened at the given topic if provided,
-- using the "info" executable in $PATH.
-- Topic can be an exact heading or a heading prefix; info will favour an exact match.
runInfoForTopic :: Tool -> Maybe Topic -> IO ()
runInfoForTopic :: Tool -> Maybe Tool -> IO ()
runInfoForTopic Tool
tool Maybe Tool
mtopic =
  Tool -> (Tool -> Handle -> IO ()) -> IO ()
forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
Tool -> (Tool -> Handle -> m a) -> m a
withSystemTempFile (Tool
"hledger-"Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
toolTool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
".info") ((Tool -> Handle -> IO ()) -> IO ())
-> (Tool -> Handle -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Tool
f Handle
h -> do
    Handle -> ByteString -> IO ()
BC.hPutStrLn Handle
h (ByteString -> IO ()) -> ByteString -> IO ()
forall a b. (a -> b) -> a -> b
$ Tool -> ByteString
manualInfo Tool
tool
    Handle -> IO ()
hClose Handle
h
    Tool -> IO ()
callCommand (Tool -> IO ()) -> Tool -> IO ()
forall a b. (a -> b) -> a -> b
$ Tool -> Tool -> Tool
forall a. Show a => Tool -> a -> a
dbg1 Tool
"info command" (Tool -> Tool) -> Tool -> Tool
forall a b. (a -> b) -> a -> b
$
      Tool
"info -f " Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool -> Tool
shellQuoteIfNeeded Tool
f Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool -> (Tool -> Tool) -> Maybe Tool -> Tool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Tool
"" (Tool -> Tool -> Tool
forall r. PrintfType r => Tool -> r
printf Tool
" -n '%s'") Maybe Tool
mtopic

-- less with any vertical whitespace squashed, case-insensitive searching, the $ regex metacharacter accessible as \$.
less :: Tool
less = Tool
"less -s -i --use-backslash"

-- | Display plain text help for this tool, scrolled to the given topic if any, using the users $PAGER or "less".
-- When a topic is provided we always use less, ignoring $PAGER.
--
-- This is less robust than the newer Hledger.Utils.IO.runPager,
-- but that one doesn't yet support scrolling to a topic.
runPagerForTopic :: Tool -> Maybe Topic -> IO ()
runPagerForTopic :: Tool -> Maybe Tool -> IO ()
runPagerForTopic Tool
tool Maybe Tool
mtopic = do
  Tool -> (Tool -> Handle -> IO ()) -> IO ()
forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
Tool -> (Tool -> Handle -> m a) -> m a
withSystemTempFile (Tool
"hledger-"Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
toolTool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
".txt") ((Tool -> Handle -> IO ()) -> IO ())
-> (Tool -> Handle -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Tool
f Handle
h -> do
    Handle -> ByteString -> IO ()
BC.hPutStrLn Handle
h (ByteString -> IO ()) -> ByteString -> IO ()
forall a b. (a -> b) -> a -> b
$ Tool -> ByteString
manualTxt Tool
tool
    Handle -> IO ()
hClose Handle
h
    envpager <- Tool -> Maybe Tool -> Tool
forall a. a -> Maybe a -> a
fromMaybe Tool
less (Maybe Tool -> Tool) -> IO (Maybe Tool) -> IO Tool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Tool -> IO (Maybe Tool)
lookupEnv Tool
"PAGER"
    let
      exactmatch = Bool
True
      (pager, searcharg) =
        case mtopic of
          Maybe Tool
Nothing -> (Tool
envpager, Tool
"")
          Just Tool
t  -> (Tool
less, Tool
"-p'^(   )?" Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool
t Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ if Bool
exactmatch then Tool
"\\$'" else Tool
"")
    callCommand $ dbg1 "pager command" $ unwords [pager, searcharg, shellQuoteIfNeeded f]

-- | Display a man page for this tool, scrolled to the given topic if provided, using "man".
-- When a topic is provided we force man to use "less", ignoring $MANPAGER and $PAGER.
runManForTopic :: Tool -> Maybe Topic -> IO ()
runManForTopic :: Tool -> Maybe Tool -> IO ()
runManForTopic Tool
tool Maybe Tool
mtopic =
  -- This temp file path should have a slash in it, man requires at least one.
  Tool -> (Tool -> Handle -> IO ()) -> IO ()
forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
Tool -> (Tool -> Handle -> m a) -> m a
withSystemTempFile (Tool
"hledger-"Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
toolTool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
".1") ((Tool -> Handle -> IO ()) -> IO ())
-> (Tool -> Handle -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Tool
f Handle
h -> do
    Handle -> ByteString -> IO ()
BC.hPutStrLn Handle
h (ByteString -> IO ()) -> ByteString -> IO ()
forall a b. (a -> b) -> a -> b
$ Tool -> ByteString
manualMan Tool
tool
    Handle -> IO ()
hClose Handle
h
    let
      exactmatch :: Bool
exactmatch = Bool
True
      pagerarg :: Tool
pagerarg =
        case Maybe Tool
mtopic of
          Maybe Tool
Nothing -> Tool
""
          Just Tool
t  -> Tool
"-P \"" Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool
less Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool
" -p'^(   )?" Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool
t Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ (if Bool
exactmatch then Tool
"\\\\$" else Tool
"") Tool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++ Tool
"'\""
    Tool -> IO ()
callCommand (Tool -> IO ()) -> Tool -> IO ()
forall a b. (a -> b) -> a -> b
$ Tool -> Tool -> Tool
forall a. Show a => Tool -> a -> a
dbg1 Tool
"man command" (Tool -> Tool) -> Tool -> Tool
forall a b. (a -> b) -> a -> b
$ [Tool] -> Tool
unwords [Tool
"man", Tool
pagerarg, Tool -> Tool
shellQuoteIfNeeded Tool
f]

-- | Get the named tldr page's source, if we know it.
tldr :: TldrPage -> Maybe ByteString
tldr :: Tool -> Maybe ByteString
tldr Tool
name = Tool -> [(Tool, ByteString)] -> Maybe ByteString
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Tool
name [(Tool, ByteString)]
tldrs

-- | Display one of the hledger tldr pages, using "tldr".
runTldrForPage :: TldrPage -> IO ()
runTldrForPage :: Tool -> IO ()
runTldrForPage Tool
name =
  case Tool -> Maybe ByteString
tldr Tool
name of
    Maybe ByteString
Nothing -> Tool -> IO ()
forall a. Tool -> a
error' (Tool -> IO ()) -> Tool -> IO ()
forall a b. (a -> b) -> a -> b
$ Tool
"sorry, there are no examples for " Tool -> Tool -> Tool
forall a. Semigroup a => a -> a -> a
<> Tool
name Tool -> Tool -> Tool
forall a. Semigroup a => a -> a -> a
<> Tool
" yet"
    Just ByteString
b -> do
      let fallback :: IO ()
fallback = do
            Handle -> Tool -> IO ()
hPutStrLn Handle
stderr Tool
"Warning: could not run tldr --render, using fallback viewer instead.\n"
            ByteString -> IO ()
BC.putStrLn ByteString
b
      -- Check for a tldr client first, so we can fall back quietly without the
      -- shell printing a "command not found" error.
      mtldr <- Tool -> IO (Maybe Tool)
findExecutable Tool
"tldr"
      case mtldr of
        Maybe Tool
Nothing -> IO ()
fallback
        Just Tool
_ -> (do
          Tool -> (Tool -> Handle -> IO ()) -> IO ()
forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
Tool -> (Tool -> Handle -> m a) -> m a
withSystemTempFile (Tool
nameTool -> Tool -> Tool
forall a. [a] -> [a] -> [a]
++Tool
".md") ((Tool -> Handle -> IO ()) -> IO ())
-> (Tool -> Handle -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Tool
f Handle
h -> do
            Handle -> ByteString -> IO ()
BC.hPutStrLn Handle
h ByteString
b
            Handle -> IO ()
hClose Handle
h
            -- tldr clients tend to auto-update their data, try to discourage that here
            -- tealdeer - doesn't auto-update by default
            -- tlrc - ?
            -- tldr-node-client - undocumented env var suggested in output
            Tool -> Tool -> IO ()
setEnv Tool
"TLDR_AUTO_UPDATE_DISABLED" Tool
"1"
            Tool -> IO ()
callCommand (Tool -> IO ()) -> Tool -> IO ()
forall a b. (a -> b) -> a -> b
$ Tool -> Tool -> Tool
forall a. Show a => Tool -> a -> a
dbg1 Tool
"tldr command" (Tool -> Tool) -> Tool -> Tool
forall a b. (a -> b) -> a -> b
$ Tool
"tldr --render " Tool -> Tool -> Tool
forall a. Semigroup a => a -> a -> a
<> Tool -> Tool
shellQuoteIfNeeded Tool
f
          ) IO () -> (IOException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(IOException
_e::IOException) -> IO ()
fallback)