以下 M(n)WE 向我传达了以下信息:
! Package keyval Error: language={bash},numbers=left undefined.
好像我的变量中的键值没有被正确定义?
\documentclass{article}
\usepackage{filecontents}
\usepackage{listings}
\begin{document}
\begin{filecontents}{temp.tex}
for i in {1..3}; do
echo $i
done
\end{filecontents}
\def\opts{[language={bash},numbers=left]}
\def\fn{temp.tex}
\lstinputlisting[language={bash},numbers=left]{\fn}%this line works fine
\lstinputlisting[\opts]{\fn}%this line does not work???
\end{document}
答案1
用 定义新样式\lstdefinestyle
,并使用style=<stylename>
,而不是宏。
\documentclass{article}
\usepackage{filecontents}
\usepackage{listings}
\lstdefinestyle{opts}{
language={bash},
numbers=left
}
\begin{document}
\begin{filecontents}{temp.tex}
for i in {1..3}; do
echo $i
done
\end{filecontents}
\def\fn{temp.tex}
\lstinputlisting[language={bash},numbers=left]{\fn}%this line works fine
\lstinputlisting[style=opts]{\fn}%this line works fine
\end{document}
答案2
这是因为您传递给的唯一“东西”\lstinputlisting
是\writelstopts
,在示例中,它是一个包含的单个标记language={bash},numbers=left
,这不是一个有效的选项。
你想要的是通过内容的\writelstopts
,所以你必须在\lstinputlisting
尝试执行其操作之前展开它们。一对\expandafter
s 解决了这个问题:
\documentclass{article}
\usepackage{listings}
\newenvironment{writelst}[2][]{%
\def\writelstopts{#1}%
\def\writelstfn{#2}%
%call-another-command-here{#2}
\lstinputlisting[#1]{\writelstfn}%this line works fine
}
{
%call-yet-another-command-here
\expandafter\lstinputlisting\expandafter[\writelstopts]{\writelstfn}%this line does not work???
}
\begin{document}
\begin{writelst}[language={bash},numbers=left]{test.sh}
some bash code here
\end{writelst}
\end{document}