how to determine the number of characters in the argument of a command
It's easy with expl3
:
\documentclass{article}
\usepackage{xparse} % loads expl3
\ExplSyntaxOn
\NewDocumentCommand{\mathvar}{m}
{
\int_compare:nTF { \tl_count:n { #1 } > 1 }
{
\mathrm{#1}
}
{
#1 % or \mathit{#1}, but I wouldn't do it
}
}
\ExplSyntaxOff
\begin{document}
$\mathvar{V}\ne\mathvar{Var}$
\end{document}
The code should be self-explaining: \tl_count:n
counts the number of items in its argument (ignoring spaces, however).
I wouldn't use \mathit
for single letter variables, as normal math italic is specially tailored for the purpose.
An implementation with xstring
:
\documentclass{article}
\usepackage{xstring}
\newcommand{\mathvar}[1]{%
\begingroup\noexpandarg
\StrLen{#1}[\temp]%
\ifnum\temp>1
\mathrm{#1}%
\else
#1%
\fi
\endgroup
}
\begin{document}
$\mathvar{V}\ne\mathvar{Var}$
\end{document}
Here's a LuaLaTeX-based solution. It defines a macro called \numchars
, which returns the number of characters in its argument, and an implementation of \mathvar
. Care is taken not to count whitespace characters in the argument of \mathvar
.
% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{luacode} % for "\luastring" macro and "luacode" environment
\begin{luacode}
function numchars ( s ) -- disregard any whitespace characters
return tex.sprint ( unicode.utf8.len ( unicode.utf8.gsub ( s , "%s", "")))
end
\end{luacode}
\newcommand\numchars[1]{\directlua{numchars(\luastring{#1})}}
\newcommand\mathvar[1]{%
\ifnum\numchars{#1}<2\mathit{#1}\else\mathrm{#1}\fi}
\begin{document}
$\mathvar{ V }$, $\mathvar{VaR}$
\end{document}
Plainer solution.
\documentclass{scrartcl}
\long\def\gobbleone#1{}
\newcommand*\var[1]{\if\relax\detokenize\expandafter{\gobbleone#1}\relax#1\else\mathrm{#1}\fi}
\begin{document}
$\var{A} = \var{B} = \var{Whatever}$
\end{document}