2

I would like to use simple example environment with listing package for printing C-code snippets, like this

\begin{example}
   \lstinputlisting[caption=Hello.c]{../C/hello.c}
\end{example}

This works well with the exception of the selected font. I use

  \lstset{basicstyle=footnotesize\ttfamily}.

but, as you can see on the figure below, which does not match with selected shape. It seems that font shape selected for example environment has higher priority. How can I properly set font shape for code snippet in the example environment, that match with \lstset command.

enter image description here

Note: I use czech language: Příklad = Example

MNWE

\documentclass[12pt,a4paper]{scrbook}
\usepackage{amsthm}
\usepackage{xltxtra}
\usepackage{listings}
\newtheorem{example}{Příklad}

\begin{document}

\lstset{ %
  language=C,                            % choose the language of the code
  basicstyle=\footnotesize\ttfamily,     % the size of the fonts that are used for the code
}

    \begin{example} 
      text text text 
      \begin{lstlisting}
        #include <stdio.h>

        int main(void)
        {
         int c;

         while ((c = getchar()) != EOF)
           putchar(c);
         return 0;
        }
      \end{lstlisting}

    \end{example}


    \end{document}
1
+50

The example environment from the amsthm package typesets the contents in italics. Internally, this is probably be done by calling \itshape at the beginning of the example. Now, when you create your listing, the style options \footnotesize\ttfamily are added, but the \itshape is still "active". For example:

\documentclass{article}
\begin{document}
    test \itshape test \ttfamily test \upshape test
\end{document}

resulting output of example

The same happens in your example: The surrounding text is in \itshape, thus adding \ttfamily creates text in your italic typewriter font. To get upright typewriter font, you have to add \upshape to your listings style, as demonstrated in the example above.

Thus, your MWE becomes

\documentclass[12pt,a4paper]{scrbook}
\usepackage{amsthm}
\usepackage{xltxtra}
\usepackage{listings}
\newtheorem{example}{Příklad}

\begin{document}

\lstset{ %
  language=C,                                    % choose the language of the code
  basicstyle=\footnotesize\upshape\ttfamily,     % the size of the fonts that are used for the code
}

    \begin{example} 
      text text text
      \begin{lstlisting}
#include <stdio.h>

int main(void)
{
  int c;

  while ((c = getchar()) != EOF)
    putchar(c);
    return 0;
  }
      \end{lstlisting}
      text text text
    \end{example}
\end{document}

and results in a listing as you would expect, with an upright typewriter font:

result for the op's complete example

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.