lstlisting
我尝试在自定义环境后缩进第一段
\documentclass{article}
\usepackage{listings,lipsum}
\lstnewenvironment{mycode}{}{\par}
\begin{document}
\lipsum[1]
\begin{mycode}
\def\cmd#1{\cs{\expandafter\cmd@to@cs\string#1}}
\def\cmd@to@cs#1#2{\char\number`#2\relax}
\DeclareRobustCommand\cs[1]{\texttt{\char`\\#1}}
\end{mycode}
\lipsum[1]
\end{document}
但上述代码失败了。我该如何修复上述代码?
答案1
使用etoolbox
及其\AfterEndEnvironment
钩子插入\par
\documentclass{article}
\usepackage{listings,lipsum}
\lstnewenvironment{mycode}{}{}
\usepackage{etoolbox}
\AfterEndEnvironment{mycode}{\par}
\begin{document}
\lipsum[1]
\begin{mycode}
\def\cmd#1{\cs{\expandafter\cmd@to@cs\string#1}}
\def\cmd@to@cs#1#2{\char\number`#2\relax}
\DeclareRobustCommand\cs[1]{\texttt{\char`\\#1}}
\end{mycode}
\lipsum[1]
\end{document}
答案2
如果要缩进,只需在环境后留一个空行:
\documentclass{article}
\usepackage{listings,lipsum}
\lstnewenvironment{mycode}{}{}
\begin{document}
\lipsum[1]
\begin{mycode}
\def\cmd#1{\cs{\expandafter\cmd@to@cs\string#1}}
\def\cmd@to@cs#1#2{\char\number`#2\relax}
\DeclareRobustCommand\cs[1]{\texttt{\char`\\#1}}
\end{mycode}
\lipsum[1]
\end{document}