如何建立一個普通的 TeX 宏,根據是否從 \item 中呼叫它來執行不同的操作?

如何建立一個普通的 TeX 宏,根據是否從 \item 中呼叫它來執行不同的操作?

我想創建一個行為不同的宏,這取決於是否從 內部調用它\item,例如

\def\mymacro{\if<INSIDE_ITEM> do this \else do that\fi}

這是一個可以使用它的範例:

This is how my macro performs outside an item: {\mymacro}

\item{1}. And this is how it performs inside an item: {\mymacro}

為了進行比較,類似的情況涉及宏,它們根據是否從數學模式中調用而執行不同的操作,例如:

\def\anothermacro{\ifmmode do this \else do that\fi}

問題是,與正常段落相比,項目的環境似乎沒有任何大的差異。有任何想法嗎?

PS:我真的很有興趣清楚的TeX(與 LaTeX 相對)!此外,不需要任何額外軟體包的簡單解決方案將受到高度讚賞!

答案1

類似什麼卡波哈建議在一個評論,但進行了一個小的安全檢查:我重新定義\item為使用新的長度\itemindent而不是\parindent,並將前者設為\parindentplus 1sp。這在光學上是無法區分的(只有幾奈米),但\ifdim\hangindent=\itemindent我想說,測試導致誤報的可能性相對較小。

\newdimen\itemindent
\itemindent\parindent
\advance\itemindent1sp
% the plain TeX definition is basically:
% \def\item{\par\hangindent\parindent\textindent}
\def\item{\par\hangindent\itemindent\textindent}
\def\mymacro{\ifdim\hangindent=\itemindent(INSIDE)\else(OUTSIDE)\fi}

Text text text text text text text text text \mymacro
\item{x} bla bla bla bla \mymacro
\item{x} bla bla bla bla \mymacro

Text text text text text text text text text \mymacro
\bye

在此輸入影像描述

答案2

根據 cabohah 在評論中的建議:

\newif\ifinitem
\initemfalse
\def\mymacro{\ifinitem hi!\else bye\fi}
\def\item{\par\initemtrue\hang\textindent}
\let\oldpar\par
\def\par{\initemfalse\oldpar}
This is how my macro performs outside an item: {\mymacro}  

\item{1}. And this is how it performs inside an item: {\mymacro}

Now we are no longer inside the item: {\mymacro}
\bye

在此輸入影像描述

相關內容