[Tex/LaTex] Add colored background to listing with colored words

colorlistings

I wish to (manually) add a colored background to particular lines in a lstlisting. There are quite a few answers already, which use realboxes package or a colorbox. However, the color I defined does not show up, and it removes the letter color that I set up. Here's a minimum working example:

% annotation background colors
\definecolor{blueannoback}{RGB}{51,51,255} % use xcolor package
\definecolor{greenannoback}{RGB}{230,244,214}

\begin{lstfloat}
\begin{lstlisting}[escapeinside={\%*}{*),morecomment=[l][\textcolor{BurntOrange}]{@}]}
%*\colorbox{blueannoback}{@Anno1}*)
%*\colorbox{greenannoback}{@Anno2}*)
@Anno3
public void MyClass {}
\end{lstlisting}\end{lstfloat}

The idea is that @Anno1, @Anno2 and @Anno3 have the text color BurntOrange (because the line starts with @). Additionally, @Anno1 should have a light blue background (that ideally spans just around the code, not the entire line), and @Anno2 should have a green background.

The background colors are correct. However, the text of @Anno1 and @Anno2 are no longer BurntOrange, presumably because the line no longer starts with @.

Additionally, the annotation text is slightly shifted to the right (which I can live with, but would be nice to fix this as well).

So how do I preserve the text color, while adding the background color?

Best Answer

My solution

(Optional) Define custom colors

I first created some custom colors in mysettings.sty.

% annotation background colors
\definecolor{blueannoback}{RGB}{234,242,250}
\definecolor{greenannoback}{RGB}{230,244,214}

My main.tex file includes the following packages:

\usepackage{xcolor} 
\usepackage{mysettings} 

Custom listing style

Next I define a custom style for each programming language of my choice. In this example I define a custom language which is based on Java.

The custom Java language allows me to color the font of my annotations automatically:

% Define custom Java language
\lstdefinelanguage{custom-java}{
    ...,
    morecomment=[l][\textcolor{BurntOrange}]{@}
}

The custom listing style provides a custom way to specify escapeinside in order to use LateX commands inside my listing, which I will need:

\lstdefinestyle{my-java-style}{
    language=custom-java,
    ...,
    escapeinside={\%*}{*)}
}

The listing

I then use a colorbox to wrap the text in a background with the color of my choosing. The text needs to be escaped so that LateX code may be executed inside the listing. Note that this overrides the BurntOrange font color I had defined for lines that start with @.

\begin{lstlisting}[style=my-java-style, otherkeywords={this}]
%*\colorbox{blueannoback}{@Entity}*)
%*\colorbox{blueannoback}{@Table(name="CourseCredits")}*)
%*\colorbox{greenannoback}{@Function}*)
public class CourseCredit %*\colorbox{blueannoback}{implements Serializable}*) {
    %*\colorbox{blueannoback}{@Id}*)
    %*\colorbox{blueannoback}{@Column(name="Course")}*)
    %*\colorbox{greenannoback}{@ArgumentType(value=1, typeName="Course")}*)
    private String course;
    %*\colorbox{blueannoback}{@Column(name="Credits")}*)
    %*\colorbox{greenannoback}{@FunctionValue("Credits")}*)
    private int credits;

    public %*\colorbox{blueannoback}{CourseCredit()}*){
    }

    public %*\colorbox{greenannoback}{CourseCredit(String course, int credits)}*){
        this.course = course;
        this.credits = credits;
    }
}\end{lstlisting}

Result

enter image description here

Full code for minimal working example

Here's the full code to reproduce the above image. I tried to keep it compact.

mysettings.sty

% Colors
\definecolor{javapurple}{rgb}{0.5,0,0.35}
\definecolor{blueannoback}{RGB}{234,242,250}
\definecolor{greenannoback}{RGB}{230,244,214}

% Define language
\lstdefinelanguage{my-java}{
    keywords={private,public,class,this}
}

% define style
\lstdefinestyle{my-java-style}{
    language=my-java,
    basicstyle=\footnotesize,   
    captionpos=b,                  
    alsoletter={.},         
    escapeinside={\%*}{*)},       
    extendedchars=true,          
    frame=tb,                     
    keepspaces=true,   
    keywordstyle=\color{javapurple}\bfseries,  
    rulecolor=\color{black},
    tabsize=4
}

main.tex

\documentclass[12pt]{article}

\usepackage[T1]{fontenc}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{mysettings} % my .sty file

\begin{document}

\begin{lstlisting}[style=my-java-style,otherkeywords={this}]
%*\colorbox{blueannoback}{@Entity}*)
%*\colorbox{blueannoback}{@Table(name="CourseCredits")}*)
%*\colorbox{greenannoback}{@Function}*)
public class CourseCredit %*\colorbox{blueannoback}{implements Serializable}*) {
    %*\colorbox{blueannoback}{@Id}*)
    %*\colorbox{blueannoback}{@Column(name="Course")}*)
    %*\colorbox{greenannoback}{@ArgumentType(value=1, typeName="Course")}*)
    private String course;
    %*\colorbox{blueannoback}{@Column(name="Credits")}*)
    %*\colorbox{greenannoback}{@FunctionValue("Credits")}*)
    private int credits;

    public %*\colorbox{blueannoback}{CourseCredit()}*){
    }

    public %*\colorbox{greenannoback}{CourseCredit(String course, int credits)}*){
        this.course = course;
        this.credits = credits;
    }
}\end{lstlisting}

\end{document}
Related Question