{-# LANGUAGE OverloadedStrings #-}
module Text.Pandoc.CrossRef.Util.Template
( Template
, makeTemplate
, applyTemplate
, applyTemplate'
) where
import Text.Pandoc.Definition
import Text.Pandoc.Builder
import Text.Pandoc.Generic
import qualified Data.Map as M hiding (toList, fromList, singleton)
import Text.Pandoc.CrossRef.Util.Meta
import Control.Applicative
import Text.Read
import qualified Data.Text as T
type VarFunc = T.Text -> Maybe MetaValue
newtype Template = Template (VarFunc -> [Inline])
makeTemplate :: Meta -> [Inline] -> Template
makeTemplate dtv xs' = Template $ \vf -> scan (\var -> vf var <|> lookupMeta var dtv) xs'
where
scan = bottomUp . go
go vf (x@(Math DisplayMath var):xs)
| (vn, idxBr) <- T.span (/='[') var
, not (T.null idxBr)
, T.last idxBr == ']'
= let idxVar = T.drop 1 $ T.takeWhile (/=']') idxBr
idx = readMaybe . T.unpack . toString ("index variable " <> idxVar) =<< vf idxVar
arr = do
i <- idx
v <- lookupMeta vn dtv
getList i v
in toList $ fromList (replaceVar var arr [x]) <> fromList xs
| otherwise = toList $ fromList (replaceVar var (vf var) [x]) <> fromList xs
go _ (x:xs) = toList $ singleton x <> fromList xs
go _ [] = []
replaceVar var val def' = maybe def' (toInlines ("variable " <> var)) val
applyTemplate' :: M.Map T.Text [Inline] -> Template -> [Inline]
applyTemplate' vars (Template g) = g internalVars
where
internalVars x | Just v <- M.lookup x vars = Just $ MetaInlines v
internalVars _ = Nothing
applyTemplate :: [Inline] -> [Inline] -> Template -> [Inline]
applyTemplate i t =
applyTemplate' (M.fromDistinctAscList [("i", i), ("t", t)])