Version 1:
My answer is using mostly TeX primitives. I know there are other ways to do it, especially using expl3, but I'm not there yet, so...
I defined the main macro \makelinesegment
that will take one argument, in the example, 1:1-1:2-2:2
.
\makelinesegment
appends will pass its argument to \@coordpair
, which takes as argument something in the form x:y-
. \@coordpair
will take the x
and y
coordinates and add them to \this@path
as (x,y)--
.
When \@coordpair
reaches the end of the input (i.e. finds \empty:\empty-
), it finishes and return to \makelinesegment
.
Up to now we have (1,1)--(1,2)--(2,2)--
. \makelinesegment
then calls \gobblemm
to remove the final --
from \this@path
.
Finally, \makelinesegment
calls \draw\this@path;
.
\documentclass{article}
\usepackage{tikz}
\makeatletter
\def\makelinesegment#1{%
\def\this@path{}%
\@coordpair#1-\empty:\empty-\@empty%
\expandafter\gobblemm\this@path;
\draw\this@path;
}
\def\gobblemm#1--;{\edef\this@path{#1}}
\def\@coordpair#1:#2-#3\@empty{%
\ifx#1\empty
\else
\edef\this@path{\this@path(#1,#2)--}%
\expandafter\@coordpair%
\fi
#3\@empty%
}
\makeatother
\begin{document}
\pagenumbering{gobble}
\begin{tikzpicture}
\makelinesegment{1:1-1:2-2:2}
\end{tikzpicture}
\end{document}
Version 2:
As I said in the comments, this notation may (and will) cause ambiguity when using negative coordinates. So I propose a slight change: replace the -
that separates the coordinate pairs by ,
. Like this: 1:1,1:2,2:2
.
The solution then becomes even simpler, for we can use LaTeX's \@for
to iterate on a comma-separated list.
Now the \makelinesegment
macro just passes its argument to \@for
, who splits the coorinate pairs and passes them to \@pair
. \@pair
then appends the coordinate pair (x,y)--
to \this@list
.
And the rest is like in the first version; \gobblemm
removes the last --
and \makelinesegment
calls \draw\this@path;
.
\documentclass{article}
\usepackage{tikz}
\makeatletter
\def\makelinesegment#1{%
\def\this@path{}%
\@for\@pair:=#1\do{%
\expandafter\splitpair\@pair\@empty%
}%
\expandafter\gobblemm\this@path;%
\draw\this@path;
}
\def\gobblemm#1--;{\edef\this@path{#1}}
\def\splitpair#1:#2\@empty{%
\edef\this@path{\this@path(#1,#2)--}%
}
\makeatother
\begin{document}
\pagenumbering{gobble}
\begin{tikzpicture}
\makelinesegment{1:1,1:2,2:2}
\end{tikzpicture}
\end{document}
1:1--1:-2-2:2
seems a bit weird. Maybe another character to separate fields?