[Tex/LaTex] Using bold/italic text inside listings

bolditaliclistings

How can I use bold text inside a code listing? I wanted to make some parts of the code bold.

Best Answer

As per Mico's answer, there is no boldfaced monospaced font in the Computer Modern font family, so you need to use a font that has bold monospaced font. Below is an example using listings that make the keywords bold using the pxfonts. Here is a comparison of the results without and with the \usepackage{pxfonts}:

enter image description here enter image description here

\documentclass[border=2pt]{standalone}
\usepackage{listings}
\usepackage{pxfonts}

\lstset{language=C,
    basicstyle=\ttfamily,
    keywordstyle=\bfseries,
    showstringspaces=false,
    morekeywords={include, printf}
}

\begin{document}
\begin{lstlisting}
    /* Prints Hello World */

    #include <stdio.h>
    
    int main(void) {
       printf("Hello World!");
       return 0;
    }
\end{lstlisting}
\end{document}

Alternate Solution:

You could also use the the courier font form ttfamily with bfseries or how to enable bold in fixed width font:

enter image description here

\documentclass[border=2pt]{standalone}
\usepackage{listings}

\lstset{language=C,
    basicstyle=\ttfamily,
    keywordstyle=\bfseries,
    showstringspaces=false,
    morekeywords={include, printf}
}

\begin{document}
\begin{lstlisting}
    /* Prints Hello World */

    #include <stdio.h>
    
    int main(void) {
       printf("Hello World!");
       return 0;
    }
\end{lstlisting}

\hrule
\renewcommand{\ttdefault}{pcr}
\begin{lstlisting}
    /* Prints Hello World */

    #include <stdio.h>
    
    int main(void) {
       printf("Hello World!");
       return 0;
    }
\end{lstlisting}
\end{document}