# Replace a single letter in xelatex

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

You can put f in its own character class:

\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.

\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}

• It's close but not quite what I am looking for. 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 f/F of CMR should be replaced by the corresponding letter of BaskervilleF. I am trying to figure out if your solution somehow leads to that Oct 24, 2021 at 20:43
• @Masum well you can add F to the fclass then make \myf re-insert #1` rather than discarding it (that will be f or F) replace the fbox silliness with selecting if \f@family is cmr \fontfamily{Baskervliie} Beskervill Oct 24, 2021 at 20:50
• Sorry, I don't quite understand what you mean. Can you please elaborate? Oct 24, 2021 at 20:51
• @Masum see updated answer Oct 24, 2021 at 21:00