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

Noa*_*ins 3 lua pandoc

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

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

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

# not a date
some data

# 2 May 2018
some more info
Run Code Online (Sandbox Code Playgroud)

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

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

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

[nwatkins@sapporo foo]$ pandoc --lua-filter test.lua test.md
1
May
2018
not
...
Run Code Online (Sandbox Code Playgroud)

在过滤器中是否有规范的方法来做到这一点?我还没有在 Lua 过滤器文档中看到任何辅助函数。

tar*_*leb 6

更新:开发版现在提供了新功能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
Run Code Online (Sandbox Code Playgroud)

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

同时,以下片段(取自本讨论)应该可以帮助您获得所需的内容:

--- 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 
Run Code Online (Sandbox Code Playgroud)