LaTeX 宏用于“代码”样式、下划线包和连字符

LaTeX 宏用于“代码”样式、下划线包和连字符

我正在寻找一种在文档中很好地设置代码的方法。我使用了\def\code#1{{\texttt{#1}}},但它仍然允许文本连字符。为了防止这种情况,我尝试了避免使用连字符,并在文本块中使用换行符并尝试了\def\code#1{{\mbox{\texttt{#1}}}},但当我写入 时字体大小会丢失,例如T_{\code{FOO}}。不幸的是,该\nohyphens{...}解决方案与其他一些包发生冲突(据我所知),并且该\hyphenpenalty 10000解决方案没有产生任何变化。

在准备 MWE 时,我发现连字符仅发生在下划线之后。

得到我想要的东西应该没那么难,不是吗?

以下是 MWE:

\documentclass{article}

\def\code#1{{\texttt{#1}}}
%\def\code#1{{\mbox{\texttt{#1}}}}

\usepackage[strings]{underscore}

\begin{document}

I really like to use \code{assert()}. Still,
\code{assertions_that_should_never_fail_even_if_they_stick_out()} 
should not be hyphenated. I know some long words: 
pneumonoultramicroscopicsilicovolcanoconiosis,
parastratiosphecomyia stratiosphecomyioides,
pseudopseudohypoparathyroidism,
floccinaucinihilipilification,
subdermatoglyphic,
squirrelled,
abstentious and 
rotavator.

Function \code{FOO} runs in time $T_{\code{FOO}}$, not $T_{FOO}$.

\end{document}

答案1

我不太明白你为什么要让长段文字突出在边缘。

但是,这里有一种方法;我避免underscore使用更安全的方法来实现相同的结果。

\documentclass{article}
\usepackage[T1]{fontenc} % better underscore
\usepackage{amsmath}
\usepackage[htt]{hyphenat}
\newcommand\code[1]{\texttt{#1}}

%% This code substitutes underscore.sty
\begingroup\lccode`~=`_
\lowercase{\endgroup
  \protected\def~{\ifmmode\sb\else\textunderscore\fi}
}
\AtBeginDocument{\catcode`_=\active}
%% end

\begin{document}

I like to use \code{assert()}. Still,
\code{assertions_that_should_never_fail_even_if_they_stick_out()}
should not be hyphenated. I know some long words:
pneumonoultramicroscopicsilicovolcanoconiosis,
parastratiosphecomyia stratiosphecomyioides,
pseudopseudohypoparathyroidism,
floccinaucinihilipilification,
subdermatoglyphic,
squirrelled,
abstentious and
rotavator.

Function \code{FOO} runs in time $T_{\code{FOO}}$, not $T_{FOO}$.

\end{document}

在此处输入图片描述

或者,使用\textnhtt(再次来自hyphenat):

\documentclass{article}
\usepackage[T1]{fontenc} % better underscore
\usepackage{amsmath}
\usepackage{hyphenat}
\DeclareRobustCommand\code[1]{%
  \ifmmode
    \expandafter\texttt
  \else
    \expandafter\textnhtt
  \fi{#1}%
}

%% This code substitutes underscore.sty
\begingroup\lccode`~=`_
\lowercase{\endgroup
  \protected\def~{\ifmmode\sb\else\textunderscore\fi}
}
\AtBeginDocument{\catcode`_=\active}
%% end

\begin{document}

I like to use \code{assert()}. Still,
\code{assertions_that_should_never_fail_even_if_they_stick_out()}
should not be hyphenated. I know some long words:
pneumonoultramicroscopicsilicovolcanoconiosis,
parastratiosphecomyia stratiosphecomyioides,
pseudopseudohypoparathyroidism,
floccinaucinihilipilification,
subdermatoglyphic,
squirrelled,
abstentious and
rotavator.

Function \code{FOO} runs in time $T_{\code{FOO}}$, not $T_{FOO}$.

\end{document}

请注意下amsmath标大小的选择是否正确。

相关内容