[Tex/LaTex] I’d like to include Markdown in a LaTeX file

includemarkdowntemplates

I have a LaTeX file, foo.tex and a bunch of markdown files {1..N}.markdown in the same directory. Basically, I'd like to be able to \include{1.markdown} and have the markdown rendered to LaTeX and included in foo.tex. How can I do this?

The closest I can come up with is pandoc which lets me define a template and variables at the command line. This can obviously work, but is cumbersome and annoying. Is there any better solution?

Best Answer

For ConTeXt, I have written a module, t-filter, that provides a nice user-interface for running external programs on a file. Using that module, you can write:

\usemodule[filter]

\defineexternalfilter
    [markdown]
    [filter={pandoc -t context -o \externalfilteroutputfile}]

after which you can use

 \processmarkdownfile{....}

to convert a markdown file to context and input the resulting back to tex. (The \defineexternalfilter command also creates an environment \startmarkdown ... \stopmarkdown. The module writes the contents of this environment to an external file, processes file through pandoc, and inputs the result.)

This is essentially a glorified wrapper around \write18. For a one-off task, you can use:

\newcommand\processmarkdownfile[1]
    {\immediate\write18{pandoc -t latex -o #1.tex #1}%
     \input{#1.tex}}

and then use \processmarkdownfile{...} to include a markdown file in LaTeX. You need to enable write18 for this to work. The easiest method is to pass -shell-escape to pdflatex:

pdflatex -shell-escape <filename>

The t-filter module provides other goodies as well (use an sub directory to store temp files, do not rerun the filter if the file has not changed, etc.). If you want, it is easy to add an interface for them in LaTeX as well.

Related Question