[英]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.