-
Notifications
You must be signed in to change notification settings - Fork 4
/
filter.hs
74 lines (63 loc) · 2.43 KB
/
filter.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
{- |
Pandoc filter for lightweight inline Haskell code blocks
-}
{-# LANGUAGE OverloadedStrings #-}
import Text.Pandoc.JSON
import Text.Pandoc.Walk
import Control.Monad
import Data.IORef
import Data.List (partition)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.Exit
import System.IO
import System.Process
collectCodeBlocks :: IORef [Text] -> Maybe Format -> Block -> IO [Block]
collectCodeBlocks blocks fmt (CodeBlock (ident, classes, attrs) code)
| fmt == Just (Format "revealjs") && "runhaskell" `elem` classes = do
let code' = T.pack code
(_,c2) = T.breakOn "\n---" code'
shownCode = if T.null c2 then code' else T.strip (T.drop 4 c2)
classes' = "haskell" : filter (/="runhaskell") classes
(attrs', runattrs) = partition ((`elem` ["width", "height"]) . fst) attrs
bs <- readIORef blocks
modifyIORef blocks (code':)
return [ CodeBlock (ident, classes', attrs') (T.unpack shownCode)
, Div (T.unpack $ divId (length bs + 1), ["runCode", "sourceCode"], runattrs) []
]
collectCodeBlocks _ _ b = return [b]
divId :: Int -> Text
divId n = T.pack ("runhaskell" ++ show n)
modName :: Int -> Text
modName n = T.pack ("M" ++ show n)
writeBlockModule :: Int -> Text -> IO ()
writeBlockModule n xs = do
tmpl <- T.readFile "module.hs.tmpl"
T.writeFile ("src/" ++ T.unpack mn ++ ".hs") $
T.replace "$modulename" mn (T.replace "$code" xs tmpl)
where
mn = modName n
writeMainModule :: Int -> IO ()
writeMainModule n = do
tmpl <- T.readFile "main.hs.tmpl"
T.writeFile "src/main.hs" $
T.replace "$imports" imports $ T.replace "$runinit" runinit tmpl
where
runinit = "runInit = " <> T.intercalate " >> " (map (\n -> modName n <> ".start \"" <> divId n <> "\"") [1..n])
imports = mconcat $ map (\n->"import qualified "<>modName n<>"\n") [1..n]
compileCode :: IO (ExitCode, String, String)
compileCode = readProcessWithExitCode "ghcjs" ["-O", "-isrc", "src/main.hs"] ""
main :: IO ()
main = do
r <- newIORef []
toJSONFilter (collectCodeBlocks r)
mods <- readIORef r
sequence_ (zipWith writeBlockModule [1..] (reverse mods))
writeMainModule (length mods)
(e, out, err) <- compileCode
when (e /= ExitSuccess) $ do
putStrLn out
hPutStrLn stderr err
exitWith e