我的目标是拥有一个稍微大一点的逐字块,并使用列表仅对特定部分进行语法突出显示。这是一个小例子:
\begin{verbatim}
How to include files in:
C: #include <stdlib.h>
C++: #include <iostream>
python: import math, from math import exp
Java: import java.util.arraylist;
\end{verbatim}
应该变成
\begin{lstlistings}[myoptions]
How to include files in:
C: \lstuselanguage{c}{#include <stdlib.h>}
C++: \lstuselanguage{c++}{#include <iostream>}
python: \lstuselanguage{python}{import math, from math import exp}
Java: \lstuselanguage{java}{import java.util.arraylist;}
\end{lstlistings}
其中\lstuselanguage
是某种以指定语言进行语法高亮显示的命令。
这可能吗?(在 LaTeX 中,一切皆有可能,所以我想我的意思是:“这有多难?”)
答案1
不幸的是,lstlisting
环境不能嵌入到其他环境中。
lstuselanguage
这里我定义了一个接受参数(语言)的新环境:
\newenvironment{lstuselanguage}[1]{%
\noindent%
\begin{minipage}{0.15\linewidth}%
\texttt{#1:}%
\end{minipage}%
\begin{minipage}{0.85\linewidth}%
}{%
\end{minipage}%
}
可以这样使用:
\documentclass{article}
\usepackage{listings}
\lstnewenvironment{C}
{\lstset{language=C}}
{}
\lstnewenvironment{CPP}
{\lstset{language=C++}}
{}
\lstnewenvironment{Java}
{\lstset{language=Java}}
{}
\lstnewenvironment{Python}
{\lstset{language=Python}}
{}
\newenvironment{lstuselanguage}[1]{%
\noindent%
\begin{minipage}{0.15\linewidth}%
\texttt{#1:}%
\end{minipage}%
\begin{minipage}{0.85\linewidth}%
}{%
\end{minipage}%
}
\begin{document}
\noindent How to include files in:
\begin{lstuselanguage}{C}
\begin{C}
#include <stdlib.h>
\end{C}
\end{lstuselanguage}
\begin{lstuselanguage}{C++}
\begin{CPP}
#include <iostream>
\end{CPP}
\end{lstuselanguage}
\begin{lstuselanguage}{Python}
\begin{Python}
import math, from math import exp
\end{Python}
\end{lstuselanguage}
\begin{lstuselanguage}{Java}
\begin{Java}
import java.util.arraylist;
\end{Java}
\end{lstuselanguage}
\end{document}
输出:
答案2
我认为这应该对你有帮助。定义环境并根据需要使用它们。以下是所需的代码:
\documentclass{article}
\usepackage{listings}
\lstnewenvironment{C}
{\lstset{language=C}}
%Add your addition parameters as required like showstringspaces , line numbering ,
% frames , etc.seperated by a comma as shown in the CPP environment
{}
\lstnewenvironment{CPP}
{\lstset{language=C++,basicstyle=\ttfamily\small,frame=none}}
{}
\lstnewenvironment{Java}
{\lstset{language=Java}}
{}
\lstnewenvironment{Python}
{\lstset{language=Python}}
{}
\begin{document}
How to include files in:\\
C:
\begin{C}
#include <stdlib.h>
\end{C}
C++:
\begin{CPP}
#include <iostream>
\end{CPP}
Python:
\begin{Python}
import math, from math import exp
\end{Python}
Java:
\begin{Java}
import java.util.arraylist;
\end{Java}
\end{document}