![](/img/trans.png)
[英]How to convert CodeBlock into LineBlock in Pandoc lua filter
[英]How to refactor repeating code in Pandoc lua filter
我正在为 Pandoc 编写一个 Lua 过滤器,专门针对 Pandoc 生成的 LaTeX 文档。
这是我的过滤器中的一小段代码:
LATEX_CODES_FOR_TAGS = {
Span = {
sans = '\\sffamily ',
serif = '\\rmfamily ',
},
Div = {
-- Font Styles
sans = '\\begin{sffamily}',
serif = '\\begin{rmfamily}',
}
}
function Span(span)
for tag, code_for_class in pairs(LATEX_CODES_FOR_TAGS) do
for class, code in pairs(code_for_class) do
if tag == "Span" then
if span.classes:includes(class) then
table.insert(span.content, 1, pandoc.RawInline('latex', code))
end
end
end
end
return span
end
function Div(div)
for tag, code_for_class in pairs(LATEX_CODES_FOR_TAGS) do
for class, code in pairs(code_for_class) do
if tag == "Div" then
if div.classes:includes(class) then
local code_end = code:gsub('begin', 'end')
table.insert(div.content, 1, pandoc.RawBlock('latex', code))
table.insert(div.content, pandoc.RawBlock('latex', code_end))
end
end
end
end
return div
end
如您所见, Div()
和Span()
函数的代码几乎完全相同,因此需要重构代码。
迄今为止,我一直无法想出一种无需重复代码即可制作过滤器的解决方案。
我对 Lua 还是很陌生,并且对这些概念很感兴趣。
提前致谢。
将循环体定义为单独的 function:
local function create_handler(tag_str, handler_func)
return
function (obj)
for tag, code_for_class in pairs(LATEX_CODES_FOR_TAGS) do
for class, code in pairs(code_for_class) do
if tag == tag_str then
if obj.classes:includes(class) then
handler_func(obj, code)
end
end
end
end
return obj
end
end
Span = create_handler("Span",
function(span, code)
table.insert(span.content, 1, pandoc.RawInline('latex', code))
end)
Div = create_handler("Div",
function(div, code)
local code_end = code:gsub('begin', 'end')
table.insert(div.content, 1, pandoc.RawBlock('latex', code))
table.insert(div.content, pandoc.RawBlock('latex', code_end))
end)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.