Highlight text in LaTeX (hl, soul)

Load xcolor and soul and write \hl{text}. The text gets a yellow background as from a marker pen and still breaks at the end of a line.

Preamble

The snippets on this page need these lines before \begin{document}:

\usepackage{xcolor}
\usepackage{soul}

Highlight in yellow

\hl{...} comes from the soul package and needs xcolor for the colour. Without a colour package \hl underlines the text instead.

This sentence has \hl{a highlighted part that is long enough to run
over the end of the line} and continues normally.
Result
The compiled example

Open in the editor

Another colour

\sethlcolor{colour} sets the colour for every \hl that follows inside the current group. Any xcolor colour works, also a mix such as green!30.

{\sethlcolor{green!30}\hl{Green highlight}} and
{\sethlcolor{cyan!40}\hl{blue highlight}}, then \hl{yellow again}.
Result
The compiled example

Open in the editor

A box for a word or a formula

\colorbox{colour}{...} from xcolor needs no further package. It does not break at the end of a line, which suits single words, numbers and inline formulas.

The result is \colorbox{yellow}{$x = 42$} and the status
is \colorbox{green!30}{passed}.
Result
The compiled example

Open in the editor

References and citations in highlighted text

\hl reads its argument piece by piece and fails on commands such as \ref and \cite. Wrap them in \mbox{...}. Font commands such as \textbf and \emph and inline formulas in $...$ work without it.

\section{Results}\label{sec:results}
\hl{Section~\mbox{\ref{sec:results}} shows that $x > 0$ holds
in \textbf{all} cases.}
Result
The compiled example

Open in the editor

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages