Change font size for verbatim as used with colorbox

fontsizeverbatim

Answer in Getting verbatim with soft grey background, as in tex.stackexchange

Shows how to make verbatim with gray background. But I am not able to make it show with smaller font size. comment below the answer says to do (I am using \tiny instead of \small but either one do not work)

\makeatletter\renewcommand\verbatim@font{\normalfont\tiny\ttfamily}

but this had no effect. I must not be using it correctly?

So instead of cluttering the comments in the above answer, I am making a new question asking how to change the font size for the verbatim environment as shown in the above answer.

I know how to do it using normal Verbatim command. But not using the above code. Here is MWE where code is taking from the above answer.

\documentclass[12pt]{article}
\usepackage{fancyvrb,newverbs,xcolor}
\definecolor{cverbbg}{gray}{0.95}

\newenvironment{cverbatim} 
 {\SaveVerbatim{cverb}}
 {\endSaveVerbatim
  \flushleft\fboxrule=0pt\fboxsep=.5em
  \colorbox{cverbbg}{\BUseVerbatim{cverb}}%
  \endflushleft
}

\makeatletter\renewcommand\verbatim@font{\normalfont\tiny\ttfamily}

\begin{document}

This is my verbatim. How to make font tiny? now font size does not change

\begin{cverbatim}
int main() { 
printf("hello, world");

`Methods for first order ODEs:

return 0;
}
\end{cverbatim}

\end{document}

Which when compiled using lualatex foo.tex gives

enter image description here

Everything is good, except the font size has not changed. I know I can explicitly add \tiny before and then add \normalsize after to make it work, but I do not want to keep doing this. I want the verbatim to automatically typeset in \tiny font.

How to correctly implement the above so that verbatim font size comes out in the smaller font size?

Best Answer

Use

\newenvironment{cverbatim}
{\SaveVerbatim{cverb}}
{\endSaveVerbatim
\tiny\flushleft\fboxrule=0pt\fboxsep=.5em % <<<<<<<<<<<<<<<<<<<<<<
    \colorbox{cverbbg}{\BUseVerbatim{cverb}}%
    \endflushleft
}

c

(remove \makeatletter\renewcommand\verbatim@font{\normalfont\tiny\ttfamily} from you code)

Related Question