git.iko.soy/typeable/pandoc
on bfbc5ee help sign in
85 lines 2.9 kB history raw
1{-# LANGUAGE NoImplicitPrelude #-}
2{-
3Copyright © 2017–2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
5This program is free software; you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation; either version 2 of the License, or
8(at your option) any later version.
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13GNU General Public License for more details.
15You should have received a copy of the GNU General Public License
16along with this program; if not, write to the Free Software
17Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18-}
19{- |
20 Module : Text.Pandoc.Lua
21 Copyright : Copyright © 2017–2018 Albert Krewinkel
22 License : GNU GPL, version 2 or above
24 Maintainer : Albert Krewinkel <tarleb+pandoc@moltkeplatz.de>
25 Stability : alpha
27Running pandoc Lua filters.
28-}
29module Text.Pandoc.Lua
30 ( LuaException (..)
31 , runLuaFilter
32 , runPandocLua
33 ) where
35import Prelude
36import Control.Monad ((>=>))
37import Foreign.Lua (FromLuaStack (peek), Lua, LuaException (..),
38 Status (OK), ToLuaStack (push))
39import Text.Pandoc.Class (PandocIO)
40import Text.Pandoc.Definition (Pandoc)
41import Text.Pandoc.Lua.Filter (LuaFilter, walkMWithLuaFilter)
42import Text.Pandoc.Lua.Init (runPandocLua, registerScriptPath)
43import Text.Pandoc.Lua.Util (popValue)
44import Text.Pandoc.Options (ReaderOptions)
45import qualified Foreign.Lua as Lua
47-- | Run the Lua filter in @filterPath@ for a transformation to target
48-- format @format@. Pandoc uses Lua init files to setup the Lua
49-- interpreter.
50runLuaFilter :: ReaderOptions -> FilePath -> String
51 -> Pandoc -> PandocIO (Either LuaException Pandoc)
52runLuaFilter ropts filterPath format doc =
53 runPandocLua (runLuaFilter' ropts filterPath format doc)
55runLuaFilter' :: ReaderOptions -> FilePath -> String
56 -> Pandoc -> Lua Pandoc
57runLuaFilter' ropts filterPath format pd = do
58 registerFormat
59 registerReaderOptions
60 registerScriptPath filterPath
61 top <- Lua.gettop
62 stat <- Lua.dofile filterPath
63 if stat /= OK
64 then do
65 luaErrMsg <- popValue
66 Lua.throwLuaError luaErrMsg
67 else do
68 newtop <- Lua.gettop
69 -- Use the returned filters, or the implicitly defined global filter if
70 -- nothing was returned.
71 luaFilters <- if newtop - top >= 1
72 then peek (-1)
73 else Lua.getglobal "_G" *> fmap (:[]) popValue
74 runAll luaFilters pd
75 where
76 registerFormat = do
77 push format
78 Lua.setglobal "FORMAT"
80 registerReaderOptions = do
81 push ropts
82 Lua.setglobal "PANDOC_READER_OPTIONS"
84runAll :: [LuaFilter] -> Pandoc -> Lua Pandoc
85runAll = foldr ((>=>) . walkMWithLuaFilter) return