# Theorem, corollary, equation numbering in amsbook

I am using the amsbook class and amsthm package as follows :

\theoremstyle{plain} %% This is the default, anyway
\newtheorem{thm}[equation]{Theorem}
\newtheorem{cor}[equation]{Corollary}
\newtheorem{lem}[equation]{Lemma}
\newtheorem{prop}[equation]{Proposition}

\theoremstyle{definition}
\newtheorem{defn}[equation]{Definition}

\theoremstyle{remark}
\newtheorem{rem}[equation]{Remark}
\newtheorem{ex}[equation]{Example}
\newtheorem{exer}[equation]{Exercise}
\newtheorem{notation}[equation]{Notation}
\newtheorem{terminology}[equation]{Terminology}
%etc


and I would like all theorems, corollaries etc being numbered as

• partnumber.chapternumber when they are inside a chapter and not in any section, subsection or "lower-level" sub-subs-...-subsections
• partnumber.chapternumber.sectionnumber when they are inside a section and not in any subsection, subsection or "lower-level" sub-subs-...-subsections
• etc

I would like the same for equations but I have no idea how to do it.

Please, don't reset chapter numbers with parts; you should also think twice before bothering your readers with this complicated numbering scheme.

\documentclass[openany]{amsbook}
\usepackage{xparse}

\newtheorem{thm}[equation]{Theorem} % one suffices for the example
\counterwithin*{equation}{subsubsection}

\renewcommand{\theequation}{%
\printuptozero{chapter,section,subsection,subsubsection}{equation}%
}

\ExplSyntaxOn
\NewExpandableDocumentCommand{\printuptozero}{mm}
{
\clist_map_function:nN { #1 } \ujs_printuptozero:n
\arabic{#2}
}

\cs_new:Nn \ujs_printuptozero:n
{
\int_compare:nTF { \value{#1}>0 } { \arabic{#1}. } { \clist_map_break: }
}
\ExplSyntaxOff

\begin{document}

\chapter{Test}

\begin{thm}
test
\end{thm}

$$0=0$$

\section{Test}

\begin{thm}
test
\end{thm}

$$0=0$$

\subsection{Test}

\begin{thm}
test
\end{thm}

$$0=0$$

\subsection{Test}

\begin{thm}
test
\end{thm}

$$0=0$$

\chapter{Test}

\begin{thm}
test
\end{thm}

$$0=0$$

\section{Test}

\begin{thm}
test
\end{thm}

$$0=0$$

\end{document}


With \counterwithin*{equation}{subsubsection} we subordinate equation to every section level including and above subsubsection.

Next I redefine \theequation to scan successively the value of the sectional counters; if the value is positive, the number and a period are printed; otherwise the loop is stopped. At the end the value of equation is printed.

The openany option has been used just to make the example fit in two pages and have a single picture of the output.