Mimic StackExchange-style inline code in LaTeX

code

I love the way StackExchange formats inline code, using both a fixed width font and a gray background.

How can I mimic the above sentence in LaTeX?

One possibility might be using a combination of the listings, helvet, and inconsolata packages (in addition to the geometry package). Here is an attempt:

\documentclass{article}

% Implement 1-inch margins using 'geometry' package
% ('geometry' package: https://ctan.org/pkg/geometry)
\usepackage[margin=1in]{geometry}

% Implement inline code using 'listings' package
% ('listings' package: https://ctan.org/pkg/listings)
\usepackage{listings}

% Implement Helvetica using 'helvet' package
% ('helvet' package: https://ctan.org/pkg/helvet)
% (use code snippet from https://tex.stackexchange.com/a/121063/15622/)
\usepackage[scaled]{helvet}
\renewcommand\familydefault{\sfdefault}
\usepackage[T1]{fontenc}

% Implement Inconsolata, a Consolas-like font, using 'inconsolata' package
% ('inconsolata' package: https://ctan.org/pkg/inconsolata)
\usepackage{inconsolata}
\lstset{basicstyle=\ttfamily}

\begin{document}

\section*{Attempt to mimic StackExchange inline code}
\noindent I love the way StackExchange \lstinline|formats inline code|,
using both a \lstinline|fixed width font| and \lstinline|a gray background|.

\end{document}

output rendering

  • However, I'm not sure how to obtain the gray background. How can I do this?

  • In what other ways can my attempt be improved to mimic StackExchange-style inline code?

Best Answer

Here's an option using tcolorbox and soulpos, adapted from my answer here. It supports line breaking and any customization available to tcolorbox commands. The command \mycode can be used like \mycode{<code>} or \mycode<char><code><char>, e.g. \mycode|bla|, \mycode!bla!, ... The latter syntax allows <code> to contain \{ and \}.

\documentclass{article}

\usepackage{soulpos}
\usepackage{tcolorbox}

\newtcbox{\mybox}[1][]{
  on line,
  arc=1pt, outer arc=2pt,
  colback=lightgray!50!white, colframe=lightgray!50!white,
  boxsep=0pt, left=0pt, right=-1pt, top=2pt, bottom=0pt,
  boxrule=0pt, #1
}

\ulposdef\codeulinner[xoffset-start=1pt]{%
    \ifulstarttype{0}%
        {\tcbset{ULsiderule/.append style={leftrule=1pt}}}%
        {\tcbset{ULsiderule/.append style={leftrule=0pt,sharp corners=west}}}%
    \ifulendtype{0}%
        {\tcbset{ULsiderule/.append style={rightrule=1pt}}}%
        {\tcbset{ULsiderule/.append style={rightrule=0pt,sharp corners=east}}}%
    \mybox[ULsiderule]{\vphantom{Ap}\rule{\ulwidth}{0pt}}%
  }

\NewDocumentCommand{\mycode}{v}{%
  \begingroup\ttfamily
  \codeulinner{#1}%
  \endgroup%
  }

\begin{document}

Some code: \mycode{\command _^%&}

Some text. \mycode{This is very very very very very very very very very very very very very very very long inline code.} Some more text.
\end{document}

code

Correct output will require two compilations.