Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.
\documentclass{article}
\newsavebox{\mybox}
\begin{document}


\fbox{%
\begin{minipage}{5cm}
\sbox{\mybox}{from first minipage}
\usebox{\mybox}
\end{minipage}%
}

%nothing rendered
\fbox{\usebox{\mybox}}

\vspace{3cm}

\fbox{%
\begin{minipage}{5cm}
%nothing rendered
\usebox{\mybox}
\end{minipage}%
}

\end{document}
share|improve this question

1 Answer 1

up vote 7 down vote accepted

There is no output because of TeX's scoping rules. This can be demonstrated by a simpler example and using \def rather than boxes.

\begin{minipage}{3cm} 
  \def\fortytwo{42}
  \fortytwo
\end{minipage}

This will typeset 42 within the minipage, but if you try and use \fortytwo outside the minipage you will get an error `Undefined control sequence'.

TeX's scoping rules work similarly to local and global scope in other programming languages. However in TeX it is a bit different. Try this:

\documentclass{article}
\begin{document}
\def\fortytwo{42}
\begin{minipage}{2cm} 
      \fortytwo
      \def\fortytwo{43}
      \fortytwo
    \end{minipage}
\fortytwo
\end{document}

As you will observe once you return to the outside of a macro, the old definition is retained, so in the example above you will get a 43 within the minipage but 42 outside it!

Using boxes, we can demonstrate this:

\documentclass{article}
\begin{document}

\newsavebox{\mybox}
\savebox{\mybox}{Outside scope}

\begin{minipage}{3cm}
  \sbox{\mybox}{from first minipage}
  \usebox\mybox
\end{minipage}

\usebox{\mybox}

\end{document}

This will typeset from first minipage within the minipage and Outside scope outside the minipage.

share|improve this answer
6  
A good answer, but I would also add how to fix this: prefix the \def or the \sbox with \global; in this case, \global\sbox{\mybox}{from first minipage}. (And for \def, this becomes \gdef.) –  Antal S-Z Dec 17 '10 at 5:48
1  
\usebox expands to \leavevmode\copy#1\relax. Your final example is flawed because you didn't use \sbox so the box was always empty. –  TH. Dec 17 '10 at 6:00
    
Also, I think you wanted to use \newsavebox (although the difference is fairly minor). –  TH. Dec 17 '10 at 6:02
    
@TH Thanks for pointing the flaw and I have edited for completeness. ` –  Yiannis Lazarides Dec 17 '10 at 6:30
1  
@xport: The easiest may be to adapt the definition of the lrbox environment to become \newenvironment {glrbox} [1] {\global\setbox#1\hbox\bgroup \@endpefalse \color@setgroup \ignorespaces} {\unskip\color@endgroup\egroup}. I'm not sure about colors, though. –  Bruno Le Floch May 29 '11 at 14:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.