為什麼當我使用 \NewDocumentEnvironment 時 tikz 會抱怨?

為什麼當我使用 \NewDocumentEnvironment 時 tikz 會抱怨?

這是代碼:

\documentclass{article}
\usepackage{tikz}
\NewDocumentEnvironment{foo}{b}{hello}{}
\AddToHook{env/foo/before}{\obeylines\obeyspaces}
\begin{document}
\begin{tikzpicture}
\node (v) {hi};
\end{tikzpicture}
\begin{foo}
first
second
\end{foo}
\begin{tikzpicture}
\node (v) {hi};
\end{tikzpicture}
\end{document}

我收到這個奇怪的消息:

! Package tikz Error: A node must have a (possibly empty) label text.

See the tikz package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.14 \node
           (v) {hi};

怎麼了?

答案1

正如所注意到的作者:@David Carlisle 的評論,你的catcode混亂將在\end{foo}...之後持續存在texdoc lthooks

在此輸入影像描述

所以你可能想使用begin鉤子:

\documentclass{article}
\usepackage{tikz}
\NewDocumentEnvironment{foo}{b}{hello}{}
\AddToHook{env/foo/begin}{\obeylines\obeyspaces}
\begin{document}
\begin{tikzpicture}
\node (v) {hi};
\end{tikzpicture}
\begin{foo}
first
second
\end{foo}
\begin{tikzpicture}
\node (v) {hi};
\end{tikzpicture}
\end{document}

在此輸入影像描述

相關內容