1

I'm trying to define a command which, upon being called with a certain parameter, 'renews' a different command. In particular, I tried the following (it doesn't work!).

\newcommand{\gap} %initialise \gap to exist
\newcommand{\GAP}{1}{
    \renewcommand{\gap}{\hspace{#1 em}} }

My idea was that \GAP{3} redefines \gap to \hspace{3em}, for example.

I've looked at a few TeX.SE questions, in particular this one, but I can't see how to correct this...

Incidentally, removing the space between #1 and em doesn't work, and putting two #-s outputs 13 (for \GAP{3}).


Here's a full MWE.

\documentclass[]{article}
\usepackage{amsmath,amssymb}
\newcommand{\gap}{} %initialise \gap to exist
\newcommand{\GAP}{1}{
    \renewcommand{\gap}{\hspace{##1em}} }
\begin{document}
\GAP{3}
\end{document}
  • I feel it did the opposite (hence putting it in), but I've removed it – Sam T Oct 16 '17 at 11:21
2

There were three things wrong

  1. The syntax for \newcommand requires the number of arguments in square brackets: \newcommand{\GAP}[1]{...}, not curly brackets \newcommand{\GAP}{1}{...}

  2. The definition of \gap, since it does not take its own argument, must be specified as #1 (i.e., evaluated within the execution of \GAP), rather than as ##1 (which would imply that it is an argument to \gap)

  3. Some stray spaces were in the definition of \GAP.

The MWE:

\documentclass[]{article}
\usepackage{amsmath,amssymb}
\newcommand{\gap}{} %initialise \gap to exist
\newcommand{\GAP}[1]{\renewcommand{\gap}{\hspace{#1em}}}
\begin{document}
a\gap b

\GAP{3}
a\gap b
\end{document}

enter image description here

|improve this answer|||||
  • To 1., well obviously, what on earth was I thinking! =P -- as for 2., that makes sense (I was only trying ## as I saw it on a different question) – Sam T Oct 16 '17 at 10:50
  • 1
    Plus two unwanted spaces. @SamT You should not have those two spaces around \renewcommand. May be a % before, but also remove the space after. – Manuel Oct 16 '17 at 10:50
  • Ok, but may I ask why? – Sam T Oct 16 '17 at 10:52
  • @SamT Why what? – Steven B. Segletes Oct 16 '17 at 10:53
  • Sorry, should've tagged @Manuel! Why not the spaces in this case? – Sam T Oct 16 '17 at 10:54
1

The number of arguments is an optional argument (in brackets) to \newcommand. Here is the corrected example:

\documentclass[]{article}
\usepackage{amsmath,amssymb}
\newcommand{\gap}{} %initialise \gap to exist
\newcommand{\GAP}[1]{%
    \renewcommand{\gap}{\hspace{#1em}} }
\begin{document}
Text\gap Text\GAP{3}
Text\gap Text
\end{document}
|improve this answer|||||
  • It is not \GAP that has an optional argument. \newcommand does. – Leonard Michlmayr Oct 16 '17 at 10:49
  • Yeah, I've realised my silly mistake! Thank you – Sam T Oct 16 '17 at 10:50

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.