
是的,你沒有看錯標題!
我想忽略一切那是在我創建文件\begin{document}
之間。我以為這會很簡單,只需使用\end{document}
\input
environ
包裹:
\RenewEnviron{document}{}
但事實證明這並不那麼容易。下面的 MWE 產生正確的結果:
但只有評論完好無損。如果您取消註解註解行,則最終結果為:
LaTeX 錯誤:\env@document@save@env 未定義
有趣的是,忽略這個錯誤可以繼續下去,並且仍然得到正確的結果。 :-)
筆記:
- 我意識到序言中可能還有其他內容,所以這絕對不是一個通用的解決方案。對於我需要此功能的地方,序言僅有的有
\documentclass
和兩個\input
/\usepackage
加載.sty
所需的所有文件,因此這足以滿足我的需求。
代碼:
\documentclass{article}
\usepackage{environ}
\usepackage{standalone}
\newtoks{\MyToken}
\usepackage{filecontents}
\begin{filecontents*}{foo.tex}
\documentclass{standalone}
\usepackage{MyStandardPackages}
\MyToken={foo}
% \begin{document}
% lots of text here
%
% \SetSomeVarable{\SomeVar}{Some Value}
%
% \begin{SomeEnvironment}
% lots more stuff here as well
% \end{SomeEnvironment}
% \end{document}
\end{filecontents*}
\MyToken={XXX}
\newcommand{\DisablePreamble}{%
\renewcommand{\documentclass}[2][]{}% remove def'n of \documentclass
\renewcommand{\usepackage}[2][]{}% ignore any \usepackage{}
% \RenewEnviron{document}{}% Ignore everything within the "document" environment.
}%
\newcommand*{\ExtractMyToken}[1]{%
\begingroup% What happens in the group stays in the group!
\DisablePreamble%
\input{#1}%
\global\MyToken=\expandafter{\the\MyToken}%
\endgroup%
}%
\begin{document}
MyToken=\the\MyToken
\ExtractMyToken{foo}
MyToken=\the\MyToken
\end{document}
答案1
這是一個常見問題environ
,我解決這個問題的方法是定義那些有問題的命令:
\makeatletter
\providecommand{\env@document@save@env}{}% To keep environ happy
\providecommand{\env@document@process}{}%
\RenewEnviron{document}{}% Ignore everything within the "document" environment.
\makeatother
實現你所追求的目標的一種快速而骯髒的方法是使用
\renewcommand{\document}{\endgroup\endinput}
\input
一旦到達 ,就會終止文檔的讀取\begin{document}
。
答案2
我(本地)定義
\def\begin#1{\endinput}`
所以文件在那一點停止,或者也許(我真的不明白你的用例
\def\documentclass[#1]#2{\endinput}
甚至更早停止(但如果你這樣做,只是不輸入文件會更容易)