Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I emphasize parts of an lstlisting?

Tags:

latex

listings

How can I set certain parts of an lstlisting in boldface?

\begin{lstlisting}[escapechar=@]
fun(foo, bar, @\textbf{baz}@ );
\end{lstlisting}

This compiles, but baz isn't set in boldface :( What am I missing?

like image 283
fredoverflow Avatar asked Apr 24 '10 10:04

fredoverflow


3 Answers

Your basic approach should be to tell listing what words to emphasise. A straightforward way to do this is like this:

\lstset{emph={baz},emphstyle=\textbf}

Of course, that will emphasise baz whenever it occurs. But this is a better approach than trying to put the markup into your listing itself, you don't (ought to) want to do that since you (ought to) want to use listings to format an unmodified piece of code. Especially so if you are including source files rather than typing code snippets.

Once you've got the basics under your belt look at the documentation, to learn how to set styles for keywords and for identifiers, and how to modify the inbuilt list(s) of keywords for your languages of choice.

like image 101
High Performance Mark Avatar answered Nov 03 '22 10:11

High Performance Mark


Your solution is correct. However, the standard LaTeX monospaced font does not have a boldface version, so \textbf doesn’t do anything within the lstlisting environment. According to macfreek.nl, you can do the following to redeclare the boldface version:

\DeclareFontShape{OT1}{cmtt}{bx}{n}{<5><6><7><8><9><10><10.95><12><14.4><17.28><20.74><24.88>cmttb10}{}

I’ve tested the following example and it works as you desire:

\documentclass{article}
\usepackage{listings}
\DeclareFontShape{OT1}{cmtt}{bx}{n}{<5><6><7><8><9><10><10.95><12><14.4><17.28><20.74><24.88>cmttb10}{}
\lstset{language=C, basicstyle=\ttfamily}
\begin{document}

\begin{lstlisting}[escapechar=@]
fun(foo, bar, @\textbf{baz}@ );
\end{lstlisting}

\end{document}

I use the same technique with \color{red} instead of \textbf to hint the audience of a beamer presentation at the difference between two almost identical code listings.

like image 45
Lumen Avatar answered Nov 03 '22 09:11

Lumen


I found an answer under http://www.mrunix.de/forums/archive/index.php/t-42976.html

\lstset{moredelim=[is][\bfseries]{[*}{*]}}
\begin{lstlisting}
bla bla bla
blupp
[*wichtiger hervorzuhebender text*]
weiter im text
\end{lstlisting}
like image 5
velop Avatar answered Nov 03 '22 08:11

velop