lua和walk_block中的pandoc过滤器 [英] pandoc filter in lua and walk_block

查看:137
本文介绍了lua和walk_block中的pandoc过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试应用LUA筛选器,该筛选器只会更改文档的主体,而使元数据保持不变.而且这比我想的要难.

过滤器应在行内元素和块元素之前和之后添加文本.如果它适用于内联元素(此处为Code),则不适用于块元素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

我想念什么?干杯,

解决方案

这里的问题是walk_blockwalk_inline处理元素的 content ,而不是元素本身.

如果wrapper是您的过滤器表,则应执行您想要的操作:

function Pandoc (doc)
  local div = pandoc.Div(doc.blocks)
  local blocks = pandoc.walk_block(div, wrapper).content
  return pandoc.Pandoc(blocks, doc.meta)
end

另一种解决方案是保存和还原元数据,如下所示:

local meta = {}
return {
  { Meta = function(m) meta = m; return {} end },
  wrapper,
  { Meta = function(_) return meta; end },
}

这可能更有效,因为仅对元数据和Code/CodeBlock元素进行序列化/反序列化可能比对整个文档进行序列化更快.

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,

解决方案

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.

这篇关于lua和walk_block中的pandoc过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆