# Error using \widthof inside tikzpicture

\documentclass{article}

\usepackage{tikz}
\usepackage{calc}

\begin{document}

\begin{tikzpicture}
\newlength{\TextWidth}
\setlength{\TextWidth}{\widthof{Text}}
%\node[draw,text width=\widthof{Text}}]{Text}; % this does not work
\node[draw,text width=\TextWidth]{Text}; % this works
\end{tikzpicture}

\end{document}


With the code above I am getting the following error:

! Undefined control sequence. \pgfmath@dimen@ ...men@@ #1=0.0pt\relax \pgfmath@

l.9 \node[draw,text width=\widthof{Text}]{ Text}

But I am not understanding why, since this code was previously working. I am using TeXLive 2015.

In a tikzpicture, the current font is \nullfont (see pp.124-125, pgfmanual), So \widthof can't work.

You may use the width function provided by TikZ math engine:

\documentclass{article}

\usepackage{tikz}
\usepackage{calc}

\begin{document}

\begin{tikzpicture}
\node[draw,text width=width("Text")]{Text and text};
\end{tikzpicture}

\end{document}


• Was this a change for TeXLive 2015? Aug 18 '15 at 14:09
• Not 100 % sure but it seems that the \real{⋅} macro suffers from something similar. Oct 2 '17 at 13:09

Tikz provides its own version of \widthof. No calc needed. However the latest version isn't loading it.

\documentclass{article}

\usepackage{tikz}

\makeatletter
% Stuff for calc compatiability.
\let\real=\pgfmath@calc@real
\let\minof=\pgfmath@calc@minof
\let\maxof=\pgfmath@calc@maxof
\let\ratio=\pgfmath@calc@ratio
\let\widthof=\pgfmath@calc@widthof
\let\heightof=\pgfmath@calc@heightof
\let\depthof=\pgfmath@calc@depthof
\makeatother

\begin{document}

\begin{tikzpicture}
\node[draw,text width=\widthof{Text}]{Text};
\end{tikzpicture}

\end{document}


• In pgfmathparser.code.tex, we found also \def\pgfmath@calc@widthof#1{width("#1")}. Aug 18 '15 at 16:11
• Can you show your \listfiles? I can't compile your code with TikZ 3.0.1. Aug 18 '15 at 16:13
• I have the same code in pgfmathparser.code.tex. But still, I cannot compile your code Aug 18 '15 at 16:47
• If I add those lines in the code within the \makeatletter ... \makeatother, your code works. It seems that some package is not being included by default. Aug 18 '15 at 16:52
• Aha, I updated the MikTex admin version but not the plain version. Updating the plain version causes me to crash too. Aug 18 '15 at 18:38

Anyway, here is a robust work-around. Perhaps someone else can figure out how to make a version of \widthof that will work in the Tikz parm parser.

\documentclass{article}
\usepackage{tikz}

\newlength{\pgfcalcparm}

\newcommand{\widthof}[1]% #1 = text
{\pgftext{\settowidth{\global\pgfcalcparm}{#1}}%
\the\pgfcalcparm}

\begin{document}
\begin{tikzpicture}
\pgftext{\settowidth{\global\pgfcalcparm}{\bfseries Text}}%
\node[draw,text width=\pgfcalcparm]{\bfseries Text};
%\node[draw,text width=\widthof{Text}]{Text};% crashes (infinite loop)
\end{tikzpicture}
\end{document}


I encountered the same error message with TikZ-UML and PGF 3.0.1.