progS
progS

Reputation: 55

Highlighting background of code inside a minted environment

I am trying to highlight some code fragments inside a minted environment.

In my example I used a \colorbox to change the background of words. The problem is that all these words have a different heights and the colorboxes are not at the same level. Is there a way to adjust the colorbox that it has the same height for all characters?

Is there a better way to solve my problem?

enter image description here

\documentclass[a4paper,12pt]{scrreprt}

\usepackage[dvipsnames]{xcolor}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[dvipsnames]{xcolor}
\usepackage[ngerman]{babel}
\usepackage[chapter, cache=false]{minted}
\setminted[python]{
    frame=single,
    framesep=2mm,
    baselinestretch=1.2,
    fontsize=\footnotesize,
    linenos=true,
}

\begin{document}

\begin{listing}[ht]
\begin{minted}[escapeinside=||]{python}
print('test Test !,?/')
|\colorbox{green}{test}| |\colorbox{yellow}{Test}| |\colorbox{red}{!,?/}|
\end{minted}
\end{listing}

\end{document}

Upvotes: 2

Views: 2434

Answers (1)

You can ensure a constant height by adding a \strut to your text:

% !TeX program = txs:///arara
% arara: pdflatex: {synctex: on, interaction: nonstopmode, shell: yes}
\documentclass[a4paper,12pt]{scrreprt}

\usepackage[dvipsnames]{xcolor}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[dvipsnames]{xcolor}
\usepackage[ngerman]{babel}
\usepackage[chapter, cache=false]{minted}
\setminted[python]{
    frame=single,
    framesep=2mm,
    baselinestretch=1.2,
    fontsize=\footnotesize,
    linenos=true,
}

\begin{document}

\begin{listing}[ht]
\begin{minted}[escapeinside=||]{python}
print('test Test !,?/')
|\colorbox{green}{\strut{}test}| |\colorbox{yellow}{\strut{}Test}| |\colorbox{red}{\strut{}!,?/}|
\end{minted}
\end{listing}

\end{document}

enter image description here

Upvotes: 1

Related Questions