Text FormattingHighlight certain Text inside Code Listing in Presentation

Information and discussion about LaTeX's general text formatting features (e.g. bold, italic, enumerations, ...)
Post Reply
turok
Posts: 7
Joined: Wed Oct 17, 2012 2:26 pm

Highlight certain Text inside Code Listing in Presentation

Post by turok »

I use beamer to create presentations with code listings. Sometimes I need to highlight some piece of text, for example one variable (counter in the code below). Now I do it using lstlisting and escapechar. Is it any way to do it automatically with \lstinputlisting, for example \lstinputlistinghighlighted[counter,red]{Main.java}

Code: Select all

\documentclass{beamer}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{listings}

\lstset{
	language=Java,
	tabsize=4,
	breaklines=true,
	breakatwhitespace=true,
	escapechar=|,
	basicstyle=\footnotesize\ttfamily,
	numberstyle=\footnotesize\ttfamily,
	aboveskip=\baselineskip,
	captionpos=b,
	columns=fullflexible,
	showstringspaces=false,
	extendedchars=true,
	breaklines=true,
	showtabs=false,
	showspaces=false,
	showstringspaces=false,
	identifierstyle=\ttfamily,
	keywordstyle=\color[rgb]{0.498,0.0,0.333},
	stringstyle=\color[rgb]{0.165,0.0,0.999},
	commentstyle=\color[rgb]{0.247,0.498,0.372}
}

\newcommand\red[1]{\setlength\fboxsep{0pt}\colorbox{red}{\strut #1}}

\begin{document}

\begin{frame}[fragile]{Test}
\begin{lstlisting}
public class Main {
    int counter;
    public static void main(String[] args) {
        for (counter = 0; counter < 10; counter++)
            System.out.println('HelloWorld');
    }
}
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]{Test}
\begin{lstlisting}
public class Main {
    int |\red{counter}|;
    public static void main(String[] args) {
        for (|\red{counter}| = 0; |\red{counter}| < 10; |\red{counter}|++)
            System.out.println('HelloWorld');
    }
}
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]{Test}
\lstinputlisting{Main.java}
\end{frame}

\begin{frame}[fragile]{Test}
%\lstinputlistinghighlighted[counter, red]{Main.java}
\end{frame}

\end{document}

Recommended reading 2024:

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

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

And: Currently, Packt sells ebooks for $4.99 each if you buy 5 of their over 1000 ebooks. If you choose only a single one, $9.99. How about combining 3 LaTeX books with Python, gnuplot, mathplotlib, Matlab, ChatGPT or other AI books? Epub and PDF. Bundle (3 books, add more for higher discount): https://packt.link/MDH5p

Post Reply