jbezos / enumitem

Customize enumerate, itemize and description
MIT License
45 stars 5 forks source link

Wrapping item's in a lualatex based environment #31

Closed kalekje closed 2 years ago

kalekje commented 2 years ago

Based on this Stack Exchange Q

I have written a lua-based function to automatically puntuate itemized lists like so:

  1. one;
  2. two; and
  3. three.

The ; etc is automatically added. I can apply this as a command or environment inside an itemize or enumerate environment. What I would prefer though, is to pass autopunc as a key to the optional key-val args that enumitem provides. Eg. \begin{itemize}[autopunc]. Please see MWE below. The error that I am getting is Error: You can't use \spacefactor' after \advance.\@->\spacefactor

\documentclass{scrartcl}
\usepackage{luacode}
\usepackage{enumitem}

\begin{luacode*}
function AutoPuncItems(s, btwn, seclast, last) -- add btwn and sec and last options
    local it = '\\item'
    local s_item = '%s*'..it
    btwn = btwn or ';'
    btwn = btwn..' '..it
    seclast = seclast or '; and'
    seclast = seclast..' '..it
    last = last or '.'
    local _, n_matches = string.gsub(s, s_item, "") -- find num items
    s, _ = string.gsub(s, s_item,    seclast,   n_matches) -- replace all items with second last type
    s, _ = string.gsub(s, seclast,   btwn,      n_matches-1) --replace all but last(ie second last) with the between
    s, _ = string.gsub(s, '%s*xxxENDxxx', last) -- add the final char
    s = string.sub(s, #btwn-#it+1, #s)
    tex.print(s)
end
\end{luacode*}

\NewDocumentCommand{\AutoPuncItems}{ O{;} O{; and} O{.} m }{
    \luadirect{AutoPuncItems(
        \luastringN{#4xxxENDxxx},
        \luastringN{#1},
        \luastringN{#2},
        \luastringN{#3}
    )}
}
\NewDocumentEnvironment{AutoPuncItemize}{ O{;} O{; and} O{.} +b }{
   \AutoPuncItems[#1][#2][#3]{#4}
}{}

%%% 
\SetEnumitemKey{autopunc}{% trying these don't seem to work
%    first*=\begin{AutoPuncItemize}, 
    before*=\begin{AutoPuncItemize},
    after=\end{AutoPuncItemize},
%% last=\end{AutoPuncItemize} % not a valid key, but this WOULD be nice
}

\begin{document}

    Works as desired
\begin{itemize}
    \AutoPuncItems{
        \item one
        \item two
        \item three
    }
\end{itemize}

    Works as desired
\begin{itemize}
    \begin{AutoPuncItemize}
        \item one
        \item two
        \item three
    \end{AutoPuncItemize}
\end{itemize}

    This is what I'm trying to get, desired interface
\begin{itemize}[autopunc]
    \item one
    \item two
    \item three
\end{itemize}

\end{document}