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.

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
\newcommand{\foo}{old header}

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

% In user tex file
\renewcommand{\foo}{new header}

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

This produces page 1 page 2

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?

share|improve this question
    
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 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 at 18:36
    
You should fix a head height that suffices for the tallest header. –  egreg Feb 2 at 18:51
add comment

1 Answer

up vote 7 down vote accepted

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}
    

    inside your document.

MWE:

\documentclass{article}
\usepackage{fancyhdr}

% In custom document class
\newcommand{\foo}{old header}

\newsavebox\mybox % declare it outside

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

\begin{document}
    Page 1
    \newpage
    \renewcommand{\foo}{new header}
    \pagestyle{mystyle}
    Page 2
\end{document} 

Output:

enter image description here

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}{}
\newcommand{\newheader}[1]{%
  \renewcommand{\foo}{#1}%
  \pagestyle{mystyle}%
}

\newsavebox\mybox % declare it outside

\fancypagestyle{mystyle}{
    \fancyhf{}
    \sbox\mybox{\foo}
    \chead{\usebox\mybox}
}
\newheader{old header}

\begin{document}
    Page 1
    \newpage
    \newheader{new header}
    Page 2
\end{document} 
share|improve this answer
add comment

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.