Replace a single letter in xelatex

fontsfontspecxetex

Is it possible to replace a single text letter of the current font in my document by another font that is available in my system. The rest of the characters of my current font should be retained. Is this possible?

I know that I can do this for math using unicode-math and \setmathfont[range={}] but the same will not work with fontspec.

Say my document font is Computer Modern Roman. I would like only the f to get automatically converted to corresponding f for BaskervilleF (or any other font available on my system). That goes for both lower and upper case f and F, both bold and italic. Basically, only one letter should be replaced by the corresponding letter from the other font

Best Answer

You can put f in its own character class:

enter image description here

\documentclass{article}
\XeTeXinterchartokenstate=1

\newXeTeXintercharclass\fclass

\XeTeXcharclass `\f \fclass

\XeTeXinterchartoks 0 \fclass = {\myf}
\XeTeXinterchartoks 4095 \fclass = {\myf}
\XeTeXinterchartoks \fclass \fclass = {\myf}

\newcommand\myf[1]{\textsf{\large \fbox{F}}}

\begin{document}

One two three four five safe iff difficult.

\end{document}

After the question edited, f and F and a check on the current font family.

enter image description here

\documentclass{article}
\XeTeXinterchartokenstate=1

\newXeTeXintercharclass\fclass

\XeTeXcharclass `\f \fclass
\XeTeXcharclass `\F \fclass

\XeTeXinterchartoks 0 \fclass = {\myf}
\XeTeXinterchartoks 4095 \fclass = {\myf}
\XeTeXinterchartoks \fclass \fclass = {\myf}

\def\ffamily{lmr}

\makeatletter
\newcommand\myf[1]{{\XeTeXinterchartokenstate=0 
  \ifx\f@family\ffamily\sffamily\large\fi % only switch if currently lmr
#1}}
\makeatother

\begin{document}

Roman lmr 
One two three Four Five safe iff difficult.
\textbf{One two three four five safe iff difficult.}

Italic lmr \textit{One two three Four Five safe iff difficult.
\textbf{One two three four five safe iff difficult.}}

tt not affected \texttt{One two three Four Five safe iff difficult.}
\end{document}