I was trying to redefine \texttt
command to make it have background color using package soul. But it seems that it is harder than I thought.
My initial code is
\documentclass{article}
\usepackage{xcolor, soul}
\colorlet{mycolor}{red!30}
\sethlcolor{mycolor}
\let\oldtexttt\texttt
\renewcommand{\texttt}[1]{
\hl{\oldtexttt{#1}}
}
\begin{document}
\texttt{can we highlight}
\end{document}
But it won't run, the error message is:
Argument of \texttt has an extra }.
I searched and found this post. The post suggests to use \soulregister
command. So I add the following line before \begin{document}
:
\soulregister{\texttt}{1}
But the error persists. I also found this post, which further suggests to use \DeclareRobustCommand
. Now my code is
\documentclass{article}
\usepackage{xcolor, soul}
\colorlet{mycolor}{red!30}
\sethlcolor{mycolor}
\let\oldtexttt\texttt
% \renewcommand{\texttt}[1]{
% \hl{\oldtexttt{#1}}
% }
\DeclareRobustCommand{\texttt}[1]{
\hl{\oldtexttt{#1}}
}
\soulregister{\texttt}{1}
\begin{document}
\texttt{can we highlight}
\end{document}
But it doesn't work. The error message is
TeX capacity exceeded, sorry [grouping levels=255]
It seems like rabbit hole of issues. Can you point out what has gone wrong? How to fix this seemingly simple problem?
Edit:
I am using Pandoc to convert Markdown file to PDF. The underlying LaTeX command for Markdown inline code is \texttt
. But there is no background color. That is why I want to combine soul and \texttt
.
I have tried the solution of @egreg and @daleif. They both work for standard alone tex code.
\documentclass{article}
\usepackage{xcolor, soul}
\colorlet{mycolor}{red!30}
\sethlcolor{mycolor}
\let\oldtexttt\texttt
% \renewcommand{\texttt}[1]{
% {\ttfamily\hl{#1}}
% }
\DeclareRobustCommand{\texttt}[1]{%
\hl{\ttfamily#1}%
}
\begin{document}
\texttt{can we highlight}
\end{document}
But if I put it in a file head.tex
and compile Markdown to PDF, there are still errors. The content of head.tex
is:
\usepackage{xcolor, soul}
\colorlet{mycolor}{red!30}
\sethlcolor{mycolor}
\let\oldtexttt\texttt
\DeclareRobustCommand{\texttt}[1]{%
\hl{\ttfamily#1}%
}
Content of test.md
is
`some inline words`
If I try to generate PDF using the new header:
pandoc -H head.tex -s test.md -o test.pdf
there occurs another error:
Package soul Error: Reconstruction failed.