\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}