module Text.Pandoc.Lua (LuaException (..), pushPandocModule, runLuaFilter) where
import Control.Monad (when, (>=>))
import Control.Monad.Identity (Identity)
import Control.Monad.Trans (MonadIO (..))
import Data.IORef (IORef, newIORef, readIORef)
import Foreign.Lua (FromLuaStack (peek), Lua, LuaException (..),
Status (OK), ToLuaStack (push))
import Text.Pandoc.Class (CommonState, PandocIO, getCommonState, getMediaBag,
setMediaBag)
import Text.Pandoc.Definition
import Text.Pandoc.Lua.PandocModule (pushMediaBagModule, pushPandocModule)
import Text.Pandoc.Lua.Filter (LuaFilter, walkMWithLuaFilter)
import Text.Pandoc.MediaBag (MediaBag)
import qualified Foreign.Lua as Lua
runLuaFilter :: Maybe FilePath -> FilePath -> String
-> Pandoc -> PandocIO (Either LuaException Pandoc)
runLuaFilter datadir filterPath format pd = do
commonState <- getCommonState
mediaBag <- getMediaBag
mediaBagRef <- liftIO (newIORef mediaBag)
res <- liftIO . Lua.runLuaEither $
runLuaFilter' commonState datadir filterPath format mediaBagRef pd
newMediaBag <- liftIO (readIORef mediaBagRef)
setMediaBag newMediaBag
return res
runLuaFilter' :: CommonState
-> Maybe FilePath -> FilePath -> String -> IORef MediaBag
-> Pandoc -> Lua Pandoc
runLuaFilter' commonState datadir filterPath format mbRef pd = do
Lua.openlibs
pushPandocModule datadir
Lua.setglobal "pandoc"
addMediaBagModule
registerFormat
top <- Lua.gettop
stat <- Lua.dofile filterPath
if stat /= OK
then do
luaErrMsg <- peek (1) <* Lua.pop 1
Lua.throwLuaError luaErrMsg
else do
newtop <- Lua.gettop
when (newtop top < 1) pushGlobalFilter
luaFilters <- peek (1)
runAll luaFilters pd
where
addMediaBagModule = do
Lua.getglobal "pandoc"
push "mediabag"
pushMediaBagModule commonState mbRef
Lua.rawset (3)
registerFormat = do
push format
Lua.setglobal "FORMAT"
pushGlobalFilter :: Lua ()
pushGlobalFilter = do
Lua.newtable
Lua.getglobal' "pandoc.global_filter"
Lua.call 0 1
Lua.rawseti (2) 1
runAll :: [LuaFilter] -> Pandoc -> Lua Pandoc
runAll = foldr ((>=>) . walkMWithLuaFilter) return
instance (FromLuaStack a) => FromLuaStack (Identity a) where
peek = fmap return . peek