summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/source/latex/tikzmark/tikzmark.dtx
blob: b1f655659f4be0770d1f6605fd6d0f292078ef95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
% \iffalse meta-comment
%<*internal>
\iffalse
%</internal>
%<*readme>
----------------------------------------------------------------
tikzmark --- remembering absolute positioning with TikZ
E-mail: stacey@math.ntnu.no
Released under the LaTeX Project Public License v1.3c or later
See http://www.latex-project.org/lppl.txt
----------------------------------------------------------------

The tikzmark package defines a command to "remember" a position
on a page for later (or earlier) use, primarily (but not
exclusively) with TikZ.
%</readme>
%<*internal>
\fi
\def\nameofplainTeX{plain}
\ifx\fmtname\nameofplainTeX\else
  \expandafter\begingroup
\fi
%</internal>
%<*install>
\input docstrip.tex
\keepsilent
\askforoverwritefalse
\preamble
----------------------------------------------------------------
tikzmark --- remembering absolute positioning with TikZ.
E-mail: stacey@math.ntnu.no
Released under the LaTeX Project Public License v1.3c or later
See http://www.latex-project.org/lppl.txt
----------------------------------------------------------------

\endpreamble
\postamble

Copyright (C) 2011 by Andrew Stacey <stacey@math.ntnu.no>

This work may be distributed and/or modified under the
conditions of the LaTeX Project Public License (LPPL), either
version 1.3c of this license or (at your option) any later
version.  The latest version of this license is in the file:

http://www.latex-project.org/lppl.txt

This work is "maintained" (as per LPPL maintenance status) by
Andrew Stacey.

This work consists of the file  tikzmark.dtx
and the derived files           tikzmark.ins,
                                tikzmark.pdf,
                                tikzlibrarytikzmark.code.tex, and
                                tikzmarklibrarylistings.code.tex
                                tikzmarklibraryhighlight.code.tex

\endpostamble
\usedir{tex/latex/tikzmark}
\generate{
  \file{tikzlibrarytikzmark.code.tex}{\from{\jobname.dtx}{tikzlibrary}}
}
\generate{
  \file{tikzmarklibrarylistings.code.tex}{\from{\jobname.dtx}{listings}}
}
%\generate{
% \file{tikzmarklibraryhighlight.code.tex}{\from{\jobname.dtx}{highlight}}
%}
%</install>
%<install>\endbatchfile
%<*internal>
\usedir{source/latex/tikzmark}
\generate{
  \file{\jobname.ins}{\from{\jobname.dtx}{install}}
}
\nopreamble\nopostamble
\usedir{doc/latex/demopkg}
\generate{
  \file{README.txt}{\from{\jobname.dtx}{readme}}
}
\ifx\fmtname\nameofplainTeX
  \expandafter\endbatchfile
\else
  \expandafter\endgroup
\fi
%</internal>
%<*package>
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{tikzmark}[2012/10/24 v1.0 TikZmark]
%</package>
%<*driver>
\documentclass{ltxdoc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
%\usepackage{morefloats}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{fit,arrows,tikzmark,shadows,decorations.pathreplacing,calc}
\usetikzmarklibrary{listings}

\usepackage[numbered]{hypdoc}
\definecolor{lstbgcolor}{rgb}{0.9,0.9,0.9} 
 
\usepackage{listings}
\lstloadlanguages{[LaTeX]TeX}
\lstset{gobble=2,breakatwhitespace=true,breaklines=true,language=TeX}
 
\usepackage{fancyvrb}

\newenvironment{example}
  {\VerbatimEnvironment
   \begin{VerbatimOut}[gobble=2]{example.out}}
  {\end{VerbatimOut}
   \begin{center}
%   \setlength{\parindent}{0pt}
   \fbox{\begin{minipage}{.9\linewidth}
     \lstset{breakatwhitespace=true,breaklines=true,language=TeX,basicstyle=\small}
     \lstinputlisting[]{example.out}
   \end{minipage}}

   \fbox{\begin{minipage}{.9\linewidth}
     \input{example.out}
   \end{minipage}}
\end{center}
}

  \newcommand\balloon[4]{%
    \pgfmathtruncatemacro\firstline{%
      #3-1
    }%
    \iftikzmark{line-#2-\firstline-start}{%
      \iftikzmark{line-#2-#3-first}{%
        \xdef\blines{({pic cs:line-#2-\firstline-start} -| {pic cs:line-#2-#3-first})}%
      }{%
        \iftikzmark{line-#2-#3-start}{%
          \xdef\blines{({pic cs:line-#2-\firstline-start} -| {pic cs:line-#2-#3-start})}%
        }{%
          \xdef\blines{(pic cs:line-#2-\firstline-start)}%
        }%
      }%
    }{%
      \xdef\blines{}%
    }%
    \foreach \k in {#3,...,#4} {%
      \iftikzmark{line-#2-\k-first}{%
        \xdef\blines{\blines (pic cs:line-#2-\k-first) }
      }{}
      \iftikzmark{line-#2-\k-end}{%
        \xdef\blines{\blines (pic cs:line-#2-\k-end) }
      }{}
    }%
    \ifx\blines\empty
    \else
    \edef\temp{\noexpand\tikz[remember         picture,overlay]\noexpand\node[fit={\blines},balloon] (#1) {};}%
    \temp
    \fi
  }
  \tikzset{
    line/.style={
      draw,
      rounded corners=3pt,
      -latex
    },
    balloon/.style={
      draw,
      fill=blue!20,
      opacity=0.4,
      inner sep=4pt,
      rounded corners=2pt
    },
    comment/.style={
      draw,
      fill=blue!70,
      text=white,
      text width=3cm,
      minimum height=1cm,
      rounded corners,
      drop shadow,
      align=left,
      font=\scriptsize
    },
  }

\EnableCrossrefs
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{\jobname.dtx}
\end{document}
%</driver>
% \fi
%
% \CheckSum{442}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
%
% \changes{1.0}{2012/11/08}{Converted to DTX file}
%
% \DoNotIndex{\newcommand,\newenvironment}
%
% \providecommand*{\url}{\texttt}
% \title{The \textsf{tikzmark} package}
% \author{Andrew Stacey \\ \url{stacey@math.ntnu.no}}
% \date{v1.0~from 2013/04/12}
%
%
% \maketitle
%
% 
% \section{Introduction}
%
% The \Verb+\tikzmark+ macro burst onto the scene in a blaze of glory on \href{http://tex.stackexchange.com}{TeX-SX}.
% Since then, it has proved embarrassingly (to its original author) popular.
% The idea behind it is extremely simple: that the machinery underneath TikZ provides a way to ``mark'' a point on a page for further use.
% This functionality is already provided by several other packages.
% The point of this one is that as TikZ can provide this feature, if already loading TikZ then it makes sense to use the TikZ version than another version.
% Moreover, if the goal is to use these marks with some TikZ code then this version is already set up for that purpose (not that it would be exactly difficult to add this to any of the other implementations).
%
% \section{Use}
%
% Using the \Verb+\tikzmark+ is extremely simple.
% You need to load the \Verb+tikz+ package and then load \Verb+tikzmark+ as a \Verb+tikzlibrary+.
% Thus in your preamble you should have something like:
%
% \begin{lstlisting}
% \usepackage{tikz}
% \usetikzlibrary{tikzmark}
% \end{lstlisting}
%
% In your document, you can now type \Verb+\tikzmark{<name>}+ at a point that you want to remember.
% This will save a mark with name \Verb+<name>+ for use later (or earlier).
% To use it in a \Verb+\tikz+ or \Verb+tikzpicture+, simply use the \Verb+pic+ coordinate system:
%
% \begin{lstlisting}
% \tikz[remember picture] \draw[overlay] (0,0) -- (pic cs:<name>);
% \end{lstlisting}
%
% There are two important points to note:
%
% \begin{enumerate}
% \item The enveloping \Verb+\tikz+ or \Verb+tikzpicture+ must have the key \Verb+remember picture+ set.
%
% This is because of how TikZ coordinates work.
% The coordinates inside a TikZ picture are relative to its origin, so that origin can move around on the page and not affect the internals of the picture.
% To use a point outside the picture, therefore, the current picture not only has to know where that point is on the page it also has to know where it itself is on the page.
% Hence the \Verb+remember picture+ key must be set.
% \item The drawing command must have the \Verb+overlay+ key set (or be in a scope or picture where it is set).
% 
% This is to keep the bounding box of the current picture under control.
% Otherwise, it would grow to encompass the remembered point as well as the current picture.
% (This isn't necessary if the remembered point is inside the current picture.)
% \end{enumerate}
%
% 
%
% \section{History}
%
% I wrote the original \Verb+\tikzmark+ macro in 2009 for use in lecture slides prepared with the \Verb+beamer+ package.
% It's original definition was:
%
% \begin{lstlisting}
% \newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}
% \end{lstlisting}
%
% Its first use was in the (inelegant) code:
%
% \begin{lstlisting}
% \begin{frame}
% \frametitle{Structure of Continuous Functions}
%
% \begin{tikzpicture}[overlay, remember picture]
% \useasboundingbox (0,0);
% \draw<2-|trans: 0|handout: 0>[red,->] (bsp) .. controls +(-1,-1) and ($(cnvs.north)+(1,1)$) .. ($(cnvs.north)+(0,1)$) .. controls ($(cnvs.north)+(-1,1)$) and +(-1,0) .. (cnvs.north);
% \draw<3-|trans: 0|handout: 0>[green!50!black,->] (cplt) .. controls +(-1,-1) and +(-1,0) .. (mcplt.north);
% \draw<4-|trans: 0|handout: 0>[blue,->] (norm) .. controls +(-1,-.5) and ($(nvs.north)+(0,1.5)$) .. ($(nvs.north)+(0,1.5)$) .. controls ($(nvs.north)+(-1.5,1.5)$) and +(-1.5,0) .. (nvs.north);
% \draw<5-|trans: 0|handout: 0>[purple,->] (vector) .. controls +(-1,-1) and ($(vsp.north)+(2,2)$) .. ($(vsp.north)+(0,2)$) .. controls ($(vsp.north)+(-2,2)$) and +(-2,0) .. (vsp.north);
% \end{tikzpicture}
%
% \begin{theorem}
% \centering
% \(\big(C([0,1],\R),d_\infty\big)\) \\
% is a \\
% \alert{Banach\tikzmark{bsp} space}
% \end{theorem}
%
% \pause
% \bigskip
%
% \begin{itemize}
% \item[\tikzmark{cnvs}] {\color<.(2)->{green!50!black}Comp\tikzmark{cplt}lete} {\color<.(3)->{blue}nor\tikzmark{norm}med} {\color<.(4)->{purple}vector\tikzmark{vector} space}.
%
% \bigskip
% \bigskip
% \pause
%
% \begin{itemize}[<+->]
% \item[\tikzmark{mcplt}] {\color{green!50!black}Cauchy sequences converge.}
% \medskip
% \item[\tikzmark{nvs}] {\color{blue}Metric from a norm.}
% \medskip
% \item[\tikzmark{vsp}] {\color{purple}Functions behave like vectors.}
% \end{itemize}
% \end{itemize}
%
% \end{frame}
% \end{lstlisting}
%
% This produced, on the final slide, Figure~\ref{fig:tikzmarkex}.
%
% \begin{figure}
% \centering
% \includegraphics{tikzmark_example}
% \caption{First use of tikzmark}
% \label{fig:tikzmarkex}
% \end{figure}
%
% Its first appearance on \href{http://tex.stackexchange.com}{TeX-SX} was in an \href{http://tex.stackexchange.com/a/316/86}{answer} to a question about how to put overlapping braces on a mathematical text.
% This was in July 2010.
% The opening statement of the answer was not overly encouraging: ``This may not be the best solution\dots''.
% And for a macro that would go on to become quite ubiquitous, its initial appearance only garnered it 2 votes.
%
% However, it started out in life as a useful macro for me and as such I found more uses for it in my own code and thus more opportunity for using it to answer questions on TeX-SX.
% The one that seems to have been where it got noticed came in \href{http://tex.stackexchange.com/a/1570/86}{August 2010}, again about putting braces in text but in a more complicated fashion.
% From this answer, it got picked up, picked over, and picked apart.
% A common use was in highlighting or adding marks to text.
%
% Gradually, as it got used, it developed.
% A major revision dates from an answer given in \href{http://tex.stackexchange.com/a/50054/86}{March 2012} where the question was actually about \Verb+\tikzmark+.
% This version added two important features: a TikZ coordinate system for referencing saved marks directly and the ability to refer to marks earlier in the document than they are defined (the mechanism for remembering points uses the \Verb+aux+ file anyway so this was more about exposing the information earlier than anything complicated).
% Then in October 2012 there was a  \href{http://tex.stackexchange.com/q/79121/86}{question} where it would have been useful to remember which page the mark was on and a \href{http://tex.stackexchange.com/q/79762/86}{question} where for some reason using the \Verb+\tikz+ macro didn't work so the \Verb+\pgfmark+ macro was introduced.
%
% \section{Usage}
%
% This package defines the following commands and usable stuff.
%
% \begin{enumerate}
% \item \Verb+\tikzmark+\oarg{drawing command}\marg{name}
%
% The mandatory argument is the name of the mark to be used to refer back to this point later.
%
% The \Verb+\tikzmark+ command can take an optional parameter which is some drawing command that can be put in a \Verb+\tikz ... ;+ command.
% This drawing command can be used to place a node or something similar at the marked point, or to set some \Verb+\tikzset+ keys.
% Sometimes this can be useful.
% Note, though, that if this is used to define an offset coordinate then this will only be available in the document \emph{after} the \Verb+\tikzmark+ command, even on later runs.
%
% \item \Verb+\pgfmark+\marg{name}
%
% This is a more basic form of the \Verb+\tikzmark+ which doesn't use any of the \Verb+\tikz+ overhead.
% One advantage of this command is that it doesn't create an \Verb+hbox+.
% 
% \item \Verb+\iftikzmark+\marg{name}\marg{true code}\marg{false code}
%
% This is a simple conditional to test if a particular mark is available.
% It executes \Verb+true code+ if it is and \Verb+false code+ if not.
%
% \item \Verb+(pic cs:<name>)+ or \Verb+(pic cs:<name>,<coordinate>)+
%
% This is the method for referring to a position remembered by \Verb+\tikzmark+ (or \Verb+\pgfmark+) as a coordinate in a \Verb+tikzpicture+ environment (or \Verb+\tikz+ command).
% If the extra \Verb+coordinate+ is specified then this is used in case the mark \Verb+name+ has not yet been defined (this can be useful for defining code that does something sensible on the first run).
%
% \item \Verb+/tikz/save picture id=<name>+
%
% This is the TikZ key that is used by \Verb+\tikzmark+ to actually save the connection between the name and the picture coordinate.
% It can be used on an arbitrary picture to save its origin.
%
% \item \Verb+/tikz/if picture id=#1#2#3+
%
% This is a key equivalent of the \Verb+\iftikzmark+ command.
%
% \item \Verb+/tikz/next page+, \Verb+/tikz/next page vector+
%
% It is possible to refer to a mark on a different page to the current page.
% When this is done, the mark is offset by a vector stored in the key \Verb+/tikz/next page vector+.
% The key \Verb+/tikz/next page+ can be used to set this to certain standard vectors by specifying where the ``next page'' is considered as lying corresponding to the current page.
% Possible values are (by default) \Verb+above+, \Verb+below+, \Verb+left+, \Verb+right+, and \Verb+ignore+.
% (The last one sets the vector to the zero vector.)
%
% \item \Verb+\subnode[options]{name}{content}+
%
% This produces a pseudo-node named \Verb+name+ around the \Verb+content+.
% The design purpose of this is to create a ``subnode'' inside a TikZ node.
% As far as TikZ is concerned, the contents of a node is just a box.
% It therefore does not know anything about it beyond its external size and so cannot easily determine the coordinates of pieces inside.
% The \Verb+\subnode+ command boxes its contents and saves the position of that box and its dimensions.
% This information is stored in the same way that PGF stores the necessary information about a node.
% It is therefore possible to use ordinary node syntax (within a \Verb+tikzpicture+) to access this information.
% Thus after \Verb+\node {a \subnode{a}{sub} node};+ it is possible to use \Verb+a+ as a node.
% The \Verb+options+ are passed to the node construction mechanism, but note that the only sensible options are those that affect the size and shape of the node: drawing options are ignored (except in so far as they affect the size -- as an example, \Verb+line width+ affects the node size).
%
% There are two important points to make about this.
% The first is that, as with all the \Verb+tikzmark+ macros, the information is always one compilation old.
% The second is that the pseudo-node is purely about coordinates: the  path information is not used and the contents are not moved.
% This is partly for reasons of implementation: the pseudo-node is constructed when TikZ is not in ``picture mode''.
% But also interleaving the background path of the pseudo-node and any containing node would be problematic and so is best left to the user.
%
% The simplest way to turn a pseudo-node into a more normal node is to use the \Verb+fit+ library.
% Using the above example, \Verb+\node[fit=(a),draw,inner sep=0pt] {};+ would draw a rectangle around the word \Verb+sub+ of exactly the same size as would appear had a normal node been created.
%
% \end{enumerate}
%
% \section{Examples and Extras}
%
% The \Verb+\tikzmark+ command has been used in numerous answers on \href{http://tex.stackexchange.com}{TeX-SX}.
% The plan is to gather some of these into extra libraries which can be loaded via \Verb+\usetikzmarklibrary+.
%
% At present, this is the code listings library (which works with the \Verb+listings+ package).
% One that is in development (as it has featured much on the TeX-SX website) is highlighting, however this is not so straightforward to implement so is still under development.
%
% \subsection{Basic Examples}
%
% A simple example of the \Verb+\tikzmark+ macro is the following.
%
% \begin{example}
% \[
%  \tikzmark{a} e^{i \pi/2} = i
% \]
%
% This\tikz[remember picture,overlay,baseline=0pt] \draw[->] (0,1em) to[bend left] ([shift={(-1ex,1ex)}]pic cs:a); is an important equation.
% \end{example}
%
% \begin{example}
% \begin{itemize}
% \item A first item,\tikzmark{b}
% \item A second item,\tikzmark{c}
% \item A third item.\tikzmark{d}
% \end{itemize}
% \begin{tikzpicture}[remember picture,overlay]
% \draw[decorate,decoration={brace}] ({pic cs:c} |- {pic cs:b}) +(0,1em) -- node[right,inner sep=1em] {some items} ({pic cs:c} |- {pic cs:d});
% \end{tikzpicture}
% \end{example}
%
% \begin{example}
% \begin{tikzpicture}[remember picture]
% \node (a) at (0,0) {This has a \subnode{sub}{subnode} in it};
% \draw[->] (0,-1) to[bend right] (sub);
% \end{tikzpicture}
% \end{example}
%
% \subsection{Code Listings}
%
% If the \Verb+listings+ package has been loaded then issuing \Verb+\usetikzmarklibrary{listings}+ will load in some code to add marks to \Verb+lstlisting+ environments.
% This code places a mark at three places on a line of code in a \Verb+listings+ environment.
% The marks are placed at the start of the line, the first non-whitespace character, and the end of the line (if the line is blank the latter two are not placed).
% (This has not been extensively tested, it works by adding code to various ``hooks'' that are made available by the \Verb+listings+ package; it is quite possible that the hooks chosen are both wrong and insufficient to cover all desired cases.)
%
%
% These are inspired by questions such as \href{http://tex.stackexchange.com/q/79762/86}{Marking lines in listings} and \href{http://tex.stackexchange.com/q/86309/86}{Macros for code annotations}.
%
% In more detail, the \Verb+listings+ library places lots of marks around the code.
% The marks are:
%
% \begin{itemize}
% \item \Verb+line-<name>-<number>-start+ at the start of each line.
% \item \Verb+line-<name>-<number>-end+ at the end of each line.
% \item \Verb+line-<name>-<number>-first+ at the first non-space character of the line (assuming it exists).
% \end{itemize}
%
% The line numbers \emph{should} match up with the line numbers in the code in that any initial offset is also applied.
%
% Not every mark is available on every line.
% If a line is blank, in particular, it will only have a \Verb+start+ mark.
% The following example shows this, where the red dots are the \Verb+start+, the blue are \Verb+end+, and the green are \Verb+first+.
%
% \begin{example}
% \begin{tikzpicture}[remember picture]
% \foreach \k in {0,...,7} {
% \iftikzmark{line-code-\k-start}{\fill[red,overlay] (pic cs:line-code-\k-start) circle[radius=4pt];}{\message{No start for \k}}
% \iftikzmark{line-code-\k-end}{\fill[blue,overlay] (pic cs:line-code-\k-end) circle[radius=2pt];}{\message{No end for \k}}
% \iftikzmark{line-code-\k-first}{\fill[green,overlay] (pic cs:line-code-\k-first) circle[radius=2pt];}{\message{No first for \k}}
% }
% \draw[->,overlay] (0,0) -- (pic cs:line-code-5-first);
% \draw[->,overlay] (0,0) -- (pic cs:line-code-5-start);
% \draw[->,overlay] (0,0) -- (pic cs:line-code-5-end);
% \node[above] at (0,0) {Line 5};
% \end{tikzpicture}
% 
% \begin{lstlisting}[language=c,name=code,numbers=left]
%   #include <stdio.h>
% 
%   int main(void)
%   {
%       printf("hello, world\n");
%       return 0;
%   }
% \end{lstlisting}
% \end{example}
%
% This example puts a fancy node behind certain lines of the code, computing the necessary extents.
%
% \begin{example}
% \balloon{comment}{more code}{3}{3}
% \balloon{comment}{more code}{7}{8}
% \begin{lstlisting}[language=c,name=more code,numbers=left,firstnumber=3]
%   #include <stdio.h>
%   
%   int main(void)
%   {
%       printf("hello, world\n");
%       return 0;
%   }
% \end{lstlisting}
% \end{example}
%
%
%
% \section{Acknowledgements}
%
% The \Verb+\tikzmark+ macro has been used and abused by many users of \href{http://tex.stackexchange.com}{TeX-SX}.
% Of particular note (but in no particular order) are \href{}{Peter Grill}, \href{}{Gonzalo Medina}, \href{}{Claudio Fiandrino}, and \href{}{percusse}.
% I would also like to mention David Carlisle whose knowledge of TikZ continues to astound us all.
% 
%
% \StopEventually{}
%
% \section{Implementation}
%
% \iffalse
%<*tikzlibrary>
% \fi
% \subsection{Main Code}
%
%    \begin{macrocode}
\tikzset{%
  remember picture with id/.style={%
    remember picture,
    overlay,
    save picture id=#1,
  },
%    \end{macrocode}
% Not totally happy with using \Verb+every picture+ here as it's too easily overwritten by the user.
% Maybe it would be better to patch \Verb+endtikzpicture+ directly.
%    \begin{macrocode}
  every picture/.append style={%
    execute at end picture={%
      \ifpgfrememberpicturepositiononpage%
      \edef\pgf@temp{%
        \noexpand\write\noexpand\pgfutil@auxout{%
        \string\savepicturepage{\pgfpictureid}{\noexpand\thepage}}}%
      \pgf@temp
      \fi%
    },
  },
%    \end{macrocode}
% The positions are already recorded in the \Verb+aux+ file, all we really need to do is provide them with better names.
%    \begin{macrocode}
  save picture id/.code={%
      \immediate\write\pgfutil@auxout{%
        \string\savepointas{#1}{\pgfpictureid}}%
  },
%    \end{macrocode}
% Provides a way to test if a picture has already been saved (in particular, can avoid errors on first runs)
%    \begin{macrocode}
  if picture id/.code args={#1#2#3}{%
    \@ifundefined{save@pt@#1}{%
      \pgfkeysalso{#3}%
    }{
      \pgfkeysalso{#2}%
    }
  },
%    \end{macrocode}
% Page handling
%    \begin{macrocode}
  next page/.is choice,
  next page vector/.initial={\pgfqpoint{0pt}{0pt}},
  next page/below/.style={%
    next page vector={\pgfqpoint{0pt}{-\the\paperheight}}%
  },
  next page/above/.style={%
    next page vector={\pgfqpoint{0pt}{\the\paperheight}}%
  },
  next page/left/.style={%
    next page vector={\pgfqpoint{-\the\paperwidth}{0pt}}%
  },
  next page/right/.style={%
    next page vector={\pgfqpoint{\the\paperwidth}{0pt}}%
  },
  next page/ignore/.style={%
    next page vector={\pgfqpoint{0pt}{0pt}}%
  },
}
%    \end{macrocode}
%
% \begin{macro}{\savepointas}
% This is what gets written to the \Verb+aux+ file.
%    \begin{macrocode}
\def\savepointas#1#2{%
  \expandafter\gdef\csname save@pt@#1\endcsname{#2}%
}
\def\savepicturepage#1#2{%
  \expandafter\gdef\csname save@pg@#1\endcsname{#2}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tmk@labeldef}
% Auxiliary command for the coordinate system.
%    \begin{macrocode}
\def\tmk@labeldef#1,#2\@nil{%
  \def\tmk@label{#1}%
  \def\tmk@def{#2}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{pic}
% This defines the new coordinate system.
%    \begin{macrocode}
\tikzdeclarecoordinatesystem{pic}{%
  \pgfutil@in@,{#1}%
  \ifpgfutil@in@%
    \tmk@labeldef#1\@nil
  \else
    \tmk@labeldef#1,(0pt,0pt)\@nil
  \fi
  \@ifundefined{save@pt@\tmk@label}{%
    \tikz@scan@one@point\pgfutil@firstofone\tmk@def
  }{%
      \pgfsys@getposition{\csname save@pt@\tmk@label\endcsname}\save@orig@pic%
      \pgfsys@getposition{\pgfpictureid}\save@this@pic%
      \pgf@process{\pgfpointorigin\save@this@pic}%
      \pgf@xa=\pgf@x
      \pgf@ya=\pgf@y
      \pgf@process{\pgfpointorigin\save@orig@pic}%
      \advance\pgf@x by -\pgf@xa
      \advance\pgf@y by -\pgf@ya
      \pgf@xa=\pgf@x
      \pgf@ya=\pgf@y
      \@ifundefined{save@pg@\csname save@pt@\tmk@label\endcsname}{}{%
        \@ifundefined{save@pg@\pgfpictureid}{}{%
          \pgfkeysvalueof{/tikz/next page vector}%
          \advance \pgf@xa by \csname save@pg@\csname save@pt@\tmk@label\endcsname\endcsname\pgf@x\relax
\advance \pgf@ya by \csname save@pg@\csname save@pt@\tmk@label\endcsname\endcsname\pgf@y\relax
          \advance \pgf@xa by -\csname save@pg@\pgfpictureid\endcsname\pgf@x\relax
\advance \pgf@ya by -\csname save@pg@\pgfpictureid\endcsname\pgf@y\relax
        }%
      }%
      \pgf@x=\pgf@xa
      \pgf@y=\pgf@ya
    }%
  }
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tikzmark}
%    \begin{macrocode}
\newcommand\tikzmark[2][]{%
\tikz[remember picture with id=#2] #1;}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pgfmark}
%    \begin{macrocode}
\newcommand\pgfmark[1]{%
    \bgroup
    \global\advance\pgf@picture@serial@count by1\relax%
    \edef\pgfpictureid{pgfid\the\pgf@picture@serial@count}%
      \pgfsys@markposition{\pgfpictureid}%
    \edef\pgf@temp{%
      \noexpand\write\noexpand\pgfutil@auxout{%
        \string\savepicturepage{\pgfpictureid}{\noexpand\thepage}}}%
    \pgf@temp
    \immediate\write\pgfutil@auxout{%
      \string\savepointas{#1}{\pgfpictureid}}%
    \egroup
  }
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\iftikzmark}
%    \begin{macrocode}
\newcommand\iftikzmark[3]{%
    \@ifundefined{save@pt@#1}{%
      #3%
    }{%
      #2%
    }%
  }%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subnode}
%    \begin{macrocode}
\newcommand\subnode[3][]{%
  \begingroup
  \pgfmark{#2}%
  \setbox\pgfnodeparttextbox=\hbox\bgroup #3\egroup
  \def\tikz@shape{rectangle}%
  \def\tikz@anchor{center}%
  \def\tikz@fig@name{#2}%
  \tikzset{every subnode/.try,#1}%
  \pgfpointorigin
  \tikz@scan@one@point\pgfutil@firstofone(pic cs:#2)\relax
  \advance\pgf@x by .5\wd\pgfnodeparttextbox
  \advance\pgf@y by .5\ht\pgfnodeparttextbox
  \advance\pgf@y by -.5\dp\pgfnodeparttextbox
  \pgftransformshift{}%
  \setbox\@tempboxa=\hbox\bgroup
  \pgfutil@ifundefined{pgf@sh@s@\tikz@shape}%
  {\PackageError{pgf}{Unknown shape ``\tikz@shape''}{}}%
  {%
    {%
      \let\pgf@sh@savedmacros=\pgfutil@empty% MW
      \let\pgf@sh@savedpoints=\pgfutil@empty%
      \def\pgf@sm@shape@name{\tikz@shape}% CJ % TT added prefix!
      \csname pgf@sh@s@\tikz@shape\endcsname%
      \pgf@sh@savedpoints%
      \pgf@sh@savedmacros% MW
      \pgftransformshift{%
        \pgf@sh@reanchor{\tikz@shape}{\tikz@anchor}%
        \pgf@x=-\pgf@x%
        \pgf@y=-\pgf@y%
      }%
      \expandafter\pgfsavepgf@process\csname pgf@sh@sa@\tikz@fig@name\endcsname{%
      	\pgf@sh@reanchor{\tikz@shape}{\tikz@anchor}% FIXME : this is double work!
      }%
      % Save the saved points and the transformation matrix
      \edef\pgf@node@name{\tikz@fig@name}%
      \ifx\pgf@node@name\pgfutil@empty%
      \else%
        \expandafter\xdef\csname pgf@sh@ns@\pgf@node@name\endcsname{\tikz@shape}%
        \edef\pgf@sh@@temp{\noexpand\gdef\expandafter\noexpand\csname pgf@sh@np@\pgf@node@name\endcsname}%
        \expandafter\pgf@sh@@temp\expandafter{\pgf@sh@savedpoints}%
        \edef\pgf@sh@@temp{\noexpand\gdef\expandafter\noexpand\csname pgf@sh@ma@\pgf@node@name\endcsname}% MW
        \expandafter\pgf@sh@@temp\expandafter{\pgf@sh@savedmacros}% MW
        \pgfgettransform\pgf@temp
        \expandafter\xdef\csname pgf@sh@nt@\pgf@node@name\endcsname{\pgf@temp}%
        \expandafter\xdef\csname pgf@sh@pi@\pgf@node@name\endcsname{\pgfpictureid}%
      \fi%
    }%
  }%
  \egroup
  \box\pgfnodeparttextbox
  \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\usetikzmarklibrary}
%    \begin{macrocode}
\def\usetikzmarklibrary{\pgfutil@ifnextchar[{\use@tikzmarklibrary}{\use@@tikzmarklibrary}}%}
\def\use@tikzmarklibrary[#1]{\use@@tikzmarklibrary{#1}}
\def\use@@tikzmarklibrary#1{%
  \edef\pgf@list{#1}%
  \pgfutil@for\pgf@temp:=\pgf@list\do{%
    \expandafter\pgfkeys@spdef\expandafter\pgf@temp\expandafter{\pgf@temp}%
    \ifx\pgf@temp\pgfutil@empty
    \else
      \expandafter\ifx\csname tikzmark@library@\pgf@temp @loaded\endcsname\relax%
      \expandafter\global\expandafter\let\csname tikzmark@library@\pgf@temp @loaded\endcsname=\pgfutil@empty%
      \expandafter\edef\csname tikzmark@library@#1@atcode\endcsname{\the\catcode`\@}
      \expandafter\edef\csname tikzmark@library@#1@barcode\endcsname{\the\catcode`\|}
      \catcode`\@=11
      \catcode`\|=12
      \pgfutil@InputIfFileExists{tikzmarklibrary\pgf@temp.code.tex}{}{
          \PackageError{tikzmark}{I did not find the tikzmark extras library '\pgf@temp'.}{}
        }%
      \catcode`\@=\csname tikzmark@library@#1@atcode\endcsname
      \catcode`\|=\csname tikzmark@library@#1@barcode\endcsname
      \fi%
    \fi
  }%
}

%    \end{macrocode}
% \end{macro}
%
% \iffalse
%</tikzlibrary>
% \fi
%
% \subsection{Listings}
%
% \iffalse
%<*listings>
% \fi
%
% From \url{http://tex.stackexchange.com/q/79762/86}
%
%    \begin{macrocode}
\@ifpackageloaded{listings}{%
%    \end{macrocode}
%
% \begin{macro}{\iflst@linemark}
% A conditional to help with placing the mark at the first non-whitespace character.
%    \begin{macrocode}
    \newif\iflst@linemark
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{EveryLine}
% This hook places the mark at the start of the line.
%    \begin{macrocode}
\lst@AddToHook{EveryLine}{%
  \begingroup
  \advance\c@lstnumber by 1\relax
  \pgfmark{line-\lst@name-\the\c@lstnumber-start}%
  \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{EOL}
% This hook places the mark at the end of the line and resets the conditional for placing the first mark.
%    \begin{macrocode}
\lst@AddToHook{EOL}{\pgfmark{line-\lst@name-\the\c@lstnumber-end}%
\global\lst@linemarktrue
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{OutputBox}
% Experimenting shows that this is the right place to set the mark at the first non-whitespace character.
% But we only want to do this once per line.
%    \begin{macrocode}
\lst@AddToHook{OutputBox}{%
  \iflst@linemark
  \pgfmark{line-\lst@name-\the\c@lstnumber-first}%
  \global\lst@linemarkfalse
  \fi
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tikzmk@lst@fnum}
% An auxiliary macro to figure out if the \Verb+firstnumber+ key was set.
% If so, it has the form \Verb+<number>\relax+.
% If not, it expands to a single token.
%    \begin{macrocode}
\def\tkzmk@lst@fnum#1\relax#2\@STOP{%
  \def\@test{#2}%
  \ifx\@test\@empty
  \def\tkzmk@lst@start{0}%
  \else
  \@tempcnta=#1\relax
  \advance\@tempcnta by -1\relax
  \def\tkzmk@lst@start{\the\@tempcnta}%
  \fi
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{Init}
% Adds a mark at the start of the listings environment.
%    \begin{macrocode}
\lst@AddToHook{Init}{%
  \expandafter\tkzmk@lst@fnum\lst@firstnumber\relax\@STOP
  \pgfmark{line-\lst@name-\tkzmk@lst@start-start}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macrocode}
}{%
    \PackageError{tikzmark listings}{The listings package has not been loaded.}{}
}
%    \end{macrocode}
% \iffalse
%</listings>
% \fi
%
%
%
% \Finale
\endinput