@@ -23,24 +23,23 @@ module Text.Pandoc.Lua.PandocLua
2323 , runPandocLua
2424 , liftPandocLua
2525 , addFunction
26− , loadScriptFromDataDir
26+ , loadDefaultModule
2727 ) where
2828
29−import Control.Monad (when)
3029import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
3130import Control.Monad.Except (MonadError (catchError, throwError))
3231import Control.Monad.IO.Class (MonadIO (liftIO))
3332import Foreign.Lua (Lua (..), NumResults, Pushable, ToHaskellFunction)
3433import Text.Pandoc.Class.PandocIO (PandocIO)
35−import Text.Pandoc.Class.PandocMonad (PandocMonad (..), readDataFile)
36−import Text.Pandoc.Error (PandocError)
34+import Text.Pandoc.Class.PandocMonad (PandocMonad (..), readDefaultDataFile)
35+import Text.Pandoc.Error (PandocError (PandocLuaError))
3736import Text.Pandoc.Lua.Global (Global (..), setGlobals)
3837import Text.Pandoc.Lua.ErrorConversion (errorConversion)
3938
4039import qualified Control.Monad.Catch as Catch
40+import qualified Data.Text as T
4141import qualified Foreign.Lua as Lua
4242import qualified Text.Pandoc.Class.IO as IO
43−import qualified Text.Pandoc.Lua.Util as LuaUtil
4443
4544-- | Type providing access to both, pandoc and Lua operations.
4645newtype PandocLua a = PandocLua { unPandocLua :: Lua a }
@@ -86,14 +85,22 @@ addFunction name fn = liftPandocLua $ do
8685 Lua.pushHaskellFunction fn
8786 Lua.rawset (-3)
8887
89−-- | Load a file from pandoc's data directory.
90−loadScriptFromDataDir :: FilePath -> PandocLua ()
91−loadScriptFromDataDir scriptFile = do
92− script <- readDataFile scriptFile
88+-- | Load a pure Lua module included with pandoc. Leaves the result on
89+-- the stack and returns @NumResults 1@.
90+--
91+-- The script is loaded from the default data directory. We do not load
92+-- from data directories supplied via command line, as this could cause
93+-- scripts to be executed even though they had not been passed explicitly.
94+loadDefaultModule :: String -> PandocLua NumResults
95+loadDefaultModule name = do
96+ script <- readDefaultDataFile (name <> ".lua")
9397 status <- liftPandocLua $ Lua.dostring script
94− when (status /= Lua.OK) . liftPandocLua $
95− LuaUtil.throwTopMessageAsError'
96− (("Couldn't load '" ++ scriptFile ++ "'.\n") ++)
98+ if status == Lua.OK
99+ then return (1 :: NumResults)
100+ else do
101+ msg <- liftPandocLua Lua.popValue
102+ let err = "Error while loading `" <> name <> "`.\n" <> msg
103+ throwError $ PandocLuaError (T.pack err)
97104
98105-- | Global variables which should always be set.
99106defaultGlobals :: PandocIO [Global]