I'm writing an algorithm with lstlisting

This is the output

enter image description here

And this is the code:

INPUT: Insieme $C$ di cubi che coprono una funzione $f$
OUTPUT: Insieme $D$ di cubi disgiunti che coprono $f$

$D = \emptyset$
while($C \neq \emptyset$):
    BUILD-SOP($C$, $P$) # crea SOP e la inserisce in $P$
    $A\ = \{d\in P\ |\ \forall c \in P \backslash \{d\} : d \cap c = \emptyset \}$
    $D = D \cup A$
    $P = P \backslash A$
    $B = \emptyset$
    while($P\neq \emptyset$):
        $p = P[0]$
        $P = P \backslash \{p\}$
        $D = D \cup \{p\}$
        forall $q \in P\ :\ p \cap q = \emptyset$:
            $P = P \backslash \{q\}$
        forall $r \in B\ :\ p \cap r \neq \emptyset$:
            $B = B \backslash \{r\}$
            $B = B \cup Q$
    $C = B$

\caption{Algoritmo DSOP}

How can I make the commands like "while","if" and "forall" in bold and the functions that are written in capital letters in a way that distinguishes them from the rest of the code?

  • This is not really a listing, it is pseudocode. There are various packages for pseudocode that highlight keywords such as forall and while, see for example algorithm2e or algorithmicx.
    – Marijn
    Sep 18, 2019 at 22:10

1 Answer 1


As mentioned in the comment, there are better alternatives for typesetting pseudo-code or algorithms. If you still want to stick to the listings package, you could use the following options for formatting:


alsoletter={-} makes listings treat the hyphen character as if it were a letter, so you can use it in keywords/identifiers more easily. Then the keywords option defines a set of special keywords (each set denoted by a number in square brackets), for which different styles can be assigned via the keywordstyle option. More fancy styles are possible; listings e.g. allows to give a separate style for all words/identifiers beside the defined keywords.

Finally, I suggest to use columns=flexible for listings with proportional fonts, as this makes identifiers have their natural width and so prevents bad innerword spacing.

The above setting applied to your example results in:

enter image description here

  • Where do I put the "\lstset" in order for it to affect just that block of code? Sep 19, 2019 at 15:08
  • 1
    @GerardoZinno \lstset sets the options globally. If you want it only for a certain listing, you can use the optional argument of \begin{lstlisting}[...]
    – siracusa
    Sep 19, 2019 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.