将 catcode 与 lstnewenvironment 和 lstinputlisting 结合使用

将 catcode 与 lstnewenvironment 和 lstinputlisting 结合使用

(这与将文件中包含的文本注入自定义环境,但我被要求将其放在单独的帖子中)

列表中的正则表达式以下代码运行良好:

\documentclass{report}
\usepackage{listings,xcolor}
\lstdefinelanguage{text}{}

{\catcode`\^^M=12 \def\marshal{\lstnewenvironment{mylang}{\lstset{language=text,comment=[s]{^^MXYZ}{^^M^^M},commentstyle=\color{green},basicstyle=\footnotesize\ttfamily,showstringspaces=false,showspaces=false,}}{}}\expandafter}\marshal

\begin{document}
\begin{mylang}
Only a test, this is not a comment
XYZ this should colored as a comment
and this line too

this is not a command, because only lines starting with XYZ
are comments

This is not a comment, too
\end{mylang}
\end{document}

我的问题是是否有可能:

Only a test, this is not a comment
XYZ this should colored as a comment
and this line too

this is not a command, because only lines starting with XYZ
are comments

This is not a comment, too

包含在一个文件中,然后将此文件加载到主 tex 文件中,然后获得与文本包含在上述 tex 文件中时相同的颜色。我尝试了以下方法,但没有奏效:

\documentclass{report}
\usepackage{listings,xcolor}

{\catcode`\^^M=12 \def\marshal{\lstdefinelanguage{text}{comment=[s]{^^MXYZ}{^^M^^M}}}\expandafter}\marshal

\begin{document}
\lstinputlisting[language=text]{input.text}
\end{document}

其中input.text包含代码:

Only a test, this is not a comment
XYZ this should colored as a comment
and this line too

this is not a command, because only lines starting with XYZ
are comments

This is not a comment, too

谢谢

相关内容