Merge in manual TOC entries in a LuaLaTeX document

I am working on a document generation infrastructure with LuaLaTeX and a Lua package. One part of the process is including an externally generated multipage PDF which includes multiple sections. My question is how to merge the TOC entries for that included PDF with the regular ones created through the main document's sectioning commands.

The included document is a multi-movement music score created with LilyPond. LilyPond has been made to export a .toc file including page numbers and movement titles as a string list (the page numbers are already correct since LilyPond is passed the starting page number from the main document).

One way I could approach this is to

• read the (LilyPond) .toc file (using Lua)
• parse the page numbers
• insert the document with multiple \includepdf commands with the determined page ranges
• manually write \section entries in between

But actually I'd prefer to be able to include the PDF in one piece and “inject” the TOC entries manually.

Say I have a Lua table

toc_entries = {
["7"] = "First movement",
["13"] = "Second movement",
["25"] = "Third movement"
}


Is it possible from there to inject corresponding entries (assuming all are on the same, predefined, sectioning level) into a TOC that is already populated by regular sectioning entries?

Something like \includepdfs addtotoc but with the option to specify multiple entries. (It would be easy to have LilyPond export the TOC entries in the format expected by addtotoc.)

• ... or something like \addcontentsline but with the option to also pass a page number. – uli_1973 Apr 24 '18 at 9:33
• I do not think there is any need for Lua here and you can directly include the LilyPond .toc file if it has a compatible format. Can you add a MWE? – Marcel Krüger Apr 24 '18 at 10:46
• I can make the .toc file any format necessary (by default it has the format for \includepdf's addtotoc option). How can I then "merge" the LilyPond .toc file with the one produced by LaTeX? – uli_1973 Apr 24 '18 at 19:16

\includepdfs addtotoc already suppports multiple entries:

\documentclass{article}
\usepackage{pdfpages,catchfile}
\newcommand\includelilypond[1]{%
\begingroup
\CatchFileDef\currentlilypondtoc{#1.toc}{}
\expandafter\endgroup\x
}
\begin{document}
\tableofcontents
\includelilypond{test}
\end{document}