如何定义可以在表格和标题中使用的 \verb-like 命令?

如何定义可以在表格和标题中使用的 \verb-like 命令?

我想定义一个\verb类似命令,\keyword例如,使以下代码按预期工作。有人能帮助我吗?

\documentclass{article}
\usepackage{float}
\usepackage{newverbs}
\usepackage{xcolor}
\usepackage{xltabular}

\newverbcommand{\keyword}{\begingroup\color{blue}}{\endgroup}

\begin{document}

\section{Introduction}

C contains the following keywords:
\begin{table}[H]
    \centering
    \begin{tabular}{|c|c|}
      \hline
      \keyword|int| & int \\ \hline
      \keyword|_Thread_local| & thread storage-class specifier  \\ \hline
    \end{tabular}
\end{table}

C contains the following keywords:
\begin{xltabular}{\linewidth}{|c|c|}
    \hline
    \keyword|int| & int \\ \hline
    \keyword|_Thread_local| & thread storage-class specifier  \\ \hline
\end{xltabular}

\subsection{Introduction to \keyword|_Thread_local|}

\keyword|_Thread_local|: thread storage-class specifier.

\end{document}

答案1

table在resp.内部使用逐字命令tabular实际上并不是问题。

在另一个命令的参数中使用逐字命令是有限的,因为在读取另一个命令的参数后,令牌已经构建。因此,如果您使用逐字命令的参数,这仅在更改 catcode 后才允许,这将不起作用。但您可以使用包裹cprotect解决方法:

\documentclass{article}
\usepackage{float}
\usepackage{newverbs}
\usepackage{cprotect}
\usepackage{xcolor}
\usepackage{xltabular}

\newverbcommand{\keyword}{\begingroup\color{blue}}{\endgroup}

\begin{document}
\tableofcontents

\section{Introduction}

C contains the following keywords:
\begin{table}[H]
    \centering
    \begin{tabular}{|c|c|}
      \hline
      \keyword|int| & int \\ \hline
      \keyword|_Thread_local| & thread storage-class specifier  \\ \hline
    \end{tabular}
\end{table}

C contains the following keywords:
\begin{xltabular}{\linewidth}{|c|c|}
    \hline
    \keyword|int| & int \\ \hline
    \keyword|_Thread_local| & thread storage-class specifier  \\ \hline
\end{xltabular}

\cprotect\subsection{Introduction to \keyword|_Thread_local|}

\keyword|_Thread_local|: thread storage-class specifier.

\end{document}

在此处输入图片描述

如您所见,onlyxltabular是一个问题。但是,由于您不使用任何X-column,因此我建议,只需使用longtable(如果需要分页符) 或tabular即可。

如果需要xltabular使用逐字参数类型\NewDocumentCommand而不是\newverbcommand

\documentclass{article}
\usepackage{float}
\usepackage{xcolor}
\usepackage{xltabular}

\NewDocumentCommand{\keyword}{v}{\textcolor{blue}{\texttt{#1}}}

\begin{document}
\tableofcontents

\section{Introduction}

C contains the following keywords:
\begin{table}[H]
    \centering
    \begin{tabular}{|c|c|}
      \hline
      \keyword|int| & int \\ \hline
      \keyword|_Thread_local| & thread storage-class specifier  \\ \hline
    \end{tabular}
\end{table}

C contains the following keywords:
\begin{xltabular}{\linewidth}{|c|c|}
    \hline
    \keyword|int| & int \\ \hline
    \keyword|_Thread_local| & thread storage-class specifier  \\ \hline
\end{xltabular}

\subsection{Introduction to \keyword|_Thread_local|}

\keyword|_Thread_local|: thread storage-class specifier.

\end{document}

使用 \NewDocumentCommand 还可以纠正 xltabular

注意:这不起作用,例如,用\keyword|\Thead_local|代替\keyword|_Thread_local|

相关内容