[Tex/LaTex] How to do literate programming in TeX

literate-programming

How can I do literate programming in TeX where TeX, or some variant, is both the used programming language and what is used for typesetting the document? Is there more than one way to do it or different approaches for different TeX variants? I would appreciate some examples.

Best Answer

Given that the question is on how to do literate programming for TeX code then one answer as already mentioned in the comment by David is using doc or xdoc package for documentation and docstrip.tex for generating for generating runable code.

The doc/docstrip combination is not the best possible way to do things (there are better approaches that could be imagined), but it offers one immense advantage, which probably explains why a large proportion of packages these days are documented in this manner:

  • It doesn't require any additional program at the user end and therefore works whereever a TeX system of any flavor is implemented.
  • It also provides the possibility to generate variants of your code from the same sources, e.g., a production version and a version with additional tracing code.

On the downside

  • It requires the code to be structured sequencially (at least unless you want to work artificially with a number of output files).
  • It has some somewhat strange conventions (as I see it these days, even if I'm the one put them in). One is that the documentation is hidden behind % signs. The initial reasoning was that you could use such a file directly as code without any processing (the docstrip program was added later.
  • Another one is that the code has to be surrounded by

    %    \begin{macrocode}
     ... code ...
    %    \end{macrocode}
    

    where the last line has to be %followed by exactly 4 spaces followed by \end{macrocode}.

However, it served fairly well as it seems. Documentation is found as part of the LaTeX distribution.

For documentation look at doc.pdf and docstrip.pdf in the LaTeX distribution and for examples of use take a look at any .dtx file in a TeX installation.

Related Question