将文件中包含的文本注入自定义环境

将文件中包含的文本注入自定义环境

如何将文件中包含的文本input.tex注入自定义环境。例如:

\documentclass{report}
\usepackage{listings}

\lstdefinelanguage{text}{}
\lstnewenvironment{my}{\lstset{language=text}}{}

\begin{document}
\begin{my}
\input{input.tex}
\end{my}
\end{document}

回复 Gonzalo Medina:

你好,如果我使用,\lstinputlisting[language=text]{file.tex}那么评论(出现在之后\\)将无法正确突出显示为评论:

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

\lstdefinelanguage{text}{
commentstyle=\color{green},
basicstyle=\footnotesize\ttfamily,
showstringspaces=false,
showspaces=false,
}

{\catcode`\^^M=12 
\def\marshal{\lstnewenvironment{my}{
\lstset{language=text,comment=[s]{\\\\}{^^M}}
}{}}\expandafter}\marshal

\begin{document}

The following works as expected (comments showing in green): 

\begin{my}
Not comment
\\Commment
Not comment
\end{my}

The following does not work as expected (comments not green):

\lstinputlisting[language=text]{input.text}

\end{document}

其中input.text包含以下代码:

Not comment
\\Commment
Not comment

@egreg

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

\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 文件中时相同的颜色。谢谢

答案1

我相信你可以做得更简单:

\begin{filecontents*}{\jobname.txt}
Not comment
\\Commment
Not comment
\end{filecontents*}
\documentclass{report}
\usepackage{listings,xcolor}

\lstdefinelanguage{text}{
  commentstyle=\color{green},
  basicstyle=\footnotesize\ttfamily,
  showstringspaces=false,
  showspaces=false,
  comment=[l]{\\\\},
}

\begin{document}

The following works as expected (comments showing in green): 

\begin{lstlisting}[language=text]
Not comment
\\Commment
Not comment
\end{lstlisting}

The following works as expected (comments showing in green):

\lstinputlisting[language=text]{\jobname.txt}

\end{document}

在此处输入图片描述

相关内容