diff --git a/margin-notes/margin-notes.lua b/margin-notes/margin-notes.lua index c7b639e..a880218 100644 --- a/margin-notes/margin-notes.lua +++ b/margin-notes/margin-notes.lua @@ -419,23 +419,35 @@ end local function template_to_function(template) --[[ - inlines_with_placeholders cannot be memoized - for it is a reference to a table that will be changed - by replace_placeholders. - paths_to_placeholders can be memoized - because it is only traversed once it has been created. + Returns a function that takes data and inserts it + into the given template. + ]]-- + --[[ + – inlines_with_placeholders and paths_to_placeholders + are created and memoized the first time the returned + function is called. + – inlines_with_placeholders cannot be used directly + for it is a reference to a table that would be changed + by replace_placeholders. That's why we create a deep + copy of it via the walk function at every call. + – paths_to_placeholders can be used directly by + replace_placeholders because it is only traversed. ]]-- if template then local paths_to_placeholders + local inlines_with_placeholders return function(instance_content, instance_attr) - local inlines_with_placeholders = template_to_pandoc_fragment(template) + if not inlines_with_placeholders then + inlines_with_placeholders = template_to_pandoc_fragment(template) + end + local inlines_copy = inlines_with_placeholders:walk({}) if not paths_to_placeholders then paths_to_placeholders = get_paths_to_placeholders(inlines_with_placeholders) end return replace_placeholders( - inlines_with_placeholders, paths_to_placeholders, + inlines_copy, paths_to_placeholders, instance_content, instance_attr) end end