Defina um comando que abre e fecha um ambiente

Defina um comando que abre e fecha um ambiente

Eu gostaria de definir um comando que inicie ( \begin{...}é isso) um ambiente se não estiver em tal ambiente, e feche ( \end{...}é isso) se estiver em tal ambiente, por exemplo:

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

Claro, isso significa que o myenumambiente não pode ser aninhado. Alguém sabe como definir tal comando?

Responder1

Não tenho certeza de quão útil isso seria; claro, o aninhamento é impossível.

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

insira a descrição da imagem aqui

Uma expl3implementação do mesmo:

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

informação relacionada