# Auto linefeed of node text in tikz

\node by tikz is used to get an effect of text highlight. It's all right except that the node text can not automatically linefeed. Is there a better way to achieve this? MWE:

\documentclass{article}
\usepackage{tikz,picture,eso-pic,calc,etoolbox}
\begin{document}
\hspace{20em}yellow green wood \tikz[baseline] \node[fill=gray!20, anchor=base,inner sep=0pt] {yellow green wood yellow green wood }; yellow green wood
\end{document}


I've had a look at a few related questions and might have a set-up that does what you want. Two ingredients:

• The \measureremainder command provided by this user. This allows us to record the length of the remaining whitespace in a line before using a tikz node.
• The varwidth environment from the varwidth package. This is a minipage of variable width that we can use inside a node.

The minimal preamble:

\documentclass{article}
\usepackage{tikz}
\usepackage{tikzpagenodes} % \measureremainder
\usetikzlibrary{calc} % \measureremainder
\usepackage{varwidth} % varwidth environment

\newcommand{\measureremainder}[1]{%
\begin{tikzpicture}[overlay,remember picture]
% measure distance to right text border
\path let \p0 = (0,0), \p1 = (current page text area.east) in
[/utils/exec={\pgfmathsetlength#1{\x1-\x0}\global#1=#1}];
\end{tikzpicture}%
}
\newlength{\whatsleft}  % length to be used in nodes


Firstly, immediately before calling \tikz save the length of the remaining line with \measureremainder{\whatsleft}. You could then set the text width property of the node to this value:

\begin{document}
This is a very long line of example text before a node.
\measureremainder{\whatsleft}
\tikz[baseline] \node[fill=gray!20, anchor=base,inner sep=0pt, text width=\whatsleft]
{This is example text inside a node.};
This is a long line of example text following a node.
\end{document}


This makes the text in the node wrap around:

But means that the node will always span the rest of the line, which may not be desired:

\begin{document}
This is a long line.
\measureremainder{\whatsleft}\tikz[baseline] \node[fill=gray!20, anchor=base,inner sep=0pt, text width=\whatsleft]
{This is example text inside a node.}; This is a long line of example text.
\end{document}


(the difficulty is that a tikz node have no equivalent of a max width property).

We can get around this by using \whatsleft in the arguemnt of a varwidth environment:

\begin{document}
This is a long line.
\measureremainder{\whatsleft}\tikz[baseline]\node[fill=gray!20, anchor=base,inner sep=0pt]
{\begin{varwidth}{\whatsleft}
This is example text inside a node.
\end{varwidth}};
This is a long line of example text following a node.
\end{document}


All said and done, I don't think tikz nodes were really designed for this purpose - have you tried using the ordinary \fbox and \parbox commands? (Info on these can be found on the LaTeX/Boxes Wikibook page.)