喜欢这个问题
但是因为我的很多关键字都有下划线,所以我创建了一个名为 \keyword 的宏,并用 \detokenize 来简化操作。然而,它又使下划线变长了。
\documentclass{article}
\usepackage{lmodern}
\usepackage{relsize}
\usepackage[T1]{fontenc}
\NewDocumentCommand\keyword{sm}{\emph{\detokenize{#2}}}
\renewcommand{\_}{\textscale{.6}{\textunderscore}}
\begin{document}
This method works for:\\
\verb|\emph{\_\_all\_\_}|\quad\textrightarrow\quad \emph{\_\_all\_\_}\\
\par
But not works for:\\
\verb|\keyword{__all__}|\quad\textrightarrow\quad \keyword{__all__}\\
Maybe the reason is the same as this one:\\
\verb|\char`_\char`_all\char`_\char`_|\quad\textrightarrow\quad \char`_\char`_all\char`_\char`_\\
\end{document}
答案1
您可以设置listings
代码格式,以您想要的方式进行设置。该选项literate
允许您即时替换字符:
\documentclass{article}
\usepackage{lmodern}
\usepackage{relsize}
\usepackage{listings}
\lstset{
basicstyle=\itshape,
literate={_}{\textscale{.6}{\textunderscore}}1
}
\renewcommand{\_}{\textscale{.6}{\textunderscore}}
\begin{document}
\verb|\emph{\_\_all\_\_}|\quad\textrightarrow\quad \emph{\_\_all\_\_}
\verb|\lstinline{__all__}|\quad\textrightarrow\quad \lstinline{__all__}
\end{document}
答案2
listings 处理输入,您可以重新定义输入的输出。将 xx/yy 替换为您想要的任何内容:
\documentclass{article}
\usepackage{lmodern}
\usepackage{relsize}
\usepackage{listings}
\lstset{
basicstyle=\itshape,
}
\makeatletter
\lst@CCPutMacro
\lst@ProcessOther {"5F}{%
\lst@ttfamily
{xx}% used with ttfamily
{yy}}% used with other fonts
\@empty\z@\@empty
\makeatother
\begin{document}
\lstinline{__all__}
\lstinline[basicstyle=\ttfamily]{__all__}
\end{document}