I often have to print Source Code, but quite often only some parts of a project. Now I got a task to improve two functions and I have to print out what I change. I use minted for printing source code.
How can I tell minted to print only a given function?
Something like:
\inputminted[functions=helloWorld,functions=abc,
fontsize=\footnotesize, tabsize=4]{c}{/home/moose/Desktop/RO/blatt02.c}
If this is not possible, I'd also accept if I could tell minted to print some given lines, e.g.:
\inputminted[from=12, to=50,
fontsize=\footnotesize, tabsize=4]{c}{/home/moose/Desktop/RO/blatt02.c}
This would not be as good as the functions, but it would be ok.
Best Answer
I did, egreg! I did it by myself! Best day ever! Well, technically it's night. Anyway.
:)
May Konrad Rudolph have mercy on me.
:)
The following code is a dirty, dirty hack. But we do love dirty code, don't we?First things first. This trick relies on the powerful
awk
. We can print ranges from a document by using the format'NR==x,NR==y'
, wherex
means "the current line is thex
th line" andy
means "the current line is they
th line". Soawk
will print the interval between them.We can pipe the
awk
output topygmentize
, which is used byminted
. Then I added two options tominted
:linestart
: the first line to be printed.lineend
: the last line to be printed.First, let's consider the following
helloworld.c
sample code (lines added for our convenience):Now the
.tex
code:After running it (of course, with
--shell-escape
enabled), this is our output:There we go,
minted
with line ranges.:)
Edit: Back to the crafting table.
:)
My good friend Marco Daniel pointed out an out-of-the-box solution which is way more appropriate for this case: using
firstline
andlastline
options fromfancyvrb/minted
themselves. It does exactly what I did in the previous attempt, but without all the dangerous bends I went through:And we shall obtain the very same result.
:)
Edit: For the sake of completeness, I decided to try again and print the function scope based on its full qualified name. Here it goes.
:)
The following
awk
code is taken from How to extract a C function definition from a C source file. According to the author, "the following assumes balanced braces, and that the closing}
for a function is the last character in its line." I modified it slightly in order to set the function name. The original code had the function to extract hardcoded.I saved it as
extract.awk
and put it in the same directory of my.tex
file. It would be wiser to create an alias or even a shell script to wrap the call to this code and export it to the path. I'm taking the easier route, for obvious reasons.:)
Lets use another
helloworld.c
:Now, our
.tex
code:Our new output:
As Konrad mentioned in the comments, this trick is not portable, since it works only with a few range of languages and it relies on certain code standards. Nonetheless, it's a neat feature.
:)