[Tex/LaTex] Arrows to text above and below line


I have been searching for an answer for some time but have not come across a solution. I am taking some notes from a programming course and need to take a line of code and identify each individual part with alternating arrows. For example, the line:

this.Something = new AnotherThing(anArgument);

Now, I need an arrow below this line pointing up to 'this' coming from some text identifying the part. Now, another arrow would need to start at some explanation text above this line and point down to the 'Something'. The =, new, and parenthesis do not need anything, just the other items. I have been trying to use \underset and \overset, but the spacing on the line goes wonky. Any guidance will be greatly appreciated.

Best Answer

Here's one option:

enter image description here

The code:




Some regular text before
@\tikzmark{a}@this.@\tikzmark{b}@Something = new AnotherThing(anArgument);
Some regular text after

\begin{tikzpicture}[remember picture,overlay]
  ([shift={(10pt,-3pt)}]pic cs:a) -- ++(10pt,-20pt) coordinate(aux1);
  at (aux1) {some explanatory text};
  ([shift={(15pt,9pt)}]pic cs:b) -- ++(10pt,20pt) coordinate(aux2);
\node[above,green!80!black,text width=4cm] 
  at (aux2) {some other explanatory text; it's longer};



  • The listings package was used to typeset the code. The package offers additional customization possibilities for typesetting code; please refer to the documentation

  • TikZ was used here. The tikzmark library was used to place some marks (the escapeinside feature from listings was used to place the marks inside lstlisting). Then those marks were used to draw the arrows and place the explanatory texts using \nodes.

  • Since the overlay option has to be used in the tikzpicture for the exaplanatory texts, some spacing will need to be added to get the proper spacing with the material surrounding the code.

  • Some internal calculations are involved, so the code needs two runs to stabilize.