[Tex/LaTex] How to get polyglossia to select font for greek script automatically

fontspecgreekpolyglossiaxetex

My question evolves around greek script, but it could be any other script I suppose.

If I have a font set with \setmainfont{#latinfont} which does not contain Greek glyphs and thus set another font with \newfontfamily\greekfont[script=Greek]{#greekfont}, I don't get Greek output from xelatex in my PDF. In order to get Greek script, I have to enclose the respective text in \textgreek{#text}.

My MWE is as follows

\documentclass{article}

\usepackage{polyglossia}

\setmainfont{Cantarell}
\setsansfont{Cantarell}
\newfontfamily\greekfont[Script=Greek]{Liberation Serif}
\newfontfamily\greekfontsf[Script=Greek]{Liberation Serif}
\setdefaultlanguage{english}
\setotherlanguage{greek}

\begin{document}
\tableofcontents{}

\section{Αυτό είναι ελληνικά.}
Welcome to Greek ``serif'': Αυτό είναι ελληνικά

Welcome to Greek ``sans'': \textsf{Αυτό είναι ελληνικά}

Another try to get Greek: \textgreek{Αυτό είναι ελληνικά}
\end{document}

This compiles to

my MWE compiles, but its not how I would like it to look

Unfortunately, always using \textgreek is not only cumbersome, but also not possible in some circumstances. For example in bibliographies, I organize my library in zotero and export from there to biblatex in UTF-8 encoding. Thus, Greek script in, e.g., article titles is contained in the bibliography, often times its just one character (like in γ-Hydroxybutyric acid).

Thus my question: Is it possible to get xelatex/xetex/polyglossia/fontspec to select the correct font depending upon which script is present in the source file? If yes, how can I achieve this? If not, are there alternatives or workarounds?

Best Answer

You can use ucharclasses, but a proper markup is better.

\documentclass{article}

\usepackage{polyglossia}
\usepackage{ucharclasses}

\setmainfont{XCharter} % no Cantarell on my machine
\setsansfont{Futura} % a different one
\newfontfamily{\greekfont}{Liberation Serif}[
  Script=Greek,
  NFSSFamily=liberationserif,
]
\newfontfamily{\greekfontsf}{Liberation Sans}[
  Script=Greek,
  NFSSFamily=liberationsans,
]

\setdefaultlanguage{english}
\setotherlanguage{greek}

\makeatletter
\newcommand{\switchtogreek}{%
  \ifnum\strcmp{\f@family}{\sfdefault}=\z@
    \usefont{\encodingdefault}{liberationsans}{\f@series}{\f@shape}
  \else
    \usefont{\encodingdefault}{liberationserif}{\f@series}{\f@shape}
  \fi
}
\makeatother
\setTransitionsForGreek{\begingroup\switchtogreek}{\endgroup}

\begin{document}
\tableofcontents

\section{Αυτό είναι ελληνικά.}
Welcome to Greek ``serif'': Αυτό είναι ελληνικά

\textsf{Welcome to Greek ``sans'': Αυτό είναι ελληνικά}

Another try to get Greek: \textgreek{Αυτό είναι ελληνικά}
\end{document}

enter image description here