[Tex/LaTex] Adding background color to \verb or \lstinline command without \Colorbox

colorlistingssourcecodeverbatim

Update:

In addition to my previous post, here's a screenshot to give you a better visual example. This was created with HTML and CSS for demo only.

In CSS, the code part is made using font-family: monospace, sans-serif;, background: #EFF0F1;, display: inline-block;, and padding: 2px 5px;.

I wonder if there's a simple way to mimic this style in LaTeX using \lstinline (or better options) without \Colorbox (if possible). All instances of \lstinline would have the same style.

What I mean by simple is that I thought I could just write something (once) inside \lstset{} in the preamble–which is simple–rather than typing \Colorbox in every instances of \lstinline–which is long and awful for a novice like me. Otherwise, using \Colorbox would be just fine.

sample image

Original question:

I need to create inline codes with gray background using either \verb or \lstinline. I've read here which use \Colorbox which works great!

My question: Could we achieve the same effect just using \lstinline alone, without \Colorbox so it would be more simple?

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\definecolor{mygray}{rgb}{0.8,0.8,0.8}
\lstset{%
basicstyle=\ttfamily,
breaklines = true,
backgroundcolor=\color{mygray},
}
\usepackage{realboxes}
\begin{document}

% demo using \lstinline only
This is \lstinline|my code|

% demo using \lstinline and \Colorbox
This is \Colorbox{mygray}{\lstinline|my code|}

\end{document}

enter image description here

Best Answer

You can patch \lstinline to use \Colorbox; of course you lose the possibility to break lines in \lstinline.

\documentclass{article}
\usepackage{xpatch}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{realboxes}

\definecolor{mygray}{rgb}{0.8,0.8,0.8}

\lstset{
  basicstyle=\ttfamily,
  backgroundcolor=\color{mygray},
}

\makeatletter
\xpretocmd\lstinline{\Colorbox{mygray}\bgroup\appto\lst@DeInit{\egroup}}{}{}
\makeatother

\begin{document}

\lstinline[language=TeX]|\my code|

\begin{lstlisting}[language=TeX]
\my code
\end{lstlisting}

\end{document}

enter image description here