module Anansi.Pandoc
( loomPandoc
, looms
) where
import Control.Monad.Reader (asks)
import Control.Monad.Writer (tell)
import qualified Data.Map
import Data.Text (Text, pack, unpack)
import Data.Text.Encoding (encodeUtf8)
import Anansi hiding (looms)
import Text.Pandoc hiding (readers, writers)
import qualified Text.Pandoc as Pandoc
looms :: Data.Map.Map Text Loom
looms = Data.Map.fromList
[ ("anansi-pandoc.pandoc", loomPandoc Pandoc.readers Pandoc.writers)
]
loomPandoc :: [(String, ParserState -> String -> Pandoc)]
-> [(String, WriterOptions -> Pandoc -> String)]
-> Loom
loomPandoc readers writers doc = do
let readerName = case Data.Map.lookup "anansi-pandoc.reader" (documentOptions doc) of
Nothing -> "html"
Just x -> unpack x
let writerName = case Data.Map.lookup "anansi-pandoc.writer" (documentOptions doc) of
Nothing -> "html"
Just x -> unpack x
let reader = case lookup readerName readers of
Just x -> x
Nothing -> error ("Unknown Pandoc reader " ++ show readerName)
let codeWriter = case lookup readerName writers of
Just x -> x
Nothing -> error ("Unknown Pandoc writer " ++ show readerName)
let outputWriter = case lookup writerName writers of
Just x -> x
Nothing -> error ("Unknown Pandoc writer " ++ show writerName)
let stringContents = concatMap (stringifyBlock codeWriter) (documentBlocks doc)
let pandoc = reader defaultParserState stringContents
let outputOptions = defaultWriterOptions
{ writerStandalone = False
}
tell (encodeUtf8 (pack (outputWriter outputOptions pandoc)))
tell "\n"
stringifyBlock :: (WriterOptions -> Pandoc -> String) -> Anansi.Block -> String
stringifyBlock writer block = case block of
BlockText text -> unpack text
BlockFile path content -> writer defaultWriterOptions (Pandoc (Meta [] [] []) [
BlockQuote [Para [Strong [Str "\xBB", Space, Str (unpack path)]], pandocContent content]
])
BlockDefine name content -> writer defaultWriterOptions (Pandoc (Meta [] [] []) [
BlockQuote [Para [Strong [Str "\xAB", Space, Str (unpack name), Str "\xBB"]], pandocContent content]
])
pandocContent :: [Content] -> Pandoc.Block
pandocContent = CodeBlock nullAttr . concatMap strContent where
strContent (ContentText _ text) = unpack text ++ "\n"
strContent (ContentMacro _ indent name) = unpack indent ++ unpack name ++ "\n"