简体   繁体   中英

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. 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). How can I convert the text property into content suitable for LineBlock ?

This is how my code looks 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.

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. This list of blocks is an acceptable return value of the CodeBlock function.

To convert the text into a LineBlock, we could modify it such that it becomes a line block in Markdown syntax. Then we can read the resulting text as Markdown using pandoc.read .

Line blocks in pandoc Markdown (and reStructuredText) have a pipe character at the start of each line. 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.

This is the full filter:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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