I found this nice solution to scale a TikZ picture to \textwidth and wanted to use it within an own defined environment.
\documentclass{article}
\usepackage{tikz}
\usepackage{environ}
\makeatletter
\newsavebox{\measure@tikzpicture}
\NewEnviron{scaletikzpicturetowidth}[1]{%
\def\tikz@width{#1}%
\def\tikzscale{1}\begin{lrbox}{\measure@tikzpicture}%
\BODY
\end{lrbox}%
\pgfmathparse{#1/\wd\measure@tikzpicture}%
\edef\tikzscale{\pgfmathresult}%
\BODY
}
\makeatother
\newenvironment{bggrid}[1]{%
\begin{scaletikzpicturetowidth}{#1\textwidth}%
\begin{tikzpicture}[transform shape, scale=\tikzscale]
\draw (-2,-2) grid (2,2);
}
{\end{tikzpicture}\end{scaletikzpicturetowidth}}
\begin{document}
% works perfectly
% \begin{scaletikzpicturetowidth}{.5\textwidth}%
% \begin{tikzpicture}[transform shape, scale=\tikzscale]
% \draw (-2,-2) grid (2,2);
% \draw (0,0) circle (1);
% \end{tikzpicture}\end{scaletikzpicturetowidth}
% this causes the problem
\begin{bggrid}{.5}
\draw (0,0) circle (1);
\end{bggrid}
\end{document}
But when I do so I obtain an error, I was not able to fix.
! LaTeX Error: \begin{scaletikzpicturetowidth} on input line 35 ended by \end{d
ocument}.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.39 \end{document}
? h
Your command was ignored.
Type I <command> <return> to replace it with another command,
or <return> to continue without it.
Does somebody has any idea how to solve this?
tikzscale. – percusse Oct 23 '14 at 21:02\begin{scaletikzpicturetowidth}and\end{scaletikzpicturetowidth}in the definition ofbbgrid; they should be\scaletikzpicturetowidthand\endscaletikzpicturetowidthbecause of the peculiarities of\NewEnviron. – egreg Oct 23 '14 at 21:03