\unprotect

%D \macros{setupsubformulas}

\def\setupsubformulas
  {\dodoubleargument\getparameters[\??sf]}

\definenumber
  [parentformula]
  [\c!text=parentformula,
   \c!way=\@@fmway]

\def\subformulaconversion#1%
  {\getnumber[parentformula]%
   \@@sfseparator%
   \convertnumber{\@@sfconversion}{#1}}

\defineconversion[subformulaconversion][\subformulaconversion]

%D \macros{startsubformulas}

\def\startsubformulas%
  {\bgroup
   \incrementnumber[\v!formula]
   \expanded{\setupnumber[parentformula][start={\rawnumber[\v!formula]}]}
   \savenumber[\v!formula]
   \setupformulas[conversion=subformulaconversion,way=\@@sfway]
   \resetnumber[\v!formula]}

\def\stopsubformulas%
  {\restorenumber[\v!formula]
   \resetlastlinewidth
   \nonoindentation
   \dochecknextindentation{\??sf}%
   \egroup
   \dorechecknextindentation} % here ?

% I have just copied the indentation checking from \stopformulas. I am not
% sure on how this works.


\setupsubformulas
  [\c!way=\v!by\v!text,
   \c!sectionnumber=\v!no,
   \c!conversion=\v!character,
   \c!separator=\@@fmseparator,
   \c!indentnext=\@@fmindentnext]

\protect

%D The test cases

\startbuffer
\placeformula \startformula
  a^2 + b^2 = c^2
\stopformula
\stopbuffer

\startsetups[test]
\dorecurse{3}{\getbuffer}

Lets start subformulas
\startsubformulas
  \dorecurse{3}{\getbuffer}
\stopsubformulas

Also works inside alignments
\startsubformulas
\placeformula \startformula \startalign
  \NC A \EQ B + C \NR[first]
  \NC D \EQ E + F \NR[+]
\stopalign \stopformula
\stopsubformulas

Notice that in \in formula[first] we get the correct reference.

\dorecurse{3}{\getbuffer}
\stopsetups


\starttext
\section{Default}
\setups[test]\page

\section{Section}
\setupformulas[way=bysection]
\setups[test]\page

\section{Roman}
\setupsubformulas[conversion=romannumerals]
\setups[test]\page

\section{Separator}
\setupsubformulas[separator=-]
\setups[test]\page

\stoptext
