[Tex/LaTex] Multiline Matlab comments in package Listings

commentslistingsMATLAB

I am using the package listings to include some Matlab code in my report.
It works well with comments beginning by % but does not recognise multiline comments %{ ... %}:

\usepackage{listings}
\lstset{language=Matlab}
...
\begin{lstlisting}
% normal comment
MATLAB code
%{
This is
a multiline
comment
%}
function [x,y] = test(x)
\end{lstlisting}

gives

enter image description here

instead of

enter image description here

in Matlab.

How can I change \lstset to make it work?

Best Answer

My recommendation would be to use the package matlab-prettifier, which is based on listings but provides enhanced features for MATLAB code above and beyond those provided by listings' Matlab language definition (including support for block comments):

\documentclass{article}
\usepackage{matlab-prettifier}
\lstset{style=Matlab-editor}

\begin{document}
\begin{lstlisting}
% normal comment
MATLAB code
%{
This is
a multiline
comment
%}
function [x,y] = test(x)
\end{lstlisting}
\end{document}

enter image description here

If, for some reason, you must use listings with its existing implementation of the Matlab language, you can add support for block comments by setting the package's morecomment key:

morecomment=[s]{\%\{}{\%\}}

Here, [s] signifies that we are looking for two delimiters, the first to open a block comment and the second to close it. The following brace groups contain the opening and closing delimiters for a block comment, respectively. Note that both the percent sign and the individual open/close braces must be escaped by backslashes when defining the comment delimiters.

\documentclass{article}
\usepackage{listings}
\lstset{
  language=Matlab,
  basicstyle=\ttfamily,
  morecomment=[s]{\%\{}{\%\}},
}

\begin{document}
\begin{lstlisting}
% normal comment
MATLAB code
%{
This is
a multiline
comment
%}
function [x,y] = test(x)
\end{lstlisting}
\end{document}

enter image description here