pandoc filter in lua and walk_block

风流意气都作罢 提交于 2020-01-24 15:35:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!