Search code examples
filterluapandoc

Pandoc replace string with table using Lua filter


In my document I have a placeholder string like:

{{changelog}}

And would like to replace this with a Markdown formatted table using a Lua filter, the following Lua filter works if I use HTML:


local string = [[
| some | table |
|------|-------|
| val1 | val2  |
]]

string = [[
<table>
    <tr>
        <td>some</td>
        <td>table</td>
    </tr>
    <tr>
        <td>val1</td>
        <td>val2</td>
    </tr>
</table>
]]
function Para(elem)
    if elem.content[1].text == "{{changelog}}" then
        return pandoc.RawBlock('html', string)
      else
        return elem
      end
end

return {{ Para = Para }}

Now this works using the HTML content of variable string but how do I get it to work with Markdown formatted content in variable string.


Solution

  • To return an arbitrary format instead of HTML, we must instruct pandoc to parse the string with pandoc.read:

    function Para(elem)
      if elem.content[1].text == "{{changelog}}" then
        return pandoc.read(tblstring, 'html').blocks
      end
    end
    

    The pandoc.read function takes a string and parses it into a pandoc document, where the second argument is the format; we need to use access the documents blocks since we are not interested in the metadata.

    I've omitted the return elem, as pandoc keeps the original element if the function does not return a value.

    The alternative would be to construct the table using functions like pandoc.Table or pandoc.utils.from_simple_table, but that's usually more work.

    Also note that string is the global used for Lua's string library, so best to chose a different name for the table HTML.