[Tex/LaTex] Color inline code

colorminted

I'm able to compile the following in Overleaf for the desired inline code-coloring effect:

\documentclass{article}
\usepackage{minted}
\usepackage{xcolor}
\definecolor{codeblue}{rgb}{0,0.3,0.6}
\newmintinline[bluecode]{c++}{\color{codeblue}}

\begin{document}

This is a blue \bluecode{keyword} and this is a normal \mintinline[]{C++}{keyword}.

Which produces:

enter image description here

Yet I have the following errors: Missing \endcsname inserted. and Package keyval Error: \color {codeblue} undefined. I need these errors to go away so I can upload to arXiv. How can I correct this, or otherwise color inline code?

Best Answer

The following patches \mintinline to place the \color inside of it. Note that this only changes the colour of things that are not coloured by the minted package (you can see this in the output of %). The patch doesn't kill the verbatim reading of the argument.

\documentclass[]{article}

\usepackage{xcolor}
\definecolor{codeblue}{rgb}{0,0.3,0.6}
\usepackage{minted}
\usepackage{etoolbox}
\newif\ifBlueCode
\BlueCodetrue
\newcommand*\mybluecode
  {%
    \ifBlueCode
      \global\BlueCodefalse
      \color{codeblue}%
    \fi
  }
\newrobustcmd*\bluecode[1][]
  {%
    \BlueCodetrue
    \mintinline[#1]{C++}%
  }
\expandafter\patchcmd\csname\string\mintinline\endcsname
  {\begingroup}{\begingroup\mybluecode}{}
  {\GenericError{}{Patching of \string\mintinline\space failed!}{}{}}

\begin{document}
This is a blue \bluecode{keyw%rd} and this is a normal
\mintinline[]{C++}{keyw%rd}.
\end{document}

enter image description here

To also suppress the colours placed by minted, you can change the definition of \mybluecode:

\makeatletter
\def\@gobble@undeclaredcolor[#1]#2{}
\newcommand*\mybluecode
  {%
    \ifBlueCode
      \global\BlueCodefalse
      \color{codeblue}%
      \let\@undeclaredcolor\@gobble@undeclaredcolor
      \let\@declaredcolor\@gobble
    \fi
  }
\makeatother