4

My question, in variants, I saw, asked many times here, but I can't solve problem.
If we use \textcolor{FirstLetter}SecondAndOtherLettersOfWord, we lost font kerning between first and second letters.
With \showoutput in log we have \special{color push rgb 1 0 0} and \special{color pop} instructions.
How we need combine \bgroup, \egroup, etc. (from previously answers) in this case (usual text, and often colorized only first letter in word)?

XeLateX. Can't use luacolor and LuaLatex.

MWE:

\documentclass{article}
\usepackage{polyglossia}
\usepackage{xcolor}
\begin{document}
\textcolor{red}{V}AR

VAR
\end{document}
3
  • You can't. The \special nodes interrupt kerning. Only LuaTeX can apply per-glyph colouring, which doesn't disrupt kerning (see the luacolor package) Oct 17, 2020 at 16:03
  • 1
    xelatex inserts specials and so destroys kerning. This is a hard fact. So either accept the missing kerning or switch to lualatex. Oct 17, 2020 at 16:04
  • Or write kenrnig table by hand, using \@ifnextchar...
    – Elisey
    Oct 17, 2020 at 16:07

1 Answer 1

5

Measure the kerning between the word parts. I've added support also for something before the coloring.

\documentclass{article}
\usepackage{xcolor}

\newcommand{\kerncolor}[4]{%
  % #1 = color, #2 = before, #3 = colored part, #4 = after
  \sbox0{#2#3}\sbox2{\mbox{#2}\mbox{#3}}%
  \dimen0=\dimexpr\wd0-\wd2\relax
  \sbox0{#3#4}\sbox2{\mbox{#3}\mbox{#4}}%
  \dimen2=\dimexpr\wd0-\wd2\relax
  #2\kern\dimen0 \textcolor{#1}{#3}\kern\dimen2 #4%
}

\begin{document}

\kerncolor{red}{}{V}{AR}

VAR

\sbox0{\kerncolor{red}{}{V}{AR}}\the\wd0

\sbox0{VAR}\the\wd0

\itshape

\kerncolor{red}{}{V}{AR}

VAR

\sbox0{\kerncolor{red}{}{V}{AR}}\the\wd0

\sbox0{VAR}\the\wd0

\end{document}

enter image description here

3
  • Nice! And it impossible #3 and #4 to unite in one - tokenize first letter?
    – Elisey
    Oct 17, 2020 at 16:42
  • @Elisey The main problem are accented letters.
    – egreg
    Oct 17, 2020 at 16:46
  • Yes, but there is packet churchslavonic (I use it) and it have macros \cu@tokenizeletter - it considers all accents for first letter (for church slavonic language). I'll try combine your answer and this tokenizer. Thank you!
    – Elisey
    Oct 17, 2020 at 17:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .