5

My question is closely related to a previous question on dealing with special characters in arguments. However, I was not able to adapt the technique described there to my needs.

The MWE

\documentclass[fontsize=11pt, paper=a4, DIV=9]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{lmodern}
\usepackage{amssymb}
\usepackage{relsize}
\usepackage{xparse}

\makeatletter

\newcommand{\IT@Def@Hash}{\begingroup\catcode`\#=12 \gdef\IT@Char@Hash{#}\endgroup}
\newcommand{\IT@Def@Tilde}{\begingroup\catcode`\~=12 \gdef\IT@Char@Tilde{~}\endgroup}

\NewDocumentCommand{\Char}{>{\TrimSpaces}m}%
{%
  \def\IT@Char{#1}
  \ifx\IT@Char\empty
    \mbox{$\varepsilon$}%
  \else
    \IT@Def@Hash
    \ifx\IT@Char\IT@Char@Hash
      \mbox{\texttt{\#}}%
    \else
      \IT@Def@Tilde
      \ifx\IT@Char\IT@Char@Tilde
        \mbox{\textscale{.87}{$\Box$}}%
      \else
        \mbox{\texttt{\IT@Char}}%
      \fi
    \fi
  \fi
}

\makeatother

\begin{document}

\Char{}
\Char{~}
\Char{#}
\Char{x}

\end{document}

produces exactly the output

Desired output

I am looking for. Unfortunately, LaTeX issues five errors.

It would be quite convenient to "misuse" the special characters ~ and # in the argument of \Char{}. On the other hand, it is not really necessary, and I would avoid it if it causes too much trouble.

Matthias
  • 1,956

1 Answers1

7

You can do that with \str_case:. To take care of ~, you need to make sure TeX sees it when defining \Char (you would get a space otherwise); and regarding # you need to double it because you are in another command.

\ExplSyntaxOn

\NewDocumentCommand \Char { >{\TrimSpaces} m }
{
  \str_case_x:nnF { \tl_to_str:n { #1 } }
   {
    {    } { \ensuremath{\varepsilon} }
    { ## } { \texttt{\#} }
    { \c_tilde_str  } { \textscale{.87}{$\Box$} }
   }
   { \texttt{#1} }
}

\ExplSyntaxOff

This means you can define easily any predefined outputs for particular cases, and then one generic False output (and possible another True, but I omited that one).

egreg
  • 1,121,712
Manuel
  • 27,118
  • Are the spaces after { and before } only for the sake of better readability or do they have any technical purpose? – Matthias Nov 12 '17 at 20:31
  • 1
    They are ignored inside \ExplSyntax so they are there to give clarity following the usual way that expl3 is written. I only leave the code that is not part of expl3 (e.g., \ensuremath{\varepsilon}) so that at first sight it's easier to see (at least for me). – Manuel Nov 12 '17 at 21:30