如果我在 Netbeans 中编写代码,我可以轻松格式化代码。如何在 lstlisting 中执行此操作?我的意思是,如果我将其导入或复制到我的 TeX 文档中并使用正确的空格,一切都会正常。但是还有其他方法吗?TeX 可以自动执行此操作吗?
答案1
您可以尝试以下操作
\usepackage{courier} %% Sets font for listing as Courier.
\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, %% display line numbers on the left
commentstyle = \color{green}, %% set comment color
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,
}
\begin{lstlisting}[language = Java , frame = trBL , firstnumber = last , escapeinside={(*@}{@*)}]
public class Factorial
{
public static void main(String[] args)
{ final int NUM_FACTS = 100;
for(int i = 0; i < NUM_FACTS; i++)
System.out.println( i + "! is " + factorial(i));
}
public static int factorial(int n)
{ int result = 1;
for(int i = 2; i <= n; i++) (*@\label{for}@*)
result *= i;
return result;
}
}
\end{lstlisting}
And you can reference line \ref{for} in the code!
输出如下