[Tex/LaTex] What’s wrong with the newcommand

macrosparameters

I defined a question macro, then made it successively fancier. Right now, three macro should define a short hand for the following:

\section{Questions}
\begin{enumerate}
\item Q1...
\item Q2...
\end{enumerate}
\section{Exercises}
\begin{enumerate}
\item exercise 1
\item exercise 2
\end{enumerate}
\href{my.url.goes/here/specific}{Take the quiz}

The three commands defined to do this are:

\newcommand{\qqq}{\section{Question}\begin{enumerate}}
\newcommand{\exer}{\end{enumerate}\section{Exercises}\begin{enumerate}}
\newcommand{\endexer}[1]{\end{enumerate}\href{my.url.com/path/{#1}}{Take the quiz}}

A sample call to make this happen:

\qqq
\item What is 2+3?
\exer
\item Write a program to compute 2+3
\endexer{123}

should generate the url:

my.url.com/path/123

The error is:

! LaTeX Error: Command \endexer already defined.
Or name \end… illegal, see p.192 of the manual.

I am not posting the MWE because I think this is a stupid syntax error based on something I am missing about \newcommand, but if I'm wrong, I will create an MWE and add it here.

Best Answer

The first problem you have is that you cannot create a macro starting with \end... when using \newcommand. This check is defined inside the LaTeX kernel as part of an \@ifdefinable condition. To circumvent this you need to use TeX directives. That is,

\def\endexer#1{<stuff>}

rather than

\newcommand{\endexer}[1]{<stuff>}

Secondly, the \newcommand syntax has the following structure (see source2e.pdf):

\newcommand*{\foo}[<i>][<j>]{<text>}
  • * is optional
  • \foo is the command to be created
  • <i> is the number of arguments to gobble (up to 9); this references mandatory or a possible optional argument
  • <j> is the default value of the first optional argument (if it exists does not exist); can only have one
  • <text> is the macro definition when using \foo

For \newcommand{\foo}[1]{stuff #1} you would use it as \foo{<stuff>}, not \foo[<stuff>]. This latter usage would have required a definition of \foo of the form

\newcommand{\foo}[1][]{<stuff>}

Note the second set of [], denoting that \foo takes an optional argument (that is empty by default/if not specified).

Specific to your case, use \endexer{123}, not \endexer[123].


Here is a minimal example:

enter image description here

\documentclass{article}
\usepackage{hyperref}
\newcommand{\qqq}{\section{Question}\begin{enumerate}}
\newcommand{\exer}{\end{enumerate}\section{Exercises}\begin{enumerate}}
\def\endexer#1{\end{enumerate}\href{my.url.com/path/{#1}}{Take the quiz}}
\begin{document}

\qqq
\item What is $2+3$?
\exer
\item Write a program to compute $2+3$.
\endexer{123}

\end{document}