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

main = do
    print "Hello, world!"

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?

  • 3
    just write to a file using filecontents or similar, then you can \input and \verbatiminput the file to show it in both forms (or simpler actually write the examples in separate files to start with) – David Carlisle Feb 18 '18 at 20:38
  • That doesn't seem to help. LaTeX like this fails in pretty much the same way as my attempts to use a verbatim environment \newenvironment{code}{ \begin{filecontents}{test.cpp} } { \end{filecontents} \VerbatimInput{test.cpp} } – user207442 Feb 18 '18 at 21:51
  • 1
    you can not use verbatim commands in another enviornment, you can use a custom verbatim definition or simply use filecontents followed by verbatim input – David Carlisle Feb 18 '18 at 21:53

A possible solution with tcolorbox.

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

    listing file={#2},
    title=Listing of \texttt{#2},
    listing only,breakable, #1}

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

main = do
    print "Hello, world!"

And this use it:


enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.