{-# LANGUAGE NoImplicitPrelude #-}
module Text.Pandoc.Lua
( LuaException (..)
, runLuaFilter
, runPandocLua
) where
import Prelude
import Control.Monad ((>=>))
import Foreign.Lua (Lua)
import Text.Pandoc.Class (PandocIO)
import Text.Pandoc.Definition (Pandoc)
import Text.Pandoc.Lua.Filter (LuaFilter, walkMWithLuaFilter)
import Text.Pandoc.Lua.Init (LuaException (..), runPandocLua, registerScriptPath)
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
registerScriptPath filterPath
top <- Lua.gettop
stat <- Lua.dofile filterPath
if stat /= Lua.OK
then Lua.throwTopMessage
else do
newtop <- Lua.gettop
luaFilters <- if newtop - top >= 1
then Lua.peek Lua.stackTop
else Lua.pushglobaltable *> fmap (:[]) Lua.popValue
runAll luaFilters pd
where
registerFormat = do
Lua.push format
Lua.setglobal "FORMAT"
registerReaderOptions = do
Lua.push ropts
Lua.setglobal "PANDOC_READER_OPTIONS"
runAll :: [LuaFilter] -> Pandoc -> Lua Pandoc
runAll = foldr ((>=>) . walkMWithLuaFilter) return