diff --git a/_extensions/diagram/diagram.lua b/_extensions/diagram/diagram.lua index 37f4a62..8cbfd07 100644 --- a/_extensions/diagram/diagram.lua +++ b/_extensions/diagram/diagram.lua @@ -291,6 +291,75 @@ local cetz = { end, } +--- LaTeX template used to compile forest syntax trees. +--- We provide the \begin{forest} item, too, so that only the [] syntax is needed. +local forest_template = pandoc.template.compile [[ +\documentclass{standalone} +\usepackage[linguistics]{forest} +$for(header-includes)$ +$it$ +$endfor$ +$additional-packages$ +\begin{document} +\begin{forest} +$body$ +\end{forest} +\end{document} +]] + +--- The forest engine is adopted from the TikZ template. +local forest = { + line_comment_start = '%%', + + mime_types = { + ['application/pdf'] = true, + }, + + --- Compile LaTeX with forest syntax trees to an image + compile = function (self, src, user_opts) + return with_temporary_directory("forest", function (tmpdir) + return with_working_directory(tmpdir, function () + -- Define file names: + local file_template = "%s/forest-image.%s" + local forest_file = file_template:format(tmpdir, "tex") + local pdf_file = file_template:format(tmpdir, "pdf") + + -- Treat string values as raw LaTeX + local meta = { + ['header-includes'] = user_opts['header-includes'], + ['additional-packages'] = {pandoc.RawInline( + 'latex', + stringify(user_opts['additional-packages'] or '') + )}, + } + local tex_code = pandoc.write( + pandoc.Pandoc({pandoc.RawBlock('latex', src)}, meta), + 'latex', + {template = forest_template} + ) + write_file(forest_file, tex_code) + + -- Execute the LaTeX compiler: + local success, result = pcall( + pipe, + self.execpath or 'pdflatex', + { '-interaction=nonstopmode', '-output-directory', tmpdir, forest_file }, + '' + ) + if not success then + warn(string.format( + "The call\n%s\nfailed with error code %s. Output:\n%s", + result.command, + result.error_code, + result.output + )) + end + return read_file(pdf_file), 'application/pdf' + end) + end) + end +} + local default_engines = { asymptote = asymptote, dot = graphviz, @@ -298,6 +367,7 @@ local default_engines = { plantuml = plantuml, tikz = tikz, cetz = cetz, + forest = forest, } --