Export code samples AND display verbatim

Export code samples AND display verbatim

I'd like to write a LaTeX document with code samples in a verbatim environment. I'd also like to export those code samples to named files so that they can be built and run. This allows me to easily run tests on my code samples to make sure my document doesn't contain buggy code. So I'd like to write LaTeX like this

\begin{code}[test1.hs]
main = do
    print "Hello, world!"
\end{code}

and have that code sample appear both in my document verbatim and, as a side effect, in the file test1.hs.

Unfortunately, my attempts to write LaTeX to both display code verbatim and output code to a file have ended up with me tying myself in knots. Is there an easy way to do this?

답변1

A possible solution with tcolorbox.

Of course, you can customize the box as you like, also without the frame.

\documentclass{book}
\usepackage{tcolorbox}
\tcbuselibrary{breakable,listings}
\newtcbinputlisting{\mylisting}[2][]{%
    listing file={#2},
    title=Listing of \texttt{#2},
    colframe=red,fonttitle=\bfseries,
    listing only,breakable, #1}

\begin{document}
This creates a file \texttt{test1.hs}:

\begin{tcbverbatimwrite}{test1.hs}
main = do
    print "Hello, world!"
\end{tcbverbatimwrite}

And this use it:

\mylisting{test1.hs}
\end{document}

enter image description here

관련 정보