如何在LaTeX文档中插入代码?比如:

\begin{code}## Heading ##
...
\end{code}

我唯一真正需要的是缩进和固定宽度的字体。语法高亮显示可能很好,尽管它绝对不是必需的。


当前回答

由于这里还没有提到它,可能值得再添加一个选项,package spverbatim(没有语法高亮显示):

\documentclass{article}
\usepackage{spverbatim}

\begin{document}

\begin{spverbatim}
  Your code here
\end{spverbatim}

\end{document}

此外,如果不需要语法高亮显示,则打包alltt:

\documentclass{article}
\usepackage{alltt}

\begin{document}

\begin{alltt}
  Your code here
\end{alltt}

\end{document}

其他回答

下面是如何添加内联代码:

您可以使用{\tt code}或\texttt{code}添加内联代码。如果您想格式化内联代码,那么最好创建自己的命令

\newcommand{\code}[1]{\texttt{#1}}

另外,请注意,代码块可以从其他文件中加载

\lstinputlisting[breaklines]{source.c}

折线不是必需的,但我发现它很有用。注意,您必须为此指定\usepackage{listings}。

更新:清单包还包括\lstinline命令,该命令具有与\lstlisting和\lstinputlisting命令相同的语法高亮显示功能(有关配置细节,请参阅Cloudanger的回答)。正如在其他一些回答中提到的,还有一个minted包,它提供了\mintinline命令。像\lstinline一样,\mintinline提供了与常规铸造代码块相同的语法高亮显示:

\documentclass{article}

\usepackage{minted}

\begin{document}
  This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}

使用pyggies !

如果你的代码是Python的,我不需要安装Python包,一个非常简单的方法是:

\documentclass[11pt]{article}  
\usepackage{pythonhighlight}

\begin{document}

The following is some Python code

\begin{python}
# A comment
x = [5, 7, 10]
y = 0

for num in x:
    y += num
    
print(y)
\end{python}

\end{document}

它看起来像:

不幸的是,这只适用于Python。

Minted,无论是来自GitHub还是CTAN,综合TeX档案网络,工作在Overleaf, TeX Live和MiKTeX。

它需要安装Python包pyptions;这在上面两种源代码的文档中都有解释。尽管pyptions标榜自己是Python语法突出显示工具,但Minted保证覆盖了数百种其他语言。

例子:

\documentclass{article}
\usepackage{minted}
\begin{document}

\begin{minted}[mathescape, linenos]{python}

# Note: $\pi=\lim_{n\to\infty}\frac{P_n}{d}$
title = "Hello World"

sum = 0
for i in range(10):
 sum += i

\end{minted}

\end{document}

输出:

您也可以使用逐字记录环境

\begin{verbatim}
your
code
example
\end{verbatim}