{-|

The help command.

|-}
--TODO rename manuals
--TODO substring matching

{-# LANGUAGE PackageImports #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}

module Hledger.Cli.Commands.Help (

   helpmode
  ,manual

  ) where

import Control.Monad (void)
import Data.Char (toLower)
import Data.List (isInfixOf)
import Data.Maybe
import System.Console.CmdArgs.Explicit
import System.Environment
import System.IO

import Hledger.Cli.CliOptions
import Hledger.Cli.DocFiles
import Hledger.Cli.Utils (openBrowserOn)
import Hledger.Cli.Version (webManualUrl)
import Hledger.Data.RawOptions
import Hledger.Utils (embedFileRelative, runPager, titleLine)
--import Hledger.Utils.Debug

helpmode :: Mode RawOpts
helpmode = Topic
-> [Flag RawOpts]
-> [(Topic, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Help.txt")
  -- The help-* names avoid a clash with the --info and --man flags handled in Cli.hs.
  [[Topic] -> (RawOpts -> RawOpts) -> Topic -> Flag RawOpts
forall a. [Topic] -> (a -> a) -> Topic -> Flag a
flagNone [Topic
"i"] (Topic -> RawOpts -> RawOpts
setboolopt Topic
"help-i") Topic
"use info when showing the manual"
  ,[Topic] -> (RawOpts -> RawOpts) -> Topic -> Flag RawOpts
forall a. [Topic] -> (a -> a) -> Topic -> Flag a
flagNone [Topic
"m"] (Topic -> RawOpts -> RawOpts
setboolopt Topic
"help-m") Topic
"use man when showing the manual"
  ,[Topic] -> (RawOpts -> RawOpts) -> Topic -> Flag RawOpts
forall a. [Topic] -> (a -> a) -> Topic -> Flag a
flagNone [Topic
"p"] (Topic -> RawOpts -> RawOpts
setboolopt Topic
"help-p") Topic
"use less (or $PAGER) when showing the manual"
  ,[Topic] -> (RawOpts -> RawOpts) -> Topic -> Flag RawOpts
forall a. [Topic] -> (a -> a) -> Topic -> Flag a
flagNone [Topic
"w"] (Topic -> RawOpts -> RawOpts
setboolopt Topic
"help-w") Topic
"use a web browser when showing the manual"
  ,[Topic] -> (RawOpts -> RawOpts) -> Topic -> Flag RawOpts
forall a. [Topic] -> (a -> a) -> Topic -> Flag a
flagNone [Topic
"l"] (Topic -> RawOpts -> RawOpts
setboolopt Topic
"help-l") Topic
"just list the manual topics matching TOPIC"
  -- These three limit the commands list to one category of command; with none of them, all are shown.
  ,[Topic] -> (RawOpts -> RawOpts) -> Topic -> Flag RawOpts
forall a. [Topic] -> (a -> a) -> Topic -> Flag a
flagNone [Topic
"builtins"] (Topic -> RawOpts -> RawOpts
setboolopt Topic
"builtins") Topic
"with commands: show only builtin commands"
  ,[Topic] -> (RawOpts -> RawOpts) -> Topic -> Flag RawOpts
forall a. [Topic] -> (a -> a) -> Topic -> Flag a
flagNone [Topic
"addons"]   (Topic -> RawOpts -> RawOpts
setboolopt Topic
"addons")   Topic
"with commands: show only addon commands"
  ,[Topic] -> (RawOpts -> RawOpts) -> Topic -> Flag RawOpts
forall a. [Topic] -> (a -> a) -> Topic -> Flag a
flagNone [Topic
"aliases"]  (Topic -> RawOpts -> RawOpts
setboolopt Topic
"aliases")  Topic
"with commands: show only command aliases"
  ]
  [(Topic
helpflagstitle, [Flag RawOpts]
helpflags)]
  [Flag RawOpts]
hiddenflags  -- accept --conf/--no-conf etc., eg so "help commands" can show config aliases
  ([], Arg RawOpts -> Maybe (Arg RawOpts)
forall a. a -> Maybe a
Just (Arg RawOpts -> Maybe (Arg RawOpts))
-> Arg RawOpts -> Maybe (Arg RawOpts)
forall a b. (a -> b) -> a -> b
$ Topic -> Arg RawOpts
argsFlag Topic
"[TOPIC]")

-- | Display the hledger manual in various formats, optionally positioned at the given topic.
-- You can select a docs viewer with one of the `--info`, `--man`, `--pager` flags.
-- Otherwise it will use the first available of: info, man, $PAGER, less, stdout
-- (and always stdout if output is non-interactive, the terminal is dumb, or we are
-- in an Emacs buffer that can't render fullscreen viewers, eg shell/comint or eshell).
manual :: CliOpts -> Maybe Topic -> IO ()
manual :: CliOpts -> Maybe Topic -> IO ()
manual CliOpts
opts Maybe Topic
mtopic
  -- With -l, just list the matching topics rather than showing the manual.
  | Bool
listonly  = case Topic -> [(Topic, Int)]
manualTopicsMatching Topic
topic of
      [] -> IO ()
notFound
      [(Topic, Int)]
ts -> Topic -> [(Topic, Int)] -> IO ()
listTopics Topic
matchingHeading [(Topic, Int)]
ts
  | Bool
otherwise = case Topic -> TopicResolution
resolveManualTopic Topic
topic of
      -- The title isn't a line the viewers can scroll to, so show that manual
      -- from the top for it (rather than searching for the title text, which eg
      -- makes info jump to the first node starting with the program name).
      TopicFound Topic
tool Topic
h
        | Topic -> Maybe Topic
forall a. a -> Maybe a
Just Topic
h Maybe Topic -> Maybe Topic -> Bool
forall a. Eq a => a -> a -> Bool
== Topic -> Maybe Topic
manualTitle Topic
tool -> Topic -> Maybe Topic -> IO ()
showManualAt Topic
tool Maybe Topic
forall a. Maybe a
Nothing
        | Bool
otherwise                  -> Topic -> Maybe Topic -> IO ()
showManualAt Topic
tool (Topic -> Maybe Topic
forall a. a -> Maybe a
Just Topic
h)
      -- No match: show a note on stderr and stop, rather than raising an error.
      TopicResolution
TopicNotFound     -> IO ()
notFound
      -- Several matches (or none requested, ie the empty topic, which matches
      -- every heading): list them so the user can pick a specific topic. This
      -- is what `hledger help manual` (with no topic) does.
      TopicAmbiguous [(Topic, Int)]
ts -> Topic -> [(Topic, Int)] -> IO ()
listTopics Topic
ambiguousHeading [(Topic, Int)]
ts
  where
    listonly :: Bool
listonly = Topic -> RawOpts -> Bool
boolopt Topic
"help-l" (RawOpts -> Bool) -> RawOpts -> Bool
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
opts
    topic :: Topic
topic    = Topic -> Maybe Topic -> Topic
forall a. a -> Maybe a -> a
fromMaybe Topic
"" Maybe Topic
mtopic
    -- Are we listing all the topics (rather than just those matching a TOPIC)?
    listall :: Bool
listall  = Topic -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Topic
topic
    -- List the given topic names, in the pager if the list is long and one is available.
    -- When listing all topics, indent each by its manual heading level (minus one)
    -- to show the hierarchy; when listing just the matches, indent them all equally.
    listTopics :: Topic -> [(Topic, Int)] -> IO ()
listTopics Topic
heading [(Topic, Int)]
nls = Topic -> IO ()
runPager (Topic -> IO ()) -> Topic -> IO ()
forall a b. (a -> b) -> a -> b
$ [Topic] -> Topic
unlines ([Topic] -> Topic) -> [Topic] -> Topic
forall a b. (a -> b) -> a -> b
$ Topic
heading Topic -> [Topic] -> [Topic]
forall a. a -> [a] -> [a]
: ((Topic, Int) -> Topic) -> [(Topic, Int)] -> [Topic]
forall a b. (a -> b) -> [a] -> [b]
map (Topic, Int) -> Topic
fmt [(Topic, Int)]
nls
      where fmt :: (Topic, Int) -> Topic
fmt (Topic
n, Int
lvl) = Int -> Char -> Topic
forall a. Int -> a -> [a]
replicate (if Bool
listall then Int
lvl Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1 else Int
2) Char
' ' Topic -> Topic -> Topic
forall a. Semigroup a => a -> a -> a
<> Topic
n
    notFound :: IO ()
notFound = Handle -> Topic -> IO ()
hPutStrLn Handle
stderr (Topic -> IO ()) -> Topic -> IO ()
forall a b. (a -> b) -> a -> b
$
      Topic
"\"" Topic -> Topic -> Topic
forall a. Semigroup a => a -> a -> a
<> Topic
topic Topic -> Topic -> Topic
forall a. Semigroup a => a -> a -> a
<> Topic
"\" does not match any manual section heading.\n"
      Topic -> Topic -> Topic
forall a. Semigroup a => a -> a -> a
<> Topic
"Run `hledger help manual` to list all topics, or `hledger help` for the quick reference."
    ambiguousHeading :: Topic
ambiguousHeading
      | Topic -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Topic
topic = Topic -> Topic
titleLine Topic
"HLEDGER MANUAL TOPICS"
      | Bool
otherwise  = Topic
"\"" Topic -> Topic -> Topic
forall a. Semigroup a => a -> a -> a
<> Topic
topic Topic -> Topic -> Topic
forall a. Semigroup a => a -> a -> a
<> Topic
"\" matches several manual sections, try a more specific topic:"
    matchingHeading :: Topic
matchingHeading
      | Topic -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Topic
topic = Topic -> Topic
titleLine Topic
"HLEDGER MANUAL TOPICS"
      | Bool
otherwise  = Topic
"manual topics matching \"" Topic -> Topic -> Topic
forall a. Semigroup a => a -> a -> a
<> Topic
topic Topic -> Topic -> Topic
forall a. Semigroup a => a -> a -> a
<> Topic
"\":"
    -- Show the given tool's manual, positioned at the given heading if any, in the best viewer.
    showManualAt :: Topic -> Maybe Topic -> IO ()
showManualAt Topic
tool Maybe Topic
mtopic' = do
      exes <- IO [Topic]
likelyExecutablesInPath
      pagerprog <- fromMaybe "less" <$> lookupEnv "PAGER"
      interactive <- hIsTerminalDevice stdout
      -- A dumb terminal (eg TERM=dumb, as in emacs shells) can't run info, and
      -- degrades man/less, so fall back to plain text there like the non-interactive case.
      dumbterminal <- ((== "dumb") . map toLower . fromMaybe "") <$> lookupEnv "TERM"
      -- Inside Emacs, only its terminal-emulator modes (term/ansi-term/vterm, whose
      -- INSIDE_EMACS mode contains "term") can render fullscreen viewers like info/man/less;
      -- other modes (shell/comint, eshell) are line-oriented and would garble them, so fall
      -- back to plain text there like the dumb/non-interactive case.
      emacsnonterm <- (\Topic
m -> Bool -> Bool
not (Topic -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Topic
m) Bool -> Bool -> Bool
&& Bool -> Bool
not (Topic
"term" Topic -> Topic -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` Topic
m)) . fromMaybe "" <$> lookupEnv "INSIDE_EMACS"
      let
        [info, man, pager, cat] =
          [runInfoForTopic, runManForTopic, runPagerForTopic, printHelpForTopic]
        web Topic
t Maybe Topic
mt = 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
$ Topic -> IO ExitCode
openBrowserOn (Topic -> IO ExitCode) -> Topic -> IO ExitCode
forall a b. (a -> b) -> a -> b
$ Topic -> Maybe Topic -> Topic
webManualUrl Topic
t Maybe Topic
mt
        viewer
          | Topic -> RawOpts -> Bool
boolopt Topic
"help-w" (RawOpts -> Bool) -> RawOpts -> Bool
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
opts = Topic -> Maybe Topic -> IO ()
web
          | Topic -> RawOpts -> Bool
boolopt Topic
"help-i" (RawOpts -> Bool) -> RawOpts -> Bool
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
opts = Topic -> Maybe Topic -> IO ()
info
          | Topic -> RawOpts -> Bool
boolopt Topic
"help-m" (RawOpts -> Bool) -> RawOpts -> Bool
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
opts = Topic -> Maybe Topic -> IO ()
man
          | Topic -> RawOpts -> Bool
boolopt Topic
"help-p" (RawOpts -> Bool) -> RawOpts -> Bool
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
opts = Topic -> Maybe Topic -> IO ()
pager
          | Bool -> Bool
not Bool
interactive Bool -> Bool -> Bool
|| Bool
dumbterminal Bool -> Bool -> Bool
|| Bool
emacsnonterm = Topic -> Maybe Topic -> IO ()
cat
          | Topic
"info"    Topic -> [Topic] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Topic]
exes            = Topic -> Maybe Topic -> IO ()
info
          | Topic
"man"     Topic -> [Topic] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Topic]
exes            = Topic -> Maybe Topic -> IO ()
man
          | Topic
pagerprog Topic -> [Topic] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Topic]
exes            = Topic -> Maybe Topic -> IO ()
pager
          | Topic
"less"    Topic -> [Topic] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Topic]
exes            = Topic -> Maybe Topic -> IO ()
pager
          | Bool
otherwise                        = Topic -> Maybe Topic -> IO ()
cat
      viewer tool mtopic'