One command that detects none letter in an argument
Quite naturally, check with regular expressions:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\doubleit}{m}
{
\projetmbc_doubleit:n { #1 }
}
\prg_generate_conditional_variant:Nnn \regex_match:nn { nV } { T,F,TF }
\cs_new_protected:Nn \projetmbc_doubleit:n
{
\tl_set:Nn \l_tmpa_tl { #1 }
% get rid of spaces
\regex_replace_all:nnN { \s } { } \l_tmpa_tl
\regex_match:nVTF { .. } \l_tmpa_tl
{% more than one token
\regex_match:nVTF { \A -[0-9]* \Z } \l_tmpa_tl
{% we have a negative number
\int_eval:n { 2 * (\l_tmpa_tl) }
}
{
2(\l_tmpa_tl)
}
}
{% one token
\regex_match:nVTF { [0-9] } \l_tmpa_tl
{% it's a single digit number
\int_eval:n { 2 * \l_tmpa_tl }
}
{%
2\l_tmpa_tl
}
}
}
\ExplSyntaxOff
\begin{document}
$\doubleit{3}$
$\doubleit{-3}$
$\doubleit{x}$
$\doubleit{-x}$
$\doubleit{x-3}$
\end{document}
Add \,
if you want in the middle case, but there's no reason to.
Here's a LuaLaTeX-based solution. If the argument of \doubleit
-- say, x
-- is a single digit, it is multiplied by 2 directly; if it's a single uppercase or lowercase letter, the output is 2x
; in all other cases, the output is 2(x)
. (If x
consists of a single character that's neither a letter nor a digit, nothing is returned since we're presumably dealing with a typo...)
\documentclass{article}
\usepackage{luacode} % for "\luaexec" macro
\luaexec{ % Set up a Lua function:
function doubleit ( s )
if string.len ( s ) == 1 then
if s:find ( "\%d" ) then % it's a number!
tex.sprint ( 2*tonumber(s) )
elseif s:find ( "\%a" ) then % it's a letter!
tex.sprint ( "2" .. s )
end % do nothing if neither number nor letter
else
tex.sprint ( "2(" .. s .. ")" )
end
end
}
% Create a LaTeX "wrapper" macro:
\newcommand\doubleit[1]{\directlua{doubleit("#1")}}
\begin{document}
$\doubleit{x} \quad
\doubleit{3} \quad
\doubleit{-x} \quad
\doubleit{x-3} \quad
\doubleit{.}$
\end{document}
The case where the single token is a digit is not really specified in the question. I like egreg's approach of actually doubling, but taking the question literally we could go with
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\doubleit}{m}
{
\projetmbc_doubleit:n { #1 }
}
\cs_new_protected:Nn \projetmbc_doubleit:n
{
2
\bool_lazy_and:nnTF
{ \tl_if_single_token_p:n {#1} }
{ \token_if_letter_p:N #1 }
{#1}
{ (#1) }
}
\ExplSyntaxOff
\begin{document}
$\doubleit{3}$
$\doubleit{-3}$
$\doubleit{x}$
$\doubleit{-x}$
$\doubleit{x-3}$
\end{document}