Something I forgot to mention earlier: I have a nice Python script that will take all of the source code files in a directory and generate the LaTeX to form an appendix to a document out of them, with labels and everything. I’d love to see a similar script for Word, but I don’t think I will any time soon.
For those who are interested, here it is:
import getopt;
import glob;
import os;
import re;
import sys;
usage = "Usage: convert.py -p path -e extension -o output_filename
";
extension = "";
outputFileName = "";
path = "";
try:
opts, args = getopt.getopt(sys.argv[1:], "e:o:p:");
for opt, arg in opts:
if opt == "-e":
extension = arg;
elif opt == "-o":
outputFileName = arg;
elif opt == "-p":
path = arg;
except getopt.GetoptError:
print usage;
exit(0);
if extension == "" or outputFileName == "" or path == "":
print usage;
exit(0);
outputFile = None;
try:
outputFile = open(outputFileName, "w");
except IOError, (errno, strerror):
print "I/O error(%s) attempting to open %s: %s" % (errno, outputFileName, strerror);
exit(0);
fileNameParts = outputFileName.split(".");
sectionName = fileNameParts[0];
for i in range(1, len(fileNameParts) - 1):
sectionName = sectionName + "_" + fileNameParts*;
outputFile.write("\\section{" + sectionName + "}
");
outputFile.write("\\label{sec_" + sectionName + "}
");
outputFile.write("
");
path = os.getcwd() + "/" + path.replace("\\", "/") + "/";
searchPath = os.path.join(path, "*." + extension);
for inputFileName in glob.glob(searchPath):
inputFile = None;
try:
inputFile = open(inputFileName, "r");
except IOError, (errno, strerror):
print "I/O error(%s) attempting to open %s: %s" % (errno, inputFileName, strerror);
continue;
localNames = re.compile("\/").split(inputFileName);
name = localNames[len(localNames) - 1];
outputFile.write("\\paragraph{" + name.replace('_', '\\_') + "}
");
functionName = re.compile("\." + extension).split(name)[0];
outputFile.write("\\label{" + sectionName + "_" + functionName + "}
");
outputFile.write("\\begin{verbatim}
");
for line in inputFile:
if len(line) <= 80:
outputFile.write(line);
else:
while len(line) > 80:
outputFile.write(line[0:80] + "
");
line = line[80:len(line)];
outputFile.write(line);
outputFile.write("\\end{verbatim}
");
outputFile.write("
");
inputFile.close();
outputFile.close();
The only thing that needs work is that it doesn’t indent properly when it has to split a line of code, but that seems like a hard problem in general, so I usually just do that part by hand.