我想将选择的listings
样式保存到变量中\mlstyle
并稍后在某些命令或定义中使用它。
然而,虽然:
\lstinputlisting[style=Matlab-editor]{a.mat}
我期望使用的版本:
\newcommand{\mlstyle}{Matlab-editor}
\lstinputlisting[style=\mlstyle]{a.mat}
才不是。
包裹清单错误:
样式 Matlab 编辑器未定义.
\lstinputlisting[style=\mlstyle]{a.mat}
\documentclass{article}
\usepackage{filecontents} % only need to provide the file a.mat
\usepackage{listing}
\usepackage{matlab-prettifier}
\newcommand{\mlstyle}{Matlab-editor}%{Matlab-bw}%{Matlab-Pyglike}
\begin{filecontents*}{a.mat}
a = 1;
\end{filecontents*}
\begin{document}
\lstinputlisting[style=Matlab-editor]{a.mat} % WORKS
%\lstinputlisting[style=\mlstyle]{a.mat} % DOES NOT WORK
\end{document}
有没有什么解决方法?
答案1
当listings
解析选项时,它通常不进行扩展,但我们可以强制它执行此操作style
:
\begin{filecontents*}{\jobname.mat}
a = 1;
\end{filecontents*}
\documentclass{article}
\usepackage{listing}
\usepackage{matlab-prettifier}
\makeatletter
\AtBeginDocument{%
\lst@Key{style}\relax{%
\begingroup\edef\x{\endgroup
\noexpand\lst@LAS{style}{sty}{[]{#1}}%
}\x\lst@NoAlias\lststylefiles
\lsthk@SetStyle{}%
}%
}
\makeatother
\newcommand{\mlstyle}{Matlab-editor}
\begin{document}
\lstinputlisting[style=Matlab-editor]{\jobname.mat}
\lstinputlisting[style=\mlstyle]{\jobname.mat}
\end{document}
答案2
如果在样式名称中使用小写字母,则它会起作用:
\documentclass{article}
\usepackage{filecontents} % only need to provide the file a.mat
\usepackage{listings}
\usepackage{matlab-prettifier}
\newcommand{\mlstyle}{matlab-editor}%
\begin{filecontents*}{a.mat}
a = 1;
\end{filecontents*}
\begin{document}
\lstinputlisting[style=\mlstyle]{a.mat} %
\end{document}
答案3
这是扩展问题。我建议做成\mlstyle
宏。例如,如果你定义
\newcommand{\mlstyle}[2][editor]{\lstinputlisting[style=Matlab-#1]{#2}}
那么你可以使用:
\mlstyle{a.mat} % DOES WORK with style = Matlab-editor
\mlstyle[bw]{a.mat} % DOES WORK with style = Matlab-bw
\mlstyle[Pyglike]{a.mat} % DOES WORK with style = Matlab-Pyglike
完整代码如下:
\documentclass{article}
\usepackage{filecontents} % only need to provide the file a.mat
\usepackage{listing}
\usepackage{matlab-prettifier}
% usage: \mlstyle[matlab style]{filename}
% where the default matlab style is Matlab-editor
% and \mlstyle[X]{filename} uses style=Matlab-X
\newcommand{\mlstyle}[2][editor]{\lstinputlisting[style=Matlab-#1]{#2}}
\begin{filecontents*}{a.mat}
a = 1;
\end{filecontents*}
\begin{document}
\lstinputlisting[style=Matlab-editor]{a.mat} % WORKS
\mlstyle{a.mat} % DOES WORK with style = Matlab-editor
\mlstyle[bw]{a.mat} % DOES WORK with style = Matlab-bw
\mlstyle[Pyglike]{a.mat} % DOES WORK with style = Matlab-Pyglike
\end{document}