# Wrong box placement depending odd page

In a two sided memoir document, I'm trying to add a box with an offset in the margin, depending if \c@page is odd or not.

It almost works but when this box appears near a page break. In the MWE below, Écriture on p. 2 should be on the left margin, while Histoire on p. 3 should be on the opposite side.

How to get the correct page number to print the box at the right place?

% !TeX TS-encoding = utf8
% !TeX TS-spellcheck = fr_FR
% !BIB TS-program = biber
% !TeX TS-program = lualatex

\documentclass[12pt,a4paper]{memoir}

\usepackage[french]{babel}
\usepackage{xparse}

\RequirePackage{tcolorbox}
\tcbuselibrary{most}

\makeatletter
\NewDocumentCommand{\matiere}{mO{#1}go}{%
\vskip \onelineskip
\ifodd\thepage
\hspace{\linewidth+6em}\makebox[0pt][r]{\tcbox[
tcbox raise base,
boxrule=0.2mm,
fontupper=\sffamily\bfseries\LARGE,
nobeforeafter,
colback=blue!3,colframe=blue!50,
]{#1 p.~\thepage}}
\else
\noindent\hspace{-6em}\makebox[0pt][l]{\tcbox[
tcbox raise base,
boxrule=0.2mm,
fontupper=\sffamily\bfseries\LARGE,
nobeforeafter,
colback=blue!3,colframe=blue!50,
]{#1 p.~\thepage}}
\fi
\IfValueTF{#3}{\nobreak\section*{#3}%
%        \index[#2]{\thepart \thechapter @#3}%
\IfValueT{#4}{\nobreak #4}
\sectionmark{#1}
\vskip 2.3ex \@plus .2ex
}
\makeatother

\usepackage{lipsum}

\begin{document}

\chapter{chapitre}
\lipsum[1-2]

\matiere{Écriture}[Ecriture]
\lipsum[3-4]

\matiere{Géographie}[Geographie]{Les fleuves}
\lipsum[5]

\matiere{Histoire}
\lipsum[6-9]

\clearpage
\tableofcontents

\end{document}

• you can never reliably test \thepage (or better \value{page} within the document you need to set a \label and then test the \pagref next time (see the zref package for some tests that simplify that a bit) – David Carlisle Mar 31 '18 at 11:44
• Since it is memoir, see its build in facilities for checking the page. I don't have the manual with me, but look up strictpagecheck – daleif Mar 31 '18 at 11:47
• since it's memoir do as @daleif says :-) – David Carlisle Mar 31 '18 at 11:58
• Time to look at the manual and go deeper here for example, I turn it as an answer. Obviously, @daleif can make his own answer, I'll accept it! – NBur Mar 31 '18 at 12:07

Thanks to @daleif's hint and this answer it seems to work correctly now.

I just changed the line

\ifodd\thepage


by

\strictpagechecktrue
\checkoddpage
\ifoddpage

• You can place strict... In the preamble, but yes this is the idea. It implements the label feature David mentioned. – daleif Mar 31 '18 at 12:51