[Tex/LaTex] Linewidth resets when using input files

groupinginputlengths

I'm trying to set some figure files in standalone .tex files, and then input them in the main file. Those files looks something like this

\ifx \plotwidth \undefined
 \newlength{\plotwidth} \setlength{\plotwidth}{0.9\linewidth} 
\else \fi% width of the total figure
\rule{\linewidth}{\plotwidth}% figure goes here

The main idea I have is to set standard widths using \linewidth, and being able to change the size in the main file by defining the \plotwidth before inputting the file. However, when I call the figures the second time in the same file, for some reason the \plotwidth is defined but its lenght is zero. As this example show

\documentclass{article}

\begin{document}

\begin{figure}
\input{fig.tex}
\caption{Test}
\end{figure}

\begin{figure}
\input{fig.tex}
\caption{Test}
\end{figure}

\end{document}

Can someone explain me why this is not working, and how to solve it?

Best Answer

The problem is that \newlength is a "global" command; so after the first figure, \plotwidth is defined. However, \setlength is a "local" command, so its setting is forgotten after the figure environment and reset to the initial value which is 0pt.

In general \newlength should be a preamble command. You can set it globally to a sentinel value, say -1000pt,

\newlength{\plotwidth}
\setlength{\plotwidth}{-1000pt}

and then check against this value with

\ifdim\plotwidth=-1000pt

in fig.tex. If you say

\begin{figure}
\setlength{\plotwidth}{100pt}
\input{fig}

then the code in fig.tex will know that \plotwidth has been set.

Let's work out an example. Your fig.tex file contains

\ifdim\plotwidth=-1000pt
  \setlength{\figwidth}{0.9\linewidth}
\else
  \setlength{\figwidth}{\plotwidth}
\fi
\includegraphics[width=\figwidth]{somefigure}

(the parameter will be \figwidth instead of \linewidth, for greater flexibility).

Your main file can be

\documentclass{article}

\newlength{\plotwidth}
\setlength{\plotwidth}{-1000pt}
\newlength{\figwidth}

\begin{document}

\begin{figure}
\input{fig.tex}
\caption{Test (this figure is 90\% of the line width)}
\end{figure}

\begin{figure}
\setlength{\plotwidth}{100pt}
\input{fig.tex}
\caption{Test (this figure is 100pt wide)}
\end{figure}

\end{document}
Related Question