2

This is somewhat hacky. I'm ultimately trying to create an exam template that rearranges itself. But, I want a lot of flexibility and the randomizing exam packages that exist don't seem to work.

I'm stuck on something that I can't really figure out. I want to define two commands, \before and \after that switch places along with everything after them. So, something like this:

Hi there!
\begin{switcher}
\before Blah blah

Paragraphs make things hard. \lipsum \foo
\begin{itemize}\item A\item B\item etc.\end{itemize}

\after This should hopefully come first.

As well as this!
\end{switcher}
This is normal!

Should give the exact same result as something like this:

Hi there!
This should hopefully come first.

As well as this!

Blah blah

Paragraphs make things hard. \lipsum \foo
\begin{itemize}\item A\item B\item etc.\end{itemize}

This is normal!

Ideally, I want the flexibility to rearrange a list like scenario. But, I'm pretty sure I can figure it out myself if I know how to do this basic example. I'm just not sure where to start.

1 Answer 1

2

Welcome to TeX.SE! You can grab the contents (tokens) of an environment using the environ package. Then the contents is available as the replacement text of a \BODY macro. The puzzle is solved by calling a macro of yours (here called \@myswitch) defined with delimited arguments on the expansion of the \BODY macro.

Note that this can also be done with commands from the xparse package if you like expl3.

\documentclass{article}
\usepackage{environ}
\usepackage{lipsum}

\makeatletter

% I only added the \par to match the output requested in the question.
\long\def\@myswitch#1\before#2\after#3\@nil{#1#3\par #2}

\NewEnviron{switcher}{%
  \expandafter\@myswitch\BODY\@nil
}

\makeatother

\newcommand*\foo{Bleh!}

\begin{document}

Hi there!
\begin{switcher}
\before Blah blah

Paragraphs make things hard. \lipsum[1-2] \foo
\begin{itemize}\item A\item B\item etc.\end{itemize}

\after This should hopefully come first.

As well as this!
\end{switcher}
This is normal!

\end{document}

enter image description here

Roadmap for an expl3 version than can handle an arbitrary number of parts

In case you want to handle an arbitrary number of parts and shuffle them, my suggestion would be to use expl3 and xparse:

  • grab the body of the environment using a +b argument specifier with xparse's \NewDocumentEnvironment command;

  • use \seq_set_split:Nnn to store all parts (separated by a common delimiter of your choice) into a sequence variable; the delimiter can be a token list, it doesn't have to be a single token;

  • use \seq_shuffle:N to randomly shuffle the sequence populated in the previous step;

  • use \seq_use:Nn (or a similar function such as \seq_use:Nnnn) to output the shuffled parts to the document stream.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .