在Pandoc lua过滤器中连接字符串片段

问题描述 投票:2回答:1

我正在尝试创建一个pandoc过滤器,它将帮助我汇总数据。我见过一些创建目录的过滤器,但我想根据标题中的内容组织索引。

例如,下面我想根据标题中的标记日期提供内容摘要(某些标题不包含日期......)

[nwatkins@sapporo foo]$ cat test.md
# 1 May 2018
some info

# not a date
some data

# 2 May 2018
some more info

我开始尝试查看标题的内容。目的是为不同的日期/时间模式应用一个简单的正则表达式。

[nwatkins@sapporo foo]$ cat test.lua
function Header(el)
  return pandoc.walk_block(el, {
    Str = function(el)
      print(el.text)
    end })
end

不幸的是,这似乎为每个以空格分隔的字符串应用了打印状态,而不是允许我分析整个标题内容的串联:

[nwatkins@sapporo foo]$ pandoc --lua-filter test.lua test.md
1
May
2018
not
...

在过滤器中有这样的规范方法吗?我还没有在Lua过滤器文档中看到任何帮助函数。

lua pandoc
1个回答
3
投票

更新:开发版现在提供新功能pandoc.utils.stringifypandoc.utils.normalize_date。它们将成为下一个pandoc发布的一部分(可能是2.0.6)。使用这些,您可以测试标头是否包含具有以下代码的日期:

function Header (el)
  content_str = pandoc.utils.stringify(el.content)
  if pandoc.utils.normalize_date(content_str) ~= nil then
    print 'header contains a date'
  else
    print 'not a date'
  end
end

目前还没有辅助功能,但我们计划在不久的将来提供pandoc.utils.tostring功能。

在此期间,以下代码片段(取自this discussion)应该可以帮助您获得所需内容:

--- convert a list of Inline elements to a string.
function inlines_tostring (inlines)
  local strs = {}
  for i = 1, #inlines do
    strs[i] = tostring(inlines[i])
  end
  return table.concat(strs)
end

-- Add a `__tostring` method to all Inline elements. Linebreaks
-- are converted to spaces.
for k, v in pairs(pandoc.Inline.constructor) do
  v.__tostring = function (inln)
    return ((inln.content and inlines_tostring(inln.content))
        or (inln.caption and inlines_tostring(inln.caption))
        or (inln.text and inln.text)
        or " ")
  end
end

function Header (el)
  header_text = inlines_tostring(el.content)
end 
© www.soinside.com 2019 - 2024. All rights reserved.