5

I want to have both code snippets ABC and ABC_DEF in red (in both cases only ABC is red). If I remove the literate line it works but I also want to have automatic line breaks at underlines. How can I achieve both aims?

\documentclass{article}

\usepackage{listings}
\lstset{
    emph={ABC, ABC_DEF},
    emphstyle={\color{red}},
    literate={\_}{}{0\discretionary{\_}{}{\_}} % line breaks at underlines
}
\usepackage[colorlinks=true]{hyperref}


\begin{document}
\lstinline{ABC}
\lstinline{ABC_DEF}
\end{document}
jub0bs
  • 58,916

1 Answers1

1

I would advise you against allowing for hyphenation in the middle of inline code, because you run the risk of confusing your readers. If I were you, I'd reorganise the text a bit to make sure that no inline code sticks out of the right-hand-side margin.

If you're set on doing it anyway, I wouldn't follow your approach, though; it's a roundabout way of doing things. A simpler approach could be to

  • eschew \lstinline and the literate key entirely,
  • use a custom macro that applies the same emphasis style as the one in your listings:

    \makeatletter
    \newcommand\inlinecode[1]{{\lst@basicstyle\lst@emphstyle #1}}
    \makeatother
    
  • load the underscore package (for more details, see this answer by diabonas), in order to allow for hyphenation after underscore characters:

    \usepackage{underscore}
    

enter image description here

\documentclass{article}

\usepackage[textwidth=1.5cm,showframe]{geometry}  % only for illustration purposes, here

\usepackage{xcolor}
\usepackage{listings}
\usepackage{underscore} % allows hyphenation after \_

\makeatletter
\newcommand\inlinecode[1]{{\lst@basicstyle\lst@emphstyle #1}}
\makeatother

\lstset{
    basicstyle=\ttfamily,
    emph={ABC, ABC_DEF},
    emphstyle={\color{red}},
}

\setlength{\parindent}{0pt}    


\begin{document}

\verb|\lstinline|:
\lstinline|ABC|
\lstinline|ABC_DEF|

\verb|\inlinecode|:
\inlinecode{ABC}
\inlinecode{ABC\_DEF}

\end{document}
jub0bs
  • 58,916
  • 2
    This is nice, but I found this question while searching for the general case solution; in my case I need to break at forward slashes, not underscores (the discretionary command is screwing up the syntax highlighting of comments, which use //). This is also in the straight lstlistings environment, it doesn't only happen in the inline case. Would be nice to know how to deal the with the problem generically. – Ben Farmer Jun 16 '16 at 16:47