5

What is the syntax for storing some width in order to change it temporarily and then restore to the original?

Example:

%save length here
\setlength\somewidth{\textwidth}
some text
\begin{someenvironment}
more text
\end{someenvironment}
%restore length here
3
  • 2
    Put a {...} pair around your whole instruction or set the with inside your environment.
    – user31729
    Sep 3, 2016 at 19:03
  • Can I do something like \setlength\anotherlength{\somelength} then reverse that? Or do I need to somehow define \anotherlength first?
    – ajeh
    Sep 3, 2016 at 19:03
  • 1
    Lengths have to be defined first anyway, but you don't need to use this explicit setting. Just use groups!
    – user31729
    Sep 3, 2016 at 19:09

1 Answer 1

6

Lengths are group safe, i.e. any change inside a {...} will be restricted to that group, unless explicitly made global. For example, lengths being set in tabular cell are changed in that cell only, in the next cells the value is not affected by this!

Either you place a {...} (or a \begingroup...\endgroup pair) or use the setting inside of the environment (if possible) -- environments form groups as well.

Third possibility: Define a scratch width with \newlength and either say \setlength{\helperwidth}{\somewidth} or the more TeX - like \helperwidth=\somewidth or even shorter: \helperwidth\somewidth, if really needed.

The definition of an extra length (or using another one that is not needed at the moment) has its advantages if the old definition ('value') must be used for some extra calculations etc.

The 'right' method depends on the actual requirements.

\documentclass{article}

\newlength{\somewidth}
\newlength{\helperwidth}% Just for fun

\newenvironment{someenvironment}{%
Width is \the\somewidth%

}{}

\begin{document}

\setlength{\somewidth}{\textwidth}
\begin{someenvironment}
more text
\setlength\somewidth{0.5\textwidth}
Now width is \the\somewidth%

\end{someenvironment}
Outside the width is \the\somewidth

Or using a group:

{%
\setlength{\somewidth}{0.5\textwidth}
\begin{someenvironment}
Now width is \the\somewidth%

\end{someenvironment}
}%
Outside of the group the width is \the\somewidth

\helperwidth=\somewidth
% Or \helperwidth\somewidth
\setlength\somewidth{0.75\textwidth}
\begin{someenvironment}
Now width is \the\somewidth%

\end{someenvironment}
Outside of the environment the width is \the\somewidth
\setlength{\somewidth}{\helperwidth}

Now restoring the width: \the\somewidth



\end{document}

enter image description here

The same group feature is true for TeX count registers -- they are group safe, however LaTeX counters are not group safe!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .