使用列表或动词定义通用内联代码命令时出现问题

使用列表或动词定义通用内联代码命令时出现问题

我正在尝试定义一个内联\code命令(不是特定于语言的,只是更智能的,\texttt{}例如,无需转义下划线或波浪号)。我尝试了以下基于的三个版本listings。最好看的是\codeThree,但在环境中使用时它会突然失败enumerate。可以修复吗?

\documentclass{scrartcl}

\usepackage{listings}
\newcommand*{\codeOne}[1]{\lstinline[basicstyle=\ttfamily]{#1}}
\newcommand*{\codeTwo}[1]{\scantokens{\lstinline[basicstyle=\ttfamily]{#1}}}
\newcommand*{\codeThree}[1]{\lstinline[basicstyle=\ttfamily, literate={~}{{$\sim$}}1 ]{#1}}

\begin{document}
% \codeOne{~/.bashrc} % fails to display the tilde; don't comment in (side-effects on the below)
\lstinline[basicstyle=\ttfamily]{~/.bashrc} % works
\codeTwo{~/.bashrc} % also works (but only due to the \scantokens command; see https://tex.stackexchange.com/questions/175919/pathological-listings-problem-tilde-in-lstinline-in-a-footnote )
\codeThree{~/.bashrc} % works (and shows nicest tilde)
\begin{enumerate}
\item ... but not in an environment (see \codeThree{~/.bashrc}). % fails
\end{enumerate}
\end{document}

或者,可以使用\verb,但定义一个命令\code(调整字体大小并)将其参数传递给\verb似乎很无望(?)我猜(见https://texfaq.org/FAQ-verbwithin

答案1

只是不要定义\code要采取什么论点。

\documentclass{scrartcl}

\usepackage{listings}

\newcommand*{\code}{\lstinline[basicstyle=\ttfamily,literate={~}{{$\sim$}}1]}

\begin{document}

\lstinline[basicstyle=\ttfamily]{~/.bashrc}        

\lstinline[basicstyle=\ttfamily, literate={~}{{$\sim$}}1]{~/.bashrc}        

\code{~/.bashrc}

\begin{enumerate}
\item ... also in an environment (see \code{~/.bashrc}).        
\end{enumerate}

\end{document}

在此处输入图片描述

您还可以\code|...|根据需要在特定情况下拨打电话。

答案2

\lstinline也是逐字命令,您不能简单地将其放在另一个命令的主体中(并且您在枚举之外也会在日志中收到有关开放简单组的消息)。请改为复制定义\lstinline

\documentclass{scrartcl}

\usepackage{listings}
\makeatletter
\newcommand\codeThree[1][]{%
    \leavevmode\bgroup % \hbox\bgroup --> \bgroup
      \def\lst@boxpos{b}%
      \lsthk@PreSet
     \lstset{flexiblecolumns,basicstyle=\ttfamily,literate={~}{{$\sim$}}1,#1}%
      \lsthk@TextStyle
      \@ifnextchar\bgroup{%
        \afterassignment\lst@InlineG \let\@let@token}%
                         \lstinline@}
 \makeatother                        
\begin{document}
\lstinline[basicstyle=\ttfamily]{~/.bashrc} % works

\codeThree{~/.bashrc} % works (and shows nicest tilde)
\begin{enumerate}
\item ... and in an environment (see \codeThree{~/.bashrc}). % fails
\end{enumerate}
\end{document}

在此处输入图片描述

相关内容