Different \section for odd and even pages

I would like to make the section titles look different on even and odd pages. I have the following MnWE with the trivial approach. The problem is that you don't know that your section header gets moved to the next page. I even tried to check the oddity of the page number after the section is typeset, but with no success (that is the "After:" text).

\documentclass[a4paper,twoside]{article}

\makeatletter
\let\X@section\section
\def\section#1{%
\ifodd\c@page\relax
\X@section{ODD: #1}%
\else
\X@section{EVEN: #1}%
\fi
\par After:\ifodd\c@page\relax odd\else even\fi \par % <-- for testing purposes
}
\makeatother

\usepackage{lipsum}

\begin{document}

\section{Test section} \lipsum[1]
\section{Test section} \lipsum[1]
\section{Test section} \lipsum[1]
\section{Test section} \lipsum[1]
\section{Test section} \lipsum[1]

\end{document}

-

Try using the titlesec package. The command \titleformat included in it can take an page=odd or page=even option to give different formatting depending on even or odd page numbers, just like you want.

\usepackage{titlesec}
\titleformat{name=\section,page=odd}{}{ODD:}{.5em}{}
\titleformat{name=\section,page=even}{}{EVEN:}{.5em}{}


in the preamble should give what you want.

-
I use titlesec anyways (not in MWE, in the real document), but I wasn't aware of this option and I'll try it later. – yo' Mar 7 '12 at 16:15
Perfect! Thanks – yo' Mar 7 '12 at 18:07

The ifoddpage package does this check for you.

Basically you need to use the \label \pageref mechanism to get reliable page number (and correct in the next run of latex) but ifoddpage hides the messy details.

-
As mentioned in the ifoddpage documentation, it was inspired by changepage, which also provides \ifoddpage. – Werner Mar 7 '12 at 17:36

Even though I used another solution, I made my own way to do that for float captions, which works pretty well (and the ifoddpage package doesn't solve it). It requires the Table of Contents to be included in the document and to be latexed 3 times. It doesn't solve the optional argument for \caption.

\def\l@xfloatx#1#2{
\ifodd#2\relax
\protected@write\@auxout{}{%
\string\@setxflxodd{\string\@xflxoddtrue}
}
\else
\protected@write\@auxout{}{%
\string\@setxflxodd{\string\@xflxoddfalse}
}
\fi
}
\newif\if@xflxodd
\def\@writexflxodd{%
}
\newcounter{xflxoddpre}
\def\@setxflxodd#1{
\stepcounter{xflxoddpre}
\expandafter\gdef\csname @xflxodd@\roman{xflxoddpre}\endcsname{#1}
}
\newcounter{xflxodd}
\def\@usexflxodd{
\stepcounter{xflxodd}
\ifodd\c@page\relax
\@xflxoddtrue
\else
\@xflxoddfalse
\fi
\csname @xflxodd@\roman{xflxodd}\endcsname%
}
\let\x@caption\caption
\def\caption#1{\@writexflxodd\@usexflxodd\if@xflxodd odd\else even\fi\ #1}

-