字串中引號的列表問題

字串中引號的列表問題

字串內出現的單引號listings似乎被解釋為字串的結尾。有沒有辦法避免這種情況的發生?

\documentclass[12pt]{article}
\usepackage[top=0.3in, bottom=1.2in, left=0.8in, right=0.8in]{geometry}

\setlength{\parindent}{0cm}

\usepackage[english]{babel}

\usepackage{listings}

\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}

\begin{document}

\lstset{language=Matlab,
        basicstyle=\ttfamily,
        keywordstyle=\color{Blue}\ttfamily,
        stringstyle=\color{Red}\ttfamily,
        commentstyle=\color{Emerald}\ttfamily,
        morecomment=[l][\color{Magenta}]{\#},
        breaklines=true,
        breakindent=0pt,
        breakatwhitespace,
        columns=fullflexible,
        showstringspaces=false
}


\begin{lstlisting}
a=1;
if a==1
    disp('Is 1')
elseif a==2
    disp('Is 2')
else
    disp('I don't know')
end
\end{lstlisting}

\end{document}

在此輸入影像描述

答案1

由於單引號在 Matlab 中用作字串分隔符,因此您需要轉義該字元才能使其成為字串的一部分。這是透過連續輸入兩個單引號來完成的:

disp('I don''t know')

Matlab由 定義的語言夠listings聰明,可以排版正確的內容,在本例中:

在此輸入影像描述

作為旁注,您可能對matlab-prettifier包裹;看這個答案

答案2

一個可能的解決方案來自清單.pdfmathescape參數:

\documentclass[12pt]{article}
\usepackage[top=0.3in, bottom=1.2in, left=0.8in, right=0.8in]{geometry}

\setlength{\parindent}{0cm}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage{listings}




\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}

\begin{document}

\lstset{language=Matlab,
        basicstyle=\ttfamily,
        keywordstyle=\color{Blue}\ttfamily,
        stringstyle=\color{Red}\ttfamily,
        commentstyle=\color{Emerald}\ttfamily,
        morecomment=[l][\color{Magenta}]{\#},
        breaklines=true,
        breakindent=0pt,
        breakatwhitespace,
        columns=fullflexible,
        showstringspaces=false
}


\begin{lstlisting}[mathescape]
a=1;
if a==1
    disp('Is 1')
elseif a==2
    disp('Is 2')
else
    disp('I don$\texttt{\color{red}'}$t know')
end
\end{lstlisting}

\end{document}

在此輸入影像描述

相關內容