定义打开和关闭环境的命令

定义打开和关闭环境的命令

我想定义一个命令,\begin{...}如果不在这样的环境中,则启动( 's it)该环境,\end{...}如果在这样的环境中,则关闭( 's it)该环境,例如:

\myenum
    \item Item A
    \item Item B
\myenum

当然,这意味着myenum环境不能嵌套。有人知道如何定义这样的命令吗?

答案1

不确定这有多大用处;当然,嵌套是不可能的。

\documentclass{article}

\usepackage{pdftexcmds}
\makeatletter
\catcode`*=\active
\def*{\@ifnextchar*{\check@enumerate}{\item}}

\def\check@enumerate{%
  \ifnum\pdf@strcmp{\@currenvir}{enumerate}=\z@
    % we're already in enumerate
    \end{enumerate}
  \else
    \begin{enumerate}
  \fi
  \@gobble
}
\makeatother

\begin{document}

Some text which we try to make long enough to reach
the right margin, so that we can see a line break
before the \texttt{enumerate} environment.
**
* First
* Second
**

Some other text which we try to make long enough to reach
the right margin, so that we can see a line break
after the \texttt{enumerate} environment.

\end{document}

在此处输入图片描述

expl3相同的实现:

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\cs_new:Nn \carucel_item_or_enum:
 {
  \peek_charcode_remove:NTF * 
   {
    \carucel_enum:
   }
   {
    \item
   }
 }
\cs_new:Nn \carucel_enum:
 {
  \tl_if_eq:vnTF { @currenvir } { enumerate }
   {
    \end{enumerate}
   }
   {
    \begin{enumerate}
   }
 }
\cs_generate_variant:Nn \tl_if_eq:nnTF { v }

\char_set_catcode_active:N *
\cs_set_eq:NN * \carucel_item_or_enum:
\ExplSyntaxOff

\begin{document}

Some text which we try to make long enough to reach
the right margin, so that we can see a line break
before the \texttt{enumerate} environment.
**
* First
* Second
**

Some other text which we try to make long enough to reach
the right margin, so that we can see a line break
after the \texttt{enumerate} environment.

\end{document}

相关内容