Here is a solution based on atbegshi
and answers
packages.
The idea is to use answers
that write contents of theorem, lemma to an external file (mtfile.tex), discard all pages (all contents of the main file https://tex.stackexchange.com/a/267555/71471) and then use the external file to output only theorems.
We use a newif test \onlytrue
for only theorem and \onlyfalse
for normal use.
Auxiliary environments used to save the original definitions of theorem
and lemma
.
\newtheorem{xtheorem}{Theorem}
\newtheorem{xlemma}{Lemma}
Complete code.
\documentclass{article}
\usepackage{lipsum}
\usepackage{atbegshi}
\newcommand{\handlethispage}{}
\AtBeginShipout{\handlethispage}
\newtheorem{xtheorem}{Theorem}
\newtheorem{xlemma}{Lemma}
\newif\ifonly % uncomment next line
%\onlytrue
\ifonly
\usepackage{answers}
\Newassociation{lemma}{mtlemma}{mtfile}
\Newassociation{theorem}{mttheorem}{mtfile}
\renewenvironment{mttheorem}{\begin{xtheorem}}{\end{xtheorem}}
\renewenvironment{mtlemma}{\begin{xlemma}}{\end{xlemma}}
\Opensolutionfile{mtfile}
\AtBeginDocument{%
\let\handlethispage\AtBeginShipoutDiscard}
\AtEndDocument{%
\clearpage\pagenumbering{arabic}
\let\handlethispage\relax
\Closesolutionfile{mtfile}
\Readsolutionfile{mtfile}}
\else
\newenvironment{theorem}{\begin{xtheorem}}{\end{xtheorem}}
\newenvironment{lemma}{\begin{xlemma}}{\end{xlemma}}
\fi
\begin{document}
\lipsum[1-12]
\begin{lemma}
this is some bla bla in lamma
\end{lemma}
\lipsum[1-12]
\begin{theorem}
some bla bla in lamma
\end{theorem}
\lipsum[1-12]
\begin{lemma}
some bla bla in lamma
\end{lemma}
\end{document}