The following example patches the internal macro of \newtheorem (amsthm version) to collect the theorem environment name in a list, then redefines those environments at the beginning of document. Here the code execution order is significant, you must firstly patch the internal, then use \newtheorem, at last redefine theorems.
\documentclass{article}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{etoolbox}
%% codes added before every occurrances of \newtheorem
\makeatletter
% init a comma-seperated list
\let\thm@list@empty
% patch @xnthm, collect theorem env names in \thm@list
% This patch must be used before any use of \newtheorem.
\patchcmd@xnthm
{\global@xp\let}
{\g@addto@macro\thm@list{,#2}\global@xp\let}
{}{\fail}
% patch every theorem env defined before \begin{document}
\AtBeginDocument{
% strip comma from left
\def\lstrip@comma,#1@nil#2{\def#2{#1}}
\expandafter\lstrip@comma\thm@list@nil\thm@list
% patch theorem envs
@for@tempa:=\thm@list\do{%
% backup
\csletcs{@tempa @backup}{@tempa}%
\csletcs{end@tempa @backup}{end@tempa}%
% redefine
\edef\temp{%
\noexpand\renewenvironment{@tempa}
{\noexpand\begin{samepage}\noexpand\begin{@tempa @backup}}
{\noexpand\end{@tempa @backup}\noexpand\end{samepage}}%
}
\temp
}
}
\makeatother
\newtheorem{thm}{Theorem}[section]
\newtheorem{defn}[thm]{Definition}
\begin{document}
\section{title}
\begin{thm}
content
\end{thm}
\begin{defn}
content
\end{defn}
\begin{thm}[title]
content
\end{thm}
\begin{defn}[title]
content
\end{defn}
\end{document}
PS: From document source2e, section 17.4, in LaTeX2e \samepage is no longer supported. So I'm not sure if it is recommended to use samepage environment in 2020. Normally you can use minipage environment, see Unbreakable block.
Update on 2023-05-27: The upcoming LaTeX2e 2023-06-01 release confirms \samepage is still supported. The sentence read in source2e.pdf
Since in 2e |\samepage| is no longer supported, ...
is deleted. Related links
- commit
ecf19e5a (Gh1022 (#1023), 2023-03-22)
- pull request #1023 Gh1022
- issue #1022 Resetting \predisplaypenalty in \samepage
- commit
a7187bb5 (update some documentation around "samepage"; it is still (reluctantly) supported after all [ci skip], 2023-05-26)
\newtheoremis defined. – muzimuzhi Z Jun 08 '20 at 06:38amsthm, but then I haveamsmathandamssymbtoo (Not sure how they work). – Carbonard Jun 08 '20 at 14:30amsmathworks withamsthmto control placement of equation numbers and the qed markere, but is neither related otherwise nor necessary for theorems.amssymbis totally separate and unrelated. – barbara beeton Oct 27 '22 at 17:52\needspace{4\baselineskip}before theorem-class objects. – barbara beeton Oct 27 '22 at 17:59