How do I use textcolor inside discretionary?

Instead of using \textcolor inside a discretionary, you can use it around the discretionary:

\newcommand*{\code}{\lstinline[basicstyle=\relscale{0.9}\ttfamily\color{red},keywordstyle=\color{red},stringstyle=\color{red},keepspaces=true,breaklines=true,literate={\\\-}{}{0\textcolor{black}{\rmfamily\discretionary{-}{}{}}}]}

Are you aware of the \lstset macro? Instead of using your \code, you can write

\lstset{basicstyle=\relscale{0.9}\ttfamily\color{red},keywordstyle=\color{red},stringstyle=\color{red},keepspaces=true,breaklines=true,literate={\\\-}{}{0\textcolor{black}{\rmfamily\discretionary{-}{}{}}}}

in your preamble. Then \lstinline always uses the options.


\textcolor colour whatsits to change the colour which are not allowed in a discretionary, however you can have boxes so you just need to put the content of each field in an \hbox

enter image description here

\documentclass{article}

\usepackage{color}

\begin{document}

aaaaaaaaaaaaaaaa\discretionary
{\hbox{\textcolor{red}{AAA}}}{\hbox{\textcolor{blue}{BBB}}}{\hbox{\textcolor{green}{CCC}}}%
bbbbb
aaaaaaaaaaaaaaaa\discretionary
{\hbox{\textcolor{red}{AAA}}}{\hbox{\textcolor{blue}{BBB}}}{\hbox{\textcolor{green}{CCC}}}%
bbbbb
aaaaaaaaaaaaaaaa\discretionary
{\hbox{\textcolor{red}{AAA}}}{\hbox{\textcolor{blue}{BBB}}}{\hbox{\textcolor{green}{CCC}}}%
bbbbb
\end{document}