Source code
When you’re explaining an algorithm or a complex workflow, using source code or pseudocode can be exceptionally effective.
LaTeX offers the listings
environment, which accommodates syntax highlighting for various programming languages, as well as for custom-defined and -styled languages.
For instance, Listing 1 showcases a “Hello World” example in Java, while Listing 3 presents the equivalent in pseudocode.
Notably, “Pseudo” is a custom language defined in template/custom_listings.sty
.
Show the code
\begin{listingsbox}[t]
\lstinputlisting[
language=Java,
label=lst:sample-java,
caption={Hello World in Java}
]{listings/HelloWorld.java}
\end{listingsbox}
Listings side by side
The listingsbox
environment automatically manages the spacing around your code block.
If you need to display two listings adjacent to each other, utilize the sublistingsbox
environment.
Unlike figures and subfigures, when using sublistingsboxes
, you do not need to provide separate captions and labels for each listingsbox
.
Show the code
\begin{listingsbox}[t]
\begin{sublistingsbox}
\lstinputlisting[
language=Java,
label=lst:sample-java,
caption={Hello World in Java}
]{listings/HelloWorld.java}
\end{sublistingsbox}
\hfill
\begin{sublistingsbox}
\lstinputlisting[
language=pseudo,
label=lst:sample-pseudo,
caption={Hello World in Pseudo}
]{listings/HelloWorld.pseudo}
\end{sublistingsbox}
\end{listingsbox}
Labels
You should discuss the code within your text, even if the code appears self-explanatory.
Make use of labels to refer to specific code lines. For Example:
Line 3 in Listing 1 and line 2 in Listing 2 highlight critical sections of the code.
To achieve this, enclose the \label
command within the language-specific escape characters (e.g., $|$
for Java and §
for Pseudo).
HelloWorld.java
public class HelloWorld {
public static void main (String[] args) {
System.out.println("Hello World!"); |\label{line:sample-java-print}|
// and some other stuff
for (int i = 0; i < 6; i++)
foo(i);
}
}
HelloWorld.pseudo
define HelloWorld():
print "Hello World!" §\label{line:sample-pseudo-print}§
// and some other stuff
for i in [0,6]:
foo(i)