19

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?

3

2 Answers 2

23

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

2
  • 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. Commented Nov 4, 2018 at 9: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
    Commented Mar 18, 2021 at 16:14
34

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

3
  • 2
    This is the correct answer Commented Jun 10, 2020 at 21:22
  • Can this be used to highlight two lines in different colors?
    – Eric
    Commented Apr 17, 2023 at 16:08
  • @Eric I had a quick look at minted's documentation and it doesn't seem to be possible.
    – ComFreek
    Commented Apr 18, 2023 at 21:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .