[英]How pandoc lua filters can be used to add the title as the level-1 header?
当我将多个markdown文件从markdown转换为pdf时,我想使用pandoc lua过滤器。 我希望将单个降价文件的标题用作章节(第一级标题)。
我了解了现有示例,并且我认为这很接近我的需要-基本上我需要将pandoc.Header(1,doc.meta.title)添加到我的所有markdown文件中,但是我正在努力编写lua过滤并使其正常工作。
我认为这个问题正在lua和walk_block中执行类似的动作pandoc过滤器
pandoc命令:
pandoc -N --lua-filter add-title.lua blog/*.md --pdf-engine=xelatex --toc -s -o my_book.pdf
add-title.lua(这是错误的,没有异常,但输出没有任何反应):
function add_header (header)
return {
{Header = pandoc.Header(1, meta.title)}}
end
输入文件:
1.md
---
title: Topic1
---
## Sample Header from file 1.md
text text text
2.md
---
title: Topic2
---
## Sample Header from file 2.md
text text text
预期输出等于此降价促销(但我的最终格式为pdf)
---
title: Title from pandoc latex variable
---
# Topic1
## Sample Header from file 1.md
text text text
# Topic2
## Sample Header from file 2.md
text text text
我认为关键问题在于lua过滤器仅在将全部文档解析为单个AST后才运行。 因此,在解析之前可以有效地连接各个文件,以创建具有单组元数据的单个文档。 过滤器有机会运行之前,将覆盖yaml元数据块中的各个title
设置。 假设您需要从每个单独的元数据块中获取标题(并且不能仅将标题直接放入),这意味着您不能让pandoc加入文件。 您将需要分别阅读和解析每个文件。 幸运的是,使用过滤器很容易。
第一步是制作一个包含所有其他文件链接的参考文件。
---
title: Combined title
---
![First file](1.md){.markdown}
![Second file](2.md){.markdown}
请注意,链接是使用带有特殊类.markdown
图像指定的。 您可以使用其他方法,但是图像很方便,因为它们支持属性并且易于识别。
现在,我们只需要一个过滤器即可将这些图像替换为链接的markdown文件中的已解析元素。 为此,我们可以打开lua中的文件,然后使用pandoc.read
其解析为完整的文档(请参阅https://www.pandoc.org/lua-filters.html#module-pandoc )。 获得文档后,我们可以从元数据中读取标题并插入新的标题。 请注意,我们将滤镜应用于Para
元素,而不是Image
本身。 这是因为pandoc将Block
元素与Inline
元素分开,并且过滤器的返回值必须为相同类型。 Image
过滤器不能返回从文件中解析出的块列表,但是Para
可以。
所以这是结果代码。
function Para(elem)
if #elem.content == 1 and elem.content[1].t == "Image" then
local img = elem.content[1]
if img.classes:find('markdown',1) then
local f = io.open(img.src, 'r')
local doc = pandoc.read(f:read('*a'))
f:close()
-- now we need to create a header from the metadata
local title=pandoc.utils.stringify(doc.meta.title) or "Title has not been set"
local newHeader=pandoc.Header(1, {pandoc.Str(title)})
table.insert(doc.blocks, 1, newHeader)
return doc.blocks
end
end
end
如果您使用
pandoc -f markdown -t markdown -i combined.md -s --lua-filter addtitle.lua
你会得到
---
title: Combined title
---
Topic 1
=======
Sample Header from file 1.md
----------------------------
text text text
Topic 2
=======
Sample Header from file 2.md
----------------------------
text text text
按要求。
请注意,包含文件中的任何其他Yaml元数据都将丢失。 您可以通过从单个meta
对象中获取其他任何内容并将其放入全局对象中来捕获其他任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.