4

How can I use \textit in a listing?

\documentclass[a4paper]{article}

\begin{document}

\begin{lstlisting}[label=test]
Some code.
\textit{This should be italic.}
Some code.
\end{lstlisting}

\end{document}
3
  • Welcome to TeX.SX! Please help us to help you and add a minimal working example (MWE) that illustrates your problem. It will be much easier for us to reproduce your situation and find out what the issue is when we see compilable code, starting with \documentclass{...} and ending with \end{document}.
    – user31729
    May 30, 2014 at 18:24
  • Use the mathescape option, then inside your lstlisting you can use $\textit{Hello World.}$.
    – Werner
    May 30, 2014 at 18:44
  • 1
    Related/duplicate: Escaping in \lstinline (since it also applies to lstlisting); Using commands inside inline code
    – Werner
    May 30, 2014 at 18:47

1 Answer 1

7

You can emphasize words using the emph and emphstyle keys. See page 19 in the listings manual.

\documentclass[a4paper]{article}

\usepackage{listings}

\begin{document}

\lstset{emph={world}, emphstyle=\itshape} % the word "world" shall be italic
\begin{lstlisting}[label=test]
   Hello world
\end{lstlisting}

\end{document}

enter image description here

I agree, it is not a good solution for highlighting single lines of code. I think here is what you are looking for:

\documentclass[a4paper]{article}

\usepackage{listings}
\lstset{escapeinside={(*@}{@*)}}

\begin{document}

\begin{lstlisting}[label=test]
Some code.
(*@\textit{This should be italic.}@*)
Some code.
\end{lstlisting}

\end{document}

enter image description here

1
  • 1
    Hi, thanks :-). But I just want to have one sentence in italic. Rest should be normal. May 30, 2014 at 18:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .