0
\documentclass[]{article}

\usepackage{xstring}

\newcommand{\hyb}[1]{\IfStrEqCase{#1}{%
        {2}{$\sqrt{#1}$}%
        {3}{Hi}%
        % you can add more cases here as desired
    }[\PackageError{hyb}{Undefined option to hyb: #1}{}]%
} 

\begin{document}
   \hyb{3}
   \begin{figure}[htp!]
     \centering
     \caption{\hyb{3}}
   \end{figure}
\end{document}

I'm trying to use cases in a command based on the example new command with cases / conditionals / 'if... then's. This works fine in the main text, but when I put it in a figure caption, I get error messages (it still compiles correctly, so I suspect Overleaf is correcting the error, but I can't tell what the error is).

The error messages I get are (

Argument of xs_execfirst has an extra }
                \par 
l.16      \caption{\protect{\hyb{3}}}

and

Runaway Argument?
! Paragraph ended before \xs_execfirst was complete.
<to be read again> 
                   \par 
l.16      \caption{\protect{\hyb{3}}}

! Argument of \xs_IfStringCase has an extra }. <inserted text> \par l.16 \caption{\protect{\hyb{3}}}

! Paragraph ended before \xs_IfStringCase was complete. <to be read again> \par l.16 \caption{\protect{\hyb{3}}}

! Argument of \xs_IfStringCase_ii has an extra }. <inserted text> \par l.16 \caption{\protect{\hyb{3}}}

{Hi}{3}{{2}{$\sqrt {3}$}{3}{Hi}} ! Paragraph ended before \xs_IfStringCase_ii was complete. <to be read again> \par l.16 \caption{\protect{\hyb{3}}}

Is there a workaround for this?

Tyberius
  • 145
  • 2
  • 7
  • 3
    Use \caption{\protect\hyb{3}} to avoid expansion of \hyb within a moving argument (\caption), which is fragile. – Werner Dec 10 '20 at 18:21
  • @Werner \protect seems to result in the same error messages – Tyberius Dec 10 '20 at 18:30
  • When I use your example code I have no problem after adding \protect before \hyb. Can you provide more detail as to why it fails in your case? – Werner Dec 10 '20 at 19:10
  • @Werner the file builds correctly, but I get these error messages. For the toy example, these don't matter much, but for a full document I would rather not have 50 error messages every time I compile even if the output is correct. I also tried building using the CoCalc online editor (output works, same error messages). I'll try to include more detail on the error messages in the question. – Tyberius Dec 10 '20 at 19:17
  • 1
    You're doing it wrong. Note: \protect\hyb, not \protect{\hyb{3}}. – Werner Dec 10 '20 at 19:24
  • @Werner sorry about that, that did the trick. Thank you for your help! – Tyberius Dec 10 '20 at 19:28

0 Answers0