How to globally set \verb font style to match the default document style?

2,230

With the default font encoding OT1 you cannot switch the typewriter font to a normal text font, because of encoding issues (burden of compatiblity). The encoding issues are resolved in font encoding T1, for example. Then the font for \ttfamily can be changed to use the roman font instead, e.g.:

\documentclass{article}
\usepackage[T1]{fontenc}% NOT OT1!
\usepackage{lmodern}% Latin Modern fonts,
  % a modern variant of Computer Modern fonts
\let\ttdefault\rmdefault

\begin{document}
  Hello \texttt{World}! \verb|\relax %$&#|
\end{document}

Result

If you need to inherit the font settings from the context, then \[email protected] can be redefined to do nothing. It is used for \verb and environment verbatim:

\documentclass{article}

\usepackage[T1]{fontenc}% NOT OT1
\usepackage{lmodern}

\makeatletter
\renewcommand*{\[email protected]}{}
\makeatother

\begin{document}
  Hello \texttt{World}! \verb|\relax %$&#|

  {\sffamily Hello \texttt{World}! \verb|\relax %$&#|}

  {\itshape Hello \texttt{World}! \verb|\relax %$&#|}

  {\bfseries Hello \texttt{World}! \verb|\relax %$&#|}
\end{document}

Result

Share:
2,230

Related videos on Youtube

Francesco
Author by

Francesco

Updated on September 19, 2020

Comments

  • Francesco
    Francesco about 2 years

    I would like to set the \verb{} font so to correspond to the current family and size of my document. That is, the output must be indistinguishable by the rest of the text body whatever style is set as default.

    • egreg
      egreg about 9 years
      What do you need \verb for, then?
    • Francesco
      Francesco about 9 years
      Good question. I need to cheat on my text editor. See here.