3

I'm typesetting source code with the listings package's lstlisting environment. Since I have to draw custom stuff in some lines, I use escapeinside in these lines to insert a tikzpicture.

Since these lines may be indented, I need to know the length of the indentation, or the remaining width of the line. Is there any way to access that? \linewidth still contains the full line length, so a box of width \linewidth sticks out on the right as much as the line was indented.


For example, consider this document:

\documentclass{article}

\usepackage{tikz}
\usepackage{listings}

\begin{document}

\newcommand{\mwebox}{\begin{tikzpicture}[baseline]\path[fill=black!10, draw=black!0, thick] (0,-0.20) rectangle (5, 0.30);\end{tikzpicture}}

\begin{lstlisting}[escapeinside=~~]
Test
~\mwebox~
Test

    Test
    ~\mwebox~
    Test
\end{lstlisting}

\end{document}

I want to extend the gray boxes to the end of the lines.

2
  • 1
    Please give a full minimal working example. Currently we have to guess what packages etc you are using and this makes it really hard to help you. A MWE should start with a \documentclass command, have a minimal preamble and then \begin{document}...\end{document}. The code should compile and be as small as possible to demonstrate your problem. This makes it much easier for people to help you --- and much more likely that they will!
    – user30471
    Aug 11, 2016 at 23:28
  • I added a minimal document that could use this length.
    – fefrei
    Aug 11, 2016 at 23:46

1 Answer 1

1

This isn't really answering your question as I am not doing this automatically, but I think that you probably need to manually tweak your tikzpicture environment because the listings manual says "indention must be done by hand".

For example, using

\documentclass{article}

\usepackage{tikz}
\usepackage{listings}

\begin{document}

\newcommand{\mwebox}[1][12]{\begin{tikzpicture}[baseline]\path[fill=black!10, draw=black!0, thick] (0,-0.20) rectangle (#1, 0.30);\end{tikzpicture}}

\begin{lstlisting}[escapeinside=~~]
Test
~\mwebox~
Test

    Test
    ~\mwebox[11.2]~
    Test
\end{lstlisting}

\end{document}

gives the output that I think you want:

enter image description here

So, I have defined \mwebox to have an optional argument that defaults to 12, which is close to the margin. I then found 11.2 by trial and error for the second box.

1
  • That's what I've been doing so far, but getting these numbers right is awful, and of course it always feels like your're just a bit off...
    – fefrei
    Aug 12, 2016 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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