![内联突出显示的代码](https://linux22.com/image/406513/%E5%86%85%E8%81%94%E7%AA%81%E5%87%BA%E6%98%BE%E7%A4%BA%E7%9A%84%E4%BB%A3%E7%A0%81.png)
我想将一些代码与其他文本内联在一起。不过,代码应该与我在文档中编写的其他代码相匹配。因此,它应该突出显示(比如说黄色),应该采用打字机字体,并且不需要对特殊字符进行转义。此外,它应该能够在行末换行。我可以单独做这些事情,但不能将它们结合在一起。
这篇文章似乎做了类似的事情,也是我想到使用灵魂包的地方,但没有解决转义特殊字符的问题,而仅仅把它放入 \verb 是行不通的:Colorbox 不换行
梅威瑟:
\documentclass{minimal}
\usepackage {color}
\usepackage {soul}
\usepackage {listings}
\lstset{breaklines=true, basicstyle=\ttfamily}
\begin{document}
text \colorbox{yellow}{\texttt{Code which cannot break lines and needs special characters escaped \_ bla bla bla very long line of code}} text
\sethlcolor{yellow}
text \texttt{\hl{Code which can break very long lines and is highlighted but needs escaping of special characters \_ }} text
text \lstinline[language={}]{Code which can break lines of very long code and can escape special characters such as \ and & but cannot be highlighted} text
\end{document}
答案1
这确实不容易实现。我发现最好的方法是使用铸造包,需要使用该--shell-escape
选项编译您的文档(查看这个问题了解如何自动化这一过程)。
以下文件:
% !TeX TXS-program:compile = txs:///pdflatex/[--shell-escape]
% Need to be compiled with the --shell-escape option!
% E.g., pdflatex --shell-escape test.tex
\documentclass{article}
\usepackage{minted}
\usepackage{soul}
\begin{document}
\begin{minted}[%
escapeinside=||, % Anything between those symbols will be interpreted as a TeX command.
breaklines, % We allow lines to be broken.
breaksymbolleft =
{ \tiny \ensuremath{\hookrightarrow} }% Symbol used when a line is broken. We use the default.
] % We want to format simple text, but you can have programing languages too.
{text}
Code which can break, does not need escaping (&, _) and can be highlighted using \hl : |\hl{test}| Lines are automatically broken!
\end{minted}
\end{document}
生成:
您可以使用选项调整 minted 使用的字体fontfamily
(请参阅其文档,第 25 页)。但是,默认情况下,tt
使用字体,因此应该与文档的其余部分保持一致。
一个限制是,如果需要换行,突出显示的文本将导致 minted 崩溃:您需要“手动”处理这个问题。