如何编写Lua过滤器合并Pandoc的相邻多个引用?
Pandoc Lua Filter to Merge Adjacent Citations
To merge adjacent citation elements like [@anand2011]; [@bachman1996] into a single grouped citation [@anand2011; @bachman1996], you can use a Lua filter that traverses Pandoc's Abstract Syntax Tree (AST) to identify and combine consecutive citation nodes.
Filter Code
Save the following code as merge-citations.lua:
local function is_separator(inline) -- Check if inline is semicolon plus optional whitespace if inline.t == 'Str' and inline.text == ';' then return true elseif inline.t == 'Space' or inline.t == 'SoftBreak' or inline.t == 'LineBreak' then return true end return false end function Para(para) local new_inlines = {} local current_cites = {} local skip_separators = false for i, inline in ipairs(para.content) do if inline.t == 'Cite' then -- Add citations from current Cite element to the group for _, cit in ipairs(inline.citations) do table.insert(current_cites, cit) end skip_separators = true -- Next separators are part of the citation group elseif skip_separators and is_separator(inline) then -- Ignore separators between citations goto continue else -- If we have a group of citations, create a new Cite element if #current_cites > 0 then -- Create a single Cite element with merged citations local merged_cite = pandoc.Cite(current_cites, {pandoc.Str('')}) table.insert(new_inlines, merged_cite) current_cites = {} skip_separators = false end -- Add non-citation/non-separator element table.insert(new_inlines, inline) end ::continue:: end -- Add any remaining citations at the end of the paragraph if #current_cites > 0 then local merged_cite = pandoc.Cite(current_cites, {pandoc.Str('')}) table.insert(new_inlines, merged_cite) end return pandoc.Para(new_inlines) end return { {Para = Para} }
Key Functionality
- Separator Detection: The
is_separatorfunction identifies semicolons and whitespace (spaces, line breaks) that separate citations. - Citation Grouping: As we iterate through paragraph elements, we collect consecutive
Citenodes, ignoring any separating semicolons or whitespace. - Merge and Replace: Once we encounter a non-citation/non-separator element, we merge the collected citations into a single
Citeelement and add it to the output. Any remaining citations at the end of the paragraph are also merged.
Usage
Run Pandoc with the filter applied:
pandoc your-document.md --lua-filter=merge-citations.lua -o formatted-document.md
Example
Input
For example, see [@anand2011]; [@bachman1996]; [@clark2000]
Output
For example, see [@anand2011; @bachman1996; @clark2000]
内容的提问来源于stack exchange,提问作者TomBen
相关产品推荐
相关产品推荐

