6

I'm trying the add a grey highlight to the \texttt command to essentially achieve the same effect as the code blocks on here.

This is something I attempted to do when I first started writing my current document. I don't remember how I got there but the renew command I wrote looks like this:

\definecolor{Light}{gray}{.90}
\sethlcolor{Light}

\renewcommand{\texttt}{\hl}

This gives me the grey highlight, but the font it no longer monospace.

Can anyone help me?

Jivings
  • 163

2 Answers2

15

You need to make a small tweak:

\let\OldTexttt\texttt
\renewcommand{\texttt}[1]{\OldTexttt{\hl{#1}}}

to get normal text \texttt{foo bar} normal text to yield:

enter image description here

Alternative Solution:

Note that the above solution will effect all uses of \texttt{}. If that is not desired, an alternative solution would be to define a custom macro:

\newcommand{\hltexttt}[1]{\texttt{\hl{#1}}}

and then use \hltexttt{} when you want both the \hl and \texttt effect.

Code:

\documentclass{article}
\usepackage{xcolor}
\usepackage{soul}

\definecolor{Light}{gray}{.90} \sethlcolor{Light}

\let\OldTexttt\texttt \renewcommand{\texttt}[1]{\OldTexttt{\hl{#1}}}% will affect all \texttt %\newcommand{\hltexttt}[1]{\texttt{\hl{#1}}}% comment above \renewcommand if want this

\begin{document} normal text \texttt{foo bar} normal text \end{document}

Peter Grill
  • 223,288
1

Peter Grill already provided a great answer. Just as an alternative, you can also achieve this using \colorbox or \fcolorbox. The letter additionally allows you to specify a border color:

enter image description here

Code:

\usepackage{xcolor}
\definecolor{codebg}{gray}{0.95}
\definecolor{codeframe}{gray}{0.8}

\newcommand{\inlinecode}[1]{\fcolorbox{codeframe}{codebg}{\small!\texttt{#1}!}}

normal text \inlinecode{foo bar} normal text
scavi
  • 161