Text FormattingHighlighting a Chunk of Code within a lstlisting

Information and discussion about LaTeX's general text formatting features (e.g. bold, italic, enumerations, ...)
Post Reply
gadgetto
Posts: 11
Joined: Wed Oct 24, 2012 8:28 am

Highlighting a Chunk of Code within a lstlisting

Post by gadgetto »

Hi everyone,

I have got some lines of code inserted by lstlisting:

Code: Select all

\begin{lstlisting}
public class MyRunnable implements Runnable{
	String name;
	public MyRunnable(String name){
		this.name = name;
	}
\end{lstlisting}
Now I want to hightlight for example >>class MyRunnable<<. An easy way is to use colorbox:

Code: Select all

\begin{lstlisting}
public §\colorbox{yellow}{class MyRunnable}§ implements Runnable{
	String name;
	public MyRunnable(String name){
		this.name = name;
	}
\end{lstlisting}
It works fine, but you are losing the syntax highlighting inside a colorbox.

Is there a way to save the syntax highlighting???
I tested to insert a "\lstinline" in the "lstlisting", but I had no success :(

Has anyone an idea how to solve my problem???

best regards,
Gadgetto

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

esdd
Posts: 36
Joined: Sat Jan 25, 2014 9:13 pm

Highlighting a Chunk of Code within a lstlisting

Post by esdd »

You can use hf-tikz:

Code: Select all

\documentclass{scrartcl}
\usepackage{listings}
\lstset{escapechar=§}

\usepackage[norndcorners,customcolors]{hf-tikz}
\hfsetbordercolor{yellow}
\hfsetfillcolor{yellow}

\begin{document}
\begin{lstlisting}
public §\tikzmarkin{glw}§class MyRunnable§\tikzmarkend{glw}§ implements Runnable{
        String name;
        public MyRunnable(String name){
                this.name = name;
        }
\end{lstlisting}
\end{document}
Run twice to get the result:
listing.png
listing.png (7.79 KiB) Viewed 5782 times
Best regards
Elke
Post Reply