10

I'm usinglistingspackage to put a python code inside an article. I want it to be written in \ttfamily. The problem is I can't change keywordstyle to bold text.

\documentclass{article}
\usepackage{listings}

\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}

\begin{document}
\begin{lstlisting}[language=Python]
if x==0:
    print(x)
\end{lstlisting}
\end{document}

Any help please ? Thanks !

5

You need a font that has a bold version of the typewriter family. If you look in the .log file you will find:

LaTeX Font Info:    Font shape `OT1/cmtt/bx/n' in size <10> not available
(Font)              Font shape `OT1/cmtt/m/n' tried instead on input line 9.

A recent new choice of typewriter font with a bold version is provided by the newtxttt package:

Sample output

\documentclass{article}

\usepackage{listings,newtxtt}

\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}

\begin{document}
\begin{lstlisting}[language=Python]
if x==0:
    print(x)
\end{lstlisting}
\end{document}

An alternative is the zlmtt package:

zlmtt sample

which fits better with the standard computer modern fonts of LaTeX.

If you do not wish to change fonts in this way and just want to use the ordinary bold font, then you should switch to \rmfamily before selecting \bfseries:

Computer modern bf sample

\documentclass{article}

\usepackage{listings}

\lstset{basicstyle=\ttfamily, keywordstyle=\rmfamily\bfseries}

\begin{document}
\begin{lstlisting}[language=Python]
if x==0:
    print(x)
\end{lstlisting}
\end{document}
| improve this answer | |
5

You can use lmodern with the lighttt option.

\documentclass{article}
\usepackage[lighttt]{lmodern}
\usepackage{listings}

\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}

\begin{document}

\begin{lstlisting}[language=Python]
if x==0:
    print(x)
\end{lstlisting}

\end{document}

enter image description here

Without the lighttt option:

enter image description here

Latin Modern fonts are mostly equivalent to Computer Modern. However, the boldface version of Latin Modern Mono is not so distinct from the medium font, so the lighttt option uses a light series instead of medium.

You can also use any other mono font, maybe scaling it to fit the text font, for instance FiraMono:

\documentclass{article}

\usepackage[scaled=0.85]{FiraMono}
\usepackage{listings}

\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}

\begin{document}

Abc\texttt{Abc}

\begin{lstlisting}[language=Python]
if x==0:
    print(x)
\end{lstlisting}

\end{document}

enter image description here

| improve this answer | |

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.