![新环境中的 lstinline 无法逃避数学](https://linux22.com/image/445054/%E6%96%B0%E7%8E%AF%E5%A2%83%E4%B8%AD%E7%9A%84%20lstinline%20%E6%97%A0%E6%B3%95%E9%80%83%E9%81%BF%E6%95%B0%E5%AD%A6.png)
\lstinline
我正在尝试使用该包创建一个新环境listings
。但它无法逃避数学。
下面是我正在尝试的代码及其输出
\documentclass[12pt,a4paper]{article}
\usepackage{listings}
\usepackage{parskip}
\lstset{mathescape,keepspaces}
\newenvironment{newEnv}[1]{\lstinline[basicstyle=\bfseries\ttfamily,escapeinside={||},mathescape=true]{#1}\\
}
{}
\begin{document}
\lstinline{let $v_1$ = 10 in $v_1$ + $v_2$}
\begin{newEnv}{let $v_1$ = 10 in $v_1$ + $v_2$}
Some random text.
\end{newEnv}
\end{document}
输出
更新:LaTeX 转义无效
\documentclass[12pt,a4paper]{article}
\usepackage{listings}
\usepackage{parskip}
\lstset{mathescape,keepspaces}
\NewDocumentEnvironment{newEnv}{v}
{%
\begingroup
\everyeof{\noexpand}%
\expandafter
\endgroup
\scantokens
{%
\lstinline
[basicstyle=\bfseries\ttfamily,escapeinside=||,mathescape=true]%
{#1}%
}%
\\
}
{}
\begin{document}
\lstinline
[basicstyle=\bfseries\ttfamily,escapeinside=||,mathescape=true]%
{let $v_1$ = 10 in $v_1$ + $v_2$ |this should be escaped\textsuperscript{3}|}
\begin{newEnv}{let $v_1$ = 10 in $v_1$ + $v_2$ |this should be escaped\textsuperscript{3}|}
Some random text.
\end{newEnv}
\end{document}
输出
答案1
以下工作通过逐字抓取参数并将其转发到\lstinline
(包装在里面\scantokens
以便\lstinline
可以分配所需的任何类别代码)。
此解决方案仅适用于单行逐字参数。如果您也需要它适用于多行参数,我可以进行调整(但这需要更多工作)。
\documentclass[12pt,a4paper]{article}
\usepackage{listings}
\usepackage{parskip}
\lstset{mathescape,keepspaces}
\NewDocumentEnvironment{newEnv}{v}
{%
\begingroup
\everyeof{\noexpand}%
\expandafter
\endgroup
\scantokens
{%
\lstinline
[basicstyle=\bfseries\ttfamily,escapeinside={||},mathescape=true]%
{#1}%
}%
\\
}
{}
\begin{document}
\lstinline
[basicstyle=\bfseries\ttfamily,escapeinside={||},mathescape=true]%
{let $v_1$ = 10 in $v_1$ + $v_2$}
\begin{newEnv}{let $v_1$ = 10 in $v_1$ + $v_2$}
Some random text.
\end{newEnv}
\end{document}