Home > Enterprise >  Pandoc lua filter to move image caption at the end of the document
Pandoc lua filter to move image caption at the end of the document

Time:03-01

I'm totally new to Lua pandoc filter so this problem is over my level.

Starting from a markdown document, I want to collect all figures in the manuscript, remove the latex call to display them, capture their captions and display them in a block at the end called Figures.

For example, figures are rendered in the intermediate .tex as:

\begin{figure}
  \includegraphics[width=1\linewidth]{figure1} \caption{Figure 1. Caption.}\label{fig:figure1}
\end{figure}

I want to remove the afore mentioned block, take the caption and move it in the (existing) Figure section with this structure:

\section*{Figures}
  \begin{figure}[h!]
    \caption{Figure 1. Caption.}
  \end{figure}

  \begin{figure}[h!]
    \caption{Figure 2. Caption.}
  \end{figure}

I want to stress that the figures should not be shown anymore in the final document. This structure is required by the journal I'm sending the .tex to, which require the pictures to be loaded separately and just keep a reference to them in the manuscript.

I tried some Lua coding with no luck. But then I discovered that lua was not seeing at all my images.

I put this into the .md file:

\begin{figure}
  \includegraphics[width=1\linewidth]{figure1} \caption{Figure 1. Caption.}\label{fig:figure1}
\end{figure}

and then trying to check how it was seen by Lua with:

function Para (el) print(pandoc.utils.stringify(el)) end

But no reference to the image was printed (the other elements were printed, as a test). I tried substituting Para for Str, Inline, Image, Pandoc but nothing.

So I am not even able to catch the figure in the AST...

CodePudding user response:

The problem with putting raw LaTeX into your R Markdown input is that it will not be processed by pandoc, but is passed through verbatim. That can be very useful, but in this case it limits the usefulness of Lua filters. However, the \begin{figure}...\end{figure} code becomes a "raw block" in pandoc, and can still be accessed from Lua filters via RawBlock. You might be able to collect the captions with code similar to this:

local captions = pandoc.List()

function RawBlock (raw)
  local caption = raw.text:match('\\caption%{(.*)%}')
  if caption then
    captions:insert(caption)
  end
end

function Pandoc (doc)
  -- append collected captions at the end
  doc.blocks:insert(captions:map(function(x) return pandoc.Para(x) end))
  return doc
end

Or to put all figures into a metadata field:

function Pandoc (doc)
  doc.meta.figures = captions:map(function (c)
      return pandoc.RawBlock('latex', c)
  end)
  return doc
end

CodePudding user response:

Instead of actually moving the figures, you can just tell latex to show the captions at the end:

\usepackage{figcaps}
  • Related