{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE IncoherentInstances  #-}
{-# LANGUAGE OverloadedStrings    #-}
{-# LANGUAGE ScopedTypeVariables  #-}
{- |
Module      : Text.Pandoc.Lua.Filter
Copyright   : © 2012-2022 John MacFarlane,
              © 2017-2022 Albert Krewinkel
License     : GNU GPL, version 2 or above
Maintainer  : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
Stability   : alpha

Types and functions for running Lua filters.
-}
module Text.Pandoc.Lua.Filter
  ( runFilterFile
  ) where
import Control.Monad ((>=>), (<$!>))
import HsLua as Lua
import Text.Pandoc.Definition
import Text.Pandoc.Error (PandocError)
import Text.Pandoc.Lua.ErrorConversion ()
import Text.Pandoc.Lua.Marshal.AST
import Text.Pandoc.Lua.Marshal.Filter


-- | Transform document using the filter defined in the given file.
runFilterFile :: FilePath -> Pandoc -> LuaE PandocError Pandoc
runFilterFile :: FilePath -> Pandoc -> LuaE PandocError Pandoc
runFilterFile FilePath
filterPath Pandoc
doc = do
  StackIndex
oldtop <- forall e. LuaE e StackIndex
gettop
  Status
stat <- forall e. FilePath -> LuaE e Status
dofileTrace FilePath
filterPath
  if Status
stat forall a. Eq a => a -> a -> Bool
/= Status
Lua.OK
    then forall e a. LuaError e => LuaE e a
throwErrorAsException
    else do
      StackIndex
newtop <- forall e. LuaE e StackIndex
gettop
      -- Use the returned filters, or the implicitly defined global
      -- filter if nothing was returned.
      [Filter]
luaFilters <- forall e a. LuaError e => Peek e a -> LuaE e a
forcePeek forall a b. (a -> b) -> a -> b
$
        if StackIndex
newtop forall a. Num a => a -> a -> a
- StackIndex
oldtop forall a. Ord a => a -> a -> Bool
>= StackIndex
1
        then forall a e. LuaError e => Peeker e a -> Peeker e [a]
peekList forall e. LuaError e => Peeker e Filter
peekFilter StackIndex
top
        else (forall a. a -> [a] -> [a]
:[]) forall (m :: * -> *) a b. Monad m => (a -> b) -> m a -> m b
<$!> (forall e a. LuaE e a -> Peek e a
liftLua forall e. LuaE e ()
pushglobaltable forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> forall e. LuaError e => Peeker e Filter
peekFilter StackIndex
top)
      forall e. StackIndex -> LuaE e ()
settop StackIndex
oldtop
      [Filter] -> Pandoc -> LuaE PandocError Pandoc
runAll [Filter]
luaFilters Pandoc
doc

runAll :: [Filter] -> Pandoc -> LuaE PandocError Pandoc
runAll :: [Filter] -> Pandoc -> LuaE PandocError Pandoc
runAll = forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (forall (m :: * -> *) a b c.
Monad m =>
(a -> m b) -> (b -> m c) -> a -> m c
(>=>) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e. LuaError e => Filter -> Pandoc -> LuaE e Pandoc
applyFully) forall (m :: * -> *) a. Monad m => a -> m a
return