定義開啟和關閉環境的命令

定義開啟和關閉環境的命令

我想定義一個命令,\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}

相關內容