module Text.Pandoc.Lua
( LuaException (..)
, runLuaFilter
, runPandocLua
) where
import Control.Monad ((>=>))
import Foreign.Lua (FromLuaStack (peek), Lua, LuaException (..),
Status (OK), ToLuaStack (push))
import Text.Pandoc.Class (PandocIO)
import Text.Pandoc.Definition (Pandoc)
import Text.Pandoc.Lua.Filter (LuaFilter, walkMWithLuaFilter)
import Text.Pandoc.Lua.Init (runPandocLua)
import Text.Pandoc.Lua.Util (popValue)
import Text.Pandoc.Options (ReaderOptions)
import qualified Foreign.Lua as Lua
runLuaFilter :: ReaderOptions -> FilePath -> String
-> Pandoc -> PandocIO (Either LuaException Pandoc)
runLuaFilter ropts filterPath format doc =
runPandocLua (runLuaFilter' ropts filterPath format doc)
runLuaFilter' :: ReaderOptions -> FilePath -> String
-> Pandoc -> Lua Pandoc
runLuaFilter' ropts filterPath format pd = do
registerFormat
registerReaderOptions
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
luaFilters <- if (newtop top >= 1)
then peek (1)
else Lua.getglobal "_G" *> fmap (:[]) popValue
runAll luaFilters pd
where
registerFormat = do
push format
Lua.setglobal "FORMAT"
registerReaderOptions = do
push ropts
Lua.setglobal "PANDOC_READER_OPTIONS"
runAll :: [LuaFilter] -> Pandoc -> Lua Pandoc
runAll = foldr ((>=>) . walkMWithLuaFilter) return