使用{listings}宏包以及依赖于{listings}的宏包,如{matlab-prettifier}和{mcode}等,在{beamer}中都有兼容性问题.
解决的办法是给{frame}环境添加选项[fragile]:
\begin{frame}[fragile]
\frametitle{XeLatex中自定义matlab代码语法高亮-标题}
下面是Matlab代码,显示效果如下:
\begin{lstlisting}
s=0;
for n=1:0.5:10
s=s+n;
end
disp(s)
\end{lstlisting}
显示效果如上.
\end{frame}
上面的代码可以正确显示matlab语法高亮.
下面给出完整代码,编译环境MikTex2.9+Win7+Xelatex,在windows中强烈推荐MikTex,而不是TexLive.看看发行说明再使用过后你就会感受很深!
\documentclass[mathserif]{beamer}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{ctex}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{color}
\usepackage{textcomp} % 应该加上,否则容易报错
%===========================================================
\definecolor{myred}{rgb}{0.9,0,0}
\definecolor{mygreen}{rgb}{0,0.9,0}
\definecolor{myblue}{rgb}{0,0,0.9}
\definecolor{DarkGreen}{rgb}{0.0,0.4,0.0}
\definecolor{myPurple}{rgb}{0.5,0.0,0.5}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%注意begin{frame}[fragile]
%==========================================================
\lstloadlanguages{Matlab}
\lstset{language=Matlab,
frame=single, % single framed
basicstyle=\small\ttfamily,
keywordstyle=\color{myblue}\bfseries, % primitive funs in bold blue
stringstyle=\color{myPurple}, % strings in purple
showstringspaces=false,
commentstyle=\usefont{T1}{pcr}{m}{sl}\color{DarkGreen}\small,
tabsize=4,
% more standard MATLAB funcs
morekeywords={for,end,if,elseif,break,switch,case,while,do,on, off, disp,plot,subplot,grid,hold,clc,clear,figure,handles,get,set,imwrite,aviread, strcat,aviinfo},
morecomment=[l][\color{myblue}]{...}, % line continuation (...) like blue comment
numbers=left,
numberstyle=\tiny\color{myblue},
firstnumber=1,
stepnumber=1
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
%----------------------------------------------
\begin{frame}[fragile]
\frametitle{自定义matlab代码-标题}
下面是matlab代码,显示效果如下:
\begin{lstlisting}
s=0;
for n=1:0.5:10
s=s+n;
end
disp(s)
\end{lstlisting}
显示效果如上.
\end{frame}
%-------------------------------------------
\end{document}
使用{listings}宏包在{article}中等问题会少一点.