简体   繁体   English

如何在 Pandoc lua 过滤器中将 CodeBlock 转换为 LineBlock

[英]How to convert CodeBlock into LineBlock in Pandoc lua filter

I'd like to convert a CodeBlock into a LineBlock in a Pandoc Lua filter.我想在 Pandoc Lua 过滤器CodeBlock转换为LineBlock The problem with that conversion is that the CodeBlock element has a text property (a string), but the LineBlock expects inline content elements (each word, space, newline etc. its own element).这种转换的问题在于CodeBlock元素有一个text属性(一个字符串),但LineBlock需要内联内容元素(每个单词、空格、换行符等,它自己的元素)。 How can I convert the text property into content suitable for LineBlock ?如何将text属性转换为适合LineBlock内容?

This is how my code looks ATM:这是我的代码在 ATM 上的样子:

function CodeBlock(el)
    -- test for manually generating content
    -- return pandoc.LineBlock {{pandoc.Str("Some")}, {pandoc.Space()}, {pandoc.Str("content")}}

    -- using read does not work, how can I convert the string el.text?
    local contentElements = pandoc.read(el.text)
    return pandoc.LineBlock(contentElements)
end

I'm assuming the text in the code block is formatted in Markdown, as that's the most frequently used input format for pandoc.我假设代码块中的文本采用 Markdown 格式,因为这是 pandoc 最常用的输入格式。

Your approach is good, there just seems to be some lack of clarity about the different types: pandoc.read takes a string, as in el.text , and returns a Pandoc object, which has a list of Block values in its blocks field.您的方法很好,只是似乎对不同类型缺乏明确性: pandoc.read接受一个字符串,如el.text ,并返回一个Pandoc对象,该对象在其blocks字段中有一个Block值列表。 This list of blocks is an acceptable return value of the CodeBlock function.此块列表是 CodeBlock 函数可接受的返回值。

To convert the text into a LineBlock, we could modify it such that it becomes a line block in Markdown syntax.要将文本转换为 LineBlock,我们可以修改它,使其成为 Markdown 语法中的行块。 Then we can read the resulting text as Markdown using pandoc.read .然后我们可以使用pandoc.read将结果文本读取为 Markdown。

Line blocks in pandoc Markdown (and reStructuredText) have a pipe character at the start of each line. pandoc Markdown(和 reStructuredText)中的行块在每行的开头都有一个管道字符。 So we must add |所以我们必须加上| after each newline character and also prepend it that to the first line.在每个换行符之后,并将其添加到第一行。

We can pass the result into pandoc.read , then return the resulting blocks, which should really be just a single LineBlock in our case.我们可以将结果传递给pandoc.read ,然后返回结果块​​,在我们的例子中它应该只是一个 LineBlock。

This is the full filter:这是完整的过滤器:

function CodeBlock (el)
  return pandoc.read('| ' .. el.text:gsub('\n', '\n| '), 'markdown').blocks
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM