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?
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With