This is a follow-up question to my previous one on using special characters in user-defined commands. I have extended the command \Char{}
to take an optional parameter for a fixed with. \Char{}
is supposed to work in text mode and math mode.
The MWE
\documentclass{article}
\usepackage{lmodern}
\usepackage{xparse}
\usepackage{relsize}
\usepackage{amssymb}
\ExplSyntaxOn
\NewDocumentCommand \Char { o m }
{
\IfNoValueTF {#1}
{
\str_case_x:nnF { \tl_to_str:n {#2} }
{
{ } { \mbox{$\varepsilon$} }
{ ## } { \mbox{\texttt{\#}} }
{ \c_tilde_str } { \mbox{\textscale{.87}{$\Box$}} }
}
{ \mbox{\texttt{#2}} }
}
{
\str_case_x:nnF { \tl_to_str:n {#2} }
{
{ } { \makebox[#1]{$\varepsilon$} }
{ ## } { \makebox[#1]{\texttt{\#}} }
{ \c_tilde_str } { \makebox[#1]{\textscale{.87}{$\Box$}} }
}
{ \makebox[#1]{\texttt{#2}} }
}
}
\ExplSyntaxOff
\begin{document}
\Char{}\Char{~}\Char{#}\Char{x}
$\Char{}\Char{~}\Char{#}\Char{x}$
\Char[1em]{}\Char[1em]{~}\Char[1em]{#}\Char[1em]{x}
$\Char[1em]{}\Char[1em]{~}\Char[1em]{#}\Char[1em]{x}$
\end{document}
produces the desired result
However, is there a better way to implement this functionality based on expl3?
\str_case
rather than having two of them, and may be moving\texttt
out of the cases if possible, i.e.,\makebox{\texttt{\str_case .. }}
).O{\width}
instead ofo
and then you don't need the IfNoValue test you can just use the\makebox
form always as\makebox[\width]{zzz}
is the same as\mbox{\zzz}
just marginally less efficient. but it would halve the size of your definition and save you checking the two halves were in sync as you add more cases.