简单嵌套环境问题

简单嵌套环境问题

我以为这会很简单,也许确实如此,但我忽略了一些东西。以下(非功能性代码)给出了此错误:

./mwe-environments.tex:28: LaTeX Error: \begin{innerii} on input line 28 ended by \end{inneri}.

我遗漏了什么?我想outer开始inneriinnerii结束inner1并最终完成\end{outer}innerii(这是一个基本的 MWE——环境中有很多内容。)

\documentclass{article}

\usepackage{xparse}
\usepackage{calc}

\NewDocumentEnvironment{myouter}{}{%
    \begin{inneri}
}{%
    \end{innerii}
}

\NewDocumentEnvironment{inneri}{}{%
    \bfseries
}{%
}

\NewDocumentEnvironment{innerii}{}{%
    \end{inneri}
    \itshape
}{%
%
}

\begin{document}

\begin{myouter}
Bla bla bla
\begin{innerii}
BLA bLA bLA
\end{myouter}

\end{document}

答案1

正如 David 所说,不建议这样做,因为它破坏了每个人都期望的 LaTeX范式。话虽如此,这里有另一种方法来解决这个问题:在环境中\begin{env}...\end{env}不要使用\begin{inneri}和,而只使用和。这会阻止 LaTeX 向前查找并搜索。完整代码:\end{inneri}\inneri\endinneri\end{inneri}

\documentclass{article}

\usepackage{xparse}
\usepackage{calc}

\NewDocumentEnvironment{myouter}{}{%
    \inneri
}{%
    \end{innerii}
}

\NewDocumentEnvironment{inneri}{}{%
    \bfseries
}{%
}

\NewDocumentEnvironment{innerii}{}{%
    \endinneri
    \itshape
}{%
%
}

\begin{document}

\begin{myouter}
Bla bla bla
\begin{innerii}
BLA bLA bLA
\end{myouter}

\end{document}

答案2

LaTeX 非常灵活,但是如果弯曲太多,它可能会断裂,但运行时不会出现错误。

\documentclass{article}

\usepackage{xparse}
\usepackage{calc}

\makeatletter
\NewDocumentEnvironment{myouter}{}{%
    \begin{inneri}%
}{%
% please don't do this in any public package
% it completely breaks latex syntax and any editors, syntax
% highlighters or humans trying to read the document.
   \def\@currenvir{innerii}%
    \end{innerii}%
}

\NewDocumentEnvironment{inneri}{}{%
    \bfseries
}{%
}

\NewDocumentEnvironment{innerii}{}{%
% please don't do this in any public package
% it completely breaks latex syntax and any editors, syntax
% highlighters or humans trying to read the document.
    \def\@currenvir{inneri}%
    \end{inneri}%
    \itshape
}{%
%
}
\makeatother
\begin{document}

\begin{myouter}
Bla bla bla
\begin{innerii}
BLA bLA bLA
\end{myouter}

\end{document}

相关内容