我使用 XeLaTeX 和 Overleaf 作为编辑器。我想使用该listings
包列出我的 LaTeX 代码。我可以使用下面的我的样式正确列出大多数正常代码,但是当我尝试在序言中列出某些行时,会出现很多错误。(例如未定义的控制序列。LaTeX 错误:环境 lstlisting 未定义。LaTeX 错误:缺少 \begin{document}。...等)
有没有办法列出\documentclass
而不损坏 PDF?我应该改用\verb
吗?
这是我的代码:
\documentclass[11pt, a4paper]{article}
\usepackage{listings,xcolor}
\definecolor{code-keyword-color}{rgb}{0.61, 0.14, 0.58} % purple
\definecolor{code-comment-color}{rgb}{0.36, 0.42, 0.47} % gray
\definecolor{code-string-color}{rgb}{0.77, 0.1, 0.09} % orange
\definecolor{code-identifier-color}{rgb}{0.42, 0.21, 0.66} %purple
\lstdefinestyle{mystyle}{
basicstyle=\ttfamily\footnotesize,
numbers=left, % Position of line numbers
numberstyle=\sffamily\scriptsize, % Style of line numbers
stepnumber=1, % Margin between line numbers
numbersep=5pt, % Margin between line numbers and text
tabsize=2,
extendedchars=true, % Lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
breaklines=true, % Lines will be wrapped
breakatwhitespace=false, % Sets if automatic breaks should only happen at whitespace
keepspaces=true, % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
showspaces=false, % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
showstringspaces=false, % underline spaces within strings only
showtabs=false % show tabs within strings adding particular underscores
captionpos=t, % Caption position: top
escapeinside={\%*}{*)}, % If you want to add LaTeX within your code
backgroundcolor=\color{white},
commentstyle=\itshape\color{code-comment-color},
keywordstyle=\color{code-keyword-color},
identifierstyle=\color{code-identifier-color},
stringstyle=\color{code-string-color},
language=[LaTeX]TeX
}
\lstset{style=mystyle}
\begin{document}
\title{title}
\author{name}
\date{date}
\maketitle
% this works
\begin{lstlisting}
\begin{equation}
E=mc^2
\end{equation}
\end{lstlisting}
% this does not work
\begin{lstlisting}
\documentclass[11pt, a4paper]{article}
\end{lstlisting}
\end{document}
答案1
这是由 Overleaf 选择要编译的文件的机制决定的。
当 Overleaf 中没有指定主文档时,编译器会在执行“编译”时尝试编译当前文件。
当指定主文档时,Overleaf 将仍然如果该文档包含字符串,则尝试编译当前文件\documentclass
,无论它是哪一行,或者是否以新行开始。
\texttt{\textbackslash documentclass}
我的解决方法是通过、 或来排版\verb!\!\verb!documentclass!
。
参考:Overleaf - 设置主文档 https://www.overleaf.com/learn/how-to/Set_Main_Document