Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I am trying to highlight portions of code inside a listings environment. However, using tikz introduces some extra spaces that I do not understand and would like to ask how I can rid of them.

Here is a small document that shows my problem:

\documentclass[10pt,a4paper,twoside,openright,titlepage,abstracton]{scrreprt} %report}
\usepackage{listings}
\lstset{language=Java,escapechar=!}

\usepackage{tikz}
\newcommand\eh{\tikz[remember picture]\node (end highlight){};\tikz[remember picture, overlay]\draw[yellow,line width=10pt,opacity=0.3](begin highlight)--(end highlight);}
\newcommand{\bh}{\tikz[remember picture]\node(begin highlight){};}


\begin{document}
\begin{lstlisting}
Lol rofl roflcopter
\end{lstlisting}
\begin{lstlisting}
Lol !\bh!rofl!\eh! roflcopter
\end{lstlisting}
\end{document}

Although I expected it to be yellow, you get the point: rofl has more spacing when highlighted :

enter image description here

share|improve this question
add comment

2 Answers

up vote 7 down vote accepted

Instead of \nodes you can use \coordinates which don't introduce extra spacing:

\documentclass[10pt,a4paper,twoside,openright,titlepage,abstracton]{scrreprt} %report}
\usepackage{listings}
\lstset{language=Java,escapechar=!}

\usepackage{tikz}

\newcommand\eh{%
\tikz[remember picture,overlay]{
  \coordinate (end highlight){};%
  \draw[yellow,line width=10pt,opacity=0.3]
    ([yshift=.9ex]begin highlight) -- ([yshift=.9ex]end highlight);}%
}
\newcommand{\bh}{%
  \tikz[remember picture]\coordinate(begin highlight){};}

\begin{document}
\begin{lstlisting}
Lol rofl roflcopter
\end{lstlisting}
\begin{lstlisting}
Lol !\bh!rofl!\eh! roflcopter
\end{lstlisting}
\end{document}

enter image description here

share|improve this answer
    
Thank you for your quick answer! Worked like a charm! –  KoenigGunther Oct 30 '12 at 10:28
add comment

If you use use the overlay option, you don't get any additional horizontal space introduced. So,

\newcommand\eh{%
    \tikz[remember picture, overlay] \node (end highlight){};%
    \tikz[remember picture, overlay]\draw[yellow,line width=10pt,opacity=0.3]
        (begin highlight)--(end highlight);%
}
\newcommand{\bh}{\tikz[remember picture, overlay] \node(begin highlight){};}

yields no additional spacing:

enter image description here

share|improve this answer
    
Aparently, I can only set one answer as accepted, although both work out well. Thank you very much! –  KoenigGunther Oct 30 '12 at 10:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.