0

I'm getting the error Illegal parameter number in definition of \setuplateloadedpackages. for the following code. It seems like newcommand can't recognise that the "macro arguments" passed to crefformat are not its own, but placeholders to be substituted later by cleveref. I have also tried defining \setuplateloadedpackages using \def and \let, to no avail.

\newcommand*{\setuplateloadedpackages}{
    % Configure styles for references.
    \crefformat{section}{\S#2#1#3}
    \crefformat{subsection}{\S#2#1#3}
    \crefformat{subsubsection}{\S#2#1#3}
    \crefrangeformat{section}{\S\S#3#1#4 to~#5#2#6}
    \crefmultiformat{section}{\S\S#2#1#3}{ and~#2#1#3}{, #2#1#3}{ and~#2#1#3}
}
egreg
  • 1,121,712
Noldorin
  • 890
  • 1
    Double the # symbols if you are defining macros inside another macro: \crefformat{section}{\S##2##1##3}. You need to double the number of #s for eac nesting level. – moewe Jan 27 '21 at 05:10
  • @moewe Thank you! I tried escaping them, but didn't think of that for some reason. – Noldorin Jan 27 '21 at 06:02
  • Would you be OK with closing this question as a duplicate of https://tex.stackexchange.com/q/42463/35864? It might not be clear a priori that \crefformat{<counter>}{<code>} basically works like \def/\newcommand, but once you know that, the linked question is a good duplicate. If you'd prefer a separate answer instead, just let me know, I could type something up later. – moewe Jan 27 '21 at 06:51
  • Probably nice to have a brief answer here, because that question presumes the answer to this one... hence they're different enough. Maybe just write a short answer that links to that question, and I'll gladly upvote and mark it as the answer. – Noldorin Jan 27 '21 at 07:25

1 Answers1

2

For the purposes of this problem \crefformat{<counter>}{<code>} works very similar to \def<macroname>{<code>}: The #1, #2, #3 work just like normal macro arguments.

In order for TeX to properly pick up to which macro the arguments belong when you nest macro definitions, you need to double the #s for each nesting level as explained in What is the meaning of double pound symbol (number sign, hash character) ##1 in an argument?.

Because you have to say

\newcommand*{\setuplateloadedpackages}{%
  \newcommand*{\myfoo}[1]{Aha! ##1!}%
}

for LaTeX to have \setuplateloadedpackages properly define \myfoo as a macro taking a single argument and producing Aha! <argument>!, you also have to say

\newcommand*{\setuplateloadedpackages}{%
  % Configure styles for references.
  \crefformat{section}{\S##2##1##3}%
  \crefformat{subsection}{\S##2##1##3}%
  \crefformat{subsubsection}{\S##2##1##3}%
  \crefrangeformat{section}{\S\S##3##1##4 to~##5##2##6}%
  \crefmultiformat{section}{\S\S##2##1##3}{ and~##2##1##3}{, ##2##1##3}{ and~##2##1##3}%
}
moewe
  • 175,683