问题
I'm trying to apply a LUA filter that would only alter the body of a document, leaving the Metadata untouched. And it's harder than I thought.
The filter should prepend and append text to inline elements as well as block elements. If it works for the inline element, here Code
, it fails for the block element CodeBlock
.
function Pandoc(doc)
blocks = {}
for k,block in pairs(doc.blocks) do
table.insert(blocks, pandoc.walk_block(block, {
-- Doesn't work!?
CodeBlock = function(el)
return {
pandoc.Para({pandoc.Str("Before")}),
el,
pandoc.Para({pandoc.Str("After")})}
end,
-- Works!
Code = function(el)
return {pandoc.Str("Before"), el, pandoc.Str("After")}
end,
}))
end
return pandoc.Pandoc(blocks, doc.meta)
end
What am I missing? Cheers,
回答1:
The issue here is that walk_block
and walk_inline
process the content of an element, not the element itself.
If wrapper
is your filter table, this should do what you want:
function Pandoc (doc)
local div = pandoc.Div(doc.blocks)
local blocks = pandoc.walk_block(div, wrapper).content
return pandoc.Pandoc(blocks, doc.meta)
end
An alternative solution would be to save and restore the metadata, like so:
local meta = {}
return {
{ Meta = function(m) meta = m; return {} end },
wrapper,
{ Meta = function(_) return meta; end },
}
This is probably more efficient, as serializing/deserializing only metadata and Code/CodeBlock elements is likely faster than doing the same for the full document.
来源:https://stackoverflow.com/questions/47350104/pandoc-filter-in-lua-and-walk-block