# Reference to sidenote

I am trying to create a scholia book document using the sidenotes package.

When I refer to the second sidenote the text is "sidenote 1.1.2" but for the first sidenote what appears is "sidenote 1.1". How to fix this bug?

Here is a compact working code:

\documentclass[12pt]{book}

\usepackage{float}
\usepackage{caption}

\usepackage{sidenotes}

\usepackage[outer=7cm]{geometry}

\usepackage{chngcntr}
\counterwithin{sidenote}{section}
\makeatletter
\renewcommand{\thesidenote}{\@arabic{\numexpr\value{chapter}\relax}.\@arabic{\numexpr\value{section}\relax}.\@arabic{\numexpr\value{sidenote}+1\relax}}
\makeatother

\begin{document}

\chapter{Example}

\section{Cake}

This is an example.\sidenote{First sidenote.\label{first}} \\
This is second\sidenote{Second sidenote.\label{second}} \\
More text... \\
...
... \\
Then I refer to sidenote \ref{first} and then to sidenote \ref{second}.

\end{document}


The code compiles but the last sentence appers as

Then I refer to sidenote 1.1 and then to sidenote 1.1.2.

The problem is that the sidenotes package increases the sidenote counter at the end, so the referencees are only set up after the sidenote already ended. This can be fixed by changing \sidenotetext to do \refstepcounter before setting the sidenote:

\makeatletter
\ExplSyntaxOn
\RenewDocumentCommand \sidenotetext { o o +m }
{
\IfNoValueOrEmptyTF{#1}
{
\refstepcounter{sidenote}
\@sidenotes@placemarginal{#2}{\textsuperscript{\thesidenote}{}~#3}
}
{
\@sidenotes@placemarginal{#2}{\textsuperscript{#1}~#3}
}
}
\ExplSyntaxOff
\makeatother


Then \sidenote has to be changed too to avoid printing the wrong number in the text: In the original code the mark is set first(with the old counter value), we want to add the note (and increase the counter) first:

\RenewDocumentCommand \sidenote { o o +m }
{
\@sidenotes@multichecker
\sidenotetext[#1][#2]{#3}
\sidenotemark[#1]
\@sidenotes@multimarker
}


This also replaces your \renewcommand\thesidenote, so we get

\documentclass[12pt]{book}

\usepackage{float}
\usepackage{caption}

\usepackage{sidenotes}

\usepackage[outer=7cm]{geometry}

\usepackage{chngcntr}
\counterwithin{sidenote}{section}
\makeatletter
\ExplSyntaxOn
\RenewDocumentCommand \sidenote { o o +m }
{
\@sidenotes@multichecker
\sidenotetext[#1][#2]{#3}
\sidenotemark[#1]
\@sidenotes@multimarker
}
\RenewDocumentCommand \sidenotetext { o o +m }
{
\IfNoValueOrEmptyTF{#1}
{
\refstepcounter{sidenote}
\@sidenotes@placemarginal{#2}{\textsuperscript{\thesidenote}{}~#3}
}
{
\@sidenotes@placemarginal{#2}{\textsuperscript{#1}~#3}
}
}
\ExplSyntaxOff
\makeatother

\begin{document}

\chapter{Example}

\section{Cake}

This is an example.\sidenote{First sidenote.\label{first}} \\
This is second\sidenote{Second sidenote.\label{second}} \\
More text... \\
...
... \\
Then I refer to sidenote \ref{first} and then to sidenote \ref{second}.

\end{document}