[Tex/LaTex] Listings for OCaml and quotes

listings

The listings syntax highlighting for OCaml breaks whenever the OCaml literal character '"' appears in the source.

It's not possible to let the language definition treat single quotes as a delimiter for string literals because single quotes are also used for type variables (e.g. 'a list)

The following document shows the problem. On the last line of the output the let keyword should be in bold. This doesn't happen because listings thinks it is inside a string literal. If we treat single quotes as string literal delimiters then first line breaks the rendering of the subsequent lines.

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage[scaled]{beramono}
\usepackage{listings}
\lstset{
 language=caml,
 columns=[c]fixed,
 basicstyle=\small\ttfamily,
 keywordstyle=\bfseries,
 upquote=true,
 commentstyle=,
 breaklines=true,
 showstringspaces=false}
\begin{document}
 \begin{lstlisting}
 type 'a t = ..
 let double_quote = '"'
 let broken_highlight = ()
 \end{lstlisting}
\end{document}

Is there a way to configure the listings package for OCaml so that this problem doesn't happen ?

Best Answer

In this particular case you can use the literate option which doesn't break with double-quoted strings or other highlighting:

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
%\usepackage[scaled]{beramono}
\usepackage{listings}
\usepackage{xcolor}

\lstset{
 language=caml,
 columns=[c]fixed,
% basicstyle=\small\ttfamily,
 keywordstyle=\bfseries,
 upquote=true,
 commentstyle=,
 breaklines=true,
 showstringspaces=false,
 stringstyle=\color{blue},
 literate={'"'}{\textquotesingle "\textquotesingle}3
}

\begin{document}
 \begin{lstlisting}
 type 'a t = ..
 let double_quote = "foo"
 let double_quote = '"'
 let double_quote = 'a'
 let double_quote = "'"
 let broken_highlight = ()
 \end{lstlisting}
\end{document}

enter image description here