# \savebox in page header with redefinable commands

I'm making a document class with some redefinable commands for page headers. However, I'm running into the following issue:

\documentclass{article}
\usepackage{fancyhdr}

% In custom document class

\fancypagestyle{mystyle}{
\fancyhf{}
\newsavebox\mybox
\sbox\mybox{\foo}
}
\pagestyle{mystyle}

% In user tex file

\begin{document}
Page 1
\newpage
Page 2
\end{document}


This produces

How can I allow the user to redefine these commands, but still use \sbox so I can use \wd inside the page header for positioning purposes?

-
Be careful that fancyhdr wants the header height to be the same across the document; if it finds \headheight is not sufficient to contain the header, it changes it from the next page, which could lead to various problems. – egreg Feb 2 '14 at 12:01
@egreg Thanks for the tip. Where is this documented? What should one do if differently-sized headers are desirable? – jtbandes Feb 2 '14 at 18:36
You should fix a head height that suffices for the tallest header. – egreg Feb 2 '14 at 18:51

You can proceed in this way.

• First of all, declare the new box outside the command \fancypagestyle
• When you want to change the header, issue both the commands

\renewcommand{\foo}{new header}
\pagestyle{mystyle}


MWE:

\documentclass{article}
\usepackage{fancyhdr}

% In custom document class

\newsavebox\mybox % declare it outside

\fancypagestyle{mystyle}{
\fancyhf{}
\sbox\mybox{\foo}
}
\pagestyle{mystyle}

\begin{document}
Page 1
\newpage
\pagestyle{mystyle}
Page 2
\end{document}


Output:

Since it is supposed to go in a document class, I suggest you to define a new command \newheader and use it in this way:

\documentclass{article}
\usepackage{fancyhdr}

% In custom document class
\newcommand{\foo}{}
\renewcommand{\foo}{#1}%
\pagestyle{mystyle}%
}

\newsavebox\mybox % declare it outside

\fancypagestyle{mystyle}{
\fancyhf{}
\sbox\mybox{\foo}