如何使下劃線在環境中處於活動狀態,但在數學模式中保留其原始用途?

如何使下劃線在環境中處於活動狀態,但在數學模式中保留其原始用途?

我正在嘗試創建一個格式化速記包。我想使用下劃線來分隔帶下劃線的文字範圍,如下所示

some text _underlined text_ more text

只需使下劃線處於活動狀態即可定義宏

\catcode`_=\active%
\def_#1_{\underline{1}}%

不可行,因為這顯然與數學模式下使用下劃線相衝突。

可以兩者兼得嗎?如果是這樣,怎麼辦?

答案1

你可以這樣做,但最好不要這樣做。確實如此,不僅因為下劃線被認為是排版中的不良做法。你一無所獲。

\documentclass{article}

\def\ustextormath{\ifmmode\expandafter_\else\expandafter\usunderline\fi}

\begingroup\lccode`~=`_
\lowercase{\endgroup
  \def\usunderline#1~{\underline{#1}}
  \protected\def~{\ustextormath}
}

\AtBeginDocument{\catcode`\_=\active}

\begin{document}

\section{Some _underlined_ text and $a_1$}

some text _underlined text_ more text and $a_1$

\end{document}

在此輸入影像描述

答案2

晚上好,如果符合您的需求,請嘗試。從技術上講,在我的範例中,在排版過程中,下劃線是類別 8 中的活躍字元。我在文字模式的組中使用了\sb數學模式和關閉\it( ) 的條件。離開群組時自動返回\itshape\myconditionfalse

感謝您提供有用的評論和提示,egreg、alexis 和 FK82!好玩!

\catcode`\_=13% Or use \active; from category 8.
\def\false{false}\def\mycondition{false}%
\def_{\ifmmode\sb
  \else
    \ifx\mycondition\false
      \begingroup\def\mycondition{true}\it%\itshape for LaTeXists
        \else
      \endgroup
    \fi
  \fi}
Text _more of text_ ToDo $abc_i^2 math$ even more _text_ etc.
%\bye

獎金:這是一篇單行文,其中\newif涉及:

\catcode`_=13\newif\ifmyif\myiffalse\def_{\ifmmode\sb\else\ifmyif\endgroup\else\begingroup\myiftrue\it\fi\fi}Text _more of text_ ToDo $abc_i^2 math$ even more _text_ etc.%\bye

微量元素

相關內容