Search code examples
latexhighlightlistings

Highlighting inline code snippets with the latex listings package


In my latex document I am using the listings package extensively. I have many short inline code snippets that I like to give a proper highlighting in the text, and I am using the \lstMakeShortInline construct. Now I am interested in highlighting (background coloring) at least some of those code inserts for clarity, and was trying the following: \lstMakeShortInline[language=Python,basicstyle=\ttfamily, backgroundcolor=\color{lightgray}]! hoping that usage like:

some text some text !read_csv()! some more text

Will result in read_csv() appearing on a light-gray background, but it does not seem to work. The \ttfamily format works well in this situation.

(Thanks to samcarter_is_at_topanswers.xyz)

Here is a minimal example:

\documentclass{book}

\usepackage{listings}
\usepackage{color}
\lstset{language=Python}

\begin{document}

\lstMakeShortInline[language=Python, keywordstyle={\bfseries \color{blue}}, backgroundcolor=\color{yellow}]!

Here is the keyword !for!, showing that the \textbf{keywordstyle} setting takes effect, but the \textbf{backgroundcolor} setting does not.

\textbf{backgroundcolor} fails to take effect also when applied to a non-keyword !df.read_csv()! code snippet.

\end{document}

Is this possible with the listings package?

Thanks

Michael


Solution

  • Based on https://tex.stackexchange.com/a/357239/36296 you could do something like (make sure that ! does not occur in the normal text or use a different character):

    % !TeX program = lualatex
    \documentclass{article}
    \usepackage{xcolor,listings,realboxes,fancyvrb} % fancyvrb for '\Verb' macro
    \definecolor{mygray}{rgb}{0.8,0.8,0.8}
    \lstset{basicstyle=\ttfamily, breaklines = true, backgroundcolor=\color{mygray}}
    \usepackage[doublespacing]{setspace} % just for this example
    
    \usepackage{luacode} % for 'luacode' environment
    \begin{luacode}
    -- the following code employs Lua's powerful "string.gsub" function
    function color_lstinline ( s )
       s = string.gsub ( s , "%b!!", "\\Colorbox{mygray}{%0}" ) 
       return s
    end
    \end{luacode}
    %% Define 2 LaTeX macros to switch operation of Lua function on and off
    \newcommand{\ColorLstinlineOn}{\directlua{
       luatexbase.add_to_callback ( "process_input_buffer" , 
       color_lstinline, "color_lstinline" )}}
    \newcommand{\ColorLstinlineOff}{\directlua{
       luatexbase.remove_from_callback ( "process_input_buffer" , 
       "color_lstinline" )}}
    \AtBeginDocument{\ColorLstinlineOn} % Default: activate the Lua function 
    
    \lstMakeShortInline[language=Python, keywordstyle={\bfseries \color{blue}}, backgroundcolor=\color{yellow}]!
    
    \begin{document}
    
    !for!
    
    \end{document}
    

    enter image description here