For kicks, I would like to include the source code as an appendix. It's rather superfluous, yes, but it's puzzling.

I commonly have documents that are structured thusly:

includes: part_1.tex
          includes: subsection_a.tex
          includes: subsection_b.tex
          .... etc
includes: part_2.tex
.... etc ....
includes: appendix.tex

I'd like to programatically traverse my document (as a whole), and extract the source code for everything except code listings, then include this extracted source-code as a code listing in the appendix. Does anyone have an idea on where to start?

  • So, within (say) subsection_a.tex there is a (say) lstlistings environment that you want to exclude from the inclusion? Since it's close to Christmas, do you want cookies with that too? :) Okay, seriously, how about just attaching the source code to your output PDF rather than including it in a typeset form?
    – Werner
    Commented Dec 12, 2011 at 3:26
  • Attaching the code to the PDF: tex.stackexchange.com/questions/13187/…
    – Caramdir
    Commented Dec 12, 2011 at 3:38
  • I removed the thanks. This is just the style here, intended to keep the questions clear. The best way to thank people is to upvote the answers that are helpful to you.
    – qubyte
    Commented Dec 12, 2011 at 4:04
  • 2
    This is probably much simpler with tools externals to TeX. Consider using a few lines of shell, perl or python to do that instead; Commented Dec 12, 2011 at 6:46

1 Answer 1


You could use the DocStrip program to do this. That would still be an entirely TeXnical solution!

Split up your document as you've used to, however, instead of using \input use DocStrip to yank together all the files in the correct order. (Of course, you can still use \input to source out text that occurs at multiple places.)

DocStrip allows you to selectively include/exclude portions of code. For your listings, you could write

A common operating system is basically coded like this:
catch (Exception e)

Now, if you tell DocStrip to \generate{\file{doc.tex}{\from{doc.dtx{listings}}} it will write the complete code as shown above to doc.tex (assuming the sample is in the file doc.dtx of course). If the listings is omitted, everything between <*listings> and </listings> will be skipped. This way you can make DocStrip yank together two documents and then \lstinputlisting the latter at the end of the former.

I have made a simple demonstration basically featuring the structure of your post. I don't seem to be able to upload it here but you can get it from here.

Unfortunately, I couldn't find a solution for the cookies yet. Perhaps if someone else has an idea: please post it!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .