add a lua version

This commit is contained in:
2025-10-09 19:51:29 +08:00
parent a6dc981e6b
commit a0aa9e611b
4 changed files with 37 additions and 14 deletions

View File

@@ -6,15 +6,14 @@ import qualified Data.Text as T
file2Block :: FilePath -> IO [Block]
file2Block f = do
contents <- TIO.readFile f
return [Plain [Str contents]]
contents <- TIO.readFile f
return [Plain [Str contents]]
doInclude :: Block -> IO Block
doInclude cb@(Div (id, classes, namevals) contents) =
case lookup (T.pack "include") namevals of
Just f -> Div (id, classes, namevals) <$>
file2Block (T.unpack f)
Nothing -> return cb
case lookup (T.pack "include") namevals of
Just f -> Div (id, classes, namevals) <$> file2Block (T.unpack f)
Nothing -> return cb
doInclude x = return x
main :: IO ()

20
filter.lua Normal file
View File

@@ -0,0 +1,20 @@
function File2Block(filename)
local fh = io.open(filename, "r")
if not fh then
io.stderr:write("Cannot open file: " .. filename .. "\n")
return { pandoc.Plain { pandoc.Str("[Error: cannot read file " .. filename .. "]") } }
end
local contents = fh:read("*a")
fh:close()
return { pandoc.Plain { pandoc.Str(contents) } }
end
function Div(e)
local include = e.attributes["include"]
if include then
local blocks = File2Block(include)
-- Replace the Div contents
return pandoc.Div(blocks, e.attr)
end
return nil -- no change
end

View File

@@ -4,8 +4,11 @@
nofilter:
pandoc -fmarkdown -thtml input.md > output.html
filter:
hs:
pandoc -fmarkdown -thtml input.md --filter ./filter.hs > output.html
lua:
pandoc -fmarkdown -thtml input.md --lua-filter ./filter.lua > output.html
showAST:
pandoc -fmarkdown -tnative input.md

View File

@@ -1,5 +1,6 @@
<p>Heres the pandoc README:</p>
<div class="sourceCode" id="cb1" data-include="filter.hs"><pre
<div class="sourceCode" id="cb1" data-include="filter.hs"
style="background-color: red"><pre
class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="dt">Foo</span><span class="ot">::</span> <span class="dt">Div</span> <span class="ot">-&gt;</span> <span class="dt">Div</span></span></code></pre></div>
<div data-include="filter.hs">
#!/usr/bin/env runhaskell
@@ -10,15 +11,15 @@ import qualified Data.Text as T
file2Block :: FilePath -&gt; IO [Block]
file2Block f = do
contents &lt;- TIO.readFile f
return [Plain [Str contents]]
contents &lt;- TIO.readFile f
return [Plain [Str contents]]
doInclude :: Block -&gt; IO Block
doInclude cb@(Div (id, classes, namevals) contents) =
case lookup (T.pack "include") namevals of
Just f -&gt; Div (id, classes, namevals) &lt;$&gt;
file2Block (T.unpack f)
Nothing -&gt; return cb
case lookup (T.pack "include") namevals of
Just f -&gt; Div (id, classes, namevals) &lt;$&gt; file2Block
(T.unpack f)
Nothing -&gt; return cb
doInclude x = return x
main :: IO ()