[Tex/LaTex] Automatically check if a math character is greek or latin

math-mode

My question is similar to Bold math: Automatic choice between \mathbf and \boldsymbol for Latin and Greek symbols?, yet slightly different. My non-compilable minimal example is the following one:

\documentclass{book}
\usepackage{amssymb}
\newcommand{\tensor}[1]{if latin alphabet \mathbb{#1} else \mathbf{#1}}
\begin{document}
$\tensor{A}$ $\tensor{\Lambda}$
\end{document}

Is what is suggested achievable? From the example below, I understand that there is no efficient switch at this time between Latin and Greek math alphabets if one uses pdflatex. I also understand that one solution would be to switch to lualatex where Latin and Greek alphabets are handled differently.

Best Answer

I don't have the mtpro2 fonts, so I'll use a different choice of fonts.

The idea is that Latin letters are called by themselves (that is, characters), while Greek letters are called by control sequences. So

\documentclass{article}
\usepackage{bm}
\newcommand\tensor[1]{%
  \ifcat\noexpand#1\relax % check if the argument is a control sequence
    \bm{#1}% probably Greek
  \else
    \textsf{#1}% single character
  \fi
}

\begin{document}
$\tensor{X}\tensor{\Lambda}$
\end{document}

enter image description here

Limitation. Only one token should be given as argument to \tensor. Either \tensor{AB} or \tensor{A\Lambda} or any multiple token variation thereof would fail.


A multitoken macro based on the same idea:

\documentclass{article}
\usepackage{xparse}
\usepackage{bm}

\ExplSyntaxOn
\NewDocumentCommand\tensor{m}
 {
  \pluton_tensor:n { #1 }
 }

\cs_new_protected:Npn \pluton_tensor:n #1
 {
  \tl_map_inline:nn { #1 }
   {
    \token_if_cs:NTF ##1 { \bm { ##1 } } { \textsf { ##1 } }
   }
 }
\ExplSyntaxOff
\begin{document}
$\tensor{X}\tensor{\Lambda}$

$\tensor{X\Lambda}$
\end{document}

Of course this will still fail if arbitrary input is used.

A perhaps more robust version, with a fallback for unknown tokens.

\documentclass{article}
\usepackage{xparse}
\usepackage{bm}

\ExplSyntaxOn
\NewDocumentCommand\tensor{m}
 {
  \pluton_tensor:n { #1 }
 }

\cs_new_protected:Npn \pluton_tensor:n #1
 {
  \tl_map_inline:nn { #1 }
   {
    \pluton_tensor_inner:n { ##1 }
   }
 }

\cs_new_protected:Npn \pluton_tensor_inner:n #1
 {
  \tl_if_in:VnTF \g_pluton_latin_tl { #1 }
   {
    \textsf { #1 } % a Latin letter
   }
   {
    \tl_if_in:VnTF \g_pluton_greek_tl { #1 }
     {
      \bm { #1 } % a Greek letter
     }
     {
      #1 % fall back
     }
   }
 }

\tl_new:N \g_pluton_latin_tl
\tl_new:N \g_pluton_greek_tl
\tl_gset:Nn \g_pluton_latin_tl
 {
  ABCDEFGHIJKLMNOPQRSTUVWXYZ
  abcdefghijklmnopqrstuvwxyz
 }
\tl_gset:Nn \g_pluton_greek_tl
 {
  \Gamma\Delta\Theta\Lambda\Pi\Sigma\Upsilon\Phi\Chi\Psi\Omega
 }

\ExplSyntaxOff
\begin{document}
$\tensor{X}\tensor{\Lambda}$

$\tensor{X\Lambda}$
\end{document}