While I adore the power of the \tikzmark
concept, too, it seems (with the necessity to compile twice) to be overkill for this situation. Why not just box the content and measure its size?
The following implements this idea based on some code I originally developed for this answer to a question about highlighting elements in a lstlisting
environment while also keeping the syntax highlighting. The result is the \btHL
command, which works like a font-changing command (such as \color
or \bfseries
) in that it affects everything until the end of the group (not across line breaks); this was a requirement for playing together with listings
. The basic idea is to box the content and then typeset it inside a TikZ node. The bounding box of the tikzpicture
, however, is adjusted to the size of the content, so that the highlighting does not take extra space (to prevent "jumping content" if used with beamer overlays).
As a quick solution, I have implemented your \tikzhighlight
macro on this base; the code, however, could be simplified quite a bit if the content to highlight is always given as a macro parameter.
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage{amsmath}
\makeatletter
\newenvironment{btHighlight}[1][]
{\begingroup\tikzset{bt@Highlight@par/.style={#1}}\begin{lrbox}{\@tempboxa}}
{\end{lrbox}\bt@HL@box[bt@Highlight@par]{\@tempboxa}\endgroup}
\newcommand\btHL[1][]{%
\begin{btHighlight}[#1]\bgroup\aftergroup\bt@HL@endenv%
}
\def\bt@HL@endenv{%
\end{btHighlight}%
\egroup
}
\newcommand{\bt@HL@box}[2][]{%
\tikz[#1]{%
\pgfpathrectangle{\pgfpoint{0pt}{0pt}}{\pgfpoint{\wd #2}{\ht #2}}%
\pgfusepath{use as bounding box}%
\node[anchor=base west, fill=orange!30,outer sep=0pt,inner xsep=0.2em, inner ysep=0.1em, #1]{\usebox{#2}};
}%
}
\makeatother
\newcommand{\tikzhighlight}[2][red]{%
{\btHL[fill=#1!10,draw=#1,rounded corners]#2}%
}
\begin{document}
\begin{itemize}
\item this is \tikzhighlight[yellow]{a text to be highlighted}
\item {\tiny{this is a text to be \tikzhighlight{highlighted}}}
\item \huge{this is a text to be \tikzhighlight{highlighted}}
\end{itemize}
\begin{align*}
&\tikzhighlight[green]{\ensuremath{x+\dfrac{z}{y}}}=100\\
&x+\tikzhighlight[blue]{\ensuremath{y}}=100
\end{align*}
\end{document}
Some additional fine tuning could be applied to the dimensioning of the boxes and the bounding box.
Best Answer
With a little help of
grep
: The standard classes define this command:For example
article.cls
Within
\maketitle
:Later on in the class:
In
letter.cls
The definitions from
book
andreport
classes are equal toarticle.cls
, for the KOMA classes the definition is somewhat different.