Why are strings interpreted wrong in MatLab code with listings

I am trying to include MatLab code in my document using the listings package, but it seems like strings are not interpreted correct.

fprintf('ABC %s:\n', mystring);
fprintf("ABC %s:\n", mystring);

\documentclass{article}
\usepackage[english]{babel}     %use english or ngerman
\usepackage[utf8]{inputenc}     %German äöü for input
\usepackage[T1]{fontenc}        %German äöü for pdf
\usepackage{textcomp}           %Additional Symbols e.g. degree
\usepackage{xcolor}
\usepackage{listings}

\definecolor{keyword}{RGB}{0,175,203}      %color
\definecolor{comment}{rgb}{0.06,0.58,0.07} %color
\definecolor{label}{rgb}{0.5,0.5,0.5}      %color

\lstset{                                   %Configure code
keywordstyle=\bfseries\color{keyword},
stringstyle=\ttfamily\color{label},
commentstyle=\color{comment}
}

\begin{document}

\begin{lstlisting}[
language=MatLab,
label=lst:broken,
caption={Broken Syntax Highlighting}
]
fprintf('ABC %s:\n', mystring);
fprintf("ABC %s:\n", mystring);
\end{lstlisting}

\end{document}


Result:

Is it possible to add " to the same list that ' is in?

1 Answer

The Matlab language definition only defines ' as string delimiter by default. But you can also make " one by adding the following line to the listing's options:

morestring=[m]"


m is a special delimiter type for Matlab code defined as

[...] a special type for Ada and Matlab and possibly other languages where the string delimiters are also used for other purposes. It is equivalent to d, except that a string does not start after a letter, a right parenthesis, a right bracket, or some other characters.

If you don't want that special behavior, use morestring=[d]".

You can also define a new language which is based on Matlab with the new string type added:

\lstdefinelanguage{MyMatlab}{
language=Matlab,
morestring=[m]"
}


Using that new language in your listing gives the desired output: