如何在 verbatim 中插入普通字体的文本?

如何在 verbatim 中插入普通字体的文本?

在 ISO C++ 标准论文中,代码块以类似 - 的格式显示verbatim,但代码中的注释采用普通字体。例如:

带注释的示例代码

注释“7.3.5,CommonReference:”等字体正常,链接也正常。这是如何实现的?

答案1

您可以使用listings。但是,转义为 LaTeX 不会保留当前样式(在您的情况下为注释),因此我提供了一个适合该工作的命令。

\documentclass{book}
\usepackage{xcolor}
\usepackage{listings}

\usepackage{hyperref}

\lstset{
  language=C++,
  columns=fullflexible,
  basicstyle=\ttfamily,
  commentstyle=\mycommentstyle,
  escapechar=\$,
}

\hypersetup{
  colorlinks,
  linkcolor=blue,
}

\newcommand{\mycommentstyle}{\normalfont\itshape}
\newcommand{\commentref}[1]{{\mycommentstyle\ref{#1}}}


\begin{document}

\setcounter{chapter}{7} % to emulate your numbering
\setcounter{section}{3}
\setcounter{subsection}{4}

\subsection{Common reference}\label{cr}

This will be pointed to by the link.

\begin{lstlisting}
// $\commentref{cr}$, CommonReference:
template <class T, class U>
concept bool CommonReference = see below;
\end{lstlisting}

\end{document}

在此处输入图片描述

答案2

这在lstlisting以下环境中是可能的,

% !TEX encoding = UTF-8 Unicode
\documentclass[UTF8, english]{article}

\usepackage{listings, xcolor}
\lstset{
tabsize = 4, %% set tab space width
showstringspaces = false, %% prevent space marking in strings, string is defined as the text that is generally printed directly to the console
numbers = left, %% Displays line numbers on the left
keywordstyle = \color{blue}, %% set keyword color
stringstyle = \color{red}, %% set string color
rulecolor = \color{black}, %% set frame color to avoid being affected by text color
basicstyle = \small \ttfamily , %% set listing font and size
breaklines = true, %% enable line breaking
numberstyle = \tiny,
commentstyle = \rmfamily,
}
\usepackage[colorlinks, linkcolor = blue, anchorcolor = blue, citecolor = green]{hyperref}

\begin{document}

\begin{lstlisting}[language = C++, frame = trBL, firstnumber = last, escapeinside = {(*@}{@*)}]
#include <iostream>
// here is the comment and clickable (*@\href{https://ctan.org/pkg/listings}{link}@*) in roman font family
int main() 
{
    std::cout << "Hello, World!";
    return 0;
}
\end{lstlisting}

\end{document}

你会得到

评论和链接

相关内容