# Highlight commands inside lstlisting algorithm

I'm writing an algorithm with lstlisting

This is the output

And this is the code:

\begin{figure}
\begin{lstlisting}[mathescape=true]
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$
WEIGHT($P$)
SORP($P$)
$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\}$
BREAK($q$,$p$,$Q$)
OPT($q$,$Q$,$P$,$B$)
forall $r \in B\ :\ p \cap r \neq \emptyset$:
$B = B \backslash \{r\}$
BREAK($r$,$p$,$Q$)
$B = B \cup Q$
$C = B$

\end{lstlisting}
\caption{Algoritmo DSOP}
\end{figure}


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?

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:

\lstset{
alsoletter={-},
keywords=[1]{while,if,forall},
keywords=[2]{BUILD-SOP,WEIGHT,SORP,BREAK, OPT},
keywordstyle=[1]{\bfseries},
keywordstyle=[2]{\slshape},
columns=flexible
}


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:

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