6

I wish to design a convenience command \lazycmd that works like this (simplified version):

\newcommand{\lazycmd}[1]{%
  ...
}

% Use case 1.
\lazycmd{
  \item one
  \item two
}

% Use case 2.
\lazycmd{
  custom
}

\lazycmd is expected to:

  • Add \begin{itemize} and \end{itemize} in the front and the back of #1, if the argument begins with \item (with leading spaces skipped). This is my "normal case".
  • Otherwise, copy #1. This is my "special case", as the argument will provides its own format.

The problems are, how to use "\item" as a string in the comparison, and how to skip any potential leading spaces? Thanks a lot!

7

Option one.

\newcommand\lazycmd[1]{\begingroup
  \let\saveditem\item
  \let\auxend\relax
  \def\item{\let\item\saveditem\def\auxend{\end{itemize}}\begin{itemize}\item}%
  #1%
  \auxend\endgroup
}

Option two.

\newcommand\lazycmd[1]{\dolazycmd#1\endlazycmd}
\def\dolazycmd#1\endlazycmd
  {\@ifnextchar\item{\def\auxend{\end{itemize}}\begin{itemize}}{\let\auxend\relax}#1\auxend}

Third option.

\newcommand\lazycmd[1]{\dolazycmd#1\endlazycmd}
\def\dolazycmd#1#2\endlazycmd
  {\ifx\item#1
     \begin{itemize}#1#2\end{itemize}%
   \else
     #1#2%
   \fi}
1

You may be interested in an expl3 based solution:

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\lazycmd}{O{\use:n} m}
 {
  \seq_set_split:Nnn \l_wdscxsj_lazycmd_seq { \item } { #2 }
  \int_compare:nTF { \seq_count:N \l_wdscxsj_lazycmd_seq > 1 }
   { % more than one item, there was \item
    \begin{itemize}
    \seq_use:Nn \l_wdscxsj_lazycmd_seq { \item }
    \end{itemize}
   }
   {
    #1 { \tl_trim_spaces:n { #2 } }
   }
 }
\seq_new:N \l_wdscxsj_lazycmd_seq
\ExplSyntaxOff

\begin{document}

Here is some text followed by the command
\lazycmd{
  \item one
  \item two
}
and the same without any item
\lazycmd{
  single
}
that can also be typeset in a different way
\lazycmd[\textbf]{
  single
}

\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.