根據布林值在出貨時執行簡單指令

根據布林值在出貨時執行簡單指令

我只使用lualatex,但也許這是一個一般的 LaTeX 問題。假設使用 TeXlive 2023 或更高版本,因為不需要向後相容。

我已經查看了atbegshi和其他一些文檔,但它們沒有滿足我的需要,或者比必要的複雜得多。我還看到,不久前,有人問了類似的問題,但沒有有用的答案: 使用shipout hooks來操縱全域狀態

情況:我有兩個命令,我稱之為\foo\unfoo。該\foo命令包含\clearpage在其頂部,因此我無需擔心\foo排版時出現的位置。該\unfoo命令以 結束\clearpage

如果一個頁面有\foo,那麼同一個頁面也一定有\unfoo。如果使用者在頁面發布\unfoo之前未能寫入\foo,則會出現錯誤。我知道如何編寫合適的錯誤訊息,停止編譯。我不需要儲存、編輯、丟棄或以其他方式操作頁面內容。

我的問題:有沒有一種簡單的方法可以使用\shipout鉤子(或類似的東西)來做到這一點?雖然atbegshi看起來應該是有能力的,但那個包包有很多事情,這讓我很緊張。

微量元素:

\documentclass{article} % Compile with lualatex.
\usepackage{fontspec}
\newif\ifusedfoo
\def\foo{\clearpage Hello.\par\usedfootrue}
\def\unfoo{Goodbye.\par\usedfoofalse\clearpage}

% \WhenPageShips{ % This is what I need. I know how to create an error, instead of typeout.
%   \ifusedfoo
%     \typeout{EEEEK. The page with \string\foo\space did not have \string\unfoo.}
%   \fi
% }

\begin{document}
Welcome.\par
\foo
No problem here.\par
\unfoo
\foo % With too many lines on that page, causes problem:
x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\
x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\
x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\
x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\par
% Whether or not there is a later \unfoo, does not matter.
Moving right along\par
\clearpage
This is too late.\par
\unfoo
I cannot wait until this far in the document.\par
\end{document}

另外:我不想aux為此使用文件。程式碼不會出現在任何複雜的內容中(例如參考書目、目錄等)。就在正在運行的文字中。

編輯:明確指出應該快速偵測到問題,而不是在文件的後面。

EDIT2:接受的解決方案適用於我的具體情況但在一般情況下可能不起作用。看評論。

答案1

\documentclass{article} % Compile with lualatex.
\usepackage{fontspec}
\newif\ifusedfoo
\def\foo{\clearpage Hello.\par\usedfootrue}
\def\unfoo{Goodbye.\par\usedfoofalse\clearpage}

\AddToHook{shipout/before}[rallg]{%
% \WhenPageShips{ % This is what I need. I know how to create an error, instead of typeout.
  \ifusedfoo
    \typeout{EEEEK. The page with \string\foo did not have \string\unfoo.}
  \fi
}

\begin{document}
Welcome.\par
\foo
No problem here.\par
\unfoo
\foo % With too many lines on that page, causes problem:
x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\
x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\
x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\
x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\par
% Whether or not there is a later \unfoo, does not matter.
\end{document}

這會輸出最後兩頁的訊息,因為這兩頁都沒有\unfoo.如果您想避免第二種情況,則需要適當管理條件邏輯。

相關內容