@@ -29,22 +29,51 @@ module Text.Pandoc.Lua.Module.Utils
2929 ( pushModule
3030 ) where
3131
32−import Data.Digest.Pure.SHA (sha1, showDigest)
33−import Foreign.Lua (Lua, NumResults)
32+import Control.Applicative ((<|>))
33+import Foreign.Lua (FromLuaStack, Lua, NumResults)
34+import Text.Pandoc.Definition (Pandoc, Meta, Block, Inline)
3435import Text.Pandoc.Lua.StackInstances ()
3536import Text.Pandoc.Lua.Util (addFunction)
3637
38+import qualified Data.Digest.Pure.SHA as SHA
3739import qualified Data.ByteString.Lazy as BSL
3840import qualified Foreign.Lua as Lua
41+import qualified Text.Pandoc.Shared as Shared
3942
4043-- | Push the "pandoc.utils" module to the lua stack.
4144pushModule :: Lua NumResults
4245pushModule = do
4346 Lua.newtable
44− addFunction "sha1" sha1HashFn
47+ addFunction "sha1" sha1
48+ addFunction "stringify" stringify
4549 return 1
4650
4751-- | Calculate the hash of the given contents.
48−sha1HashFn :: BSL.ByteString
49− -> Lua String
50−sha1HashFn = return . showDigest . sha1
52+sha1 :: BSL.ByteString
53+ -> Lua String
54+sha1 = return . SHA.showDigest . SHA.sha1
55+
56+stringify :: AstElement -> Lua String
57+stringify el = return $ case el of
58+ PandocElement pd -> Shared.stringify pd
59+ InlineElement i -> Shared.stringify i
60+ BlockElement b -> Shared.stringify b
61+ MetaElement m -> Shared.stringify m
62+
63+data AstElement
64+ = PandocElement Pandoc
65+ | MetaElement Meta
66+ | BlockElement Block
67+ | InlineElement Inline
68+ deriving (Show)
69+
70+instance FromLuaStack AstElement where
71+ peek idx = do
72+ res <- Lua.tryLua $ (PandocElement <$> Lua.peek idx)
73+ <|> (InlineElement <$> Lua.peek idx)
74+ <|> (BlockElement <$> Lua.peek idx)
75+ <|> (MetaElement <$> Lua.peek idx)
76+ case res of
77+ Right x -> return x
78+ Left _ -> Lua.throwLuaError
79+ "Expected an AST element, but could not parse value as such."