18

I'm currently doing some work on error messages in programming languages. As such, I'm showing faulty pieces of code, alongside the compiler-errors accompanying them.

I'm using minted for the code snippets, but ideally, in addition to normal syntax highlighting, I'd like to highlight the sections of the code at which the error is located, by underlining them, putting a red box around them, shading their background, etc.

Is this possible using Minted?

2 Answers2

32

You can highlight certain lines with highlightlines={1,2-3,5-10}, e.g.

Screenshot of rendered code showing highlighted lines

\begin{minted}[highlightlines={1,3-4,6-10}]{python}
def f(x):
    y = x ** 2
    return y

def f(x):
    y = x ** 2
    return y

def f(x):
    y = x ** 2
    return y
\end{minted}

You can change the color by using, say, highlightcolor=red. In general, quoting from the minted package documentation:

highlightcolor: Set the color used for highlightlines, using a predefined color name from color or xcolor, or a color defined via \definecolor

ComFreek
  • 1,248
  • 2
  • 15
  • 22
21

The minted documentation has an example using escapeinside. I’m just copying it here:

\begin{minted}[escapeinside=||]{py}
def f(x):
    y = x|\colorbox{green}{**}|2
    return y
\end{minted}

Highlights as

screenshot

Konrad Rudolph
  • 39,394
  • 22
  • 107
  • 160
  • 8
    Color boxes start with a small but noticeable space, which can be annoying when highlighting whole lines of Python where indentation matters. The command \setlength{\fboxsep}{0pt} prevents this. – Anthony Labarre Nov 04 '18 at 09:53
  • The || did not work for me, giving some "File ended while scanning use of \FancyVerbGetLine" error that I couldn't easily resolve. Using [someoptions,escapeinside=@@] instead worked for me. Thanks! – Luc Mar 18 '21 at 16:14