# How can I use \renewcommand to wrap \colorbox around \Verb by only changing the preamble?

What works:

I have TeX files which contain code like:

I want \texttt{this text} to have a background color.


I want the \texttt to have a background color:

I want \colorbox{lightgray}{\texttt{this text}} to have a background color.


However, I cannot modify the body of the TeX files - only the preamble. So I added:

\let\oldtexttt\texttt
\renewcommand{\texttt}[1]{\colorbox{lightgray}{\oldtexttt{#1}}}


That works perfectly.

What doesn't work:

Unfortunately, I also have:

I want \Verb|this text| to have a background color.


Which should really be:

I want \colorbox{lightgray}{\Verb|this text|} to have a background color.


But I cannot get \renewcommand to work the same way as above to add the \colorbox around it.

MCVE:

\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{xcolor}
\usepackage{fancyvrb}

\let\oldtexttt\texttt
\renewcommand{\texttt}[1]{\colorbox{lightgray}{\oldtexttt{#1}}}

\begin{document}

I want \texttt{this text} to have a background color.

I want \Verb|this text| to have a background color.

\end{document}

• Please don't overwrite basic macros like \texttt, just define your own macro and use this inside your document. Use logical formatting macros (i.e. which name what they highlight) and not physical formatting macros (e.g. bold, italic). For example if you write a software documentation and want to highlight all your variable names with a lighgray box and tt font create a macro \varname which uses a code like {\colorbox{lightgray}{\ttfamily #1}} in this case. – Martin Scharrer Dec 20 '18 at 16:26

## 1 Answer

Use newverbs package:

\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{xcolor}
\usepackage{fancyvrb}
\usepackage{newverbs}

\let\oldtexttt\texttt
\renewcommand{\texttt}[1]{\colorbox{lightgray}{\oldtexttt{#1}}}

\renewcommand{\Verb}{\collectverb{\colorbox{lightgray}}}

\begin{document}

I want \texttt{this text} to have a background color.

I want \Verb|this text| to have a background color.

\end{document}